-
Notifications
You must be signed in to change notification settings - Fork 2
/
population_eos_posteriors_emcee.py
1097 lines (907 loc) · 37.7 KB
/
population_eos_posteriors_emcee.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
import numpy as np
import numpy.random as npr
import bilby
import bilby.gw.conversion as bc
import matplotlib.pyplot as mp
import matplotlib.cm as mpcm
import matplotlib.colors as mpc
import os
import os.path as osp
import errno
import getdist as gd
import getdist.plots as gdp
import corner
import copy
import lalsimulation as lalsim
import sys
import sklearn.decomposition as skd
#import matplotlib
#matplotlib.use('TkAgg')
def comp_masses_to_chirp_q(m_1, m_2):
m_c = (m_1 * m_2) ** 0.6 / (m_1 + m_2) ** 0.2
q_inv = m_2 / m_1
return m_c, q_inv
def chirp_q_to_comp_masses(m_c, q_inv):
q = 1.0 / q_inv
m_2 = (1 + q) ** 0.2 / q ** 0.6 * m_c
m_1 = q * m_2
return m_1, m_2
def prior_change_jac(m_c, q_inv):
d_m_1_d_m_c = (1.0 + q_inv) ** 0.2 / q_inv ** 0.6
d_m_2_d_m_c = (1.0 + q_inv) ** 0.2 * q_inv ** 0.4
d_m_1_d_q_inv = -(3.0 + 2.0 * q_inv) * m_c / 5.0 / \
q_inv ** 1.6 * (1.0 + q_inv) ** 0.8
d_m_2_d_q_inv = (2.0 + 3.0 * q_inv) * m_c / 5.0 / \
q_inv ** 0.6 * (1.0 + q_inv) ** 0.8
jac = np.abs(d_m_1_d_m_c * d_m_2_d_q_inv - \
d_m_1_d_q_inv * d_m_2_d_m_c)
return jac
def lalinf_adiabatic_index(gammas, x):
'''
Python version of AdiabaticIndex:
https://lscsoft.docs.ligo.org/lalsuite/lalinference/_l_a_l_inference_8c_source.html#l02608
'''
logGamma = 0.0
for i in range(len(gammas)):
logGamma += gammas[i] * (x ** i)
return np.exp(logGamma)
def lalinf_sd_gamma_check(gammas):
'''
Modified from LALInferenceSDGammaCheck, much faster than below:
https://lscsoft.docs.ligo.org/lalsuite/lalinference/_l_a_l_inference_8c_source.html#l02564
'''
p0 = 4.43784199e-13
xmax = 12.3081
pmax = p0 * np.exp(xmax)
ndat = 500
# Generating higher density portion of EOS with spectral decomposition
logpmax = np.log(pmax)
logp0 = np.log(p0)
dlogp = (logpmax-logp0) / float(ndat)
# Calculating pressure and adiabatic index table
for i in reversed(range(ndat)):
pdat = np.exp(logp0 + dlogp * i)
xdat = np.log(pdat / p0)
adat = lalinf_adiabatic_index(gammas, xdat)
if adat < 0.6 or adat > 4.5:
return False
return True
def lalinf_sd_gamma_check_slow(gammas):
'''
Python version of LALInferenceSDGammaCheck:
https://lscsoft.docs.ligo.org/lalsuite/lalinference/_l_a_l_inference_8c_source.html#l02564
'''
p0 = 4.43784199e-13
xmax = 12.3081
pmax = p0 * np.exp(xmax)
ndat = 500
pdats = np.zeros(ndat)
adats = np.zeros(ndat)
xdats = np.zeros(ndat)
# Generating higher density portion of EOS with spectral decomposition
logpmax = np.log(pmax)
logp0 = np.log(p0)
dlogp = (logpmax-logp0) / float(ndat)
# Calculating pressure and adiabatic index table
for i in range(ndat):
pdat = np.exp(logp0 + dlogp * i)
xdat = np.log(pdat / p0)
adat = lalinf_adiabatic_index(gammas, xdat)
pdats[i] = pdat
xdats[i] = xdat
adats[i] = adat
for i in range(ndat):
if adats[i] < 0.6 or adats[i] > 4.5:
return False
#mp.plot(xdats, adats)
#mp.show()
return True
def lal_inf_eos_physical_check(gammas, verbose=False):
'''
Python version of LALInferenceEOSPhysicalCheck:
https://lscsoft.docs.ligo.org/lalsuite/lalinference/_l_a_l_inference_8c_source.html#l02404
'''
# apply 0.6 < Gamma(p) < 4.5 constraint
if not lalinf_sd_gamma_check(gammas):
return False
else:
# create LAL EOS object
eos = lalsim.SimNeutronStarEOS4ParameterSpectralDecomposition(*gammas)
# ensure mass turnover doesn't happen too soon
mdat_prev = 0.0
logpmin = 75.5
logpmax = np.log(lalsim.SimNeutronStarEOSMaxPressure(eos))
dlogp = (logpmax - logpmin) / 100.0
for j in range(4):
# determine if maximum mass has been found
pdat = np.exp(logpmin + j * dlogp)
rdat, mdat, kdat = lalsim.SimNeutronStarTOVODEIntegrate(pdat, eos)
if mdat <= mdat_prev:
if verbose:
print('rejecting: too few EOS points', gammas)
return False
mdat_prev = mdat
# make EOS family, and calculate speed of sound and max
# and min mass allowed by EOS
fam = lalsim.CreateSimNeutronStarFamily(eos)
min_mass_kg = lalsim.SimNeutronStarFamMinimumMass(fam)
max_mass_kg = lalsim.SimNeutronStarMaximumMass(fam)
pmax = lalsim.SimNeutronStarCentralPressure(max_mass_kg, fam)
hmax = lalsim.SimNeutronStarEOSPseudoEnthalpyOfPressure(pmax, eos)
vsmax = lalsim.SimNeutronStarEOSSpeedOfSoundGeometerized(hmax, eos)
# apply constraints on speed of sound and maximum mass
if vsmax > c_s_max:
if verbose:
print('rejecting:', \
'sound speed {:4.2f} too high'.format(vsmax), \
gammas)
return False
if max_mass_kg < ns_mass_max_kg:
if verbose:
print('rejecting:', \
'max NS mass {:4.2f} too low'.format(max_mass_kg / m_sol_kg), \
gammas)
return False
return True
def lal_inf_sd_gammas_mass_to_lambda(gammas, mass_m_sol):
'''
Modified from LALInferenceSDGammasMasses2Lambdas:
https://lscsoft.docs.ligo.org/lalsuite/lalinference/_l_a_l_inference_8c_source.html#l02364
'''
# create EOS & family
eos = lalsim.SimNeutronStarEOS4ParameterSpectralDecomposition(*gammas)
fam = lalsim.CreateSimNeutronStarFamily(eos)
# calculate lambda(m|eos)
mass_kg = mass_m_sol * m_sol_kg
rad = lalsim.SimNeutronStarRadius(mass_kg, fam)
love = lalsim.SimNeutronStarLoveNumberK2(mass_kg, fam)
comp = big_g * mass_kg / (c ** 2) / rad
return 2.0 / 3.0 * love / comp ** 5
def lal_inf_sd_gammas_fam(gammas):
'''
Modified from LALInferenceSDGammasMasses2Lambdas:
https://lscsoft.docs.ligo.org/lalsuite/lalinference/_l_a_l_inference_8c_source.html#l02364
'''
# create EOS & family
eos = lalsim.SimNeutronStarEOS4ParameterSpectralDecomposition(*gammas)
fam = lalsim.CreateSimNeutronStarFamily(eos)
return fam
def lal_inf_sd_gammas_mass_to_lambda(fam, mass_m_sol):
'''
Modified from LALInferenceSDGammasMasses2Lambdas:
https://lscsoft.docs.ligo.org/lalsuite/lalinference/_l_a_l_inference_8c_source.html#l02364
'''
# calculate lambda(m|eos)
mass_kg = mass_m_sol * m_sol_kg
rad = lalsim.SimNeutronStarRadius(mass_kg, fam)
love = lalsim.SimNeutronStarLoveNumberK2(mass_kg, fam)
comp = big_g * mass_kg / (c ** 2) / rad
return 2.0 / 3.0 * love / comp ** 5
def emcee_log_prior(gammas):
# check gammas are in appropriate range
for i in range(n_inds):
if gammas[i] < prior_ranges[i][0] or \
gammas[i] > prior_ranges[i][1]:
return -np.inf
# check if physical using LAL code, which is much quicker
try:
is_phys = lal_inf_eos_physical_check(gammas)
except:
print('LAL error')
return -np.inf
if not is_phys:
return -np.inf
else:
return 0.0
def emcee_log_post(gammas):
# first call prior and immediately return if non-physical EOS
log_prior = emcee_log_prior(gammas)
if not np.isfinite(log_prior):
return log_prior
# calculate log-likelihood. this is a numerical integration
# over each merger's mass-lambda likelihood.
log_like = 0.0
n_grid = 1000 # @TODO: test this out. 100, 1000 and 10000 agree pretty well
lambdas = np.zeros(n_grid)
likes = np.zeros(n_grid)
# use gammas to define mass grid for integration
fam = lal_inf_sd_gammas_fam(gammas)
m_max_eos = lalsim.SimNeutronStarMaximumMass(fam) / m_sol_kg
masses = np.linspace(m_min_ns, m_max_eos * 0.99999999, n_grid)
# calculate lambdas on that grid
for j in range(n_grid):
lambdas[j] = lal_inf_sd_gammas_mass_to_lambda(fam, masses[j])
# loop over targets performing integrals
for k in range(n_targets):
for j in range(n_grid):
likes[j] = m_l_ns_posts[k](masses[j], lambdas[j])[0, 0]
# correct for -ve spline likelihoods and integrate
neg_like = likes < 0.0
likes[neg_like] = 0.0
integral = np.trapz(likes, masses)
log_like += np.log(integral)
# @TODO: mass prior volume effect!
# return log-posterior
return log_prior + log_like
def emcee_log_prior_wysocki(thetas):
# check projected gammas are in appropriate range
for i in range(n_inds):
if thetas[i] < gammas_rs_tf_min[i] * 1.1 or \
thetas[i] > gammas_rs_tf_max[i] * 1.1:
return -np.inf
# deproject
gammas = gammas_std * pca.inverse_transform(thetas) + \
gammas_mean
# check if physical using LAL code, which is much quicker
try:
is_phys = lal_inf_eos_physical_check(gammas)
except:
print('LAL error')
return -np.inf
if not is_phys:
return -np.inf
else:
return 0.0
def emcee_log_post_wysocki(thetas):
# evaluate prior within this function to save a second
# deprojection. first check projected gammas are in
# appropriate range
for i in range(n_inds):
if thetas[i] < gammas_rs_tf_min[i] * 1.1 or \
thetas[i] > gammas_rs_tf_max[i] * 1.1:
return -np.inf
# deproject
gammas = gammas_std * pca.inverse_transform(thetas) + \
gammas_mean
# check if physical using LAL code, which is much quicker
try:
is_phys = lal_inf_eos_physical_check(gammas)
except:
print('LAL error')
return -np.inf
if not is_phys:
return -np.inf
else:
log_prior = 0.0
# calculate log-likelihood. this is a numerical integration
# over each merger's mass-lambda likelihood.
log_like = 0.0
n_grid = 1000 # @TODO: test this out. 100, 1000 and 10000 agree pretty well
lambdas = np.zeros(n_grid)
likes = np.zeros(n_grid)
# use gammas to define mass grid for integration
fam = lal_inf_sd_gammas_fam(gammas)
m_max_eos = lalsim.SimNeutronStarMaximumMass(fam) / m_sol_kg
masses = np.linspace(m_min_ns, m_max_eos * 0.99999999, n_grid)
# calculate lambdas on that grid
for j in range(n_grid):
lambdas[j] = lal_inf_sd_gammas_mass_to_lambda(fam, masses[j])
# loop over targets performing integrals
for k in range(n_targets):
for j in range(n_grid):
likes[j] = m_l_ns_posts[k](masses[j], lambdas[j])[0, 0]
# correct for -ve spline likelihoods and integrate
neg_like = likes < 0.0
likes[neg_like] = 0.0
integral = np.trapz(likes, masses)
log_like += np.log(integral)
# @TODO: mass prior volume effect!
# return log-posterior
return log_prior + log_like
def dd2_lambda_from_mass(m):
return 1.60491e6 - 23020.6 * m**-5 + 194720. * m**-4 - 658596. * m**-3 \
+ 1.33938e6 * m**-2 - 1.78004e6 * m**-1 - 992989. * m + 416080. * m**2 \
- 112946. * m**3 + 17928.5 * m**4 - 1263.34 * m**5
# plot settings
lw = 1.5
mp.rc('font', family = 'serif')
mp.rcParams['text.latex.preamble'] = [r'\boldmath']
mp.rcParams['axes.linewidth'] = lw
mp.rcParams['lines.linewidth'] = lw
# fix a weird LaTeX bug with exponents
mp.rcParams['text.latex.preamble'] = r'\newcommand{\mathdefault}[1][]{}'
# constants
m_sol_kg = 1.988409902147041637325262574352366540e30 # LAL_MSUN_SI = LAL_GMSUN_SI / LAL_G_SI
lal_mrsun_si = 1.476625061404649406193430731479084713e3 # LAL_MRSUN_SI = LAL_GMSUN_SI / (LAL_C_SI * LAL_C_SI)
big_g = 6.67430e-11 # m^3/kg/s^2
c = 2.998e8 # m/s
log_zero = -1.0e10
# @TODO: incorporate maximum mass per EOS?
# needs some thinking. there's a maximum mass used in the
# initial sampling (which, in turn, is complicated by the
# fact we had to use M_c and q): this is the maximum mass
# specified in the prior. 1) if the EOS permits larger
# masses than this, should we alter the prior volume and
# normalization? 2) if the EOS's maximum mass is lower
# than the prior, we need to reject prior draws higher
# than the EOS's m_max. should we instead draw from an
# EOS-specific range each time? 3) do we need to adjust
# the prior volume each time?
# @TODO: KDE version
# @TODO: skip duff IMRPhenom run
# @TODO: store log prior separately
# @TODO: parallelize w/ MPI
# EOS inference settings
n_inds = 4
prior_ranges = [[0.2, 2.0], [-1.6, 1.7], [-0.6, 0.6], [-0.02, 0.02]]
c_s_max = 1.1
ns_mass_max_kg = 1.97 * m_sol_kg
reparam = True
emcee_sample = True
if emcee_sample:
import emcee
n_walkers = 2 * n_inds
else:
n_samples = 12 # 160 # @TODO: update w/ mass samples too
n_m_samples = 100
# data sample settings
use_mpi = False
snr_thresh = 12.0
duration = 32.0 # 8.0
sampling_frequency = 2048.
minimum_frequency = 20.0 # 40.0
reference_frequency = 14.0 # 50.0
min_network = False
if min_network:
ifo_list = ['H1', 'L1', 'V1', 'K1-']
else:
ifo_list = ['H1+', 'L1+', 'V1+', 'K1+', 'A1']
use_polychord = True
use_weighted_samples = True
imp_sample = True
if use_polychord:
n_live = 1000 # 500
else:
n_live = 1000
zero_spins = False
remnants_only = True
min_remnant_mass = 0.01
tight_loc = False
fixed_ang = True
sample_z = True
redshift_rate = True
uniform_bh_masses = True
uniform_ns_masses = True
low_metals = True
broad_bh_spins = True
seobnr_waveform = False
if seobnr_waveform:
waveform_approximant = 'SEOBNRv4_ROM_NRTidalv2_NSBH'
aligned_spins = True
else:
waveform_approximant = 'IMRPhenomPv2_NRTidal'
aligned_spins = False
lam_det_test = False
old = False
outdir = 'outdir'
support_thresh = 1.0e-3
# BH mass and spin prior limits
if uniform_bh_masses:
m_min_bh = 2.5
if low_metals:
m_max_bh = 40.0
else:
m_max_bh = 12.0
else:
m_min_bh = 5.0
m_max_bh = 20.0
spin_min_bh = 0.0
if broad_bh_spins:
spin_max_bh = 0.99
else:
spin_max_bh = 0.5
# NS mass and spin prior limits
m_min_ns = 1.0
if uniform_ns_masses:
m_max_ns = 2.42
else:
m_max_ns = 2.0
spin_min_ns = 0.0
spin_max_ns = 0.05
# conversions
m_c_min, _ = comp_masses_to_chirp_q(m_min_bh, m_min_ns)
m_c_max, _ = comp_masses_to_chirp_q(m_max_bh, m_max_ns)
_, q_inv_min = comp_masses_to_chirp_q(m_max_bh, m_min_ns)
_, q_inv_max = comp_masses_to_chirp_q(m_min_bh, m_max_ns)
# getdist settings
if old:
gd_ranges={'a_1':(0.0, 0.8), 'iota':(0.0, np.pi), \
'q':(0.02, 0.4), 'lambda_2':(0.0, 4000.0), \
'lambda_tilde':(0.0, None)}
else:
gd_ranges={'a_1':(spin_min_bh, spin_max_bh), \
'iota':(0.0, np.pi), \
'q':(q_inv_min, q_inv_max), \
'lambda_2':(0.0, 4500.0), \
'lambda_tilde':(0.0, None)}
# set up identical within-chain MPI processes
if use_mpi:
import mpi4py.MPI as mpi
n_procs = mpi.COMM_WORLD.Get_size()
rank = mpi.COMM_WORLD.Get_rank()
elif len(sys.argv) > 1:
if len(sys.argv) == 3:
n_procs = int(sys.argv[1])
rank = int(sys.argv[2])
if rank > n_procs or rank < 1:
exit('ERROR: 1 <= rank <= number of processes.')
rank -= 1
else:
exit('ERROR: please call using ' + \
'"python sim_nsbh_analysis.py <n_procs> <rank>" format ' + \
'to specify number of processes and rank without MPI. ' + \
'NB: rank should be one-indexed.')
else:
n_procs = 1
rank = 0
# set rank-specific random seed
npr.seed(221216 + rank * 10)
# filename stub
if ifo_list == ['H1', 'L1', 'V1']:
ifo_str = ''
else:
ifo_str = '_'.join(ifo_list) + '_'
label_str = 'nsbh_pop_' + ifo_str + \
'd_{:04.1f}_mf_{:4.1f}_rf_{:4.1f}'
if sample_z:
label_str += '_dndz'
if redshift_rate:
label_str += '_rr'
if uniform_bh_masses:
label_str += '_ubhmp_{:.1f}_{:.1f}'.format(m_min_bh, m_max_bh)
if uniform_ns_masses:
label_str += '_unsmp_{:.1f}_{:.1f}'.format(m_min_ns, m_max_ns)
if broad_bh_spins:
label_str += '_bbhsp'
if seobnr_waveform:
label_str += '_seobnr'
if aligned_spins:
label_str += '_aligned'
base_label = label_str.format(duration, minimum_frequency, \
reference_frequency)
# read injections from file
if old:
targets = np.genfromtxt('data/remnant_sorted_detected.txt', delimiter=' ')
target_ids = targets[:, 0].astype(int)
target_snrs = targets[:, 2]
if remnants_only:
target_ids = target_ids[targets[:, 1] > 0.0]
target_snrs = target_snrs[targets[:, 1] > 0.0]
else:
par_file = base_label + '.txt'
raw_pars = np.genfromtxt('data/' + par_file, \
dtype=None, names=True, delimiter=',', \
encoding=None)
det = raw_pars['snr'] >= snr_thresh
if remnants_only:
det = np.logical_and(det, raw_pars['remnant_mass'] > min_remnant_mass)
raw_pars = raw_pars[det]
ids = np.array([int(i_sim.split(':')[-1]) for i_sim in \
raw_pars['simulation_id']])
snrs = raw_pars['snr']
i_sort = np.argsort(snrs)[::-1]
target_snrs = snrs[i_sort]
target_ids = ids[i_sort]
target_iotas = raw_pars['inclination'][i_sort]
# useful grids in neutron star mass and lambda
m_ns_grid = np.linspace(m_min_ns, m_max_ns, 1000)
# loop over targets to read in the merger NS mass-lambda posteriors
n_targets = len(target_ids)
samples = []
truths = []
post_at_true_m_ns = []
m_ns_like_support = []
post_at_true_m_l_ns = []
m_l_ns_posts = []
skip = np.full(n_targets, False)
for i in range(n_targets):
# read in results file, which contains tonnes of info
label = base_label + '_inj_{:d}'.format(target_ids[i])
if use_polychord:
label = 'pc_' + label
if zero_spins:
label += '_zero_spins'
if tight_loc:
label += '_tight_loc'
elif fixed_ang:
label += '_fixed_ang'
if n_live != 1000:
label += '_nlive_{:04d}'.format(n_live)
res_file = label + '_result.json'
#print(osp.join(outdir, res_file))
if not osp.exists(osp.join(outdir, res_file)):
skip[i] = True
samples.append(None)
truths.append(None)
post_at_true_m_ns.append(None)
m_ns_like_support.append(None)
post_at_true_m_l_ns.append(None)
continue
result = bilby.result.read_in_result(filename=osp.join(outdir, res_file))
# NB: result.injection_parameters contains incorrect IMRPhenom iotas
# due to a bug in bilby!
all_pars = bc.generate_all_bns_parameters(result.injection_parameters)
truths.append([all_pars['mass_1'], \
all_pars['a_1'], 0.0, \
target_iotas[i], \
all_pars['luminosity_distance'], \
all_pars['mass_ratio'], \
all_pars['lambda_2'], \
all_pars['lambda_tilde'], \
all_pars['spin_1z'], \
all_pars['mass_2'], \
all_pars['mass_1_source'], \
all_pars['mass_2_source']])
# if sampling with polychord optionally use full, variable weight
# posterior samples: bilby takes the equal-weight posterior samples
# to build its result.posterior. there are no distance samples this
# way though!
if use_polychord and use_weighted_samples:
# set up required paramnames file
if aligned_spins:
template = 'nsbh_aligned_spins.paramnames'
else:
template = 'nsbh_precess_spins.paramnames'
gd_root = osp.join(outdir, osp.join('chains', label))
gd_pars = gd_root + '.paramnames'
#print(gd_pars)
if not osp.exists(gd_pars):
# prevent race conditions: can have all processes trying
# to create a symlink simultaneously, with the slow ones
# finding it's already been created despite not existing
# before this if statement
try:
os.symlink(template, gd_pars)
except OSError as e:
if e.errno != errno.EEXIST:
raise e
# read in samples and fill in derived parameters
gd_samples = gd.loadMCSamples(gd_root)
pars = gd_samples.getParams()
m_1, m_2 = chirp_q_to_comp_masses(pars.chirp_mass, \
pars.mass_ratio)
gd_samples.addDerived(m_1, name='mass_1', label=r'm_{\rm BH}')
gd_samples.addDerived(m_2, name='mass_2', label=r'm_{\rm NS}')
if aligned_spins:
gd_samples.addDerived(np.abs(pars.chi_1), name='a_1', label='a_1')
# optionally importance sample the input mass priors
if imp_sample:
# extract posterior samples relevant for reweighting
m_c_samples = pars.chirp_mass
q_inv_samples = pars.mass_ratio
m_1_samples, m_2_samples = \
chirp_q_to_comp_masses(m_c_samples, q_inv_samples)
# define importance weights. we want to convert from the
# prior we used to sample, which is uniform in chirp mass
# and mass to the prior we used to simulate, which is
# uniform in component masses. we technically used a different
# redshift prior too, but they're almost identical in practice.
# note that our sampling prior extends into regions where the
# component-mass prior is zero: apply tiny weights to these
# values
mass_weights = prior_change_jac(m_c_samples, q_inv_samples)
m_1_mask = np.logical_and(m_1_samples >= m_min_bh, \
m_1_samples <= m_max_bh)
m_2_mask = np.logical_and(m_2_samples >= m_min_ns, \
m_2_samples <= m_max_ns)
m12_mask = np.logical_and(m_1_mask, m_2_mask)
mass_weights *= m12_mask
mass_weights += ~m12_mask * 1.0e-10
weights = mass_weights / np.sum(mass_weights)
gd_samples.reweightAddingLogLikes(-np.log(weights))
# build up list of samples objects
samples.append(gd_samples)
else:
# test posterior is correctly sampled
distance_label = r'(d_L - d_L^{\rm true})/d_L^{\rm true}'
try:
delta_distance = \
(result.posterior.luminosity_distance - \
result.injection_parameters['luminosity_distance']) / \
result.injection_parameters['luminosity_distance']
except ValueError:
skip[i] = True
samples.append(None)
post_at_true_m_ns.append(None)
m_ns_like_support.append(None)
post_at_true_m_l_ns.append(None)
continue
# optionally importance sample the input mass priors
if imp_sample:
# extract posterior samples relevant for reweighting
m_c_samples = result.posterior.chirp_mass
q_inv_samples = result.posterior.mass_ratio
m_1_samples, m_2_samples = \
chirp_q_to_comp_masses(m_c_samples, q_inv_samples)
# define importance weights. we want to convert from the
# prior we used to sample, which is uniform in chirp mass
# and mass to the prior we used to simulate, which is
# uniform in component masses. we technically used a different
# redshift prior too, but they're almost identical in practice.
# note that our sampling prior extends into regions where the
# component-mass prior is zero: apply tiny weights to these
# values
mass_weights = prior_change_jac(m_c_samples, q_inv_samples)
m_1_mask = np.logical_and(m_1_samples >= m_min_bh, \
m_1_samples <= m_max_bh)
m_2_mask = np.logical_and(m_2_samples >= m_min_ns, \
m_2_samples <= m_max_ns)
m12_mask = np.logical_and(m_1_mask, m_2_mask)
mass_weights *= m12_mask
mass_weights += ~m12_mask * 1.0e-10
weights = mass_weights / np.sum(mass_weights)
else:
weights = np.ones(len(result.posterior.luminosity_distance))
weights /= np.sum(weights)
# convert to GetDist MCSamples object
if aligned_spins:
gd_samples = np.array([result.posterior.a_1, \
result.posterior.mass_1, \
delta_distance, \
result.posterior.iota, \
result.posterior.mass_ratio, \
result.posterior.lambda_2, \
result.posterior.lambda_tilde, \
result.posterior.chi_1, \
result.posterior.mass_2, \
result.posterior.mass_1_source, \
result.posterior.mass_2_source]).T
samples.append(gd.MCSamples(samples=gd_samples, \
names=['a_1', 'mass_1', \
'distance', 'iota', \
'q', 'lambda_2', \
'lambda_tilde', 'chi_1', \
'mass_2', 'mass_1_source', \
'mass_2_source'], \
labels=['a_1', r'm_{\rm BH}', \
distance_label, r'\iota', \
r'm_{\rm NS}/m_{\rm BH}', \
r'\Lambda_{\rm NS}', \
r'\tilde{\Lambda}', \
r'\chi_1', r'm_{\rm NS}', \
r'm_{\rm BH}^{\rm source}', \
r'm_{\rm NS}^{\rm source}'], \
ranges=gd_ranges, weights=weights))
else:
gd_samples = np.array([result.posterior.a_1, \
result.posterior.mass_1, \
delta_distance, \
result.posterior.iota, \
result.posterior.mass_ratio, \
result.posterior.lambda_2, \
result.posterior.lambda_tilde, \
result.posterior.spin_1z, \
result.posterior.mass_2, \
result.posterior.mass_1_source, \
result.posterior.mass_2_source]).T
samples.append(gd.MCSamples(samples=gd_samples, \
names=['a_1', 'mass_1', \
'distance', 'iota', \
'q', 'lambda_2', \
'lambda_tilde', 'chi_1', \
'mass_2', 'mass_1_source', \
'mass_2_source'], \
labels=['a_1', r'm_{\rm BH}', \
distance_label, r'\iota', \
r'm_{\rm NS}/m_{\rm BH}', r'\Lambda_{\rm NS}', \
r'\tilde{\Lambda}', \
r'\chi_1', r'm_{\rm NS}', \
r'm_{\rm BH}^{\rm source}', \
r'm_{\rm NS}^{\rm source}'], \
ranges=gd_ranges, weights=weights))
# extract m_ns and m_ns-Lambda_ns GetDist posteriors. use the
# former to determine the range of m_ns over which the
# likelihood has support, which we'll use for sampling EOSs.
# we'll use the 2D posteriors in the EOS inference itself.
m_ns_post = samples[-1].get1DDensity('mass_2')
m_ns_post_grid = m_ns_post.Prob(m_ns_grid)
i_support = np.where(m_ns_post_grid > support_thresh)
if i_support[0][0] == 0:
i_support_min = 0
else:
i_support_min = i_support[0][0] - 1
if i_support[0][-1] == len(m_ns_grid) - 1:
i_support_max = len(m_ns_grid) - 1
else:
i_support_max = i_support[0][-1] + 1
m_ns_like_support.append(np.array([m_ns_grid[i_support_min], \
m_ns_grid[i_support_max]]))
post_at_true_m_ns.append(m_ns_post.Prob(truths[-1][9])[0])
m_l_ns_post = samples[-1].get2DDensity('mass_2', 'lambda_2', \
normalized=False)
post_at_true_m_l_ns.append(m_l_ns_post(truths[-1][9], \
truths[-1][6])[0, 0])
m_l_ns_posts.append(m_l_ns_post)
# choose inference algorithm: emcee or MC integration
if emcee_sample:
# use Wysocki et al (2001.01747) reparametrization
if reparam:
# read from file
gammas = np.genfromtxt('data/ns_eos_sd_gammas_wysocki.txt', \
delimiter=',')
# rescale to ~unit normal, then PCA
gammas_mean = np.mean(gammas, axis=0)
gammas_std = np.std(gammas, axis=0)
gammas_rs = (gammas - gammas_mean) / gammas_std
pca = skd.PCA(n_components=n_inds)
pca.fit(gammas_rs)
# project gammas onto PCA basis to obtain bounds
gammas_rs_tf = pca.transform(gammas_rs)
gammas_rs_tf_min = np.min(gammas_rs_tf, axis=0)
gammas_rs_tf_max = np.max(gammas_rs_tf, axis=0)
# set up walker initial conditions. the official guidance is
# to initialize a tight ball of walkers near the ML solution.
# i've not implemented that here. the first set of commented
# lines are a small ball near the prior mean. the second spreads
# the walkers across the prior. when sampling the prior, the
# former gives hardly any non-physical EOSs but then takes time
# to spread across the range. the latter is well spread out
# from the start, but produces more non-physical EOSs.
# @TODO: could fit the true gammas, transform to the PCA space
# and initialize around there?
#mu = (gammas_rs_tf_min + gammas_rs_tf_max) / 2.0
#sigma = np.diag(((gammas_rs_tf_min - gammas_rs_tf_max) / 10.0) ** 2)
#gammas_0 = npr.multivariate_normal(mu, sigma, 10)
init_pars = np.zeros((n_walkers, n_inds))
for j in range(n_inds):
init_pars[:, j] = npr.uniform(gammas_rs_tf_min[j] * 1.1, \
gammas_rs_tf_max[j] * 1.1, \
n_walkers)
else:
# initialize walkers near prior mean. see comment above.
mu = np.array([1.0, 0.0, 0.0, 0.0])
sigma = np.diag([0.01, 0.01, 0.01, 0.001]) ** 2
init_pars = npr.multivariate_normal(mu, sigma, n_walkers)
# set up sampler
if reparam:
print('PCA sampling')
max_n_samples = 20000
sampler = emcee.EnsembleSampler(n_walkers, n_inds, \
emcee_log_post_wysocki)
else:
print('direct gamma sampling. this is probably a bad idea.')
max_n_samples = 100000
sampler = emcee.EnsembleSampler(n_walkers, n_inds, emcee_log_prior)
# sample, following emcee's monitoring and convergence example
# (https://emcee.readthedocs.io/en/stable/tutorials/monitor/).
# sample for up to max_n_samples iterations, checking convergence
# every max_n_samples / 1000 samples.
i_sample = 0
n_check = max(1, int(max_n_samples / 1000))
autocorr = np.empty(max_n_samples)
old_tau = np.inf
for sample in sampler.sample(init_pars, iterations=max_n_samples, \
progress=True):
# check convergence
if sampler.iteration % n_check:
continue
# Compute the autocorrelation time so far
# Using tol=0 means that we'll always get an estimate even
# if it isn't trustworthy
tau = sampler.get_autocorr_time(tol=0)
autocorr[i_sample] = np.mean(tau)
i_sample += 1
# Check convergence
converged = np.all(tau * 100 < sampler.iteration)
converged &= np.all(np.abs(old_tau - tau) / tau < 0.01)
if converged:
break
old_tau = tau
# store samples, reprojecting if necessary
samples = sampler.get_chain(flat=True)
if reparam:
gamma_samples = gammas_std * pca.inverse_transform(samples) + \
gammas_mean
else:
gamma_samples = samples
log_probs = sampler.get_log_prob(flat=True)
all_samples = np.concatenate((gamma_samples, log_probs[:, None]), axis=1)
print(all_samples.shape)
filename = osp.join(outdir, base_label + '_eos_emcee_samples.txt')
np.savetxt(filename, all_samples)
# plot convergence
n = n_check * np.arange(1, i_sample + 1)
y = autocorr[:i_sample]
fig, ax = mp.subplots(1, 1)
mp.plot(n, n / 100.0, "--k")
mp.plot(n, y)
#mp.xlim(0, n.max())
#mp.ylim(0, y.max() + 0.1 * (y.max() - y.min()))
mp.xlabel("number of steps")
mp.ylabel(r"mean $\hat{\tau}$")
filename = osp.join(outdir, base_label + '_eos_emcee_convergence.pdf')
fig.savefig(filename)
print(autocorr[:i_sample])
# corner plot
print(np.sum(np.isfinite(log_probs)))
fig = corner.corner(gamma_samples, plot_datapoints=True, \
plot_density=False, plot_contours=False)
filename = osp.join(outdir, base_label + '_eos_emcee_post.pdf')
fig.savefig(filename)
# @TODO: find out / fit for best gammas for DD2 for overlaying & init
# @TODO: multi-processing
exit()
else:
# draw potential SD EOSs
all_gammas = []
gammas = np.zeros(n_inds)
masses = np.zeros(n_targets)
n_samples_tot = n_samples * n_m_samples
pop_samples = np.zeros((n_inds + n_targets, n_samples_tot))
log_weights = np.zeros(n_samples_tot)