-
Notifications
You must be signed in to change notification settings - Fork 0
/
real_planet_TTV_analyzer.py
1726 lines (1309 loc) · 70.6 KB
/
real_planet_TTV_analyzer.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 pandas
import os
import time
import traceback
from astropy.timeseries import LombScargle
from astropy.io import ascii
from scipy.optimize import curve_fit
import re
from scipy.stats import gaussian_kde
import matplotlib.cm as cm
import matplotlib.gridspec as gridspec
from scipy.special import factorial
from moonpy import *
import socket
from mr_forecast import Rstat2M
from scipy.stats import kstest
from astropy.constants import M_sun, M_earth
from sklearn.cluster import DBSCAN
from scipy.stats import skew, kurtosis
"""
#### THIS SCRIPT IS GOING TO PRODUCE ONE PLOT -- the plot of P_TTV vs P_plan.
###### to do this, we will
1) import the O-C values (Table3_O-C.csv),
2) run a periodogram
3) use the highest peak period as a period to fit a sinusoid
4) calculate a BIC and delta-BIC
5) grab the planet's orbital period (nasa exoplanet archive will be easiet)
6) make a scatter plot in P_TTV -- P_plan space.
7) compute a gaussian kernel density estimator
8) sav the GKDE as a pickle, so you can import it and use it elsewhere to calculate a probability for a given P_TTV and P_plan.
"""
def sinewave(tvals, frequency, offset):
return amplitude * np.sin(2*np.pi*frequency*tvals + offset)
def chisquare(data,model,error):
return np.nansum(((data-model)**2 / (error**2)))
def BIC(nparams,data,model,error):
return nparams*np.log(len(data)) + chisquare(data,model,error)
def AIC(nparams,data,model,error):
return 2*nparams + chisquare(data,model,error)
plt.rcParams["font.family"] = 'serif'
sim_prefix = input('What is the sim_prefix? ')
use_BIC_or_AIC = input("Do you want to use 'B'IC or 'A'IC? ")
####### FILE DIRECTORY INFORMATION
if socket.gethostname() == 'tethys.asiaa.sinica.edu.tw':
#projectdir = '/data/tethys/Documents/Projects/NMoon_TTVs'
projectdir = '/run/media/amteachey/Auddy_Akiti/Teachey/Nmoon_TTVs'
elif socket.gethostname() == 'Alexs-MacBook-Pro.local':
projectdir = '/Users/hal9000/Documents/Projects/Nmoon_TTVsim'
else:
projectdir = input('Please input the project directory: ')
if sim_prefix == '':
positionsdir = projectdir+'/sim_positions'
ttvfiledir = projectdir+'/sim_TTVs'
LSdir = projectdir+'/sim_periodograms'
modeldictdir = projectdir+'/sim_model_settings'
plotdir = projectdir+'/sim_plots'
else:
positionsdir = projectdir+'/'+sim_prefix+'_sim_positions'
ttvfiledir = projectdir+'/'+sim_prefix+'_sim_TTVs'
LSdir = projectdir+'/'+sim_prefix+'_sim_periodograms'
modeldictdir = projectdir+'/'+sim_prefix+'_sim_model_settings'
plotdir = projectdir+'/'+sim_prefix+'_sim_plots'
###################################
########## FUNCTION DEFINTIONS ####################
def TTVkiller(rms_amp, errors, Pplan, Tdur, unit='days', npoints=None):
### equation 20 from this paper: https://arxiv.org/pdf/2004.04230.pdf
"""
Errors should be array-like, or npoints must be specified.
Pplan and Tdur need to have the same units, as shoudl rms_amp and errors.
"""
LHS_num = rms_amp
errorbar = np.nanmedian(errors)
try:
npoints = len(errors)
except:
pass
LHS_denom = (np.sqrt(2) * errorbar) / np.sqrt(npoints)
LHS = LHS_num / LHS_denom
RHS_first_term = np.sqrt(3) / (4*np.pi)
RHS_second_term = Pplan / Tdur
RHS = RHS_first_term * RHS_second_term
if LHS < RHS:
moon_possible = True
else:
moon_possible = False
def fmin(mplan, mstar, A_TTV, Pplan, unit='minutes'):
#### units of A_TTV and Pplan have to be the same!
if np.isfinite(mstar) and (mstar != 0) and type(mplan) != None:
q = mplan / mstar
else:
q = np.nan
first_term = 9 / (q**(1/3))
second_term = A_TTV / Pplan
minimum_fRHill = first_term * second_term
return minimum_fRHill, q, mplan, mstar, A_TTV, Pplan, first_term, second_term
def n_choose_k(n,k):
numerator = factorial(n)
denominator = factorial(k) * factorial(n - k)
return numerator / denominator
def chisquare(data, model, errors):
return np.nansum(((data - model)**2) / errors**2)
########### END FUNCTION DEFINTIONS ###############################
try:
show_plots = input('Do you want to show plots (for debugging)? y/n: ')
cross_validate_LSPs = input("Do you want to run Lomb-Scargle cross-validation (removing points and recomputing)? ")
if cross_validate_LSPs == 'y':
cv_frac_to_leave_out = 0.05 #### five percent
cv_ntrials = int(1/cv_frac_to_leave_out) ### 20 trials
elif cross_validate_LSPs == 'n':
### just do a single trial
cv_frac_to_leave_out = 0
cv_ntrials = 1
exclude_short_periods = input('Do you want to exclude short period planets? (recommend y): ')
################ LOAD TTVs ##################################
Holczer_OCfile = pandas.read_csv('/data/tethys/Documents/Software/MoonPy/Table3_O-C.csv')
Holczer_KOIs = np.array(Holczer_OCfile['KOI']).astype(str)
Holczer_epochs = np.array(Holczer_OCfile['n']).astype(int)
Holczer_OCmin = np.array(Holczer_OCfile['O-C_min']).astype(str)
Holczer_OCmin_err = np.array(Holczer_OCfile['O-C_err']).astype(str)
### PURGE THOSE GODDAMN SPECIAL CHARACTERS OUT OF Holczer_OCmin and Holczer_OCmin_err
Holczer_OCmin_clean, Holczer_OCmin_err_clean = [], []
for OC, OCerr in zip(Holczer_OCmin, Holczer_OCmin_err):
### THIS NASTY NESTED FOR LOOP IS BROUGHT TO YOU BY USING NON-NUMERIC CHARACTERS IN A NUMERIC COLUMN INSTEAD OF USING FLAGS.
OCclean = ''
for val in OC:
if val in ['-', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
OCclean = OCclean+val
else:
pass
Holczer_OCmin_clean.append(float(OCclean))
OCerrclean = ''
for val in OCerr:
if val in ['-', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
OCerrclean = OCerrclean+val
else:
pass
Holczer_OCmin_err_clean.append(float(OCerrclean))
Holczer_OCmin = np.array(Holczer_OCmin_clean)
Holczer_OCmin_err = np.array(Holczer_OCmin_err_clean)
Holczer_unique_KOIs = np.unique(Holczer_KOIs)
#### LOAD TKS (GOSE PROJECT) TTVs (Teachey, Kipping & Schmitt) ################################
TKS_OCfile = pandas.read_csv('/data/tethys/Documents/Central_Data/GOSE_TTV_summaryfile.csv')
TKS_KOIs = np.array(TKS_OCfile['KOI']).astype(str)
TKS_KOI_nums = []
for TKS_KOI in TKS_KOIs:
TKS_KOI_nums.append(str(TKS_KOI[4:]))
TKS_KOIs = np.array(TKS_KOI_nums).astype(str)
TKS_epochs = np.array(TKS_OCfile['epoch']).astype(int)
TKS_OCmin = np.array(TKS_OCfile['OC_min']).astype(str)
TKS_OCmin_err = np.array(TKS_OCfile['OCmin_err']).astype(str)
TKS_unique_KOIs = np.unique(TKS_KOIs)
use_Holczer_or_gose = input("Do you want to use 'h'olczer TTVs or 'g'ose (TKS) TTVs? ")
if use_Holczer_or_gose == 'h':
OCfile = Holczer_OCfile
KOIs = Holczer_KOIs
epochs = Holczer_epochs
OCmin = Holczer_OCmin
OCmin_err = Holczer_OCmin_err
unique_KOIs = Holczer_unique_KOIs
elif use_Holczer_or_gose == 'g':
OCfile = TKS_OCfile
KOIs = TKS_KOIs
epochs = TKS_epochs
OCmin = TKS_OCmin
OCmin_err = TKS_OCmin_err
unique_KOIs = TKS_unique_KOIs
############# END LOADING TTVS ######################################
################ LOAD THE CUMULATIVE KOI FILE FROM MAST #########################
################### AND PERFORM SOME SIMPLE CALCULATIONS ON THEM ###################
cumkois = ascii.read('/data/tethys/Documents/Software/MoonPy/cumkois_mast.txt')
kepler_names = np.array(cumkois['kepler_name'])
kepois = np.array(cumkois['kepoi_name'])
kepoi_periods = np.array(cumkois['koi_period'])
dispositions = np.array(cumkois['koi_disposition'])
kepler_radius_rearth = np.array(cumkois['koi_prad'])
kepler_radius_rearth_uperr = np.array(cumkois['koi_prad_err1'])
kepler_radius_rearth_lowerr = np.array(cumkois['koi_prad_err2'])
kepler_radius_rearth_err = np.nanmean((kepler_radius_rearth_uperr, np.abs(kepler_radius_rearth_lowerr)), axis=0)
kepler_solar_mass = np.array(cumkois['koi_smass'])
kepler_solar_mass_uperr = np.array(cumkois['koi_smass_err1'])
kepler_solar_mass_lowerr = np.array(cumkois['koi_smass_err2'])
kepler_solar_mass_err = np.nanmean((np.abs(kepler_solar_mass_uperr), np.abs(kepler_solar_mass_lowerr)), axis=0)
FP_idxs = np.where(dispositions == 'FALSE POSITIVE')[0]
kepoi_nums = []
system_nums = []
for kepoi in kepois:
kepoi_num = kepoi
while (kepoi_num.startswith('K')) or (kepoi_num.startswith('0')):
kepoi_num = kepoi_num[1:]
kepoi_nums.append(kepoi_num)
system_nums.append(kepoi_num[:kepoi_num.find('.')]) #### leaves off the .01, .02, .03, etc.
kepoi_nums = np.array(kepoi_nums)
system_nums = np.array(system_nums)
kepois = kepoi_nums
#### determine if the kepois are in multi-planet systems
kepoi_multi = []
kepoi_multi_Pip1_over_Pis = [] #### P_{i+1} / P_i #### covers all but the outermost planet
kepoi_multi_Pi_over_Pim1s = [] #### P_i / P_{i - 1} #### cover all but the innermost planet
for nkep,kep in enumerate(kepois): ### kepois are already strings
kepoi_number = kep[:kep.find('.')] #### leaves off the final .01, .02, .03, etc.
#### find how many entries match this in system_nums.
all_system_planet_idxs = np.where(kepoi_number == system_nums)[0]
all_system_planet_periods = kepoi_periods[all_system_planet_idxs]
all_system_planet_periods_sorted = np.sort(all_system_planet_periods)
this_planet_idx = np.where(kep == kepois)[0]
this_planet_period = kepoi_periods[this_planet_idx][0]
this_planet_order_number_idx = np.where(all_system_planet_periods_sorted == this_planet_period)[0]
#if (exclude_short_periods == 'y') and (float(this_planet_period) < 10): ##### the lower limit on your sims!
# print("SHORT PERIOD PLANET! SKIPPING.")
# continue
try:
next_highest_period = all_system_planet_periods_sorted[this_planet_order_number_idx+1]
except:
next_highest_period = np.nan
try:
if this_planet_order_number_idx != 0:
next_lowest_period = all_system_planet_periods_sorted[this_planet_order_number_idx-1]
else:
next_lowest_period = np.nan
except:
next_lowest_period = np.nan
this_planet_Pip1_over_Pi = next_highest_period / this_planet_period
this_planet_Pi_over_Pim1 = this_planet_period / next_lowest_period
assert (this_planet_Pip1_over_Pi >= 1) or (np.isfinite(this_planet_Pip1_over_Pi) == False)
assert (this_planet_Pi_over_Pim1 >= 1) or (np.isfinite(this_planet_Pi_over_Pim1) == False)
kepoi_multi_Pip1_over_Pis.append(this_planet_Pip1_over_Pi)
kepoi_multi_Pi_over_Pim1s.append(this_planet_Pi_over_Pim1)
nplanets_in_system = len(all_system_planet_idxs)
if nplanets_in_system > 1:
kepoi_multi.append(True)
elif nplanets_in_system == 1:
kepoi_multi.append(False)
else:
raise Exception('something weird happening with the single / multi counter.')
kepoi_multi = np.array(kepoi_multi)
kepoi_multi_Pip1_over_Pis = np.array(kepoi_multi_Pip1_over_Pis)
kepoi_multi_Pi_over_Pim1s = np.array(kepoi_multi_Pi_over_Pim1s)
########### END CUMULATIVE KOI LOADING AND MANIPULATION ######################################
#### LOAD THE CROSS-VALIDATION FILES (GENERATED IN THIS SAME SCRIPT, LATER) ######################
try:
########## LOAD THE CROSS-VALIDATION RESULTS (HOLCZER) ###############################
Holczer_crossvalfile = pandas.read_csv('/data/tethys/Documents/Projects/NMoon_TTVs/Holczer_PTTV_results.csv')
Holczer_cv_KOI = np.array(Holczer_crossvalfile['KOI']).astype(str) #### of the form 1.01
Holczer_cv_PTTV_pcterr = np.array(Holczer_crossvalfile['PTTV_pcterr']).astype(float)
Holczer_cv_ATTV_pcterr = np.array(Holczer_crossvalfile['ATTV_pcterr']).astype(float)
Holczer_cv_phase_pcterr = np.array(Holczer_crossvalfile['phase_pcterr']).astype(float)
Holczer_cv_good_idxs = []
for i in np.arange(0,len(Holczer_cv_KOI),1):
if (Holczer_cv_PTTV_pcterr[i] <= 5) and (Holczer_cv_ATTV_pcterr[i] <= 5) and (Holczer_cv_phase_pcterr[i] <= 5):
Holczer_cv_good_idxs.append(i)
loaded_holczer_crossvalfile = 'y'
except:
loaded_holczer_crossvalfile = 'n'
try:
#### LOAD THE CROSS-VALIDATION RESULTS (TKS) ########################################
TKS_crossvalfile = pandas.read_csv('/data/tethys/Documents/Projects/NMoon_TTVs/GOSE_PTTV_results.csv')
TKS_cv_KOI = np.array(TKS_crossvalfile['KOI']).astype(str) #### of the form 1.01
TKS_cv_PTTV_pcterr = np.array(TKS_crossvalfile['PTTV_pcterr']).astype(float)
TKS_cv_ATTV_pcterr = np.array(TKS_crossvalfile['ATTV_pcterr']).astype(float)
TKS_cv_phase_pcterr = np.array(TKS_crossvalfile['phase_pcterr']).astype(float)
TKS_cv_good_idxs = []
for i in np.arange(0,len(TKS_cv_KOI),1):
if (TKS_cv_PTTV_pcterr[i] <= 5) and (TKS_cv_ATTV_pcterr[i] <= 5) and (TKS_cv_phase_pcterr[i] <= 5):
TKS_cv_good_idxs.append(i)
loaded_TKS_crossvalfile = 'y'
except:
loaded_TKS_crossvalfile = 'n'
#try:
#### LOAD THE CROSS-VALIDATION RESULTS (SIMULATIONS) #############################
try:
if sim_prefix == '':
sim_crossvalfile = pandas.read_csv('/data/tethys/Documents/Projects/NMoon_TTVs/sim_PTTV_results.csv')
else:
sim_crossvalfile = pandas.read_csv('/data/tethys/Documents/Projects/NMoon_TTVs/'+sim_prefix+'sim_PTTV_results.csv')
except:
if sim_prefix == '':
sim_crossvalfile = pandas.read_csv('/run/media/amteachey/Auddy_Akiti/Teachey/Nmoon_TTVs/sim_PTTV_results.csv')
else:
sim_crossvalfile = pandas.read_csv('/run/media/amteachey/Auddy_Akiti/Teachey/Nmoon_TTVs/'+sim_prefix+'sim_PTTV_results.csv')
sim_cv_KOI = np.array(sim_crossvalfile['sim']).astype(str) #### of the form 1.01
sim_cv_PTTV_pcterr = np.array(sim_crossvalfile['PTTV_pcterr']).astype(float)
sim_cv_ATTV_pcterr = np.array(sim_crossvalfile['ATTV_pcterr']).astype(float)
sim_cv_phase_pcterr = np.array(sim_crossvalfile['phase_pcterr']).astype(float)
sim_cv_good_idxs = []
for i in np.arange(0,len(sim_cv_KOI),1):
if (sim_cv_PTTV_pcterr[i] <= 5) and (sim_cv_ATTV_pcterr[i] <= 5) and (sim_cv_phase_pcterr[i] <= 5):
sim_cv_good_idxs.append(i)
loaded_sim_crossvalfile = 'y'
#except:
# loaded_sim_crossvalfile = 'n'
##### FIND THE HADDEN & LITHWICK KOIs ###############################################################
try:
HL_KOIs = np.load('/data/tethys/Documents/Projects/NMoon_TTVs/Hadden_Lithwick_posteriors/HLKOIs.npy')
print('loaded HL_KOIs...')
except:
HL_KOIs = []
print('generating HL_KOIs...')
HLplanet_list = np.load('/data/tethys/Documents/Projects/NMoon_TTVs/Hadden_Lithwick_posteriors/HLplanet_list.npy')
for HLplanet in HLplanet_list:
if HLplanet.startswith('Kepler'):
#### find the kepoi in cumkois:
HLplanet_proper_format = HLplanet[:-1]+' '+HLplanet[-1]
if HLplanet_proper_format.startswith('Kepler-25') or HLplanet_proper_format.startswith('Kepler-89') or HLplanet_proper_format.startswith('Kepler-444'):
HLplanet_proper_format = HLplanet_proper_format[:-2]+' A '+HLplanet_proper_format[-1]
HL_kepoi_idx = np.where(kepler_names == HLplanet_proper_format)[0]
HL_kepoi = kepois[HL_kepoi_idx]
else:
HL_kepoi = HLplanet #### of the form K0001.01, etc
if type(HL_kepoi) == np.ndarray:
HL_kepoi = HL_kepoi[0]
HL_KOI = HL_kepoi
while HL_KOI.startswith('K') or HL_KOI.startswith('0'):
HL_KOI = HL_KOI[1:]
HL_KOI = 'KOI-'+HL_KOI
HL_KOIs.append(HL_KOI)
HL_KOIs = np.array(HL_KOIs)
assert len(HL_KOIs) == len(HLplanet_list)
np.save('/data/tethys/Documents/Projects/NMoon_TTVs/Hadden_Lithwick_posteriors/HLKOIs.npy', HL_KOIs)
##### END PULLING OUT THE HADDEN & LITHWICK KOIS ###########################################
############### LOAD FORECASTER RESULTS ###########################################################
forecaster_MRfile = pandas.read_csv('/data/tethys/Documents/Central_Data/cumkoi_forecast_masses.csv')
forecaster_KOIs = np.array(forecaster_MRfile['KOI']).astype(str)
forecaster_mass_mearth = np.array(forecaster_MRfile['mass_mearth'])
forecaster_mass_uperr = np.array(forecaster_MRfile['mass_mearth_uperr'])
forecaster_mass_lowerr = np.array(forecaster_MRfile['mass_mearth_lowerr']) ### NEGATIVE NUMBER!!!
#################### END LOAD FORECASTER RESULTS ###################################################
##### GENERATE LISTS IN THE BIG FOR LOOP BELOW #########################################################
radii = [] #### EARTH RADII
radii_errors = []
stellar_masses = []
stellar_masses_errors = []
P_TTVs = []
P_plans = []
deltaBICs = []
deltaAICs = []
Pip1_over_Pis = []
Pi_over_Pim1s = []
forecast_masses = []
forecast_masses_uperr = []
forecast_masses_lowerr = []
TTV_amplitudes_min = []
median_timing_errors = []
single_idxs = []
multi_idxs = []
in_HLcatalog_idxs = []
notin_HLcatalog_idxs = []
cv_PTTV_pcterrs = []
cv_ATTV_pcterrs = []
cv_phase_pcterrs = []
######## PREPARE PTTV RESULTS FILES (CROSS-VALIDATION TESTS)
if use_Holczer_or_gose == 'h':
PTTV_resultsname = 'Holczer_PTTV_results.csv'
elif use_Holczer_or_gose == 'g':
PTTV_resultsname = 'GOSE_PTTV_results.csv'
if cross_validate_LSPs == 'y':
#if os.path.exists('/data/tethys/Documents/Projects/NMoon_TTVs/'+PTTV_resultsname):
### find last record KOI number:
#crossvalfile = pandas.read_csv('/data/tethys/Documents/Projects/NMoon_TTVs/'+PTTV_resultsname)
#cv_kepois_examined = np.array(crossvalfile['KOI']).astype(str)
#else:
##### DO IT FRESSSSSSHHHHHHH !!!!!!!!
crossval_resultsfile = open('/data/tethys/Documents/Projects/NMoon_TTVs/'+PTTV_resultsname, mode='w')
crossval_resultsfile.write('KOI,n_crossval_trials,n_epochs,n_removed,PTTV_median,PTTV_std,PTTV_skew,PTTV_kurtosis,PTTV_pcterr,ATTV_median,ATTV_std,ATTV_pcterr,phase_median,phase_std,phase_pcterr,deltaBIC,deltaBIC_std,deltaAIC,deltaAIC_std\n')
crossval_resultsfile.close()
cv_kepois_examined = np.array([])
else:
cv_kepois_examined = np.array([])
##### END PREPARE PTTV RESULTS FILES (CROSS-VALIDATION TESTS)
################### BIG ANALYSIS FOR LOOP ###################################
entrynum = 0
for nkepoi, kepoi in enumerate(kepois):
this_planet_idx = np.where(kepoi == kepois)[0]
this_planet_period = kepoi_periods[this_planet_idx][0]
if (exclude_short_periods == 'y') and (float(this_planet_period) < 10): ##### the lower limit on your sims!
print("SHORT PERIOD PLANET! SKIPPING.")
continue
#if (cross_validate_LSPs == 'y') and (str(kepoi) in cv_kepois_examined):
# print('ALREADY EXAMINED. SKIPPING.')
# print(' ')
# continue
if nkepoi in FP_idxs:
print('Skipping false positive: ', kepoi)
print(' ')
continue
##### FIND THE CROSS-VALIDATION INDICES FOR THIS TARGET
if loaded_holczer_crossvalfile == 'y':
cv_holczer_match_idx = np.where(kepoi == Holczer_cv_KOI)[0]
holczer_cv_period_pct_error = Holczer_cv_PTTV_pcterr[cv_holczer_match_idx]
holczer_cv_amplitude_pct_error = Holczer_cv_ATTV_pcterr[cv_holczer_match_idx]
holczer_cv_phase_pct_error = Holczer_cv_phase_pcterr[cv_holczer_match_idx]
if loaded_TKS_crossvalfile == 'y':
cv_TKS_match_idx = np.where(kepoi == TKS_cv_KOI)[0]
TKS_cv_period_pct_error = TKS_cv_PTTV_pcterr[cv_TKS_match_idx]
TKS_cv_amplitude_pct_error = TKS_cv_ATTV_pcterr[cv_TKS_match_idx]
TKS_cv_phase_pct_error = TKS_cv_phase_pcterr[cv_TKS_match_idx]
#### FIND THE FORECASTER ENTRY FOR THIS OBJECT ##########################
forecaster_idx = int(np.where(forecaster_KOIs == kepoi)[0])
print('nkepoi, forecaster_idx = ', nkepoi, forecaster_idx)
forecast_mass = forecaster_mass_mearth[forecaster_idx]
forecast_mass_uperr = np.abs(forecaster_mass_uperr[forecaster_idx])
forecast_mass_lowerr = np.abs(forecaster_mass_lowerr[forecaster_idx])
try:
kepoi_period = kepoi_periods[nkepoi]
print('KOI-'+str(kepoi))
KOI_idxs = np.where(KOIs == kepoi)[0]
if len(KOI_idxs) == 0:
print(' ')
#### it's not in the catalog! Continue!
continue
KOI_epochs, KOI_OCmins, KOI_OCerrs = np.array(epochs[KOI_idxs]).astype(int), np.array(OCmin[KOI_idxs]).astype(float), np.array(OCmin_err[KOI_idxs]).astype(float)
KOI_rms = np.sqrt(np.nanmean(KOI_OCmins**2))
orig_KOI_rms = KOI_rms
##### OUTLIER REJECTION #########################################################
DBSCAN_vector = np.vstack((KOI_epochs, KOI_OCmins)).T
db = DBSCAN(eps=5*np.nanmedian(KOI_OCerrs), min_samples=int(len(KOI_epochs)/5)).fit(KOI_OCmins.reshape(-1,1))
labels = db.labels_
outlier_idxs = np.where(labels == -1)[0]
KOI_epochs, KOI_OCmins, KOI_OCerrs = np.delete(KOI_epochs, outlier_idxs), np.delete(KOI_OCmins, outlier_idxs), np.delete(KOI_OCerrs, outlier_idxs)
KOI_rms = np.sqrt(np.nanmean(KOI_OCmins**2))
##### PERFORM A LOMB-SCARGLE PERIODOGRAM ON THE ENTIRE SAMPLE OF TRANSIT TIMES ########################
LSperiods = np.logspace(np.log10(2), np.log10(500), 5000)
LSfreqs = 1/LSperiods
LSpowers = LombScargle(KOI_epochs, KOI_OCmins, KOI_OCerrs).power(LSfreqs)
peak_power_idx = np.nanargmax(LSpowers)
peak_power_period = LSperiods[peak_power_idx]
peak_power_freq = 1/peak_power_period
### NOW FIT A SINUSOID -- HAVE TO DEFINE IT LIKE THIS TO UTILIZE curve_fit()
def sinecurve(tvals, amplitude, phase):
angfreq = 2 * np.pi * peak_power_freq
sinewave = amplitude * np.sin(angfreq * tvals + phase)
return sinewave
#### NOW FIT THAT SUCKER
popt, pcov = curve_fit(sinecurve, KOI_epochs, KOI_OCmins, sigma=KOI_OCerrs, bounds=([0, -2*np.pi], [20*KOI_rms, 2*np.pi]))
#### calculate BIC and deltaBIC -- USE ALL THE DATAPOINTS!
#BIC_flat = chisquare(KOI_OCmins, np.linspace(0,0,len(KOI_OCmins)),KOI_OCerrs) #k = 2
#BIC_curve = 2*np.log(len(KOI_OCmins)) + chisquare(KOI_OCmins, sinecurve(KOI_epochs, *popt), KOI_OCerrs)
#BIC(nparams,data,model,error):
BIC_flat = BIC(nparams=0,data=KOI_OCmins,model=np.linspace(0,0,len(KOI_OCmins)),error=KOI_OCerrs) #k=0
BIC_curve = BIC(nparams=2, data=KOI_OCmins, model=sinecurve(KOI_epochs, *popt), error=KOI_OCerrs) # k = 2
AIC_flat = AIC(nparams=0,data=KOI_OCmins,model=np.linspace(0,0,len(KOI_OCmins)),error=KOI_OCerrs) #k=0
AIC_curve = AIC(nparams=2,data=KOI_OCmins,model=sinecurve(KOI_epochs, *popt), error=KOI_OCerrs) # k = 2
### we want BIC_curve to be SMALLER THAN BIC_flat, despite the penalty, for the SINE MODEL TO HOLD WATER.
#### SO IF THAT'S THE CASE, AND WE DO BIC_curve - BIC_flat, then delta-BIC will be negative, which is what we want.
deltaBIC = BIC_curve - BIC_flat
deltaAIC = AIC_curve - AIC_flat
#### NOW WE'LL DO EXACTLY AS ABOVE, BUT WITH THE CROSS-VALIDATION REMOVALS.
if cross_validate_LSPs == 'y':
#### lists to be used for evaluating the robustness of the periodogram results.
cv_best_periods = []
cv_deltaBICs = []
cv_deltaAICs = []
cv_amplitudes = []
cv_phases = []
cv_popts = []
cv_pcovs = []
ntoremove = int(cv_frac_to_leave_out*len(KOI_epochs))
if ntoremove < 1:
ntoremove = 1
cv_ntrials_this_time = len(KOI_epochs)
else:
cv_ntrials_this_time = cv_ntrials
for cv_trialnum in np.arange(0,cv_ntrials_this_time,1):
if ntoremove == 1:
idxs_to_leave_out = cv_trialnum ### make sure you leave out every point, one per trial
else:
idxs_to_leave_out = np.random.randint(low=0, high=len(KOI_epochs), size=ntoremove)
cv_KOI_epochs = np.delete(KOI_epochs, idxs_to_leave_out)
cv_KOI_OCmins = np.delete(KOI_OCmins, idxs_to_leave_out)
cv_KOI_OCerrs = np.delete(KOI_OCerrs, idxs_to_leave_out)
cv_LSperiods = np.logspace(np.log10(2), np.log10(500), 5000)
cv_LSfreqs = 1/cv_LSperiods
cv_LSpowers = LombScargle(cv_KOI_epochs, cv_KOI_OCmins, cv_KOI_OCerrs).power(cv_LSfreqs)
cv_peak_power_idx = np.nanargmax(cv_LSpowers)
cv_peak_power_period = cv_LSperiods[cv_peak_power_idx]
cv_peak_power_freq = 1/cv_peak_power_period
if cv_trialnum == 0:
cv_LSpowers_stack = cv_LSpowers
else:
cv_LSpowers_stack = np.vstack((cv_LSpowers_stack, cv_LSpowers))
def cv_sinecurve(tvals, amplitude, phase):
angfreq = 2 * np.pi * cv_peak_power_freq
sinewave = amplitude * np.sin(angfreq * tvals + phase)
return sinewave
#### NOW FIT THAT SUCKER
cv_popt, cv_pcov = curve_fit(cv_sinecurve, cv_KOI_epochs, cv_KOI_OCmins, sigma=cv_KOI_OCerrs, bounds=([0, -2*np.pi], [20*KOI_rms, 2*np.pi]))
cv_popts.append(cv_popt)
cv_pcovs.append(cv_pcov)
cv_amplitudes.append(cv_popt[0])
cv_phases.append(cv_popt[1])
#### calculate BIC and deltaBIC -- USE ALL THE DATAPOINTS!
#cv_BIC_flat = chisquare(KOI_OCmins, np.linspace(0,0,len(KOI_OCmins)),KOI_OCerrs) #k = 2
#cv_BIC_curve = 2*np.log(len(KOI_OCmins)) + chisquare(KOI_OCmins, sinecurve(KOI_epochs, *cv_popt), KOI_OCerrs)
cv_BIC_flat = BIC(nparams=0,data=KOI_OCmins,model=np.linspace(0,0,len(KOI_OCmins)),error=KOI_OCerrs)
cv_BIC_curve = BIC(nparams=2,data=KOI_OCmins,model=sinecurve(KOI_epochs, *cv_popt),error=KOI_OCerrs)
cv_deltaBIC = cv_BIC_curve - cv_BIC_flat
cv_AIC_flat = AIC(nparams=0,data=KOI_OCmins,model=np.linspace(0,0,len(KOI_OCmins)),error=KOI_OCerrs)
cv_AIC_curve = AIC(nparams=2,data=KOI_OCmins,model=sinecurve(KOI_epochs, *cv_popt),error=KOI_OCerrs)
cv_deltaAIC = cv_AIC_curve - cv_AIC_flat
cv_best_periods.append(cv_peak_power_period)
cv_deltaBICs.append(cv_deltaBIC)
cv_deltaAICs.append(cv_deltaAIC)
#### now compute the median and std for period fits, and the same for the deltaBIC
cv_best_periods, cv_deltaBICs, cv_deltaAICs = np.array(cv_best_periods), np.array(cv_deltaBICs), np.array(cv_deltaAICs)
cv_period_skew, cv_period_kurtosis = skew(cv_best_periods), kurtosis(cv_best_periods)
cv_amplitudes, cv_phases = np.array(cv_amplitudes), np.array(cv_phases)
cv_best_period_median, cv_best_period_std = np.nanmedian(cv_best_periods), np.nanstd(cv_best_periods)
cv_period_pct_error = cv_best_period_std / cv_best_period_median
cv_deltaBICs_median, cv_deltaBICs_std = np.nanmedian(cv_deltaBICs), np.nanstd(cv_deltaBICs)
cv_deltaAICs_median, cv_deltaAICs_std = np.nanmedian(cv_deltaAICs), np.nanstd(cv_deltaAICs)
cv_amplitude_median, cv_amplitude_std = np.nanmedian(cv_amplitudes), np.nanstd(cv_amplitudes)
cv_amplitude_pct_error = cv_amplitude_std / cv_amplitude_median
cv_phase_median, cv_phase_std = np.nanmedian(cv_phases), np.nanstd(cv_phases)
#phase_pct_error = np.abs(cv_phase_std / cv_phase_median)
cv_phase_pct_error = cv_phase_std / (2*np.pi) #### SHOULD NOT BE A FRACTION OF THE VALUE! IT SHOULD BE A FRACTION OF THE CIRCLE!!!
print('PTTV = '+str(cv_best_period_median)+' +/- '+str(cv_best_period_std))
print('PTTV pct error = ', str(cv_period_pct_error*100))
print("PTTV Skew, Kurtosis = ", str(cv_period_skew), str(cv_period_kurtosis))
print('ATTV = '+str(cv_amplitude_median)+' +/- '+str(cv_amplitude_std))
print('ATTV pct error = ', str(cv_amplitude_pct_error*100))
print('Phase = '+str(cv_phase_median)+' +/- '+str(cv_phase_std))
print('Phase pct error = ', str(cv_phase_pct_error*100))
print("deltaBIC = "+str(cv_deltaBICs_median)+' +/- '+str(cv_deltaBICs_std))
print("deltaAIC = "+str(cv_deltaAICs_median)+' +/- '+str(cv_deltaAICs_std))
print(' ')
crossval_resultsfile = open('/data/tethys/Documents/Projects/NMoon_TTVs/'+PTTV_resultsname, mode='a')
#crossval_resultsfile.write('KOI,n_crossval_trials,n_epochs,n_removed,PTTV_median,PTTV_std,PTTV_skew,PTTV_kurtosis,PTTV_pcterr,ATTV_median,ATTV_std,ATTV_pcterr,phase_median,phase_std,phase_pcterr,deltaBIC,deltaBIC_std\n')
crossval_resultsfile.write(str(kepoi)+','+str(cv_ntrials_this_time)+','+str(len(KOI_epochs))+','+str(ntoremove)+','+str(cv_best_period_median)+','+str(cv_best_period_std)+','+str(cv_period_skew)+','+str(cv_period_kurtosis)+','+str(cv_period_pct_error*100)+','+str(cv_amplitude_median)+','+str(cv_amplitude_std)+','+str(cv_amplitude_pct_error*100)+','+str(cv_phase_median)+','+str(cv_phase_std)+','+str(cv_phase_pct_error*100)+','+str(cv_deltaBICs_median)+','+str(cv_deltaBICs_std)+','+str(cv_deltaAICs_median)+','+str(cv_deltaAICs_std)+'\n')
crossval_resultsfile.close()
if show_plots == 'y':
#### THIS IS THE FULL DATA FIT FROM ABOVE -- NO LEAVING OUT DATA.
KOI_epochs_interp = np.linspace(np.nanmin(KOI_epochs), np.nanmax(KOI_epochs), 1000)
KOI_TTV_interp = sinecurve(KOI_epochs_interp, *popt)
plt.scatter(KOI_epochs, KOI_OCmins, facecolor='LightCoral', edgecolor='k', alpha=0.7, zorder=2)
plt.errorbar(KOI_epochs, KOI_OCmins, yerr=KOI_OCerrs, ecolor='k', fmt='none', zorder=1, alpha=0.2)
plt.plot(KOI_epochs_interp, KOI_TTV_interp, color='k', linestyle='--', linewidth=2, alpha=0.2)
if cross_validate_LSPs == 'y':
for cv_popt in cv_popts:
cv_KOI_TTV_interp = cv_sinecurve(KOI_epochs_interp, *cv_popt)
plt.plot(KOI_epochs_interp, cv_KOI_TTV_interp, color='k', linestyle='--', linewidth=2, alpha=0.2)
plt.plot(KOI_epochs, np.linspace(0,0,len(KOI_epochs)), color='k', linestyle=':', alpha=0.5, zorder=0)
plt.xlabel("epoch")
plt.ylabel('O - C [min]')
plt.title('KOI-'+str(kepoi))
plt.show()
####### END CROSS-VALIDATION TEST #################################################
###### FOR PLANETS WITH DISCERNIBLE TTVs, INCLUDE THEM IN THESE LISTS. --
######## SCREEN BY WHETHER OR NOT THEY MEET YOUR CROSS-VALIDATION STANDARD, AS WELL.
if cross_validate_LSPs == 'y':
if (cv_period_pct_error <= 5) and (cv_amplitude_pct_error <= 5) and (cv_phase_pct_error <=5):
good_cv = 'y'
else:
good_cv = 'n'
elif cross_validate_LSPs == 'n':
if use_Holczer_or_gose == 'h':
if (holczer_cv_period_pct_error <= 5) and (holczer_cv_amplitude_pct_error <= 5) and (holczer_cv_phase_pct_error <= 5):
good_cv = 'y'
else:
good_cv = 'n'
elif use_Holczer_or_gose == 'g':
if (TKS_cv_period_pct_error <= 5) and (TKS_cv_amplitude_pct_error <= 5) and (TKS_cv_phase_pct_error <= 5):
good_cv = 'y'
else:
good_cv = 'n'
if deltaBIC <= -2:
print('GOOD delta-BIC.')
else:
print('BAD delta-BIC.')
if deltaAIC < 0:
print('GOOD delta-AIC.')
else:
print("BAD delta-AIC.')")
if good_cv == 'y':
print('Good cross-validation.')
else:
print('BAD cross-validation.')
#### FINAL SAMPLE
if ((use_BIC_or_AIC.lower() == 'b') and (deltaBIC <= -2) and (good_cv == 'y') and (peak_power_period != 2.0)) or ((use_BIC_or_AIC.lower() == 'a') and (deltaAIC < 0) and (good_cv == 'y') and (peak_power_period != 2)):
#if (deltaBIC <= -2) and (good_cv == 'y'):
print('including this system.')
radii.append(kepler_radius_rearth[nkepoi])
radii_errors.append(kepler_radius_rearth_err[nkepoi])
stellar_masses.append(kepler_solar_mass[nkepoi])
stellar_masses_errors.append(kepler_solar_mass_err[nkepoi])
P_TTVs.append(peak_power_period)
P_plans.append(kepoi_period)
#if use_BIC_or_AIC.lower() == 'b':
#amplitude = np.nanmax(np.abs(BIC_curve)) #### WTF WAS THIS?
#amplitude = np.nanmax(np.abs(sinecurve(KOI_epochs, *popt)))
amplitude = popt[0] ##### first parameter is amplitude
TTV_amplitudes_min.append(amplitude)
median_timing_errors.append(np.nanmedian(KOI_OCerrs))
Pip1_over_Pis.append(kepoi_multi_Pip1_over_Pis)
Pi_over_Pim1s.append(kepoi_multi_Pi_over_Pim1s)
forecast_masses.append(forecast_mass)
forecast_masses_uperr.append(forecast_mass_uperr)
forecast_masses_lowerr.append(forecast_mass_lowerr)
deltaBICs.append(deltaBIC)
deltaAICs.append(deltaAIC)
if 'KOI-'+kepoi in HL_KOIs:
in_HLcatalog_idxs.append(entrynum)
else:
notin_HLcatalog_idxs.append(entrynum)
if kepoi_multi[nkepoi] == True:
multi_idxs.append(entrynum)
elif kepoi_multi[nkepoi] == False:
single_idxs.append(entrynum)
#### CROSS-VALIDATION LISTS
if cross_validate_LSPs == 'y':
cv_PTTV_pcterrs.append(cv_period_pct_error)
cv_ATTV_pcterrs.append(cv_amplitude_pct_error)
cv_phase_pcterrs.append(cv_phase_pct_error)
elif (cross_validate_LSPs == 'n') and (use_Holczer_or_gose == 'h') and (loaded_holczer_crossvalfile == 'y'):
cv_PTTV_pcterrs.append(holczer_cv_period_pct_error)
cv_ATTV_pcterrs.append(holczer_cv_amplitude_pct_error)
cv_phase_pcterrs.append(holczer_cv_phase_pct_error)
elif (cross_validate_LSPs == 'n') and (use_Holczer_or_gose == 'g') and (loaded_TKS_crossvalfile == 'y'):
cv_PTTV_pcterrs.append(TKS_cv_period_pct_error)
cv_ATTV_pcterrs.append(TKS_cv_amplitude_pct_error)
cv_phase_pcterrs.append(TKS_cv_phase_pct_error)
entrynum += 1 #### advance the number of entries.
print(' ')
except:
traceback.print_exc()
time.sleep(5)
################## CONVERT LISTS TO ARRAYS ###################################
multi_idxs = np.array(multi_idxs)
single_idxs = np.array(single_idxs)
print('# singles , # multis = ', len(single_idxs), len(multi_idxs))
print('# in HL , # not in HL = ', len(in_HLcatalog_idxs), len(notin_HLcatalog_idxs))
in_HLcatalog_idxs = np.array(in_HLcatalog_idxs)
notin_HLcatalog_idxs = np.array(notin_HLcatalog_idxs)
notin_HLcatalog_single_idxs = np.intersect1d(single_idxs, notin_HLcatalog_idxs)
notin_HLcatalog_multi_idxs = np.intersect1d(multi_idxs, notin_HLcatalog_idxs)
single_notHL_idxs = np.intersect1d(notin_HLcatalog_idxs, single_idxs)
multi_notHL_idxs = np.intersect1d(notin_HLcatalog_idxs, multi_idxs)
multi_HL_idxs = np.intersect1d(in_HLcatalog_idxs, multi_idxs) #### should be the same as in_HLcatalog_idxs
TTV_amplitudes_min = np.array(TTV_amplitudes_min)
median_timing_errors = np.array(median_timing_errors)
forecast_masses, forecast_masses_uperr, forecast_masses_lowerr = np.array(forecast_masses), np.array(forecast_masses_uperr), np.array(forecast_masses_lowerr)
#### replace all forecast_masses == 0.0 with np.nan!
forecast_masses[np.where(forecast_masses == 0.0)[0]] = np.nan
P_TTVs = np.array(P_TTVs)
P_plans = np.array(P_plans)
P_plans_minutes = P_plans * 24 * 60
radii = np.array(radii)
radii_errors = np.array(radii_errors)
stellar_masses = np.array(stellar_masses)
stellar_masses_errors = np.array(stellar_masses_errors)
stellar_masses_mearth = (stellar_masses * M_sun) / M_earth
cv_PTTV_pcterrs = np.array(cv_PTTV_pcterrs)
cv_ATTV_pcterrs = np.array(cv_ATTV_pcterrs)
cv_phase_pcterrs = np.array(cv_phase_pcterrs)
deltaBICs = np.array(deltaBICs)
deltaAICs = np.array(deltaAICs)
#### CUT BASED ON A BETTER THAN 5% ERROR ON PERIOD, AMPLITUDE AND PHASE ACROSS ALL SOLUTIONS.
good_PTTV_pcterr_idxs = np.where(cv_PTTV_pcterrs <= 5)[0]
good_ATTV_pcterr_idxs = np.where(cv_ATTV_pcterrs <= 5)[0]
good_phase_pcterr_idxs = np.where(cv_phase_pcterrs <= 5)[0]
good_cv_pcterr_idxs = np.intersect1d(good_PTTV_pcterr_idxs, good_ATTV_pcterr_idxs)
good_cv_pcterr_idxs = np.intersect1d(good_cv_pcterr_idxs, good_phase_pcterr_idxs)
#### COMPUTE THE MINIMUM fraction of the Hill sphere.
fmin = np.vectorize(fmin)
fmins_vals = fmin(forecast_masses, stellar_masses_mearth.value, TTV_amplitudes_min, P_plans_minutes)
fmins, fmin_vars = fmins_vals[0], fmins_vals[1:]
possible_moon_fmin_idxs = np.where(fmins < 1.0)[0]
impossible_moon_fmin_idxs = np.where(fmins >= 1.0)[0]
highest_mass = np.nanmax(forecast_masses)
normalized_masses = forecast_masses / highest_mass
amplitudes_div_masses = TTV_amplitudes_min / normalized_masses
#########################################
## P L O T T I N G ######################
#########################################
##### NEW PLOT -- MARCH 2021 -- LOOK AT THE TTV AMPLITUDES AS A FUNCTION OF TIMING ERRORS
plt.scatter(median_timing_errors, TTV_amplitudes_min, facecolor='DodgerBlue', edgecolor='k', s=20, alpha=0.7)
plt.xlabel('Median Timing Error [seconds]')
plt.ylabel("Measured TTV amplitude [seconds]")
plt.show()
#### PLOT fmins vs P_plans for the multis in and not in the HL2017 catalog.
fig = plt.figure(figsize=(6,8))
ax = plt.subplot(111)
plt.scatter(P_plans[notin_HLcatalog_single_idxs], fmins[notin_HLcatalog_single_idxs], facecolor='green', edgecolor='k', s=20, alpha=0.5, label='single non-HL2017')
plt.scatter(P_plans[notin_HLcatalog_multi_idxs], fmins[notin_HLcatalog_multi_idxs], facecolor='DodgerBlue', edgecolor='k', s=20, alpha=0.5, label='multi non-HL2017')
plt.scatter(P_plans[in_HLcatalog_idxs], fmins[in_HLcatalog_idxs], facecolor='LightCoral', edgecolor='k', s=20, alpha=0.5, label='multi HL2017')
plt.plot(np.linspace(np.nanmin(P_plans), np.nanmax(P_plans), 100), np.linspace(0.4895, 0.4895, 100), c='k', linestyle='--', linewidth=2)
plt.fill_between(np.linspace(np.nanmin(P_plans), np.nanmax(P_plans), 100), 1e-5, 0.4895, color='green', alpha=0.1)
plt.fill_between(np.linspace(np.nanmin(P_plans), np.nanmax(P_plans), 100), 0.4895, 1e5, color='red', alpha=0.1)
plt.ylim(np.nanmin(fmins), np.nanmax(fmins))
plt.xlim(np.nanmin(P_plans), np.nanmax(P_plans))
plt.xlabel(r'$P_{\mathrm{P}}$ [days]')
plt.ylabel(r'minimum fraction $R_{\mathrm{Hill}}$')
plt.xscale('log')
plt.yscale('log')
plt.legend()
plt.subplots_adjust(left=0.125, bottom=0.09, right=0.9, top=0.95, wspace=0.2, hspace=0.2)
plt.savefig('/data/tethys/Documents/Projects/NMoon_TTVs/Plots/min_frac_Rhill_vs_Pplan.pdf', dpi=300)
plt.savefig('/data/tethys/Documents/Projects/NMoon_TTVs/Plots/min_frac_Rhill_vs_Pplan.png', dpi=300)
plt.show()
#### PLOT fmins vs P_TTVs! for the multis in and not in the HL2017 catalog. DOES THIS SHOW ANYTHING?!
fig = plt.figure(figsize=(6,8))
ax = plt.subplot(111)
plt.scatter(P_TTVs[notin_HLcatalog_single_idxs], fmins[notin_HLcatalog_single_idxs], facecolor='green', edgecolor='k', s=20, alpha=0.5, label='single non-HL2017')
plt.scatter(P_TTVs[notin_HLcatalog_multi_idxs], fmins[notin_HLcatalog_multi_idxs], facecolor='DodgerBlue', edgecolor='k', s=20, alpha=0.5, label='multi non-HL2017')
plt.scatter(P_TTVs[in_HLcatalog_idxs], fmins[in_HLcatalog_idxs], facecolor='LightCoral', edgecolor='k', s=20, alpha=0.5, label='multi HL2017')
plt.plot(np.linspace(np.nanmin(P_TTVs), np.nanmax(P_TTVs), 100), np.linspace(0.4895, 0.4895, 100), c='k', linestyle='--', linewidth=2)
plt.fill_between(np.linspace(np.nanmin(P_TTVs), np.nanmax(P_TTVs), 100), 1e-5, 0.4895, color='green', alpha=0.1)
plt.fill_between(np.linspace(np.nanmin(P_TTVs), np.nanmax(P_TTVs), 100), 0.4895, 1e5, color='red', alpha=0.1)
plt.ylim(np.nanmin(fmins), np.nanmax(fmins))
plt.xlim(np.nanmin(P_plans), np.nanmax(P_plans))
plt.xlabel(r'$P_{\mathrm{TTV}}$ [epochs]')
plt.ylabel(r'minimum fraction $R_{\mathrm{Hill}}$')
plt.xscale('log')
plt.yscale('log')
plt.legend()
plt.subplots_adjust(left=0.125, bottom=0.09, right=0.9, top=0.95, wspace=0.2, hspace=0.2)
plt.show()
####### PLOT ATTV vs Pplan for single and multis
fig = plt.figure(figsize=(6,8))
ax = plt.subplot(111)
plt.scatter(P_plans[notin_HLcatalog_single_idxs], TTV_amplitudes_min[notin_HLcatalog_single_idxs], facecolor='green', edgecolor='k', s=20, alpha=0.5, label='single non-HL2017')
plt.scatter(P_plans[notin_HLcatalog_multi_idxs], TTV_amplitudes_min[notin_HLcatalog_multi_idxs], facecolor='DodgerBlue', edgecolor='k', s=20, alpha=0.5, label='multi non-HL2017')
plt.scatter(P_plans[in_HLcatalog_idxs], TTV_amplitudes_min[in_HLcatalog_idxs], facecolor='LightCoral', edgecolor='k', s=20, alpha=0.5, label='multi HL2017')
plt.xlabel(r'$P_{\mathrm{P}}$ [days]')
plt.ylabel('TTV amplitude [s]')
plt.yscale('log')
plt.xscale('log')
plt.legend()
plt.subplots_adjust(left=0.125, bottom=0.09, right=0.9, top=0.95, wspace=0.2, hspace=0.2)
plt.show()
######### PLOT ATTV vs PTTV for singles and multis
plt.scatter(TTV_amplitudes_min[notin_HLcatalog_single_idxs], P_TTVs[notin_HLcatalog_single_idxs], facecolor='green', edgecolor='k', s=20, alpha=0.5, label='single non-HL2017')
plt.scatter(TTV_amplitudes_min[notin_HLcatalog_multi_idxs], P_TTVs[notin_HLcatalog_multi_idxs], facecolor='DodgerBlue', edgecolor='k', s=20, alpha=0.5, label='multi non-HL2017')
plt.scatter(TTV_amplitudes_min[in_HLcatalog_idxs], P_TTVs[in_HLcatalog_idxs], facecolor='LightCoral', edgecolor='k', s=20, alpha=0.5, label='multi HL2017')
plt.ylabel(r'$P_{\mathrm{TTV}}$ [epochs]')
plt.xlabel('TTV amplitude [s]')
plt.yscale('log')
plt.xscale('log')
plt.legend()
plt.show()
########### PLOT PTTV vs Pplan for singles and multis (not in HL2017)
"""
plt.scatter(P_plans[notin_HLcatalog_single_idxs], P_TTVs[notin_HLcatalog_single_idxs], facecolor='green', edgecolor='k', s=20, alpha=0.5, label='single non-HL2017')
plt.scatter(P_plans[notin_HLcatalog_multi_idxs], P_TTVs[notin_HLcatalog_multi_idxs], facecolor='DodgerBlue', edgecolor='k', s=20, alpha=0.5, label='multi non-HL2017')
plt.scatter(P_plans[in_HLcatalog_idxs], P_TTVs[in_HLcatalog_idxs], facecolor='LightCoral', edgecolor='k', s=20, alpha=0.5, label='multi HL2017')
plt.xlabel(r'$P_{\mathrm{P}}$ [days]')
plt.ylabel(r'$P_{\mathrm{TTV}}$ [epochs]')
plt.yscale('log')
plt.xscale('log')
plt.legend()
plt.show()
"""
#### PTTV vs PPLAN BINS FOR HEATMAPS BELOW
xbins = np.logspace(np.log10(10), np.log10(1500), 20) #### consistent with the simulation
ybins = np.logspace(np.log10(2), np.log10(100), 20) #### consistent with the simulation
xcenters, ycenters = [], []
for nxb,xb in enumerate(xbins):
try:
xcenters.append(np.nanmean((xbins[nxb+1], xbins[nxb])))
except:
pass
for nyb, yb in enumerate(ybins):
try:
ycenters.append(np.nanmean((ybins[nyb+1], ybins[nyb])))
except:
pass
xcenters, ycenters = np.array(xcenters), np.array(ycenters)
##### PTTV vs Pplan HEATMAP OF *EVERYTHING* -- SINGLES AND MULTIS###############
"""
TTV_Pplan_hist2d = np.histogram2d(P_plans, P_TTVs, bins=[xbins, ybins])
plt.imshow(TTV_Pplan_hist2d[0].T, origin='lower', cmap=cm.coolwarm)
plt.xticks(ticks=np.arange(0,len(xbins),5), labels=np.around(np.log10(xbins[::5]),2))
plt.yticks(ticks=np.arange(0,len(ybins),5), labels=np.around(np.log10(ybins[::5]), 2))
plt.xlabel(r'$\log_{10} \, P_{\mathrm{P}}$ [days]')