forked from rzellem/EXOTIC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exotic.py
2543 lines (2109 loc) · 118 KB
/
exotic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2002-2019, California Institute of Technology.
# All rights reserved. Based on Government Sponsored Research under contracts NNN12AA01C, NAS7-1407 and/or NAS7-03001.
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the California Institute of Technology (Caltech), its operating division the Jet Propulsion Laboratory (JPL), the National Aeronautics and Space Administration (NASA), nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE CALIFORNIA INSTITUTE OF TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
####################################################################
# EXOplanet Transit Interpretation Code (EXOTIC)
#
# Author: Ethan Blaser
# Co-authors: Rob Zellem, Kyle Pearson, John Engelke
# Mentors: Dr. Robert Zellem and Anya Biferno
# Supplemental Code: Kyle Pearson, Gael Roudier, and Jason Eastman
####################################################################
# EXOTIC version number
# Major releases are the first digit
# The next two digits are minor commits
# (If your commit will be #50, then you would type in 0.5.0; next commit would be 0.5.1)
versionid = "0.6.0"
# --IMPORTS -----------------------------------------------------------
import os
import logging
import sys
from numpy import mean, median
import platform
# glob import
import glob as g
# julian conversion imports
import astropy.time
import astropy.coordinates
import dateutil.parser as dup
# UTC to BJD converter import
from barycorrpy import utc_tdb
# Curve fitting imports
import math
from math import asin
from scipy.interpolate import RectBivariateSpline
from scipy.ndimage.interpolation import rotate
from scipy.optimize import least_squares
# Pyplot imports
import matplotlib.pyplot as plt
from astropy.visualization import astropy_mpl_style
from matplotlib.animation import FuncAnimation
plt.style.use(astropy_mpl_style)
# Centroiding imports
import pylab as plt
# MCMC imports
import pymc3 as pm
import theano.compile.ops as tco
import theano.tensor as tt
# astropy imports
from astropy.io import fits
from astropy.stats import sigma_clip
from photutils import CircularAperture
from photutils import aperture_photometry
# cross corrolation imports
from skimage.feature import register_translation
import json
import requests
# Lightcurve imports
from gaelLCFuncs import *
from occultquad import *
# ---HELPER FUNCTIONS----------------------------------------------------------------------
# Function that bins an array
def binner(arr,n=1):
ecks = np.pad(arr.astype(float), ( 0, ((n - arr.size%n) % n) ), mode='constant', constant_values=np.NaN).reshape(-1, n)
arr = np.nanmean(ecks, axis=1)
err = np.nanstd(ecks, axis=1)/np.sqrt(n)
return arr, err
# finds the planet line in the composite dictionary
# returns -1 if its not there
def findPlanetLineComp(planName, dataDictionary):
coun = 0
for line in dataDictionary:
if line['fpl_name'] == planName:
index = coun
coun = coun + 1
return index
# finds the line number of the planetName in the confirmed dictionary
# returns -1 if its not there
def findPlanetLineConf(planName, dataDictionary):
coun = 0
index = -1
# account for mistakes in capitalization, spaces, and dashes
noSpaceP = planName.replace(" ", "")
noSpaceDashP = noSpaceP.replace("-", "")
noCapsSpaceP = noSpaceDashP.lower()
for line in dataDictionary:
exoPname = line['pl_name']
exoPnoSpace = exoPname.replace(" ", "")
exoPnoSpaceDash = exoPnoSpace.replace("-", "")
exoPnoSpaceLower = exoPnoSpaceDash.lower()
if noCapsSpaceP == exoPnoSpaceLower:
index = coun
coun = coun + 1
if index != -1:
return index
else:
# print('Error! Could Not Find Planet with the name: '+planName)
# sys.exit()
return -1
def findPlanetLinesExt(planName, dataDictionary):
coun = 0
indexList = [] # this has multiple lines per planet so list needed
for line in dataDictionary:
if line['mpl_name'] == planName:
indexList.append(coun)
coun = coun + 1
return indexList
def scrape():
url = "https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI"
# Query the Confirmed Planets Table
confirmedstring = {"table": "exoplanets", "select": "pl_name,pl_hostname, st_mass, st_rad, pl_massj, pl_rads, pl_ratdor, pl_orbper \
pl_orbpererr1, pl_orbpererr2, pl_tranflag, pl_orbeccen, pl_orbincl, pl_orblper, st_teff,st_metfe, st_logg ",
"order": "pl_name", "format": "json"}
headers = {
'User-Agent': "PostmanRuntime/7.15.0",
'Accept': "*/*",
'Cache-Control': "no-cache",
'Postman-Token': "88fa4adf-b280-408e-989c-d5148d1292d5,ca3608a9-09a2-49d0-8d23-6c2527921127",
'Host': "exoplanetarchive.ipac.caltech.edu",
'accept-encoding': "gzip, deflate",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
response = requests.request("GET", url, headers=headers, params=confirmedstring)
confirmedText = response.text
# print(response.text)
f = open("eaConf.txt", "w+")
f.write(confirmedText)
f.close()
# Query the Composite Planets Table
compositestring = {"table": "compositepars", "select": "fpl_name, fpl_rads, fpl_eccen, fst_mass,\
fpl_orbper, fpl_orbpererr1, fpl_orbpererr2, fst_rad, fpl_smax, fpl_tranflag, fst_met, fst_teff, fst_logg ",
"order": "fpl_name", "format": "json"}
response = requests.request("GET", url, headers=headers, params=compositestring)
compositeText = response.text
# print(response.text)
f = open("eaComp.txt", "w+")
f.write(compositeText)
f.close()
# Query the Extended Table
extendedstring = {"table": "exomultpars", "select": "mpl_hostname,mpl_name,mst_mass,mst_rad,mst_teff,mpl_bmassj,mpl_rads,\
mpl_tranflag,mpl_ratdor,mpl_tranmid, mpl_orbper, mpl_tranmiderr1, mpl_tranmiderr2, mpl_orbpererr1,mpl_orbpererr2",
"order": "mpl_name", "format": "json"}
response = requests.request("GET", url, headers=headers, params=extendedstring)
extendedText = response.text
# print(response.text)
f = open("eaExt.txt", "w+")
f.write(extendedText)
f.close()
# get params method that either reads in all the parameters from the dictionary, or estimates them if not
def getParams(confirmedData, compositeData, extendedData, plaName):
newtonG = 6.67 * 10 ** (-11) # m^3/(kg*s^2)
rSun = 6.957 * 10 ** 8 # m
mSun = 1.989 * 10 ** 30 # kg
# find the planet line in the confirmed table based on UI plName
confirmedLine = findPlanetLineConf(plaName, confirmedData)
# star parameters
starRadius = confirmedData[confirmedLine]['st_rad'] # in terms of rsun
starSemi = confirmedData[confirmedLine]['pl_ratdor'] # in terms of star radius
starMass = confirmedData[confirmedLine]['st_mass'] # interms of msun
starName = confirmedData[confirmedLine]['pl_hostname']
starTemp = confirmedData[confirmedLine]['st_teff']
starMet = confirmedData[confirmedLine]['st_metfe']
starLogg = confirmedData[confirmedLine]['st_logg']
# planetParameters
planetName = confirmedData[confirmedLine]['pl_name']
planetRadS = confirmedData[confirmedLine]['pl_rads'] # *solarRadius
planetPeriod = confirmedData[confirmedLine]['pl_orbper'] # in jd
planetPerUnc1 = confirmedData[confirmedLine]['pl_orbpererr1'] # in jd
planetPerUnc2 = confirmedData[confirmedLine]['pl_orbpererr2'] # in jd
planetTranFlag = confirmedData[confirmedLine]['pl_tranflag'] # 1 or 0
planetEcc = confirmedData[confirmedLine]['pl_orbeccen']
planetInc = confirmedData[confirmedLine]['pl_orbincl'] # deg
plLineComp = findPlanetLineComp(planetName,
compositeData) # finds the planet line number in the composite data table
plLinesExt = findPlanetLinesExt(planetName, extendedData) # find the planet line numbers in the extended data table
if starTemp is None:
if compositeData[plLineComp]['fst_teff'] is not None:
starTemp = compositeData[plLineComp]['fst_teff']
else:
starTemp = -1
if starMet is None:
if compositeData[plLineComp]['fst_met'] is not None:
starMet = compositeData[plLineComp]['fst_met']
else:
starMet = -1
if starLogg is None:
if compositeData[plLineComp]['fst_logg'] is not None:
starLogg = compositeData[plLineComp]['fst_logg']
else:
starLogg = -1
# null planet radius case (gives the radius in terms of the radius of the sun)
if planetRadS is None:
if compositeData[plLineComp]['fpl_rads'] is not None:
planetRadS = compositeData[plLineComp]['fpl_rads']
else:
planetRadS = -1
# null eccentricity
if planetEcc is None:
if compositeData[plLineComp]['fpl_eccen'] is not None:
planetEcc = compositeData[plLineComp]['fpl_eccen']
else:
planetEcc = 0.0 # assume its 0 if they don't have it
# null inclination
if planetInc is None:
planetInc = 90.0 # assume default if none
# null stellar mass case
if starMass is None:
if compositeData[plLineComp]['fst_mass'] is not None:
starMass = compositeData[plLineComp]['fst_mass']
else:
starMass = -1
# mid transit time and uncertanties cases
planetMidT = -1
planetMidTUnc = -1
for extIndex in plLinesExt:
if extendedData[extIndex]['mpl_tranmid'] is not None and extendedData[extIndex][
'mpl_tranmiderr1'] is not None and extendedData[extIndex]['mpl_tranmiderr2'] is not None:
if extendedData[extIndex]['mpl_tranmid'] > planetMidT:
planetMidT = extendedData[extIndex]['mpl_tranmid']
planetMidTUnc1 = extendedData[extIndex]['mpl_tranmiderr1']
planetMidTUnc2 = extendedData[extIndex]['mpl_tranmiderr2']
midProd = math.fabs(planetMidTUnc1 * planetMidTUnc2)
planetMidTUnc = math.sqrt(midProd)
if planetPeriod is None or planetPerUnc1 is None or planetPerUnc2 is None:
if compositeData[plLineComp]['fpl_orbper'] is not None and compositeData[plLineComp][
'fpl_orbpererr1'] is not None and compositeData[plLineComp]['fpl_orbpererr2'] is not None:
planetPeriod = compositeData[plLineComp]['fpl_orbper']
planetPerUnc1 = compositeData[plLineComp]['fpl_orbpererr1']
planetPerUnc2 = compositeData[plLineComp]['fpl_orbpererr2']
perProd = math.fabs(planetPerUnc1 * planetPerUnc2)
planetPerUnc = math.sqrt(perProd)
else:
planetPeriod = -1
planetPerUnc = -1
else:
perProd = math.fabs(planetPerUnc1 * planetPerUnc2)
planetPerUnc = math.sqrt(perProd)
# null stellar radius case
if starRadius is None:
if compositeData[plLineComp]['fst_rad'] is not None:
starRadius = compositeData[plLineComp]['fst_rad']
else:
starRadius = -1
# compute rprs
if starRadius is not None and planetRadS is not None:
radPradS = planetRadS / starRadius
# semi major axis calc from interpolated mass
if starSemi is None:
if compositeData[plLineComp]['fpl_smax'] is not None:
starSemi = (compositeData[plLineComp]['fpl_smax'] * (1.5 * 10.0 ** 11.0)) / (starRadius * rSun)
elif planetPeriod != -1 and starMass != -1:
planetPeriodSecs = planetPeriod * 86400.0 # days to seconds
starSemiMeters = (((planetPeriodSecs * planetPeriodSecs) * newtonG * (starMass * mSun)) / (
4 * math.pi * math.pi)) ** (1. / 3)
starSemi = starSemiMeters / (starRadius * rSun)
else:
starSemi = -1
if planetTranFlag == 0:
if compositeData[plLineComp]['fpl_tranflag'] != 0:
planetTranFlag = compositeData[plLineComp]['tranflag']
print('Mislabeled Transit')
else:
planetTranFlag == -1
# return planetName, radPradS, starSemi, planetMidT, planetPeriod,planetMidTUnc, planetPerUnc, planetTranFlag, planetInc, planetEcc,
planetDictionary = {'pName': planetName, 'sName': starName, 'rprs': radPradS, 'aRs': starSemi, 'midT': planetMidT,
'midTUnc': planetMidTUnc, 'pPer': planetPeriod, 'pPerUnc': planetPerUnc, 'flag': planetTranFlag,
'inc': planetInc, 'ecc': planetEcc, 'teff': starTemp, 'met': starMet, 'logg': starLogg}
return planetDictionary
# Method that computes and returns the total flux of the given star
# calls the phot function for flux calculation which includes the background subtraction
def getFlux(photoData, xPix, yPix, apertureRad, annulusRad):
bgSub, totalFlux = phot(xPix, yPix, photoData, r=apertureRad, dr=annulusRad, debug=False, bgsub=True)
return bgSub, totalFlux # return the total flux for the given star in the one image
# Method that gets and returns the julian time of the observation
def getJulianTime(hdul):
exptime_offset = 0
# Grab the BJD first
if 'BJD_TDB' in hdul[0].header:
julianTime = float(hdul[0].header['BJD_TDB'])
# If the time is from the beginning of the observation, then need to calculate mid-exposure time
if "start" in hdul[0].header.comments['BJD_TDB']:
exptime_offset = hdul[0].header['EXPTIME']/2./60./60./24. # assume exptime is in seconds for now
elif 'BJD' in hdul[0].header:
julianTime = float(hdul[0].header['BJD'])
# If the time is from the beginning of the observation, then need to calculate mid-exposure time
if "start" in hdul[0].header.comments['BJD']:
exptime_offset = hdul[0].header['EXPTIME']/2./60./60./24. # assume exptime is in seconds for now
# then the DATE-OBS
elif "UT-OBS" in hdul[0].header:
gDateTime = hdul[0].header['UT-OBS'] # gets the gregorian date and time from the fits file header
dt = dup.parse(gDateTime)
time = astropy.time.Time(dt)
julianTime = time.jd
# If the time is from the beginning of the observation, then need to calculate mid-exposure time
if "start" in hdul[0].header.comments['UT-OBS']:
exptime_offset = hdul[0].header['EXPTIME']/2./60./60./24. # assume exptime is in seconds for now
# Then Julian Date
elif 'JULIAN' in hdul[0].header:
julianTime = float(hdul[0].header['JULIAN'])
# If the time is from the beginning of the observation, then need to calculate mid-exposure time
if "start" in hdul[0].header.comments['JULIAN']:
exptime_offset = hdul[0].header['EXPTIME']/2./60./60./24. # assume exptime is in seconds for now
# Then MJD-OBS last, as in the MicroObservatory headers, it has less precision
elif "MJD-OBS" in hdul[0].header:
julianTime = float(hdul[0].header["MJD-OBS"])+2400000.5
# If the time is from the beginning of the observation, then need to calculate mid-exposure time
if "start" in hdul[0].header.comments['MJD-OBS']:
exptime_offset = hdul[0].header['EXPTIME']/2./60./60./24. # assume exptime is in seconds for now
else:
gDateTime = hdul[0].header['DATE-OBS'] # gets the gregorian date and time from the fits file header
dt = dup.parse(gDateTime)
time = astropy.time.Time(dt)
julianTime = time.jd
# If the time is from the beginning of the observation, then need to calculate mid-exposure time
if "start" in hdul[0].header.comments['DATE-OBS']:
exptime_offset = hdul[0].header['EXPTIME']/2./60./60./24. # assume exptime is in seconds for now
# If the mid-exposure time is given in the fits header, then no offset is needed to calculate the mid-exposure time
return (julianTime+exptime_offset)
# Method that gets and returns the current phase of the target
def getPhase(curTime, pPeriod, tMid):
phase = ((curTime - tMid) / pPeriod) % 1
if phase >= .5:
return (-1 * (1 - phase))
else:
return (phase)
# Method that gets and returns the airmass from the fits file (Really the Altitude)
def getAirMass(hdul):
# try this and if not fit for normalized time?
if 'TELALT' in hdul[0].header:
alt = float(hdul[0].header[
'TELALT']) # gets the airmass from the fits file header in (sec(z)) (Secant of the zenith angle)
cosam = math.cos((math.pi / 180) * (90.0 - alt))
am = 1 / (cosam)
elif 'AIRMASS' in hdul[0].header:
am = float(hdul[0].header['AIRMASS'])
else:
am = 1
return (am)
# Method that defines a 2D Gaussian
def twoD_Gaussian(xdata_tuple, amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
(x, y) = xdata_tuple
xo = float(xo)
yo = float(yo)
a = (np.cos(theta) ** 2) / (2 * sigma_x ** 2) + (np.sin(theta) ** 2) / (2 * sigma_y ** 2)
b = -(np.sin(2 * theta)) / (4 * sigma_x ** 2) + (np.sin(2 * theta)) / (4 * sigma_y ** 2)
c = (np.sin(theta) ** 2) / (2 * sigma_x ** 2) + (np.cos(theta) ** 2) / (2 * sigma_y ** 2)
g = offset + amplitude * np.exp(- (a * ((x - xo) ** 2) + 2 * b * (x - xo) * (y - yo) + c * ((y - yo) ** 2)))
return g
# defines the star point spread function as a 2D Gaussian
def star_psf(x, y, x0, y0, a, sigx, sigy, b):
gaus = a * np.exp(-(x - x0) ** 2 / (2 * sigx ** 2)) * np.exp(-(y - y0) ** 2 / (2 * sigy ** 2)) + b
return gaus
# Class of star_psf objects with setters and getters
class psf(object):
def __init__(self, x0, y0, a, sigx, sigy, b, rot=0):
self.pars = [x0, y0, a, sigx, sigy, b]
self.a = a
self.x0 = x0
self.y0 = y0
self.sigx = sigx
self.sigy = sigy
self.b = b
self.rot = rot
# define the star's rotational orientation and orient the Gaussian to it
def eval(self, x, y):
if self.rot == 0:
return star_psf(x, y, *self.pars)
else:
return rotate(star_psf(x, y, *self.pars), self.rot, reshape=False)
@property
def gaussian_area(self):
# PSF area without background
return 2 * np.pi * self.a * self.sigx * self.sigy
@property
def cylinder_area(self):
# models background
return np.pi * (3 * self.sigx * 3 * self.sigy) * self.b
@property
def area(self):
return self.gaussian_area + self.cylinder_area
class ccd(object):
def __init__(self, size):
if isinstance(size, np.ndarray): # load data from array
self.data = np.copy(size)
else:
self.data = np.zeros(size)
def draw(self, star):
b = max(star.sigx, star.sigy) * 5
x = np.arange(int(star.x0 - b), int(star.x0 + b + 1))
y = np.arange(int(star.y0 - b), int(star.y0 + b + 1))
xv, yv = np.meshgrid(x, y) # make the mesh grid using gaussian dimensions
self.data[yv, xv] += star.eval(xv, yv)
# Function defines the mesh grid that is used to super sample the image
def mesh_box(pos, box, mesh=True, npts=-1):
pos = [int(np.round(pos[0])), int(np.round(pos[1]))]
if npts == -1:
x = np.arange(pos[0] - box, pos[0] + box + 1)
y = np.arange(pos[1] - box, pos[1] + box + 1)
else:
x = np.linspace(pos[0] - box, pos[0] + box + 1, npts)
y = np.linspace(pos[1] - box, pos[1] + box + 1, npts)
if mesh:
xv, yv = np.meshgrid(x, y)
return xv, yv
else:
return x, y
# Method uses the Full Width Half Max to estimate the standard deviation of the star's psf
def estimate_sigma(x, maxidx=-1):
if maxidx == -1:
maxidx = np.argmax(x)
lower = np.abs(x - 0.5 * np.max(x))[:maxidx].argmin()
upper = np.abs(x - 0.5 * np.max(x))[maxidx:].argmin() + maxidx
FWHM = upper - lower
return FWHM / (2 * np.sqrt(2 * np.log(2)))
# Method fits a 2D gaussian function that matches the star_psf to the star image and returns its pixel coordinates
def fit_centroid(data, pos, init=None, psf_output=False, lossfn='linear', box=25):
if not init: # if init is none, then set the values
init = [-1, 5, 5, 0]
# estimate the amplitude and centroid
if init[0] == -1:
# subarray of data around star
xv, yv = mesh_box(pos, box)
# amplitude guess
init[0] = np.max(data[yv, xv])
# weighted sum to estimate center
wx = np.sum(np.unique(xv) * data[yv, xv].sum(0)) / np.sum(data[yv, xv].sum(0))
wy = np.sum(np.unique(yv) * data[yv, xv].sum(1)) / np.sum(data[yv, xv].sum(1))
pos = [wx, wy]
# estimate std by calculation of FWHM
x, y = data[yv, xv].sum(0), data[yv, xv].sum(1)
init[1] = estimate_sigma(x)
init[2] = estimate_sigma(y)
# Background Estimate
# compute the average from 1/4 of the lowest values in the background
init[3] = np.mean(np.sort(data[yv, xv].flatten())[:int(data[yv, xv].flatten().shape[0] * 0.25)])
# print('init priors for centroid:',init)
# print('init2:',init)
# recenter data on weighted average of light (peak amplitude)
xv, yv = mesh_box(pos, box)
# pars = x,y, a,sigx,sigy, rotate
def fcn2min(pars):
model = star_psf(xv, yv, *pars)
return (data[yv, xv] - model).flatten() # method for LS
# return np.sum( (data[yv,xv]-model)**2 ) # method for minimize
lo = [pos[0] - box, pos[1] - box, 0, 1, 1, 0]
up = [pos[0] + box, pos[1] + box, 100000, 40, 40, np.max(data[yv, xv])]
res = least_squares(fcn2min, x0=[*pos, *init], bounds=[lo, up], loss=lossfn, jac='3-point')
del init
if psf_output:
return psf(*res.x, 0)
else:
return res.x
# Method defines the mask that when applied to the image, only leaves the background annulus remaining
def circle_mask(x0, y0, r=25, samp=10):
xv, yv = mesh_box([x0, y0], r + 1, npts=samp)
rv = ((xv - x0) ** 2 + (yv - y0) ** 2) ** 0.5
mask = rv < r
return xv, yv, mask
# Method defines the annulus used to do a background subtraction
def sky_annulus(x0, y0, r=25, dr=5, samp=10):
xv, yv = mesh_box([x0, y0], r + dr + 1, npts=samp)
rv = ((xv - x0) ** 2 + (yv - y0) ** 2) ** 0.5
mask = (rv > r) & (rv < (r + dr)) # sky annulus mask
return xv, yv, mask
# Method calculates the flux of the star (uses the skybg_phot method to do backgorund sub)
def phot(x0, y0, data, r=25, dr=5, samp=5, debug=False, bgsub=True):
if bgsub:
# get the bg flux per pixel
bgflux = skybg_phot(x0, y0, data, r, dr, samp)
else:
bgflux = 0
positions = [(x0, y0)]
apertures = CircularAperture(positions, r=r)
phot_table = aperture_photometry(data - bgflux, apertures)
# print(phot_table[0][3])
bgSubbed = phot_table[0][3]
rawPhot_Table = aperture_photometry(data, apertures)
raw = rawPhot_Table[0][3]
return bgSubbed, raw
# Method calculates the average flux of the background
def skybg_phot(x0, y0, data, r=25, dr=5, samp=3, debug=False):
# determine img indexes for aperture region
xv, yv = mesh_box([x0, y0], int(np.round(r + dr)))
# derive indexs on a higher resolution grid and create aperture mask
px, py, mask = sky_annulus(x0, y0, r=r, samp=xv.shape[0] * samp)
# interpolate original data onto higher resolution grid
subdata = data[yv, xv]
model = RectBivariateSpline(np.unique(xv), np.unique(yv), subdata)
# evaluate data on highres grid
pz = model.ev(px, py)
# zero out pixels larger than radius
pz[~mask] = 0
pz[pz < 0] = 0
quarterMask = pz < np.percentile(pz[mask], 50)
pz[~quarterMask] = 0
# scale area back to original grid, total flux in sky annulus
parea = pz.sum() * np.diff(px).mean() * np.diff(py[:, 0]).mean()
if debug:
print('mask area=', mask.sum() * np.diff(px).mean() * np.diff(py[:, 0]).mean())
print('true area=', 2 * np.pi * r * dr)
print('subdata flux=', subdata.sum())
print('bg phot flux=', parea)
import pdb
pdb.set_trace()
# return bg value per pixel
bgmask = mask & quarterMask
avgBackground = pz.sum() / bgmask.sum()
return (avgBackground)
# Mid-Transit Time Prior Helper Functions
def numberOfTransitsAway(timeData, period, originalT):
return int((np.nanmin(timeData) - originalT) / period) + 1
def nearestTransitTime(timeData, period, originalT):
nearT = ((numberOfTransitsAway(timeData, period, originalT) * period) + originalT)
return nearT
# Mid-Transit Time Error Helper Functions
def propMidTVariance(uncertainP, uncertainT, timeData, period, originalT):
n = numberOfTransitsAway(timeData, period, originalT)
varTMid = n * n * uncertainP + uncertainT
return varTMid
def uncTMid(uncertainP, uncertainT, timeData, period, originalT):
n = numberOfTransitsAway(timeData, period, originalT)
midErr = math.sqrt((n * n * uncertainP * uncertainP) + 2 * n * uncertainP * uncertainT + (uncertainT * uncertainT))
return midErr
def transitDuration(rStar, rPlan, period, semi):
rSun = 6.957 * 10 ** 8 # m
tDur = (period / math.pi) * asin((math.sqrt((rStar * rSun + rPlan * rSun) ** 2)) / (semi * rStar * rSun))
return tDur
# calculates chi squared which is used to determine the quality of the LC fit
def chisquared(observed_values, expected_values, uncertainty):
for chiCount in range(0, len(observed_values)):
zeta = ((observed_values[chiCount] - expected_values[chiCount]) / uncertainty[chiCount])
chiToReturn = np.sum(zeta ** 2)
return chiToReturn
# make and plot the chi squared traces
def plotChi2Trace(myTrace, myFluxes, myTimes, theAirmasses, uncertainty):
print("Performing Chi^2 Burn")
midTArr = myTrace.get_values('Tmid', combine=False)
radiusArr = myTrace.get_values('RpRs', combine=False)
am1Arr = myTrace.get_values('Am1', combine=False)
am2Arr = myTrace.get_values('Am2', combine=False)
allchiSquared = []
for chain in myTrace.chains:
chiSquaredList1 = []
for counter in np.arange(len(midTArr[chain])):#[::25]:
# first chain
midT1 = midTArr[chain][counter]
rad1 = radiusArr[chain][counter]
am11 = am1Arr[chain][counter]
am21 = am2Arr[chain][counter]
fittedModel1 = lcmodel(midT1, rad1, am11, am21, myTimes, theAirmasses, plots=False)
chis1 = np.sum(((myFluxes - fittedModel1) / uncertainty) ** 2.) / (len(myFluxes) - 4)
chiSquaredList1.append(chis1)
allchiSquared.append(chiSquaredList1)
plt.figure()
plt.xlabel('Chain Length')
plt.ylabel('Chi^2')
for chain in np.arange(myTrace.nchains):
plt.plot(np.arange(len(allchiSquared[chain])), allchiSquared[chain], '-bo')
plt.rc('grid', linestyle="-", color='black')
plt.grid(True)
plt.title(targetName + ' Chi^2 vs. Chain Length ' + date)
# plt.show()
plt.savefig(saveDirectory + 'temp/ChiSquaredTrace' + date + targetName + '.png')
plt.close()
chiMedian = np.nanmedian(allchiSquared)
burns = []
for chain in np.arange(myTrace.nchains):
idxburn, = np.where(allchiSquared[chain] <= chiMedian)
if len(idxburn) == 0:
burnno = 0
else:
burnno = idxburn[0]
burns.append(burnno)
completeBurn = np.max(burns)
print('Chi^2 Burn In Length: ' + str(completeBurn))
return completeBurn
# make plots of the centroid positions as a function of time
def plotCentroids(xTarg, yTarg, xRef, yRef, times, date):
times = np.array(times)
# X TARGET
plt.figure()
plt.plot(times-np.nanmin(times), xTarg, '-bo')
plt.xlabel('Time (JD-'+str(np.nanmin(times))+')')
plt.ylabel('X Pixel Position')
plt.title(targetName + ' X Centroid Position ' + date)
plt.savefig(saveDirectory +'temp/XCentroidPosition'+ targetName + date + '.png')
plt.close()
# Y TARGET
plt.figure()
plt.plot(times-np.nanmin(times), yTarg, '-bo')
plt.xlabel('Time (JD-'+str(np.nanmin(times))+')')
plt.ylabel('Y Pixel Position')
plt.title(targetName + ' Y Centroid Position ' + date)
plt.savefig(saveDirectory+ 'temp/YCentroidPos' + targetName + date + '.png')
plt.close()
# X COMP
plt.figure()
plt.plot(times-np.nanmin(times), xRef, '-ro')
plt.xlabel('Time (JD-'+str(np.nanmin(times))+')')
plt.ylabel('X Pixel Position')
plt.title('Comp Star X Centroid Position ' + date)
plt.savefig(saveDirectory + 'temp/CompStarXCentroidPos' + date + '.png')
plt.close()
# Y COMP
plt.figure()
plt.plot(times-np.nanmin(times), yRef, '-ro')
plt.xlabel('Time (JD-'+str(np.nanmin(times))+')')
plt.ylabel('Y Pixel Position')
plt.title('Comp Star Y Centroid Position ' + date)
plt.savefig(saveDirectory + 'temp/CompStarYCentroidPos' + date + '.png')
plt.close()
# X DISTANCE BETWEEN TARGET AND COMP
plt.figure()
plt.xlabel('Time (JD-'+str(np.nanmin(times))+')')
plt.ylabel('X Pixel Distance')
for e in range(0, len(xTarg)):
plt.plot(times[e]-np.nanmin(times), abs(int(xTarg[e]) - int(xRef[e])), 'bo')
plt.title('Distance between Target and Comparison X position')
plt.savefig(saveDirectory + 'temp/XCentroidDistance' + targetName + date + '.png')
plt.close()
# Y DISTANCE BETWEEN TARGET AND COMP
plt.figure()
plt.xlabel('Time (JD-'+str(np.nanmin(times))+')')
plt.ylabel('Y Pixel Difference')
d = 0
for d in range(0, len(yTarg)):
plt.plot(times[d]-np.nanmin(times), abs(int(yTarg[d]) - int(yRef[d])), 'bo')
plt.title('Difference between Target and Comparison Y position')
plt.savefig(saveDirectory + 'temp/YCentroidDistance' + targetName + date + '.png')
plt.close()
# -----CONTEXT FREE GLOBAL VARIABLES-----------------------------
def contextupdt(times=None, airm=None):
global context
if times is not None:
context['times'] = times
if airm is not None:
context['airmass'] = airm
# -- LIGHT CURVE MODEL -- ----------------------------------------------------------------
def lcmodel(midTran, radi, am1, am2, theTimes, theAirmasses, plots=False):
sep, ophase = time2z(theTimes, inc, midTran, semi, planetPeriod, eccent)
model, junk = occultquad(abs(sep), linearLimb, quadLimb, radi)
airmassModel = (am1 * (np.exp(am2 * theAirmasses)))
fittedModel = model * airmassModel
if plots:
plt.figure()
plt.plot(ophase, fittedModel, '-o')
plt.xlabel('Orbital Phase')
plt.show()
pass
return fittedModel
def realTimeReduce(i):
targetFluxVals = []
referenceFluxVals = []
normalizedFluxVals = []
fileNameList = []
timeSortedNames = []
timeList = []
timesListed = []
# -------TIME SORT THE FILES--------------------------------------------------------------------------------
while len(g.glob(directoryP)) == 0:
print("Error: .FITS files not found in " + directoryP)
directToWatch = str(input("Enter the Directory Path where FITS Image Files are located: "))
# Add / to end of directory if user does not input it
if directToWatch[-1] != "/":
directToWatch += "/"
directoryP = directToWatch
fileNumber = 1
for fileName in g.glob(directoryP): # Loop through all the fits files and time sorts
fitsHead = fits.open(fileName) # opens the file
# TIME
timeVal = getJulianTime(fitsHead) # gets the julian time registered in the fits header
timeList.append(timeVal) # adds to time value list
fileNameList.append(fileName)
# Time sorts the file names based on the fits file header
timeSortedNames = [x for _, x in sorted(zip(timeList, fileNameList))]
# sorts the times for later plotting use
sortedTimeList = sorted(timeList)
hdul = fits.open(timeSortedNames[0]) # opens the fits file
# Extracts data from the image file and puts it in a 2D numpy array: firstImageData
firstImageData = fits.getdata(timeSortedNames[0], ext=0)
# fit first image
targx, targy, targamplitude, targsigX, targsigY, targoff = fit_centroid(firstImageData, [UIprevTPX, UIprevTPY],
box=15)
refx, refy, refamplitude, refsigX, refsigY, refoff = fit_centroid(firstImageData, [UIprevRPX, UIprevRPY], box=15)
# just use one aperture and annulus
apertureR = 3 * max(targsigX, targsigY)
annulusR = 4
for imageFile in timeSortedNames:
hDul = fits.open(imageFile) # opens the fits file
# Extracts data from the image file and puts it in a 2D numpy array: imageData
imageData = fits.getdata(imageFile, ext=0)
header = fits.getheader(imageFile)
# Find the target star in the image and get its pixel coordinates if it is the first file
if fileNumber == 1:
# Initializing the star location guess as the user inputted pixel coordinates
prevTPX, prevTPY, prevRPX, prevRPY = UIprevTPX, UIprevTPY, UIprevRPX, UIprevRPY
prevTSigX, prevTSigY, prevRSigX, prevRSigY = targsigX, targsigY, refsigX, refsigY
prevImageData = imageData # no shift should be registered
# ---FLUX CALCULATION WITH BACKGROUND SUBTRACTION---------------------------------
# corrects for any image shifts that result from a tracking slip
shift, error, diffphase = register_translation(prevImageData, imageData)
xShift = shift[1]
yShift = shift[0]
prevTPX = prevTPX - xShift
prevTPY = prevTPY - yShift
prevRPX = prevRPX - xShift
prevRPY = prevRPY - yShift
# --------GAUSSIAN FIT AND CENTROIDING----------------------------------------------
txmin = int(prevTPX) - distFC # left
txmax = int(prevTPX) + distFC # right
tymin = int(prevTPY) - distFC # top
tymax = int(prevTPY) + distFC # bottom
targSearchA = imageData[tymin:tymax, txmin:txmax]
# Set reference search area
rxmin = int(prevRPX) - distFC # left
rxmax = int(prevRPX) + distFC # right
rymin = int(prevRPY) - distFC # top
rymax = int(prevRPY) + distFC # bottom
refSearchA = imageData[rymin:rymax, rxmin:rxmax]
# Guess at Gaussian Parameters and feed them in to help gaussian fitter
tGuessAmp = targSearchA.max() - targSearchA.min()
# Fits Centroid for Target
myPriors = [tGuessAmp, prevTSigX, prevTSigY, targSearchA.min()]
tx, ty, tamplitude, tsigX, tsigY, toff = fit_centroid(imageData, [prevTPX, prevTPY], init=myPriors, box=15)
currTPX = tx
currTPY = ty
# Fits Centroid for Reference
rGuessAmp = refSearchA.max() - refSearchA.min()
myRefPriors = [rGuessAmp, prevRSigX, prevRSigY, refSearchA.min()]
rx, ry, ramplitude, rsigX, rsigY, roff = fit_centroid(imageData, [prevRPX, prevRPY], init=myRefPriors, box=15)
currRPX = rx
currRPY = ry
# gets the flux value of the target star and
tFluxVal, tTotCts = getFlux(imageData, currTPX, currTPY, apertureR, annulusR)
targetFluxVals.append(tFluxVal) # adds tFluxVal to the total list of flux values of target star
# gets the flux value of the reference star and subracts the background light
rFluxVal, rTotCts = getFlux(imageData, currRPX, currRPY, apertureR, annulusR)
referenceFluxVals.append(rFluxVal) # adds rFluxVal to the total list of flux values of reference star
normalizedFluxVals.append((tFluxVal / rFluxVal))
# TIME
currTime = getJulianTime(hDul)
timesListed.append(currTime)
# UPDATE PIXEL COORDINATES and SIGMAS
# target
prevTPX = currTPX
prevTPY = currTPY
prevTSigX = tsigX
prevTSigY = tsigY
# reference
prevRPX = currRPX
prevRPY = currRPY
prevRSigX = rsigX
prevTSigY = rsigY
# UPDATE FILE COUNT
prevImageData = imageData
fileNumber = fileNumber + 1
hDul.close() # close the stream
# EXIT THE FILE LOOP
ax1.clear()
ax1.set_title(targetName)
ax1.set_ylabel('Normalized Flux')
ax1.set_xlabel('Time (jd)')
ax1.plot(timesListed, normalizedFluxVals, 'bo')
if __name__ == "__main__":
print('')
print('*************************************************************')
print('Welcome to the EXOplanet Transit Interpretation Code (EXOTIC)')
print("Version ",versionid)
print('*************************************************************')
print('')
# ---INITIALIZATION-------------------------------------------------------
targetFluxVals, referenceFluxVals, normalizedFluxVals, targUncertanties, refUncertanties, timeList, phasesList, airMassList = (
[] for l in range(8))
fileNameList, timeSortedNames, xTargCent, yTargCent, xRefCent, yRefCent, finXTargCent, finYTargCent, finXRefCent, finYRefCent = (
[] for m in range(10))
timesListed = [] # sorted times of observation
fileNumber = 1 # initializes file number to one
minSTD = 100000 # sets the initial minimum standard deviation absurdly high so it can be replaced immediately
minChi2 = 100000
distFC = 10 # gaussian search area
context = {}
# ---USER INPUTS--------------------------------------------------------------------------
realTimeAns = int(input('Enter "1" for Real Time Reduction or "2" for for Complete Reduction: '))
while realTimeAns != 1 and realTimeAns != 2:
print('Sorry, did not recognize that input')
realTimeAns = int(input('Enter "1" for Real Time Reduction or "2" for for Complete Reduction: '))
#############################
# Real Time Reduction Routine
#############################
if realTimeAns == 1:
print('')
print('**************************************************************')
print('Real Time Reduction ("Control + C" or close the plot to quit)')
print('**************************************************************')
print('')
directToWatch = str(input("Enter the Directory Path where FITS Image Files are located: "))
directoryP = directToWatch