forked from COSMIC-PopSynth/COSMIC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1876 lines (1642 loc) · 60.8 KB
/
utils.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
# -*- coding: utf-8 -*-
# Copyright (C) Scott Coughlin (2017 - 2021)
#
# This file is part of cosmic.
#
# cosmic is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cosmic is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cosmic. If not, see <http://www.gnu.org/licenses/>.
"""`utils`
"""
import scipy
import numpy as np
import pandas as pd
import scipy.special as ss
import astropy.stats as astrostats
import warnings
import ast
import operator
import json
import itertools
import os.path
from configparser import ConfigParser
from .bse_utils.zcnsts import zcnsts
__author__ = "Katelyn Breivik <katie.breivik@gmail.com>"
__credits__ = [
"Scott Coughlin <scott.coughlin@ligo.org>",
"Michael Zevin <zevin@northwestern.edu>",
]
__all__ = [
"filter_bin_state",
"conv_select",
"mass_min_max_select",
"idl_tabulate",
"rndm",
"param_transform",
"dat_transform",
"dat_un_transform",
"knuth_bw_selector",
"error_check",
"check_initial_conditions",
"convert_kstar_evol_type",
"parse_inifile",
"pop_write",
"a_from_p",
"p_from_a",
"get_Z_from_FeH",
"get_FeH_from_Z",
"get_binfrac_of_Z",
"get_porb_norm",
"get_met_dep_binfrac"
]
def filter_bin_state(bcm, bpp, method, kstar1_range, kstar2_range):
"""Filter the output of bpp and bcm, where the kstar ranges
have already been selected by the conv_select module
Parameters
----------
bcm : `pandas.DataFrame`
bcm dataframe
bpp : `pandas.DataFrame`
bpp dataframe
method : `dict`,
one or more methods by which to filter the
bpp or bcm table, e.g. ``{'binary_state' : [0,1]}``;
This means you do *not* want to select the final state of the binaries in the bcm array
kstar1_range : `list`
list containing all kstar1 values to retain
kstar2_range : `list`
list containing all kstar2 values to retain
Returns
-------
bcm : `pandas.DataFrame`
filtered bcm dataframe
"""
_known_methods = ["binary_state", "timestep_conditions"]
if not set(method.keys()).issubset(set(_known_methods)):
raise ValueError(
"You have supplied an "
"unknown method to filter out "
"the bpp or bcm array. Known methods are "
"{0}".format(_known_methods)
)
for meth, use in method.items():
if meth == "binary_state":
bin_num_save = []
# in order to filter on binary state we need the last entry of the bcm array for each binary
bcm_last_entry = bcm.groupby("bin_num").last().reset_index()
# in order to find the properities of disrupted or systems
# that are alive today we can simply check the last entry in the bcm
# array for the system and see what its properities are today
bcm_0_2 = bcm_last_entry.loc[(bcm_last_entry.bin_state != 1)]
bin_num_save.extend(bcm_0_2.bin_num.tolist())
# in order to find the properities of merged systems
# we actually need to search in the BPP array for the properities
# of the objects right at merge because the bcm will report
# the post merge object only
bcm_1 = bcm_last_entry.loc[bcm_last_entry.bin_state == 1]
# We now find the product of the kstar range lists so we can match the
# merger_type column from the bcm array which tells us what objects
# merged
merger_objects_to_track = []
merger_objects_to_track.extend(
list(
map(
lambda x: "{0}{1}".format(
str(x[0]).zfill(2), str(x[1]).zfill(2)
),
list(itertools.product(kstar1_range, kstar2_range)),
)
)
)
merger_objects_to_track.extend(
list(
map(
lambda x: "{0}{1}".format(
str(x[0]).zfill(2), str(x[1]).zfill(2)
),
list(itertools.product(kstar2_range, kstar1_range)),
)
)
)
bin_num_save.extend(
bcm_1.loc[
bcm_1.merger_type.isin(merger_objects_to_track)
].bin_num.tolist()
)
bcm_last_entry = bcm_last_entry.loc[
bcm_last_entry.bin_num.isin(bin_num_save)
]
# this will tell use the binary state fraction of the systems with a certain final kstar type
# before we throw out certain binary states if a user requested that.
bin_state_fraction = bcm_last_entry.groupby("bin_state").tphys.count()
bin_states = []
for ii in range(3):
try:
bin_states.append(bin_state_fraction.loc[ii])
except Exception:
bin_states.append(0)
bin_state_fraction = pd.DataFrame([bin_states], columns=[0, 1, 2])
bcm = bcm.loc[
bcm.bin_num.isin(
bcm_last_entry.loc[bcm_last_entry.bin_state.isin(use)].bin_num
)
]
return bcm, bin_state_fraction
def conv_select(bcm_save, bpp_save, final_kstar_1, final_kstar_2, method, conv_lims):
"""Select bcm data for special convergence cases
Parameters
----------
bcm_save : `pandas.DataFrame`
bcm dataframe containing all saved bcm data
bpp_save : `pandas.DataFrame`
bpp dataframe containing all saved bpp data
final_kstar_1 : `list`
contains list of final primary kstars specified by user
final_kstar_2 : `list`
contains list of final primary kstars specified by user
method : `str`
stage in binary evolution to check convergence for
only one method may be supplied and they are specified
in the inifile
conv_lims : `dict`
dictionary where keys are convergence params and the
values are lists containing a [lo, hi] value to filter the
convergence param between
any non-specified convergence params will not be filtered
Returns
-------
conv_save : `pandas.DataFrame`
filtered dataframe containing binaries that fulfill
user-specified convergence criteria
"""
_known_methods = [
"formation",
"1_SN",
"2_SN",
"disruption",
"final_state",
"XRB_form",
]
if method not in _known_methods:
raise ValueError(
"You have supplied an "
"unknown method to filter the "
"bcm array for convergence. Known methods are "
"{0}".format(_known_methods)
)
if method == "formation":
# filter the bpp array to find the systems that match the user-specified
# final kstars
conv_save = bpp_save.loc[
((bpp_save.kstar_1.isin(final_kstar_1))
& (bpp_save.kstar_2.isin(final_kstar_2))
)
|
((bpp_save.kstar_1.isin(final_kstar_2))
& (bpp_save.kstar_2.isin(final_kstar_1))
)
]
# select the formation parameters
conv_save = conv_save.groupby("bin_num").first().reset_index()
elif method == "1_SN":
# select out the systems which will undergo a supernova
conv_sn_ind = bpp_save.loc[bpp_save.evol_type.isin([15.0, 16.0])].bin_num
# select out the systems which will produce the user specified final kstars
# and undergo a supernova
conv_sn_ind = bpp_save.loc[
(bpp_save.bin_num.isin(conv_sn_ind))
& (bpp_save.kstar_1.isin(final_kstar_1))
& (bpp_save.kstar_2.isin(final_kstar_2))
& (bpp_save.sep > 0)
].bin_num
# select out the values just before the supernova(e)
conv_sn = bpp_save.loc[
(bpp_save.bin_num.isin(conv_sn_ind))
& (bpp_save.evol_type.isin([15.0, 16.0]))
]
# make sure to select out only the first supernova
conv_save = conv_sn.groupby("bin_num").first().reset_index()
elif method == "2_SN":
# select out the systems which will undergo a supernova
conv_sn_ind = bpp_save.loc[bpp_save.evol_type.isin([15.0, 16.0])].bin_num
# select out the systems which will produce the user specified final kstars
# and undergo a supernova
conv_sn_ind = bpp_save.loc[
(bpp_save.bin_num.isin(conv_sn_ind))
& (bpp_save.kstar_1.isin(final_kstar_1))
& (bpp_save.kstar_2.isin(final_kstar_2))
& (bpp_save.sep > 0)
].bin_num
# select out the values just before the supernova(e)
conv_sn = bpp_save.loc[
(bpp_save.bin_num.isin(conv_sn_ind))
& (bpp_save.evol_type.isin([15.0, 16.0]))
]
# select out only the systems that go through 2 supernovae
conv_sn_2 = conv_sn.loc[conv_sn.groupby("bin_num").size() == 2]
# make sure to select out only the second supernova
conv_save = conv_sn_2.groupby("bin_num").nth(1).reset_index()
elif method == "disruption":
# filter the bpp array to find the systems that match the user-specified
# final kstars
conv_ind = bpp_save.loc[
(bpp_save.kstar_1.isin(final_kstar_1))
& (bpp_save.kstar_2.isin(final_kstar_2))
].bin_num.unique()
conv_save = bpp_save.loc[(bpp_save.bin_num.isin(conv_ind))]
# select out the parameters just before disruption
# first reset the index:
conv_save_reset = conv_save.reset_index()
# next select out the index for the disrupted systems using evol_type == 11
conv_save_reset_ind = conv_save_reset.loc[
conv_save_reset.evol_type == 11.0
].index
conv_save = conv_save_reset.iloc[conv_save_reset_ind]
elif method == "final_state":
# the bcm array is all that we need!
conv_save = bcm_save
elif method == "XRB_form":
# select out the systems which undergo a SN
conv_ind = bpp_save.loc[bpp_save.evol_type.isin([15.0, 16.0])].bin_num.unique()
conv_sn = bpp_save.loc[bpp_save.bin_num.isin(conv_ind)]
# select out systems when they first enter RLO after the 1st SN
conv_xrb = conv_sn.loc[
(conv_sn.kstar_1.isin(final_kstar_1))
& (conv_sn.kstar_2.isin(final_kstar_2))
& (conv_sn.RRLO_2 >= 1.0)
& (conv_sn.sep > 0)
]
conv_save = conv_xrb.groupby("bin_num").first().reset_index()
if conv_lims:
for key in conv_lims.keys():
filter_lo = conv_lims[key][0]
filter_hi = conv_lims[key][1]
conv_save_lim = conv_save.loc[conv_save[key] < filter_hi]
conv_lims_bin_num = conv_save_lim.loc[conv_save[key] > filter_lo].bin_num
else:
conv_lims_bin_num = conv_save.bin_num
return conv_save, conv_lims_bin_num
def pop_write(
dat_store,
log_file,
mass_list,
number_list,
bcm,
bpp,
initC,
conv,
kick_info,
bin_state_nums,
match,
idx,
):
"""Writes all the good stuff that you want to save from runFixedPop in a
single function
Parameters
----------
dat_store : `pandas HDFStore`
H5 file to write to
log_file : `file write`
log file to write to
mass_list : `list`
list containing the mass of the singles, mass of the binaries,
and mass of the stars
n_list : `list`
list containing the number of singles, number of binaries,
and number of stars
bcm : `pandas.DataFrame`
bcm array to write
bpp : `pandas.DataFrame`
bpp array to write
initCond : `pandas.DataFrame`
initCond array to write
conv : `pandas.DataFrame`
conv array to write
kick_info : `pandas.DataFrame`
kick_info array to write
bin_state_nums : `list`
contains the count of binstates 0,1,2
match : pandas.DataFrame
contains the match values for each conv_param
idx : `int`
contains the index of the bcm so we can pick up where we left off
if runFixedPop hits a wall time
Returns
-------
Nothing!
"""
m_keys = ["mass_singles", "mass_binaries", "mass_stars"]
n_keys = ["n_singles", "n_binaries", "n_stars"]
for m_write, m_key, n_write, n_key in zip(mass_list, m_keys, number_list, n_keys):
# save the total_sampled_mass so far
dat_store.append(m_key, pd.DataFrame([m_write]))
dat_store.append(n_key, pd.DataFrame([n_write]))
log_file.write("The total mass sampled so far is: {0}\n".format(mass_list[2]))
# Save the bcm dataframe
dat_store.append("bcm", bcm)
# Save the bpp dataframe
dat_store.append("bpp", bpp)
# Save the initial binaries
# ensure that the index corresponds to bin_num
dat_store.append("initCond", initC.set_index("bin_num", drop=False))
# Save the converging dataframe
dat_store.append("conv", conv)
# Save the converging dataframe
dat_store.append("kick_info", kick_info)
# Save number of systems in each bin state
dat_store.append("bin_state_nums", bin_state_nums)
# Save the matches
dat_store.append("match", match)
# Save the index
dat_store.append("idx", pd.DataFrame([idx]))
return
def a_from_p(p, m1, m2):
"""Computes the separation from orbital period with KEPLER III
Parameters
----------
p : float/array
orbital period [day]
m1 : float/array
primary mass [msun]
m2 : float/array
secondary mass [msun]
Returns
-------
sep : float/array
separation [rsun]
"""
p_yr = p / 365.25
sep_3 = p_yr ** 2 * (m1 + m2)
sep = sep_3 ** (1 / 3.0)
sep_rsun = sep * 215.032
return sep_rsun
def p_from_a(sep, m1, m2):
"""Computes separation from orbital period with kepler III
Parameters
----------
sep : float/array
separation [rsun]
m1 : float/array
primary mass [msun]
m2 : float/array
secondary mass [msun]
Returns
-------
p : float/array
orbital period [day]
"""
sep_au = sep / 215.032
p_2 = sep_au ** 3 / (m1 + m2)
p_day = (p_2 ** 0.5) * 365.25
return p_day
def calc_Roche_radius(M1, M2, A):
"""Get Roche lobe radius (Eggleton 1983)
Parameters
----------
M1 : float
Primary mass [any unit]
M2 : float
Secondary mass [any unit]
A : float
Orbital separation [any unit]
Returns
-------
Roche radius : float
in units of input 'A'
"""
q = M1 / M2
return (
A
* 0.49
* q ** (2.0 / 3.0)
/ (0.6 * q ** (2.0 / 3.0) + np.log(1.0 + q ** (1.0 / 3.0)))
)
def mass_min_max_select(kstar_1, kstar_2, **kwargs):
"""Select a minimum and maximum mass to filter out binaries in the initial
parameter sample to reduce the number of unneccessary binaries evolved
in BSE
Parameters
----------
kstar_1 : int, list
BSE stellar type for the primary
or minimum and maximum stellar types for the primary
kstar_2 : int, list
BSE stellar type for the secondary
or minimum and maximum stellar types for the secondary
Returns
-------
min_mass[0] : float
minimum primary mass for initial sample
max_mass[0] : float
maximum primary mass for initial sample
min_mass[1] : float
minimum secondary mass for initial sample
max_mass[1] : float
maximum secondary mass for initial sample
"""
primary_max = kwargs["m_max"] if "m_max" in kwargs.keys() else 150.0
secondary_max = kwargs["m_max"] if "m_max" in kwargs.keys() else 150.0
primary_min = kwargs["m1_min"] if "m1_min" in kwargs.keys() else 0.08
secondary_min = kwargs["m2_min"] if "m2_min" in kwargs.keys() else 0.08
if ((primary_min < 0.08) | (secondary_min < 0.08)):
warnings.warn("Tread carefully, BSE is not equipped to handle stellar masses less than 0.08 Msun!")
if primary_max > 150:
warnings.warn("Tread carefully, BSE is not equipped to handle stellar masses greater than 150 Msun!")
min_mass = [primary_min, secondary_min]
max_mass = [primary_max, secondary_max]
if len(kstar_1) == 1:
# there is a range of final kstar_1s to save
kstar_1_lo = kstar_1[0]
kstar_1_hi = kstar_1[0]
else:
kstar_1_lo = min(kstar_1)
kstar_1_hi = max(kstar_1)
if len(kstar_2) == 1:
# there is a range of final kstar_1s to save
kstar_2_lo = kstar_2[0]
kstar_2_hi = kstar_2[0]
else:
kstar_2_lo = min(kstar_2)
kstar_2_hi = max(kstar_2)
kstar_lo = [kstar_1_lo, kstar_2_lo]
kstar_hi = [kstar_1_hi, kstar_2_hi]
ii = 0
for k in kstar_lo:
if k == 14.0:
min_mass[ii] = 8.0
elif k == 13.0:
min_mass[ii] = 3.0
elif k == 12.0:
min_mass[ii] = 1.0
elif k == 11.0:
min_mass[ii] = 0.8
elif k == 10.0:
min_mass[ii] = 0.5
ii += 1
ii = 0
for k in kstar_hi:
if k == 13.0:
max_mass[ii] = 60.0
elif k == 12.0:
max_mass[ii] = 20.0
elif k == 11.0:
max_mass[ii] = 20.0
elif k == 10.0:
max_mass[ii] = 20.0
ii += 1
return min_mass[0], max_mass[0], min_mass[1], max_mass[1]
def idl_tabulate(x, f, p=5):
"""Function that replicates the IDL int_tabulated function
which performs a p-point integration on a tabulated set of data
Parameters
----------
x : array
tabulated x-value data
f : array
tabulated f-value data, same size as x
p : int
number of chunks to divide tabulated data into
Default: 5
Returns
-------
ret : float
Integration result
"""
def newton_cotes(x, f):
if x.shape[0] < 2:
return 0
rn = (x.shape[0] - 1) * (x - x[0]) / (x[-1] - x[0])
weights = scipy.integrate.newton_cotes(rn)[0]
return (x[-1] - x[0]) / (x.shape[0] - 1) * np.dot(weights, f)
ret = 0
for idx in range(0, x.shape[0], p - 1):
ret += newton_cotes(x[idx: idx + p], f[idx: idx + p])
return ret
def rndm(a, b, g, size):
r"""Power-law generator for pdf(x)\propto x^{g} for a<=x<=b
Parameters
----------
a : float
Minimum of range for power law
b : float
Maximum of range for power law
g : float
Index for power law
size : int
Number of data points to draw
Returns
-------
power : array
Array of data sampled from power law distribution with params
fixed by inputs
"""
r = np.random.random(size=size)
ag, bg = a ** (g + 1), b ** (g + 1)
return (ag + (bg - ag) * r) ** (1.0 / (g + 1))
def param_transform(dat):
"""Transforms a data set to limits between zero and one
Leaves some wiggle room on the edges of the data set
Parameters
----------
dat : array
array of data to transform between 0 and 1
Returns
-------
datTransformed : array
array of data with limits between 0 and 1
"""
datMax = max(dat)
datMin = min(dat)
datZeroed = dat - datMin
datTransformed = datZeroed / ((datMax - datMin))
if np.max(datTransformed) == 1.0:
datTransformed[datTransformed == 1.0] = 1 - 1e-6
if np.min(datTransformed) == 0.0:
datTransformed[datTransformed == 0.0] = 1e-6
return datTransformed
def dat_transform(dat, dat_list):
"""Transform a data set to have limits between zero and one using
param_transform, then transform to log space
Parameters
----------
dat " DataFrame
Data to transform to eventually perform KDE
dat_list : list
List of DataFrame columns to include in transformation
Returns
-------
dat_trans : array
Transformed data for columns in dat_list
"""
dat_trans = []
for column in dat_list:
dat_trans.append(ss.logit(param_transform(dat[column])))
dat_trans = np.vstack([dat_trans])
return dat_trans
def dat_un_transform(dat_sample, dat_set, dat_list):
"""Un-transform data that was transformed in dat_transform
Parameters
----------
dat_sample : array
Data sampled from kde generated with transformed data
dat_set : DataFrame
Un-transformed data (same as dat in dat_transform)
dat_list : list
List of DataFrame columns to include in transformation
Returns
-------
dat : array
Array of data sampled from kde that is transformed back to
bounds of the un-transformed data set the kde is generated from
"""
dat = []
dat_exp = ss.expit(dat_sample)
for ii, column in zip(range(len(dat_list)), dat_list):
dat_untrans = dat_exp[ii, :] * (
max(dat_set[column]) - min(dat_set[column])
) + min(dat_set[column])
dat.append(dat_untrans)
dat = np.vstack(dat)
return dat
def knuth_bw_selector(dat_list):
"""Selects the kde bandwidth using Knuth's rule implemented in Astropy
If Knuth's rule raises error, Scott's rule is used
Parameters
----------
dat_list : list
List of data arrays that will be used to generate a kde
Returns
-------
bw_min : float
Minimum of bandwidths for all of the data arrays in dat_list
"""
bw_list = []
for dat in dat_list:
try:
bw = astrostats.knuth_bin_width(dat)
except Exception:
print("Using Scott Rule!!")
bw = astrostats.scott_bin_width(dat)
bw_list.append(bw)
return np.mean(bw_list)
def get_Z_from_FeH(FeH, Z_sun=0.02):
"""
Converts from FeH to Z under the assumption that
all stars have the same abundance as the sun
Parameters
----------
FeH : array
Fe/H values to convert
Z_sun : float
solar metallicity
Returns
-------
Z : array
metallicities corresponding to Fe/H
"""
Z = 10**(FeH + np.log10(Z_sun))
return Z
def get_FeH_from_Z(Z, Z_sun=0.02):
"""
Converts from Z to FeH under the assumption that
all stars have the same abundance as the sun
Parameters
----------
Z : array
metallicities to convert to Fe/H
Z_sun : float
solar metallicity
Returns
-------
FeH : array
Fe/H corresponding to metallicities
"""
FeH = np.log10(Z) - np.log10(Z_sun)
return FeH
def get_binfrac_of_Z(Z):
'''
Calculates the theoretical binary fraction as a
function of metallicity. Following Moe+2019
Parameters
----------
Z : array
metallicity Z values
Returns
-------
binfrac : array
binary fraction values
'''
FeH = get_FeH_from_Z(Z)
FeH_low = FeH[np.where(FeH<=-1.0)]
FeH_high = FeH[np.where(FeH>-1.0)]
binfrac_low = -0.0648 * FeH_low + 0.3356
binfrac_high = -0.1977 * FeH_high + 0.2025
binfrac = np.append(binfrac_low, binfrac_high)
return binfrac
def get_porb_norm(Z, close_logP=4.0, wide_logP=6.0, binfrac_tot_solar=0.66, Z_sun=0.02):
'''Returns normalization constants to produce log normals consistent with Fig 19 of Moe+19
for the orbital period distribution
Parameters
----------
Z : array
metallicity values
close_logP : float
divding line beween close and intermediate orbits
wide_logP : float
dividing line between intermediate and wide orbits
binfrac_tot : float
integrated total binary fraction at solar metallicity
Returns
-------
norm_wide : float
normalization factor for kde for wide binaries
norm_close : float
normalization factor for kde for wide binaries
'''
from scipy.stats import norm
from scipy.integrate import trapz
from scipy.interpolate import interp1d
# fix to values used in Moe+19
logP_lo_lim=0
logP_hi_lim=9
log_P = np.linspace(logP_lo_lim, logP_hi_lim, 10000)
logP_pdf = norm.pdf(log_P, loc=4.9, scale=2.3)
# set up the wide binary fraction inflection point
norm_wide = binfrac_tot_solar/trapz(logP_pdf, log_P)
# set up the close binary fraction inflection point
FeHclose = np.linspace(-3.0, 0.5, 100)
fclose = -0.0648 * FeHclose + 0.3356
fclose[FeHclose > -1.0] = -0.1977 * FeHclose[FeHclose > -1.0] + 0.2025
Zclose = get_Z_from_FeH(FeHclose, Z_sun=Z_sun)
fclose_interp = interp1d(Zclose, fclose)
fclose_Z = fclose_interp(Z)
norm_close = fclose_Z/trapz(logP_pdf[log_P < close_logP], log_P[log_P < close_logP])
return norm_wide, norm_close
def get_met_dep_binfrac(met):
'''Returns a population-wide binary fraction consistent with
Moe+19 based on the supplied metallicity
Parameters
----------
met : float
metallicity of the population
Returns
-------
binfrac : float
binary fraction of the population based on metallicity
'''
logP_hi_lim = 9
logP_lo_lim = 0
wide_logP = 6
close_logP = 4
neval = 5000
from scipy.interpolate import interp1d
from scipy.integrate import trapz
from scipy.stats import norm
norm_wide, norm_close = get_porb_norm(met)
prob_wide = norm.pdf(np.linspace(wide_logP, logP_hi_lim, neval), loc=4.9, scale=2.3)*norm_wide
prob_close = norm.pdf(np.linspace(logP_lo_lim, close_logP, neval), loc=4.9, scale=2.3)*norm_close
slope = -(prob_close[-1] - prob_wide[0]) / (wide_logP - close_logP)
prob_intermediate = slope * (np.linspace(close_logP, wide_logP, neval) - close_logP) + prob_close[-1]
prob_interp_int = interp1d(np.linspace(close_logP, wide_logP, neval), prob_intermediate)
x_dat = np.hstack([np.linspace(logP_lo_lim, close_logP, neval),
np.linspace(close_logP, wide_logP, neval),
np.linspace(wide_logP, logP_hi_lim, neval),])
y_dat = np.hstack([prob_close, prob_interp_int(np.linspace(close_logP, wide_logP, neval)), prob_wide])
binfrac = trapz(y_dat, x_dat)/0.66 * 0.5
return float(np.round(binfrac, 2))
def error_check(BSEDict, SSEDict, filters=None, convergence=None, sampling=None):
"""Checks that values in BSEDict, SSEDict,filters, and convergence are viable"""
if not isinstance(BSEDict, dict):
raise ValueError("BSE flags must be supplied via a dictionary")
if not isinstance(SSEDict, dict):
raise ValueError("SSE flags must be supplied via a dictionary")
if filters is not None:
if not isinstance(filters, dict):
raise ValueError("Filters criteria must be supplied via a dictionary")
for option in ["binary_state", "timestep_conditions"]:
if option not in filters.keys():
raise ValueError(
"Inifile section filters must have option {0} supplied".format(
option
)
)
if convergence is not None:
if not isinstance(convergence, dict):
raise ValueError("Convergence criteria must be supplied via a dictionary")
for option in [
"pop_select",
"convergence_params",
"convergence_limits",
"match",
"apply_convergence_limits",
]:
if option not in convergence.keys():
raise ValueError(
"Inifile section convergence must have option {0} supplied".format(
option
)
)
if sampling is not None:
if not isinstance(sampling, dict):
raise ValueError("Sampling criteria must be supplied via a dictionary")
for option in ["sampling_method", "SF_start", "SF_duration", "metallicity", "keep_singles"]:
if option not in sampling.keys():
raise ValueError(
"Inifile section sampling must have option {0} supplied".format(
option
)
)
if ("qmin" not in sampling.keys()) & ("m2_min" not in sampling.keys()) & (sampling["sampling_method"] == 'independent'):
raise ValueError("You have not specified qmin or m2_min. At least one of these must be specified.")
# filters
if filters is not None:
flag = "binary_state"
if any(x not in [0, 1, 2] for x in filters[flag]):
raise ValueError(
"{0} needs to be a subset of [0,1,2] (you set it to {1})".format(
flag, filters[flag]
)
)
flag = "timestep_conditions"
if (type(filters[flag]) != str) and (type(filters[flag]) != list):
raise ValueError(
"{0} needs to either be a string like 'dtp=None' or a list of conditions like [['binstate==0', 'dtp=1.0']] (you set it to {1})".format(
flag, filters[flag]
)
)
# convergence
if convergence is not None:
flag = "convergence_limits"
if convergence[flag]:
for item, key in zip(convergence.items(), convergence.keys()):
if len(item) != 2:
raise ValueError(
"The value for key '{0:s}' needs to be a list of length 2, it is length: {1:i}".format(
key, len(item)
)