# -*- coding: utf-8 -*-
"""
Created on Sun Jan 12 13:06:03 2020

@author: iansh


"""

import math
import numpy
import Useful
#import sys

import matplotlib.pyplot as plt

"""

NO!!! WRONG!!!  Eq. 8 Mandel & Agol only valid for ingree & egress


#
# Compute the analytic light curve in the small-planet approximation of Mandel
# and Agol 2002, Eq. 8 ("Analytic Lightcurves for Planetary Transit Searches")
#
# Reads in planetary system parameters for a single planet around a single star
#and computes the impact parameter and time coordinate of snapshots
# corresponding to the Gauss-Legendre quadrature as the planet transits the star
#in the stellar atmosphere coordinate system

#Integrated transit solution with stellar atmosphere and radiative tranfer code
#  :: transit light curve entirely due to specific intensity variation across
#   projected disk of background star
#  - ie. No limb darkening coefficient (LDC) parameterization!

Assumptions:
    o Planet's transit path is a chord (not an arc)
     :: equal intevals of length along chord --> equal intervals of transit time
         - okay if r_orbit >> R_star
    o Eclipsed intensity (I) does not vary as a function of position across the 
       projected disk of the planet
         - okay if R_planet << R_star
    o Planet's orbit is circular and centered on centre of star
    o Planet's intensity is 0
    o Ingress and egress excluded 
    
    - All light variation will be from background stellar intensity
        variation across projected stellar disk
    - Okay if r_planet << R_star - ??
         
#Input:
  o radius = radius of star (R_Sun)
     - NOTE: already fixed by stellar parameters massStar and grav
  o cosTheta - 2D array [2 x numThetas] - 2nd row is grid of cosTheta values in 
     stellar atmosphere coord system from main program
  o vTrans - velocity of planet's transit motion projected to surface of star
  o Input parameter "p" defined in Mandel 7 Agol (2002) Section 2
  o intensLam is the 1D monochromatic I_lambda (theta) distribution "sliced" from the
    2D I(lambda, cosTheta) "intens" array in CSPy
    
#Output:
  o 1D vector of transit times corresponding to theta values transited along transit chord

"""

def transLightAnlytc(intensLam, radius, p, cosTheta, vTrans, iFirstTheta, numTransThetas, impct):
    
    #Safety first:
    
    tiny = numpy.double(1.0e-49)
    logTiny = math.log(tiny)    
    

    if (impct >= radius):
        #There is no eclipse (transit)
        return
    #thetaMinRad is also the minimum theta of the eclipse path chord, in RAD
    thetaMinRad =  math.asin(impct/radius)
    #cos(theta) *decreases* with increasing theta in Quadrant I:
    cosThetaMax = math.cos(thetaMinRad)
    
    
    #Compute array of distances traveled, r, along semi-chord from position of
    #minimum impact parameter
    #12D array of length number-of-eclipse-thetas
    #Mandel & Agol (2002)'s "F" - "relative flux"
    F = [0.0 for i in range(numTransThetas)]
    #Mandel & Agol (2002)'s "z" parameter for their Eq. 8
    z = 0.0 
    
    #test = [0.0 for i in range(numThetas)]
    
    #Parameters for Mandel & Agol (2002) Eq. 8 for relatie flux, their "F":
    #coefficients for Claret (2000)'s four-parameter limb darkening law:
    #A&A 363, 1081
    #Estiamted from Fig. 3 for logTeff = 3.75, dot-dash line for [M/H]=0.0
    #   for y filter, log(g)=4.5 (ATLAS9 model)
    #In order of *increasing* order: c_0 to c_4 
    c = [0.0, 0.55, -0.5, 1.0, -0.4]  
    c[0] = 1.0 - c[1] - c[2] - c[3] - c[4]
    omegaMA = 0.0
    for n in range(5):
        omegaMA+= c[n] / (n+4)
    
    thisB = numpy.double(0.0)
    Istar = [0.0 for i in range(numTransThetas)] # To be accumulated
    preFacIstar = 1.0 # initialize
    preFac = 0.0
    arg = 0.0
    fac1 = 0.0
    fac2 = 0.0

#This isn't the most elegant, but accumulate the Mandel & Agol Istar values
# for each "z" first, then another loop to compute their F(z) - all for their Eq. 8"
    #Initialize lastZ (i=numTransThetas-1 in loop below):
    thisTheta = math.acos(cosTheta[1][(numTransThetas-1) + iFirstTheta])
    # impact parameter corresponding to this theta, in solar radii:
    thisB = radius * math.sin(thisTheta)
    #"z" defined in Mandel & Agol (2002) Section 2 
    lastZ = thisB / radius #M & A 2002's "z"
    Istar[numTransThetas-1] = 0.0
    for i in range(numTransThetas-2, -1, -1):
        #print("i ", i)
        thisTheta = math.acos(cosTheta[1][i+iFirstTheta])
        #test[i+iFirstTheta] = math.exp(logRatio)
        # impact parameter corresponding to this theta, in solar radii:
        thisB = radius * math.sin(thisTheta)
        #"z" defined in Mandel & Agol (2002) Section 2 
        z = thisB / radius #M & A 2002's "z"
        # Build Mandel & Agol's "F" from Eq. 8 in stages:
        a = (z - p)**2 #M & A 2002's "a" (Defined in Sect. 3)
        preFacIstar = 1.0 / (1.0-a)
        Istar[i] = Istar[i+1] + intensLam[i+iFirstTheta] * 2.0 * z * (lastZ - z)
        print("i ", i, " Istar[i+1] ", Istar[i+1], " Istar[i] ", Istar[i])
        lastZ = z

        
    for i in range(0, numTransThetas):
        #print("i ", i)
        thisTheta = math.acos(cosTheta[1][i+iFirstTheta])
        #test[i+iFirstTheta] = math.exp(logRatio)
        # impact parameter corresponding to this theta, in solar radii:
        thisB = radius * math.sin(thisTheta)
        #"z" defined in Mandel & Agol (2002) Section 2 
        z = thisB / radius #M & A 2002's "z"
        # Build Mandel & Agol's "F" from Eq. 8 in stages:
        a = (z - p)**2 #M & A 2002's "a" (Defined in Sect. 3)
        preFac = ( 1.0 - Istar[i]/(4.0*omegaMA) )
        arg = (z-1.0)/p
        if (arg < -1.0):
            arg = -1.0
        if (arg > 1.0):
            arg = 1.0
        fac1 = p**2 * math.acos(arg)
        if ((z-1)**2 <= p**2):
            fac2 = math.sqrt(p**2 - (z-1)**2)
        else:
            fac2 = 0.0
        
        F[i] = preFac * (fac1 - (z-1)*fac2)
        print("i ", i, " F[i] ", F[i])

    return F

