# -*- 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

"""
# Reads in planetary system parameters for a single planet around a single star
#and computes the theta and phi coordinates of the planet's position in front
#of the star during the eclipse 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 instantaneous (for now)
       - All light variation will be from background stellar intensity
         variation across projected stellar disk
       - Okay if r_planet << R_star - ??
         
#Input:
  o rOrb = radius of planets orbit (AU)
  o rotI = inclination of system's rotation axis wrt line-of-sight (degrees)
     - NOTE: fixed to value used for rotational broadening of the
       star's spectrum - we're assuming rotation and revolution throughout 
       the system are coplanar 
  o rPlanet = radius of planet (r_Earth units)
  o radius = radius of star (R_Sun)
     - NOTE: already fixed by stellar parameters massStar and grav
  o theta - 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
    
#Output:
     o theta[] values along transit path chord
         - for input to flux3()
     o corresponding values of r[] distance travelled along half-transit path
        (ie. semi-chord) wrt to position at minimum impact parameter 
     # NO1 - do in main program: o ratio of stellar disk blocked by planet's disk
"""

def TransLight(rotI, radius, rOrbit, rPlanet, cosTheta, numPhiD, vTrans):
    
    #Safety first:
    
    tiny = numpy.double(1.0e-49)
    logTiny = math.log(tiny)    
    
    #Angle of orbital axis wrt plane-of-sky
    iPrime = numpy.double(90.0) - rotI
    
    #Degrees to RAD
    iPrimeRad = iPrime * math.pi / numpy.double(180.0)
    
    #Right angle triangle with hypoteneuse = rOrbit
    #  angle = rotIRad, 
    #  and opposite = planet's minimum impact parameters wrt substellar point
    #impact parameter (minimum offset from substellar point)in AU
    impct = rOrbit * math.sin(iPrimeRad)
    #impact parameter in solar radii
    impct = impct * Useful.AU2cm() / Useful.rSun()
    
    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)
    
    #Length of semi-chord in solar radii
    #Right angled triangle in plane-of-sky with 
    #  hypoteneuse (C) = radius of star
    #  side B = impact parameter
    #  side C = semi-chord-length
    #semiChord = math.sqrt(radius**2 - impct**2)
    
    # ALL this phi2 stuff may not be needed and can be deleted...
    #phi2 coordinate system same as azimuthal phi coordinate of 
    #  spherical polar stellar atmosphere coord system, 
    #  BUT with phi2 = 0 corresponding to planet's offset = impact parameter
    #  (point of closest approachto substellar point)
    #  :: At phi2 = 0 distance transited = semi-chord
    
    #Maximum phi/2 when distance transited since phi2 = 0 is 
    #  equal to a semi-chord
    # at phi2 = phi2Max, theta = pi/2 Rad
    #    Right angle triangle with hypoteneuse = radius of star
    #    Adjacent = impact parameter
    #    angle phi2Max 
    #needed? phi2Max = math.cos(impct / radius)
    
    #During semi-transit, in stellar atmosphere spherical polar coords:
    #  theta increases from thetaMin to pi/2 Rad
    #  phi2 increases from 0 to phi2Max
    
    #This needs to be put into a loop over input theta values taken from 
    #Gaussian quadrature routine cosTheta, already called from main program
    #For now try sampling semi-chord (half transit) with 10 evenly spaced points
    
    #False start??
    #thisPhi2 = 0 
    #Right angle triangle in plane of sky with 
    #  hypoteneuse = current offset from substellar point in direction phi2
    #  angle = current phi2
    #  adjacent = impact parameter 
    #if (math.cos(thisPhi2) > tiny):
    #    thisOffset = impct / math.cos(thisPhi2)
    #else:
    #    print("transLight():  Something's wrong:  \n"\
    #          "math.cos(thisPhi2) > tiny ")
    #    thisOffset = radius
    #
    ##Convert current offset to current theta 
    #thisTheta = math.asin(thisOffset/radius)
    
    #Find out how many input cosTheta values from Gaussian quadrature are on
    # the half-transit semi-chord:
    numThetas = len(cosTheta[0])
    numTransThetas = 0
    i = 0
    iFirstTheta = 0
    #ifFirst = False
    #for i in range(numThetas):
    #cosTheta[1] *decreases* (ie. theta increases) with increasing array number 
    while ( (cosTheta[1][i] >= cosThetaMax)
           & (i < numThetas) ):
        #if (ifFirst == False):
        #    iFirstTheta = i
        #    ifFirst = True
        # We are on the eclipse semi-chord:
        i+=1
    iFirstTheta = i
    numTransThetas = numThetas - i   
    
    #Compute array of distances traveled, r, along semi-chord from position of
    #minimum impact parameter, and corresponding theta values:
    # 2D array of 2 x number-of-eclipse-thetas
    transit = [[0.0 for i in range(numTransThetas)] for j in range(2)]
    #test = [0.0 for i in range(numThetas)]
    #Row 0 is logarithmic ratio of planet area to annulus area 
    # - set default value to log of neglible value:
    #transit[0] = [logTiny for i in range(numThetas)]
    
    
    # rEarth to cm units:
    logRPlanetCm = math.log(rPlanet) + Useful.logREarth()
    rPlanetCm = math.exp(logRPlanetCm)
    #Projected planet area in cm^2
    logAreaPlanet = math.log(math.pi) + 2*logRPlanetCm   
    #rEarth units to rSun:
    logRPlanetRSun = logRPlanetCm - Useful.logRSun()
    rPlanetRSun = math.exp(logRPlanetRSun)
    
    #debug - Comparison check:
    rSunCheck = 7.0e10 # cm
    rEarthCheck = 6.4e8 #cm
    ratioCheck = (rEarthCheck/rSunCheck)**2
    logRatioCheck = math.log(ratioCheck)
    
    
    # row 0 should be area of planet divided by area of annulus segment 
    #  area of annulus segment = 2*pi*r*Delta_r * r*dPhi
    deltaPhi = numpy.double(2.0*math.pi / numPhiD)
    
    thisImpct = numpy.double(0.0)
    thisArc = numpy.double(0.0)
    thisArea = numpy.double(0.0)
    #ratio = 0.0
    #print("logAreaPlanet ", logAreaPlanet, " numTransThetas ", numTransThetas, " iFirstTheta ", iFirstTheta)
    for i in range(numTransThetas):
        #print("i ", i)
        thisTheta = math.acos(cosTheta[1][i+iFirstTheta])
        #Area of this annulus in units of rSun^2
        if ((i+iFirstTheta) <= 1):
            thisTheta = math.acos(cosTheta[1][1])
            thisImpct = radius * math.sin(thisTheta)
            thisArea = math.pi * thisImpct**2 
            #No? thisArea = thisArea/math.sin(thisTheta)
            #print("thisTheta ", thisTheta, " thisImpct ", thisImpct, " thisArea ", thisArea)
        else:
            thisTheta0 = math.acos(cosTheta[1][i+iFirstTheta-1])
            thisImpct0 = radius * math.sin(thisTheta0)
            thisTheta = math.acos(cosTheta[1][i+iFirstTheta])
            thisImpct = radius * math.sin(thisTheta)
            thisArc = thisImpct * deltaPhi
            thisDeltaImpct = thisImpct - thisImpct0
            #thisDeltaImpctCm = thisDeltaImpct * Useful.rSun()
            #thisArea = math.pi * (thisImpct**2 - thisImpct0**2)
            if (thisDeltaImpct < 2.0*rPlanetRSun):
                thisDeltaImpct = 2.0*rPlanetRSun
            if (thisArc < 2.0*rPlanetRSun):
                thisArc = 2.0*rPlanetRSun                 
            thisArea = numpy.double(2.0 * math.pi) * thisImpct0 * thisDeltaImpct * thisArc
            #Flux.flux3() now uses 2D summation over "pie segments" - latitudexlongitude tiles
            # - so, try dividing out by sine(theta) to correct for theta-dependence of segment area
            #No? thisArea = thisArea/math.sin(thisTheta)
            #print("thisTheta ", thisTheta, " thisTheta0 ", thisTheta0, " thisImpct ", thisImpct, " thisImpct0 ", thisImpct0, " thisArea ", thisArea)
        #No! thisArea = thisArea/numPhiD
        #print(thisArea)
        logArea = math.log(thisArea) + numpy.double(2.0)*Useful.logRSun() #from rSun^2 to cm^2
        logRatio = logAreaPlanet - logArea
        if (logRatio > 0.0):
            logRatio = 0.0
        #Weight of transited annulus:  One of the phiD "pie" segments is now dimished by
        # area fraction "x" 
        #  :: annulus weight = { (numPhiD-1) + x }
        #This isi the ratio by with a phi-integrated annulus is diminished:
        #ratio = math.exp(logRatio) 
        #ratio2 = ( (numPhiD-1) + ratio ) / numPhiD
        #logRatio = math.log(ratio2)
        print("logRatioCheck ", logRatioCheck)
        print("logArea ", logArea, " logRatio ", logRatio)
        #row 0 is log of ratio of planet area to annulus area for annulus of the current theta 
        #  coordinate of the transit path
        transit[0][i] = logRatio
        #test[i+iFirstTheta] = math.exp(logRatio)
        # impact parameter corresponding to this theta:
        thisB = radius * math.sin(thisTheta)
        # linear distance travelled along transit semi-path in solar radii
        transit[1][i] = math.sqrt(thisB**2 - impct**2)
        transit[1][i] = transit[1][i]*Useful.rSun() #RSun to cm
        #row 1 is Times at which successive annuli are eclipsed, in s:
        #Ephemeris zero point at transit mid-point  
        transit[1][i] = transit[1][i]/vTrans
        #print("i ", i, " i+iFirstTheta ", i+iFirstTheta, " transit[1] ", transit[1][i+iFirstTheta])

        
    #sys.exit()

#print("transit[0] ", transit[0]) 
#print("transit[1] ", transit[1])
    #plt.plot(transit[1], test)

##Array of snapshot displacements along transit path, DeltaR
#transDeltaR = [0.0 for i in range(numEclpsThetas)]
##In solar radii
#transDeltaR[1:numThetas-1] = [(transit[1][i]-transit[1][i-1]) for i in range(1, numEclpsThetas)]
##In cm:
#transDeltaR = [transDeltaR[i]*Useful.rSun() for i in range(numEclpsThetas)]
##Corresponding time intervals, DeltaT, in s
## - these are the amounts of time the planet spends eclipsing each annulus of each theta
#transDeltaT = [(transDeltaR[i]/vTrans) for i in range(numEclpsThetas)]


        
    return transit

        
    
    
    
    
    
     
     