-
Notifications
You must be signed in to change notification settings - Fork 5
/
_mp_manipulation.py
1582 lines (1185 loc) · 64.2 KB
/
_mp_manipulation.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
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import os
#import astropy
import warnings
from astropy.io import ascii
from astropy.time import Time
import time
#import datetime
import pandas
import traceback
from astroquery.simbad import Simbad
from astropy.constants import G, c, M_earth, M_jup, M_sun, R_earth, R_jup, R_sun, au
from astropy.timeseries import LombScargle
import socket
#### BELOW ARE MOONPY PACKAGES
from mp_tools import *
from mp_lcfind import *
from mp_detrend import phasma_detrend, untrendy_detrend, cofiam_detrend, george_detrend, medfilt_detrend, polyAM_detrend
from mp_batman import run_batman
from mp_fit import mp_multinest, mp_ultranest, mp_emcee
from mp_plotter import *
from cofiam import max_order
#from pyluna import run_LUNA, prepare_files
from pyluna import prepare_files
from mp_tpf_examiner import *
from scipy.interpolate import interp1d
plt.rcParams["font.family"] = 'serif'
moonpydir = os.path.realpath(__file__)
moonpydir = moonpydir[:moonpydir.find('/_mp_manipulation.py')]
def fit(self, custom_param_dict=None, fitter='ultranest', modelcode='Pandora', segment='n', segment_length=500, skip_ntqs='y', model='M', nlive=400, nwalkers=100, nsteps=10000, resume=True, folded=False, uninformative_priors=[]):
print('calling _mp_manipulation.py/fit().')
### optional values for code are "multinest" and "emcee"
### FOUR MODELS MAY BE RUN: a planet-only model (P) with no TTVs, a TTV model (T), freely fitting the transit times,
### a (Z) model, which gives the moon a mass but no radius, and an (M) model, which is a fully physical moon fit.
if modelcode.lower() == "luna":
folded = False ### you should not be fitting a moon model to a folded light curve!
##### LIGHT CURVES NEED TO HAVE THE DATA POINTS WELL OUTSIDE THE TRANSITS REMOVED,
###### OTHERWISE IT TAKES WAAAAAAY TOO LONG TO CHEW ON THIS. (11/25/2020)
if self.telescope.lower() != 'user':
self.get_properties(locate_neighbor='n')
self.initialize_priors(modelcode=modelcode, model=model, uninformative_priors=uninformative_priors)
param_uber_dict = self.param_uber_dict
if self.telescope.lower() == 'user':
detrend_option = input('WARNING: lc has not been detrended. Perform now? y/n: ')
if detrend_option == 'y':
self.detrend()
else:
self.fluxes_detrend = self.fluxes
self.errors_detrend = self.errors
else:
if (self.fluxes == self.fluxes_detrend) or (self.errors == self.errors_detrend):
warnings.warn("light curve has not been detrended. It will be performed now.")
### alternatively, just detrend!
self.detrend()
if folded == True:
self.fold() ### generate the folded times, in case they haven't been already.
skip_ntqs = 'n' ### if you have a phase-folded light curve you don't need to skip non-transiting quarters!
lc_times, lc_fluxes, lc_errors = self.fold_times, self.fold_fluxes, self.fold_errors
### update the tau0 prior!
self.param_uber_dict['tau0'] = ['uniform', (self.fold_tau-0.1, self.fold_tau+0.1)] ### establishing the prior.
else:
### stacks of arrays!
lc_times, lc_fluxes, lc_errors = self.times, self.fluxes_detrend, self.errors_detrend
if skip_ntqs == 'y':
### only feed in the quarters that include a transit!
if len(self.quarters) == 1:
fit_times, fit_fluxes, fit_errors = self.times, self.fluxes_detrend, self.errors_detrend
else:
fit_times, fit_fluxes, fit_errors = [], [], []
for qidx in np.arange(0,self.times.shape[0],1):
qtimes, qfluxes, qerrors = lc_times[qidx], lc_fluxes[qidx], lc_errors[qidx]
for stau in self.taus:
if (stau >= np.nanmin(qtimes)) and (stau <+ np.nanmax(qtimes)):
### transit in this quarter:
if segment == 'y':
#### we're going to segment the light curve, by including only n=segment_length data points on either side of tau
##### THIS WILL GREATLY REDUCE THE COMPUTATION TIME
stau_idx = np.nanargmin(np.abs(stau - qtimes)) #### closest index within qtimes for the transit time.
segment_idxs = np.arange(int(stau_idx - np.ceil(segment_length/2)), int(stau_idx + np.ceil(segment_length/2)), 1)
qtimes, qfluxes, qerrors = qtimes[segment_idxs], qfluxes[segment_idxs], qerrors[segment_idxs]
fit_times.append(qtimes)
fit_fluxes.append(qfluxes)
fit_errors.append(qerrors)
break
fit_times, fit_fluxes, fit_errors = np.hstack(np.array(fit_times)), np.hstack(np.array(fit_fluxes)), np.hstack(np.array(fit_errors))
else:
### using all quarters!
if folded == False:
fit_times, fit_fluxes, fit_errors = np.hstack(lc_times), np.hstack(lc_fluxes), np.hstack(lc_errors)
elif folded == True:
fit_times, fit_fluxes, fit_errors = lc_times, lc_fluxes, lc_errors ### already flattened!
if modelcode.lower() == 'luna':
if model.lower() == 'm':
pass
elif (model.lower() == 'p') or (model.lower() =='t'):
### THESE ARE INPUTS TO THE MODEL BUT SHOULD NOT BE FREE PARAMETERS!
self.param_uber_dict['RsatRp'] = ['fixed', 1e-8]
self.param_uber_dict['MsatMp'] = ['fixed', 1e-8]
self.param_uber_dict['sat_sma'] = ['fixed', 1000]
self.param_uber_dict['sat_inc'] = ['fixed', 0]
self.param_uber_dict['sat_phase'] = ['fixed', 0]
self.param_uber_dict['sat_omega'] = ['fixed', 0]
if model.lower() == 't':
transitnum = 0
for i in np.arange(0, len(self.taus),1):
#### verify that the tau is within your quarters!
for qidx,q in enumerate(self.quarters):
if self.taus[i] >= np.nanmin(self.times[qidx]) and self.taus[i] <= np.nanmax(self.times[qidx]):
### means the transit is in your data and can be fit.
taukeyname = 'tau'+str(transitnum)
transitnum += 1
param_uber_dict[taukeyname] = ['uniform', (self.taus[i] - 0.1, self.taus[i] + 0.1)]
if model.lower() == 'z':
param_uber_dict['RsatRp'] = ['fixed', 1e-8]
### prepare seriesP.jam and plotit.f90... only needs to be done once!
if model.lower() == "m" or model.lower() == "p" or model.lower() == "z":
ntaus = 1
elif model.lower() == 't':
ntaus = 0
for paramkey in param_uber_dict.keys():
if paramkey.startswith('tau'):
ntaus += 1
if model.lower() == "m":
nparamorig = 14
nparam = 14
nvars = 14 ### fitting all the parameters!
elif model.lower() == "p":
nparamorig = 14 ### all these inputs must still be present, even if some of them are fixed at zero!
nparam = 14
nvars = 8 ### RpRstar, rhostar, bplan, Pplan, tau0, q1, q2, rhoplan
elif model.lower() == 't':
nparamorig = 14
nparam = nparamorig + (ntaus-1) ### tau0 is a STANDARD nparamorig input... every additional tau needs to be counted.
nvars = 8 + (ntaus-1) ### standard P model variables plus all additional taus.
elif model.lower() == 'z':
nparam = 14
nparamorig = 14
nvars = 13 ### not fitting Rsat/Rp
try:
prepare_files(np.hstack(fit_times), ntaus, nparam, nparamorig)
except:
prepare_files(fit_times, ntaus, nparam, nparamorig)
if custom_param_dict != None:
### update the parameter dictionary values!!!
for cpdkey in custom_param_dict.keys():
param_uber_dict[cpdkey] = custom_param_dict[cpdkey]
### HAS TO BE DONE HERE, SINCE YOU MAY HAVE UPDATED THE DICTIONARY!
param_labels = []
param_prior_forms = []
param_limit_tuple = []
for pkey in self.param_uber_dict.keys():
param_labels.append(pkey) ### name of the prior
param_prior_forms.append(param_uber_dict[pkey][0]) ### the shape of the prior
param_limit_tuple.append(param_uber_dict[pkey][1]) ### limits of the prior
self.param_labels = param_labels
self.param_prior_forms = param_prior_forms
self.param_limit_tuple = param_limit_tuple
for parlab, parprior, parlim in zip(param_labels, param_prior_forms, param_limit_tuple):
print(parlab, parprior, parlim)
#### CHOOSE YOUR FIGHTER -- I MEAN FITTER
if fitter.lower() == 'multinest':
mp_multinest(fit_times, fit_fluxes, fit_errors, param_dict=self.param_uber_dict, nlive=nlive, targetID=self.target, modelcode=modelcode, model=model, nparams=nvars)
elif fitter.lower() == 'ultranest':
if resume == True:
ultranest_resume = 'resume'
else:
ultranest_resume = 'overwrite'
mp_ultranest(times=fit_times, fluxes=fit_fluxes, errors=fit_errors, param_dict=self.param_uber_dict, nlive=nlive, targetID=self.target, model=model, modelcode=modelcode, resume=ultranest_resume, show_plot='y')
elif fitter.lower() == 'emcee':
mp_emcee(fit_times, fit_fluxes, fit_errors, param_dict=self.param_uber_dict, nwalkers=nwalkers, nsteps=nsteps, targetID=self.target, modelcode=modelcode, model=model, resume=resume, nparams=nvars) ### outputs to a file
### ONE FINAL STEP -- RESTORE DEFAULT VALUES (REMOVE tau0 = folded_tau) by initializing priors again.
self.initialize_priors(modelcode=modelcode, model=model, uninformative_priors=uninformative_priors)
def prep_for_CNN(self, save_lc='y', window=6, cnn_len=493, exclude_neighbors='y', flag_neighbors='y', show_plot='n', extra_path_info=None, center_transit='y', cnnlc_path=moonpydir+'/cnn_lcs'):
print('calling _mp_manipulation.py/prep_for_CNN().')
### this function will produce an arrayy that's ready to be fed to a CNN for moon finding.
if os.path.exists(cnnlc_path) == False:
os.system('mkdir '+cnnlc_path)
localpath_list = []
for taunum,tau in enumerate(self.taus):
cnn_min, cnn_max = tau-window, tau+window
print('cnn_min, cnn_max = ', cnn_min, cnn_max)
cnn_idxs = np.where((np.hstack(self.times) >= cnn_min) & (np.hstack(self.times) <= cnn_max))[0]
print('cnn_idxs (first): ', cnn_idxs)
print('len(cnn_idxs) = ', len(cnn_idxs))
if len(cnn_idxs) < cnn_len:
continue
### grab the times, fluxes, and errors
cnn_times, cnn_fluxes, cnn_errors, cnn_fluxes_detrend, cnn_errors_detrend = np.hstack(self.times)[cnn_idxs], np.hstack(self.fluxes)[cnn_idxs], np.hstack(self.errors)[cnn_idxs], np.hstack(self.fluxes_detrend)[cnn_idxs], np.hstack(self.errors_detrend)[cnn_idxs]
if center_transit == 'y':
##### take the weighted average of the detrended_fluxes to find tmid
dFs = 1 - cnn_fluxes_detrend
#print('dFs: ', dFs)
print('np.nansum(dFs) = ', np.nansum(dFs))
try:
tmid = np.average(a=cnn_times, weights=dFs)
tmid_idx = np.nanargmin(np.abs(tmid - np.hstack(self.times)))
print('tmid_idx: ', tmid_idx)
tmid_idx = int(tmid_idx)
print('|tmid - tau| = '+str(tmid - tau))
#cnn_min, cnn_max = tmid-window, tmid+window
#cnn_idxs = np.where((np.hstack(self.times) >= cnn_min) & (np.hstack(self.times) <= cnn_max))[0]
cnn_idxs = np.arange(tmid_idx - int(cnn_len/2), tmid_idx + 1 + int(cnn_len/2), 1)
print('cnn_idxs (second): ', cnn_idxs)
print('len(cnn_idxs) = ', len(cnn_idxs))
### grab the times, fluxes, and errors
cnn_times, cnn_fluxes, cnn_errors, cnn_fluxes_detrend, cnn_errors_detrend = np.hstack(self.times)[cnn_idxs], np.hstack(self.fluxes)[cnn_idxs], np.hstack(self.errors)[cnn_idxs], np.hstack(self.fluxes_detrend)[cnn_idxs], np.hstack(self.errors_detrend)[cnn_idxs]
except:
traceback.print_exc()
if len(cnn_times) < cnn_len: ### the size of the array you need to feed into the CNN.
### not enough times
continue
print('len(cnn_times) = ', len(cnn_times))
while len(cnn_times) > cnn_len:
### shave off from the front end.
cnn_times, cnn_fluxes, cnn_errors, cnn_fluxes_detrend, cnn_errors_detrend = cnn_times[1:], cnn_fluxes[1:], cnn_errors[1:], cnn_fluxes_detrend[1:], cnn_errors_detrend[1:]
if len(cnn_times) > cnn_len:
### shave off at the back end.
cnn_times, cnn_fluxes, cnn_errors, cnn_fluxes_detrend, cnn_errors_detrend = cnn_times[:-1], cnn_fluxes[:-1], cnn_errors[:-1], cnn_fluxes_detrend[:-1], cnn_errors_detrend[:-1]
assert len(cnn_times) == cnn_len
if exclude_neighbors == 'y':
neighbor_contam = 'n'
if len(self.neighbors) > 0:
for neighbor in self.neighbor_dict.keys():
neighbor_taus = self.neighbor_dict[neighbor].taus
if np.any((neighbor_taus >= np.nanmin(cnn_times)) & (neighbor_taus <= np.nanmax(cnn_times))):
### there's another transiting planet in your window!
neighbor_contam = 'y'
else:
neighbor_taus = []
neighbor_contam = 'n'
if neighbor_contam == 'y':
continue
if flag_neighbors=='y':
flag_idxs = []
if len(self.neighbors) > 0:
for neighbor in self.neighbor_dict.keys():
neighbor_taus = self.neighbor_dict[neighbor].taus
for nt in neighbor_taus:
if (nt >= np.nanmin(cnn_times)) and (nt <= np.nanmax(cnn_times)):
ntidxs = np.where((cnn_times >= nt-((self.mask_multiple/2)*self.neighbor_dict[neighbor].duration_days)) & (cnn_times <= nt+((self.mask_multiple/2)*self.neighbor_dict[neighbor].duration_days)))[0]
flag_idxs.append(ntidxs)
#try:
if len(flag_idxs) > 0:
flag_idxs = np.unique(np.hstack(np.array(flag_idxs)))
else:
flag_idxs = np.array([])
flag_array = np.zeros(shape=len(cnn_times))
try:
flag_array[flag_idxs] = 1
except:
pass
### at this point you've excluded neighbors (if selected; by default) and made the light curve the right size. Save it!
if flag_neighbors == 'y':
cnn_stack = np.vstack((cnn_times, cnn_fluxes, cnn_errors, cnn_fluxes_detrend, cnn_errors_detrend, flag_array))
else:
cnn_stack = np.vstack((cnn_times, cnn_fluxes, cnn_errors, cnn_fluxes_detrend, cnn_errors_detrend))
if type(extra_path_info) == type(None):
localpath = cnnlc_path+'/'+self.target+"_transit"+str(taunum)+'_cnnstack.npy'
elif type(extra_path_info) != type(None):
localpath = cnnlc_path+'/'+self.target+'_transit'+str(taunum)+'_'+extra_path_info+'_cnnstack.npy'
localpath_list.append(localpath)
np.save(localpath, cnn_stack)
if show_plot == 'y':
plt.scatter(cnn_stack[0], cnn_stack[3], facecolor='LightCoral', edgecolor='k', s=10)
if flag_neighbors == 'y':
neighbor_transit_idxs = np.where(flag_array == 1)[0]
plt.scatter(cnn_stack[0][neighbor_transit_idxs], cnn_stack[3][neighbor_transit_idxs], c='g', marker='x', s=15)
if (self.telescope.lower() == 'kepler') or (self.telescope.lower() == 'k2'):
plt.xlabel("BKJD")
elif self.telescope.lower() == 'tess':
plt.xlabel("BTJD")
plt.ylabel('Flux')
plt.show()
return localpath_list
def make_UltraNest_outputdir(self, model, modelcode='Pandora'):
### MAKE THE OUTPUT DIRECTORY IF IT DOESN'T ALREADY EXIST
outputdir = moonpydir+'/ultranest_fits'
if os.path.exists(outputdir) == False:
os.system('mkdir '+outputdir) ### create UltraNest_fits directory
outputdir = outputdir+'/'+str(modelcode.lower())
if os.path.exists(outputdir) == False:
os.system('mkdir '+outputdir) ### creates modelcode directory
outputdir = outputdir+'/'+str(self.target.lower())
if os.path.exists(outputdir) == False:
os.system('mkdir '+outputdir) ### creates target directory
outputdir = outputdir+'/'+str(model.lower())
print('model: ', model)
if os.path.exists(outputdir) == False:
os.system('mkdir '+outputdir) ### creates model directory
print('outputdir: ', outputdir)
return outputdir
def prep_for_ultranest_fit(self, dmeth='cofiam'):
#### make priors and light curve file
#### NOTE: THIS IS ONLY FOR USE WITH A STANDALONE CODE (a la standalone_pandora_ultranest.py'.) IT IS NOT NEEDED TO RUN A FIT WITHIN MOONPY.
self.initialize_priors(modelcode='Pandora', model='M')
self.initialize_priors(modelcode='Pandora', model='P')
#### make the light curve file
try:
cctimes, ccfluxes, ccerrors = np.concatenate(self.times), np.concatenate(self.fluxes_detrend), np.concatenate(self.errors_detrend)
except:
#### probably need to detrend first!
self.detrend(dmeth=dmeth)
cctimes, ccfluxes, ccerrors = np.concatenate(self.times), np.concatenate(self.fluxes_detrend), np.concatenate(self.errors_detrend)
outputdir = self.make_UltraNest_outputdir(model='M')[:-2] #### will be in the planet directory, not in the M or P folders.
lcfile = open(outputdir+'/'+self.target+'_lcfile.txt', mode='w')
for cctime, ccflux, ccerror in zip(cctimes, ccfluxes, ccerrors):
newline = str(cctime)+' '+str(ccflux)+' '+str(ccerror)+'\n'
lcfile.write(newline)
lcfile.close()
print('new light curve file written to: '+outputdir+'/'+self.target+'_lcfile.txt .')
def initialize_priors(self, modelcode, model='M', uninformative_priors=[]):
print('calling _mp_manipulation.py/intialize_priors().')
param_uber_dict = {}
### THE FOLLOWING PARAMETERS ARE PLANET-SPECIFIC.
self.get_properties(locate_neighbor='n')
#### used for LUNA, batman, and pandora.
if (modelcode.lower() == 'luna') or (modelcode.lower() == 'batman'):
param_uber_dict['RpRstar'] = ['uniform', (1e-6, 0.9999)]
param_uber_dict['bplan'] = ['uniform', (0,1)]
param_uber_dict['rhostar'] = ['uniform', (1, 1e6)] ## roughly the density of betelgeuse to the density of Mercury.
param_uber_dict['rhoplan'] = ['uniform', (1, 1e6)]
param_uber_dict['Pplan'] = ['uniform', (self.period-1, self.period+1)]
param_uber_dict['tau0'] = ['uniform', (self.tau0-0.1, self.tau0+0.1)]
param_uber_dict['q1'] = ['uniform', (0,1)]
param_uber_dict['q2'] = ['uniform', (0,1)]
if modelcode.lower() == "luna":
### these parameters are only relevant for LUNA!
param_uber_dict['sat_phase'] = ['uniform', (0,2*np.pi)]
param_uber_dict['sat_inc'] = ['uniform', (-1,3)] ### actually cos(i_s), natively.
param_uber_dict['sat_omega'] = ['uniform', (-np.pi,np.pi)]
param_uber_dict['MsatMp'] = ['uniform', (1e-8, 1)]
param_uber_dict['RsatRp'] = ['uniform', (1e-8, 1)]
param_uber_dict['sat_sma'] = ['uniform', (2,7.897*(self.period**(2/3)))]
if modelcode.lower() == 'batman':
### these parameters are only relevant for batman!
param_uber_dict['Rstar'] = ['loguniform', (1e6,1e16)] #### meters!
param_uber_dict['long_peri'] = ['uniform', (0,4*np.pi)] ### longitude of periastron is the sum of the ascending node (0-2pi) and the argument of periaspe (also 0-2pi).
param_uber_dict['ecc'] = ['uniform', (0,1)]
# # # # # # # # # # #
# # # GEFERA # # # #
# # # # # # # # # # #
if modelcode.lower() == 'gefera':
#### https://github.com/tagordon/gefera#basic-usage
### ap -- semimajor axis in stellar radii
estimated_sma_Rstar = (self.pl_orbsmax * au.value) / (self.st_rad * R_sun.value)
estimated_sma_err_Rstar = (np.nanmax((np.abs(self.pl_orbsmaxerr1), np.abs(self.pl_orbsmaxerr2))) * au.value) / (self.st_rad * R_sun.value)
if np.isfinite(estimated_sma_Rstar) and np.isfinite(estimated_sma_err_Rstar) and (np.ma.is_masked(estimated_sma_Rstar) == False) and (np.ma.is_masked(estimated_sma_err_Rstar) == False):
param_uber_dict['ap'] = ['normal', (estimated_sma_Rstar, estimated_sma_err_Rstar)]
else:
if np.isfinite(estimated_sma_Rstar) and (np.ma.is_masked(estimated_sma_Rstar) == False):
param_uber_dict['ap'] = ['normal', (estimated_sma_Rstar, 0.05 * estimated_sma_Rstar)]
else:
####
estimated_sma_Rstar = Kep3_afromp(period=self.period, m1=self.st_mass*M_sun.value, m2=self.pl_bmasse*M_earth.value) / (self.st_rad * R_sun.value)
estimated_sma_err_Rstar = 0.1 * estimated_sma_Rstar
param_uber_dict['ap'] = ['normal', (estimated_sma_Rstar, estimated_sma_err_Rstar)]
#### tp -- starting epoch in days
param_uber_dict['tp'] = ['fixed', self.tau0]
#### ep -- eccentricity of the planet-moon system
NEA_ecc_err = np.nanmax((np.abs(self.pl_orbeccenerr1), np.abs(self.pl_orbeccenerr2)))
if 'ep' not in uninformative_priors:
if np.isfinite(self.pl_orbeccen) and np.isfinite(NEA_ecc_err) and (np.ma.is_masked(self.pl_orbeccen) == False) and (np.ma.is_masked(NEA_ecc_err) == False):
param_uber_dict['ep']= ['truncnormal', (self.pl_orbeccen, NEA_ecc_err, 0, 1)]
else:
if np.isfinite(self.pl_orbeccen) and (np.ma.is_masked(self.pl_orbeccen) == False):
param_uber_dict['ep']= ['truncnormal', (self.pl_orbeccen, 0.05, 0, 1)]
else:
param_uber_dict['ep'] = ['uniform', (0., 1.)]
elif 'ep' in uninformative_priors:
param_uber_dict['ep'] = ['uniform', (0., 1.)]
#### pp -- period in days
planet_period_err_days = np.nanmax((np.abs(self.pl_orbpererr1), np.abs(self.pl_orbpererr2)))
param_uber_dict['pp'] = ['normal', (self.period, planet_period_err_days)] ### normal supplies mu, sigma
#### wp -- longitude of periastron in degrees
NEA_w_err = np.nanmax((np.abs(self.pl_orblpererr1), np.abs(self.pl_orblpererr2)))
if 'wp' not in uninformative_priors:
if np.isfinite(self.pl_orblper) and np.isfinite(NEA_w_err) and (np.ma.is_masked(self.pl_orblper) == False) and (np.ma.is_masked(NEA_w_err) == False):
param_uber_dict['wp'] = ['normal', (self.pl_orblper, NEA_w_err)]
else:
if np.isfinite(self.pl_orblper) and (np.ma.is_masked(self.pl_orblper) == False):
param_uber_dict['wp'] = ['normal', (self.pl_orblper, 20)]
else:
param_uber_dict['wp'] = ['uniform', (0,360)]
elif 'wp' in uninformative_priors:
param_uber_dict['wp'] = ['uniform', (0,360)]
#### ip -- inclination in degrees
NEA_inc_err = np.nanmax((np.abs(self.pl_orbinclerr1), np.abs(self.pl_orbinclerr2)))
if 'ip' not in uninformative_priors:
if np.isfinite(self.pl_orbincl) and np.isfinite(NEA_inc_err) and (np.ma.is_masked(self.pl_orbincl) == False) and (np.ma.is_masked(NEA_inc_err) == False):
param_uber_dict['ip'] = ['normal', (self.pl_orbincl, NEA_inc_err)]
else:
#### try to compute an inclination from impact
if np.isfinite(self.pl_imppar) and (np.ma.is_masked(self.pl_imppar) == False):
NEA_inc_from_impact = inc_from_impact(self.pl_imppar, self.st_rad * R_sun.value, self.pl_orbsmax * au.value, unit='degrees')
param_uber_dict['ip'] = ['normal', (NEA_inc_from_impact, 10)]
else:
param_uber_dict['ip'] = ['normal', (90, 10)]
elif 'ip' in uninformative_priors:
param_uber_dict['ip'] = ['uniform', (80,100)]
### rp -- radius of the planet in stellar radii
NEA_RpRstar = (self.pl_rade * R_earth.value) / (self.st_rad * R_sun.value) #### units of Rstar https://github.com/hippke/Pandora/blob/main/examples/example.py#:~:text=params.a_bary,0.1%20%23%20%5BR_star%5D
NEA_RpRstar_err = ( np.nanmax((np.abs(self.pl_radeerr1), np.abs(self.pl_radeerr2))) * R_earth.value ) / (self.st_rad * R_sun.value)
if 'r_planet' not in uninformative_priors:
if np.isfinite(NEA_RpRstar) and np.isfinite(NEA_RpRstar_err) and (np.ma.is_masked(NEA_RpRstar) == False) and (np.ma.is_masked(NEA_RpRstar_err) == False):
param_uber_dict['rp'] = ['normal', (NEA_RpRstar, NEA_RpRstar_err)] ### units of Rstar
else:
param_uber_dict['rp'] = ['uniform', (0.01, 0.1)]
elif 'r_planet' in uninformative_priors:
param_uber_dict['rp'] = ['uniform', (0.01, 0.1)]
##### STAR PARAMETERS
"""
### R_star
star_radius_meters = self.st_rad * R_sun.value
star_radius_err_meters = np.nanmax((np.abs(self.st_raderr1), np.abs(self.st_raderr2))) * R_sun.value
param_uber_dict['R_star'] = ['fixed', star_radius_meters] ### EXPERIMENT JULY 27 2022
"""
#### u1
param_uber_dict['u1'] = ['uniform', (0.,1.)] # 0 -1
#### u2
param_uber_dict['u2'] = ['uniform', (0.,1.)] # 0 - 1
##### BELOW ARE DIFFERENCES BASED ON WHICH MODEL YOU USE.
if model.lower().startswith('m'):
#### am -- semimajor axis of the moon in units of stellar radii
param_uber_dict['am'] = ['loguniform', (1e-2, 1e1)] # [days]
#### tm -- starting epoch in days
param_uber_dict['tm'] = ['fixed', self.tau0]
#### em -- eccentricity of the moon
param_uber_dict['em'] = ['fixed', 0]
##### pm -- period of the moon
param_uber_dict['pm'] = ['loguniform', (1e-1, 1e2)]
#### om -- longitude of the ascending node in degrees
param_uber_dict['om'] = ['uniform', (0, 360.)] ### 0 - 180
#### wm -- longitude of periastron in degrees
param_uber_dict['wm'] = ['fixed', 0] #### eccentricity is zero, so this is meaningless
#### im -- inclination in degrees
#### i_moon
if model.lower() == 'm':
param_uber_dict['im'] = ['uniform', (0, 180.)] # 0 - 180
elif model.lower() == 'm_eo':
#### moon orbit is Edge-On! very artificial, but forces transits every time.
param_uber_dict['im'] = ['fixed', 90]
#### mm -- mass of the moon in units of the mass of the planet
param_uber_dict['mm'] = ['loguniform', (1e-5, 1)]
#### rm -- radius of the moon
param_uber_dict['rm'] = ['loguniform', (1e-3, 0.1)] ### [Rstar]
elif model.lower() == ('p'):
#### am -- semimajor axis of the moon in units of stellar radii
param_uber_dict['am'] = ['fixed', 1e1] # [days]
#### tm -- starting epoch in days
param_uber_dict['tm'] = ['fixed', self.tau0]
#### em -- eccentricity of the moon
param_uber_dict['em'] = ['fixed', 0]
##### pm -- period of the moon
param_uber_dict['pm'] = ['fixed', 30]
#### om -- longitude of the ascending node in degrees
param_uber_dict['om'] = ['fixed', 0] ### 0 - 180
#### wm -- longitude of periastron in degrees
param_uber_dict['wm'] = ['fixed', 0] #### eccentricity is zero, so this is meaningless
#### im -- inclination in degrees
param_uber_dict['im'] = ['fixed', 0] # 0 - 180
#### mm -- mass of the moon in units of the mass of the planet
param_uber_dict['mm'] = ['fixed', 1e-8]
#### rm -- radius of the moon
param_uber_dict['rm'] = ['fixed', 1e-8] ### [Rstar]
# # # # # # # # # # #
# # # PANDORA # # # #
# # # # # # # # # # #
if modelcode.lower() == 'pandora':
##### STAR PARAMETERS
### R_star
star_radius_meters = self.st_rad * R_sun.value
star_radius_err_meters = np.nanmax((np.abs(self.st_raderr1), np.abs(self.st_raderr2))) * R_sun.value
param_uber_dict['R_star'] = ['fixed', star_radius_meters] ### EXPERIMENT JULY 27 2022
#### q1
param_uber_dict['q1'] = ['uniform', (0.,1.)] # 0 -1
#### q2
param_uber_dict['q2'] = ['uniform', (0.,1.)] # 0 - 1
##### PLANET PARAMETERS
### per_bary
planet_period_err_days = np.nanmax((np.abs(self.pl_orbpererr1), np.abs(self.pl_orbpererr2)))
param_uber_dict['per_bary'] = ['normal', (self.period, planet_period_err_days)] ### normal supplies mu, sigma
### a_bary
estimated_sma_Rstar = (self.pl_orbsmax * au.value) / (self.st_rad * R_sun.value)
estimated_sma_err_Rstar = (np.nanmax((np.abs(self.pl_orbsmaxerr1), np.abs(self.pl_orbsmaxerr2))) * au.value) / (self.st_rad * R_sun.value)
if np.isfinite(estimated_sma_Rstar) and np.isfinite(estimated_sma_err_Rstar) and (np.ma.is_masked(estimated_sma_Rstar) == False) and (np.ma.is_masked(estimated_sma_err_Rstar) == False):
param_uber_dict['a_bary'] = ['normal', (estimated_sma_Rstar, estimated_sma_err_Rstar)]
else:
if np.isfinite(estimated_sma_Rstar) and (np.ma.is_masked(estimated_sma_Rstar) == False):
param_uber_dict['a_bary'] = ['normal', (estimated_sma_Rstar, 0.05 * estimated_sma_Rstar)]
else:
####
estimated_sma_Rstar = Kep3_afromp(period=self.period, m1=self.st_mass*M_sun.value, m2=self.pl_bmasse*M_earth.value) / (self.st_rad * R_sun.value)
estimated_sma_err_Rstar = 0.1 * estimated_sma_Rstar
param_uber_dict['a_bary'] = ['normal', (estimated_sma_Rstar, estimated_sma_err_Rstar)]
### r_planet
NEA_RpRstar = (self.pl_rade * R_earth.value) / (self.st_rad * R_sun.value) #### units of Rstar https://github.com/hippke/Pandora/blob/main/examples/example.py#:~:text=params.a_bary,0.1%20%23%20%5BR_star%5D
NEA_RpRstar_err = ( np.nanmax((np.abs(self.pl_radeerr1), np.abs(self.pl_radeerr2))) * R_earth.value ) / (self.st_rad * R_sun.value)
if 'r_planet' not in uninformative_priors:
if np.isfinite(NEA_RpRstar) and np.isfinite(NEA_RpRstar_err) and (np.ma.is_masked(NEA_RpRstar) == False) and (np.ma.is_masked(NEA_RpRstar_err) == False):
param_uber_dict['r_planet'] = ['normal', (NEA_RpRstar, NEA_RpRstar_err)] ### units of Rstar
else:
if np.isfinite(NEA_RpRstar) and (np.ma.is_masked(NEA_RpRstar) == False):
param_uber_dict['r_planet'] = ['normal', (NEA_RpRstar, 0.05 * NEA_RpRstar)]
else:
param_uber_dict['r_planet'] = ['uniform', (0.01, 0.1)]
elif 'r_planet' in uninformative_priors:
param_uber_dict['r_planet'] = ['uniform', (0.01, 0.1)]
#### b_bary
#param_uber_dict['b_bary'] = ['uniform', (0,1)] ### Pandora recommends a value between 0 and 2.
NEA_impact_err = np.nanmax((np.abs(self.pl_impparerr1), np.abs(self.pl_impparerr2)))
if 'b_bary' not in uninformative_priors:
if np.isfinite(self.pl_imppar) and np.isfinite(NEA_impact_err) and (np.ma.is_masked(self.pl_imppar) == False) and (np.ma.is_masked(NEA_impact_err) == False):
param_uber_dict['b_bary'] = ['truncnormal', (self.pl_imppar, NEA_impact_err, 0, 2)]
else:
if np.isfinite(self.pl_imppar) and (np.ma.is_masked(self.pl_imppar) == False):
param_uber_dict['b_bary'] = ['truncnormal', (self.pl_imppar, 0.05, 0, 2)]
else:
param_uber_dict['b_bary'] = ['uniform', (0., 2.)]
elif 'b_bary' in uninformative_priors:
param_uber_dict['b_bary'] = ['uniform', (0., 2.)]
#### w_bary
NEA_w_err = np.nanmax((np.abs(self.pl_orblpererr1), np.abs(self.pl_orblpererr2)))
if 'w_bary' not in uninformative_priors:
if np.isfinite(self.pl_orblper) and np.isfinite(NEA_w_err) and (np.ma.is_masked(self.pl_orblper) == False) and (np.ma.is_masked(NEA_w_err) == False):
param_uber_dict['w_bary'] = ['normal', (self.pl_orblper, NEA_w_err)]
else:
if np.isfinite(self.pl_orblper) and (np.ma.is_masked(self.pl_orblper) == False):
param_uber_dict['w_bary'] = ['normal', (self.pl_orblper, 20)]
else:
param_uber_dict['w_bary'] = ['uniform', (0,360)]
elif 'w_bary' in uninformative_priors:
param_uber_dict['w_bary'] = ['uniform', (0,360)]
#### ecc_bary
#param_uber_dict['ecc_bary'] = ['uniform', (0,1)]
NEA_ecc_err = np.nanmax((np.abs(self.pl_orbeccenerr1), np.abs(self.pl_orbeccenerr2)))
if 'ecc_bary' not in uninformative_priors:
if np.isfinite(self.pl_orbeccen) and np.isfinite(NEA_ecc_err) and (np.ma.is_masked(self.pl_orbeccen) == False) and (np.ma.is_masked(NEA_ecc_err) == False):
param_uber_dict['ecc_bary']= ['truncnormal', (self.pl_orbeccen, NEA_ecc_err, 0, 1)]
else:
if np.isfinite(self.pl_orbeccen) and (np.ma.is_masked(self.pl_orbeccen) == False):
param_uber_dict['ecc_bary']= ['truncnormal', (self.pl_orbeccen, 0.05, 0, 1)]
else:
param_uber_dict['ecc_bary'] = ['uniform', (0., 1.)]
elif 'ecc_bary' in uninformative_priors:
param_uber_dict['ecc_bary'] = ['uniform', (0., 1.)]
#### t0_bary
param_uber_dict['t0_bary'] = ['fixed', self.tau0]
#### t0_bary_offset
param_uber_dict['t0_bary_offset'] = ['uniform', (-1, 1)] ## [days]
#### M_planet
planet_mass_kg = self.pl_bmasse * M_earth.value
planet_mass_err_kg = np.nanmax((np.abs(self.pl_bmasseerr1), np.abs(self.pl_bmasseerr2))) * M_earth.value
#param_uber_dict['M_planet'] = ['normal', (planet_mass_kg, planet_mass_err_kg)]
param_uber_dict['M_planet'] = ['fixed', planet_mass_kg]
##### BELOW ARE DIFFERENCES BASED ON WHICH MODEL YOU USE.
if model.lower().startswith('m'):
##### MOON PARAMETERS
#### r_moon
param_uber_dict['r_moon'] = ['loguniform', (NEA_RpRstar * 1e-3, NEA_RpRstar)] ### [Rstar]
#### per_moon
param_uber_dict['per_moon'] = ['loguniform', (1e-1, 1e2)] # [days]
#### tau
param_uber_dict['tau_moon'] = ['uniform', (0,1)] ### 0 - 1 time of perapsis passage normalized by the period.
#### Omega_moon
param_uber_dict['Omega_moon'] = ['uniform', (0, 180.)] ### 0 - 180
#### i_moon
if model.lower() == 'm':
param_uber_dict['i_moon'] = ['uniform', (0, 180.)] # 0 - 180
elif model.lower() == 'm_eo':
#### moon orbit is Edge-On! very artificial, but forces transits every time.
param_uber_dict['i_moon'] = ['fixed', 90]
#### ecc_moon
param_uber_dict['ecc_moon'] = ['fixed', 0]
#### w_moon
param_uber_dict['w_moon'] = ['fixed', 0]
#### M_moon
param_uber_dict['M_moon'] = ['loguniform', (1e-5 * self.pl_bmasse * M_earth.value, 1e-1 * self.pl_bmasse * M_earth.value)]
elif model.lower() == 'p':
######## MOON PARAMETERS
#### r_moon
param_uber_dict['r_moon'] = ['fixed', 1e-8] ### [Rstar]
##### per_moon
param_uber_dict['per_moon'] = ['fixed', 30] # [days]
#### tau
param_uber_dict['tau_moon'] = ['fixed', 0] ### 0 - 1 time of perapsis passage normalized by the period.
#### Omega_moon
param_uber_dict['Omega_moon'] = ['fixed', 0] ### 0 - 180
#### i_moon
param_uber_dict['i_moon'] = ['fixed', 0] # 0 - 180
#### ecc_moon
param_uber_dict['ecc_moon'] = ['fixed', 0]
#### w_moon
param_uber_dict['w_moon'] = ['fixed', 0]
#### M_moon
param_uber_dict['M_moon'] = ['fixed', 1e-8]
self.param_uber_dict = param_uber_dict
#### finished building the param_uber_dict!
### OK TO LEAVE HERE, SO LONG AS IT ALSO STAYS WITHIN THE FIT() FUNCTION.
param_labels = []
param_prior_forms = []
param_limit_tuple = []
for pkey in self.param_uber_dict.keys():
param_labels.append(pkey)
param_prior_forms.append(param_uber_dict[pkey][0])
param_limit_tuple.append(param_uber_dict[pkey][1])
self.param_labels = param_labels
self.param_prior_forms = param_prior_forms
self.param_limit_tuple = param_limit_tuple
### MAKE THE OUTPUT DIRECTORY IF IT DOESN'T ALREADY EXIST
outputdir = moonpydir+'/ultranest_fits'
if os.path.exists(outputdir) == False:
os.system('mkdir '+outputdir) ### create UltraNest_fits directory
outputdir = outputdir+'/'+str(modelcode.lower())
if os.path.exists(outputdir) == False:
os.system('mkdir '+outputdir) ### creates modelcode directory
outputdir = outputdir+'/'+str(self.target.lower())
if os.path.exists(outputdir) == False:
os.system('mkdir '+outputdir) ### creates target directory
outputdir = outputdir+'/'+str(model.lower())
print('model: ', model)
if os.path.exists(outputdir) == False:
os.system('mkdir '+outputdir) ### creates model directory
print('outputdir: ', outputdir)
#### write out to a file
priorfile = open(outputdir+'/'+modelcode+'_model'+str(model)+'_priors.txt', mode='w')
for key in param_uber_dict.keys():
priortype = param_uber_dict[key][0]
bounds = param_uber_dict[key][1]
print('priortype: ', priortype)
print('bounds: ', bounds)
newline = str(key)+' '+str(priortype)
if type(bounds) != tuple:
newline = newline+' '+str(bounds)+'\n'
else:
for entry in bounds:
newline = newline+' '+str(entry)
newline = newline+'\n'
priorfile.write(newline)
priorfile.close()
### DETRENDING!
def detrend(self, dmeth='cofiam', save_lc='y', mask_transits='y', period=None, mask_neighbors='y', mask_multiple=None, skip_ntqs='n', medfilt_kernel_transit_multiple=5, GP_kernel='ExpSquaredKernel', GP_metric=1.0, max_degree=30, use_holczer='y', downsample_factor=20):
print('calling _mp_manipulation.py/detrend().')
#if mask_multiple == None:
# mask_multiple = self.mask_multiple
if period == None:
try:
period = self.period
except:
period_manual_entry = input('Period is missing... please enter one (or press enter for median_value detrend): ')
if period_manual_entry == '':
### change the detrending method to median value -- you can't mask anything!
print('switching detrending method to "median_value, because there is no planet ephemerides for transit masking.')
dmeth = 'median_value'
else:
period = float(period_manual_entry)
self.period = period
exceptions_raised = 'n'
self.dmeth=dmeth
### make sure you get_neighbors() first!
if self.telescope.lower() != 'user':
self.get_neighbors()
if self.telescope.lower() != 'kepler':
use_holczer == 'n' ### mazeh is only for Kepler targets!
if mask_neighbors == 'y':
mask_transits = 'y'
### optional values for detrending method (dmeth) are "cofiam", "untrendy", "medfilt", "george", and "polyAM"
### EACH QUARTER SHOULD BE DETRENDED INDIVIDUALLY!
nquarters = len(self.quarters)
master_detrend_model, master_detrend, master_error_detrend, master_flags_detrend = [], [], [], []
if dmeth == 'phasma':
mask_transit_idxs = []
all_quarter_mask_transit_idxs = []
#### PHASMA HAS TO WORK ON THE FULL LIGHT CURVE! NOT ON INDIVIDUAL SEGMENTS!
#### SO DO IT HERE
norm_fluxes = []
norm_errors = []
#### have to normalize fluxes on a quarter by quarter basis first!
for nq,q in enumerate(self.fluxes):
norm_fluxes.append(self.fluxes[nq] / np.nanmedian(self.fluxes[nq]))
norm_errors.append(self.errors[nq] / self.fluxes[nq])
norm_fluxes = np.array(norm_fluxes)
cctimes, ccfluxes, ccerrors = np.concatenate(self.times), np.concatenate(norm_fluxes), np.concatenate(norm_errors)
try:
detrend_model, fluxes_detrend, errors_detrend = phasma_detrend(times=cctimes, fluxes=ccfluxes, errors=ccerrors, period=period, downsample_factor=downsample_factor)
except:
detrend_model, fluxes_detrend, errors_detrend = phasma_detrend(times=np.array(cctimes, dtype=np.float64), fluxes=np.array(ccfluxes, dtype=np.float64), errors=np.array(ccerrors, dtype=np.float64), period=period, downsample_factor=downsample_factor)
#flags_detrend = np.concatenate(self.flags)
flags_detrend = np.linspace(2097152,2097152,len(fluxes_detrend))
### now need to stitch this back together as master_detrend_model
for nq,q in enumerate(self.quarters):
qmin_idx, qmax_idx = np.where(cctimes == np.nanmin(self.times[nq]))[0][0], np.where(cctimes == np.nanmax(self.times[nq]))[0][0]
print('qmin_idx, qmax_idx: ', qmin_idx, qmax_idx)
dmodel, dfluxes_detrend, derrors_detrend = detrend_model[qmin_idx:qmax_idx+1], fluxes_detrend[qmin_idx:qmax_idx+1], errors_detrend[qmin_idx:qmax_idx+1]
dflags = flags_detrend[qmin_idx:qmax_idx+1]
master_detrend_model.append(dmodel)
master_detrend.append(dfluxes_detrend)
master_error_detrend.append(derrors_detrend)
master_flags_detrend.append(dflags)
#### dummy append.
all_quarter_mask_transit_idxs.append(mask_transit_idxs)
self.mask_transit_idxs = np.array(all_quarter_mask_transit_idxs, dtype=object)
else:
#### FOR ALL OTHER METHODS -- DETREND ON A QUARTER BY QUARTER BASIS.
all_quarter_mask_transit_idxs = []
for qidx in np.arange(0,nquarters,1):
skip_quarter = 'n'
print('quarter = ', self.quarters[qidx])
if nquarters != 1:
dtimes, dfluxes, derrors, dflags = self.times[qidx], self.fluxes[qidx], self.errors[qidx], self.flags[qidx]
elif nquarters == 1:
dtimes, dfluxes, derrors, dflags = self.times, self.fluxes, self.errors, self.flags
if dtimes.shape[0] == 0:
exceptions_raised = 'y'
fluxes_detrend, errors_detrend = dfluxes, derrors
flags_detrend = np.linspace(2097152,2097152,len(fluxes_detrend))
master_detrend.append(np.array(fluxes_detrend))
master_error_detrend.append(np.array(errors_detrend))
master_flags_detrend.append(np.array(flags_detrend))
continue
dtimesort = np.argsort(dtimes)
dtimes, dfluxes, derrors, dflags = dtimes[dtimesort], dfluxes[dtimesort], derrors[dtimesort], dflags[dtimesort]
for ndt,dt in enumerate(dtimes):
try:
timediff = dtimes[ndt+1] - dtimes[ndt]
if timediff <= 0:
print("WARNING: timestamps are not sorted.")
except:
pass
### identify in-transit idxs, and mask them!
if mask_transits == 'y':
### find out which transit midtimes, if any, are in this quarter
mask_transit_idxs = []
if (self.telescope.lower() == 'kepler') and (use_holczer == 'y'):
print("Using TTV Catalog to identify transit times for detrending...")
### taus should be calculated based on the Mazeh table.
mazeh = pandas.read_csv(moonpydir+'/Table3_O-C.csv')
maz_koi = np.array(mazeh['KOI']).astype(str)
maz_epoch = np.array(mazeh['n'])
maz_reftime = np.array(mazeh['ref_time'])
maz_reftime = maz_reftime + 2454900 - 2454833 #### adjusts into BKJD -- a difference of 67 days from the Holczer catalog.
maz_OCmin = np.array(mazeh['O-C_min'])
### find the indices of the target!
target_idxs = np.where(self.target[4:] == maz_koi)[0]
if len(target_idxs) == 0:
print('no TTV record under the name '+str(self.target)+'. Checking aliases...')
### check for aliases -- your self.target may not be a KOI natively!
try:
for planet_alias in self.aliases:
if planet_alias.lower().startswith('koi'):
target_idxs = np.where(planet_alias[4:] == maz_koi)[0]