-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnltm_plot_utils_v4.py
More file actions
1896 lines (1709 loc) · 68.8 KB
/
nltm_plot_utils_v4.py
File metadata and controls
1896 lines (1709 loc) · 68.8 KB
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 matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from collections import defaultdict, OrderedDict
from copy import deepcopy
import pandas as pd
import corner
# import acor
from emcee.autocorr import integrated_time, AutocorrError
# import pymc3
import la_forge
import la_forge.diagnostics as dg
from la_forge.core import TimingCore, Core
def get_pardict(psrs, datareleases):
"""assigns a parameter dictionary for each psr per dataset the parfile values/errors
:param psrs: enterprise pulsar instances corresponding to datareleases
:param datareleases: list of datareleases
"""
pardict = {}
for psr, dataset in zip(psrs, datareleases):
pardict[psr.name] = {}
pardict[psr.name][dataset] = {}
for par, vals, errs in zip(
psr.fitpars[1:],
np.longdouble(psr.t2pulsar.vals()),
np.longdouble(psr.t2pulsar.errs()),
):
pardict[psr.name][dataset][par] = {}
pardict[psr.name][dataset][par]["val"] = vals
pardict[psr.name][dataset][par]["err"] = errs
return pardict
def make_dmx_file(parfile):
dmx_dict = {}
with open(parfile, "r") as f:
lines = f.readlines()
for line in lines:
splt_line = line.split()
if "DMX" in splt_line[0] and splt_line[0] != "DMX":
for dmx_group in [
y.split()
for y in lines
if str(splt_line[0].split("_")[-1]) in str(y.split()[0])
]:
# Columns: DMXEP DMX_value DMX_var_err DMXR1 DMXR2 DMXF1 DMXF2 DMX_bin
lab = f"DMX_{dmx_group[0].split('_')[-1]}"
if lab not in dmx_dict.keys():
dmx_dict[lab] = {}
if "DMX_" in dmx_group[0]:
if isinstance(dmx_group[1], str):
dmx_dict[lab]["DMX_value"] = np.double(
("e").join(dmx_group[1].split("D"))
)
else:
dmx_dict[lab]["DMX_value"] = np.double(dmx_group[1])
if isinstance(dmx_group[-1], str):
dmx_dict[lab]["DMX_var_err"] = np.double(
("e").join(dmx_group[-1].split("D"))
)
else:
dmx_dict[lab]["DMX_var_err"] = np.double(dmx_group[-1])
dmx_dict[lab]["DMX_bin"] = "DX" + dmx_group[0].split("_")[-1]
else:
dmx_dict[lab][dmx_group[0].split("_")[0]] = np.double(dmx_group[1])
for dmx_name, dmx_attrs in dmx_dict.items():
if any([key for key in dmx_attrs.keys() if "DMXEP" not in key]):
dmx_dict[dmx_name]["DMXEP"] = (
dmx_attrs["DMXR1"] + dmx_attrs["DMXR2"]
) / 2.0
dmx_df = pd.DataFrame.from_dict(dmx_dict, orient="index")
neworder = [
"DMXEP",
"DMX_value",
"DMX_var_err",
"DMXR1",
"DMXR2",
"DMXF1",
"DMXF2",
"DMX_bin",
]
final_order = []
for order in neworder:
if order in dmx_dict["DMX_0001"]:
final_order.append(order)
dmx_df = dmx_df.reindex(columns=final_order)
new_dmx_file = (".dmx").join(parfile.split(".par"))
with open(new_dmx_file, "w") as f:
f.write(
f"# {parfile.split('/')[-1].split('.par')[0]} dispersion measure variation\n"
)
f.write(
f"# Mean DMX value = {np.mean([dmx_dict[x]['DMX_value'] for x in dmx_dict.keys()])} \n"
)
f.write(
f"# Uncertainty in average DM = {np.std([dmx_dict[x]['DMX_value'] for x in dmx_dict.keys()])} \n"
)
f.write(f"# Columns: {(' ').join(final_order)}\n")
dmx_df.to_csv(f, sep=" ", index=False, header=False)
def get_map_param(core, params, to_burn=True):
map_idx = np.argmax(core.get_param("lnpost", to_burn=True))
"""
print(stats.mode(core.get_param('lnpost',to_burn=to_burn)))
values, counts = np.unique(core.get_param('lnpost',to_burn=to_burn), return_counts=True)
ind = np.argmax(counts)
print(values[ind]) # prints the most frequent element
print(map_idx)
"""
if isinstance(params, str):
params = [params]
else:
if not isinstance(params, list):
raise ValueError("params need to be string or list")
map_params = {}
for par in params:
if isinstance(core, TimingCore):
if not any(
[
x in par
for x in ["ecorr", "equad", "efac", "lnpost", "lnlike", "accept"]
]
):
if "DMX" in par:
tm_par = "_".join(par.split("_")[-2:])
else:
tm_par = par.split("_")[-1]
if core.tm_pars_orig[tm_par][-1] == "normalized":
unscaled_param = core.get_param(
par, to_burn=to_burn, tm_convert=False
)
else:
unscaled_param = core.get_param(
par, to_burn=to_burn, tm_convert=True
)
map_params[tm_par] = unscaled_param[map_idx]
elif isinstance(core, Core):
unscaled_param = core.get_param(par, to_burn=to_burn)
map_params[par] = unscaled_param[map_idx]
return map_params
def tm_delay(t2pulsar, tm_params_orig, new_params, plot=True):
"""
Compute difference in residuals due to perturbed timing model.
:param t2pulsar: libstempo pulsar object
:param tm_params_orig: dictionary of TM parameter tuples, (val, err)
:return: difference between new and old residuals in seconds
"""
residuals = np.longdouble(t2pulsar.residuals().copy())
# grab original timing model parameters and errors in dictionary
orig_params = {}
tm_params_rescaled = {}
error_pos = {}
for tm_scaled_key, tm_scaled_val in new_params.items():
if "DMX" in tm_scaled_key:
tm_param = "_".join(tm_scaled_key.split("_")[-2:])
else:
tm_param = tm_scaled_key.split("_")[-1]
if tm_param == "COSI":
orig_params["SINI"] = np.longdouble(tm_params_orig["SINI"][0])
else:
orig_params[tm_param] = np.longdouble(tm_params_orig[tm_param][0])
if "physical" in tm_params_orig[tm_param]:
# User defined priors are assumed to not be scaled
if tm_param == "COSI":
# Switch for sampling in COSI, but using SINI in libstempo
tm_params_rescaled["SINI"] = np.longdouble(
np.sqrt(1 - tm_scaled_val**2)
)
else:
tm_params_rescaled[tm_param] = np.longdouble(tm_scaled_val)
else:
if tm_param == "COSI":
# Switch for sampling in COSI, but using SINI in libstempo
rescaled_COSI = np.longdouble(
tm_scaled_val * tm_params_orig[tm_param][1]
+ tm_params_orig[tm_param][0]
)
tm_params_rescaled["SINI"] = np.longdouble(
np.sqrt(1 - rescaled_COSI**2)
)
# print("Rescaled COSI used to find SINI", np.longdouble(rescaled_COSI))
# print("rescaled SINI", tm_params_rescaled["SINI"])
else:
tm_params_rescaled[tm_param] = np.longdouble(
tm_scaled_val * tm_params_orig[tm_param][1]
+ tm_params_orig[tm_param][0]
)
# set to new values
# print(tm_params_rescaled)
# TODO: Find a way to not do this every likelihood call bc it doesn't change and it is in enterprise.psr._isort
# Sort residuals by toa to match with get_detres() call
isort = np.argsort(t2pulsar.toas(), kind="mergesort")
t2pulsar.vals(tm_params_rescaled)
new_res = np.longdouble(t2pulsar.residuals().copy())
# remeber to set values back to originals
t2pulsar.vals(orig_params)
if plot:
plotres(t2pulsar, new_res, residuals, tm_params_rescaled)
else:
# Return the time-series for the pulsar
return new_res[isort], residuals[isort]
# return -(new_res[isort] - residuals[isort])
def plotres(psr, new_res, old_res, par_dict, deleted=False, group=None, **kwargs):
"""Plot residuals, compute unweighted rms residual."""
t, errs = psr.toas(), psr.toaerrs
meannewres = np.sqrt(np.mean(new_res**2)) / 1e-6
meanoldres = np.sqrt(np.mean(old_res**2)) / 1e-6
if (not deleted) and np.any(psr.deleted != 0):
new_res, old_res, t, errs = (
new_res[psr.deleted == 0],
old_res[psr.deleted == 0],
t[psr.deleted == 0],
errs[psr.deleted == 0],
)
print("Plotting {0}/{1} nondeleted points.".format(len(new_res), psr.nobs))
if group is None:
i = np.argsort(t)
pars = [x for x in par_dict.keys()]
vals = []
for p, v in zip(psr.pars(), psr.vals()):
for pa in pars:
if p == pa:
vals.append(v)
plt.errorbar(
t[i],
old_res[i] / 1e-6,
yerr=errs[i],
fmt="x",
label="Old Residuals",
**kwargs,
)
plt.errorbar(
t[i],
new_res[i] / 1e-6,
# yerr=errs[i],
fmt="+",
label="New Residuals",
**kwargs,
)
# plt.legend()
else:
if (not deleted) and np.any(psr.deleted):
flagmask = psr.flagvals(group)[~psr.deleted]
else:
flagmask = psr.flagvals(group)
unique = list(set(flagmask))
for flagval in unique:
f = flagmask == flagval
flagnewres, flagoldresflagt, flagerrs = (
new_res[f],
old_res[f],
t[f],
errs[f],
)
i = np.argsort(flagt)
plt.errorbar(
flagt[i],
flagoldres[i] / 1e-6,
yerr=flagerrs[i],
fmt="d",
label="Old Residuals",
**kwargs,
)
plt.errorbar(
flagt[i],
flagnewres[i] / 1e-6,
yerr=flagerrs[i],
fmt="x",
label="New Residuals",
**kwargs,
)
# plt.legend(unique,numpoints=1,bbox_to_anchor=(1.1,1.1))
plt.legend()
plt.xlabel(r"MJD")
plt.ylabel(r"res [$\mu s$]")
plt.title(
rf"{psr.name}: RMS, Old Res = {meanoldres:.3f} $\mu s$, New Res = {meannewres:.3f} $\mu s$"
)
def check_convergence(core_list):
cut_off_idx = -3
for core in core_list:
lp = np.unique(np.max(core.get_param("lnpost")))
ll = np.unique(np.max(core.get_param("lnlike")))
print("-------------------------------")
print(f"core: {core.label}")
print(f"\t lnpost: {lp[0]}, lnlike: {ll[0]}")
try:
grub = grubin(core.chain[:, :cut_off_idx])
if len(grub[1]) > 0:
print(
"\t Params exceed rhat threshold: ",
[core.params[p] for p in grub[1]],
)
except:
print("\t Can't run Grubin test")
pass
try:
geweke = geweke_check(core.chain[:, :cut_off_idx], burn_frac=0.25)
if len(geweke) > 0:
print("\t Params fail Geweke test: ", [core.params[p] for p in geweke])
except:
print("\t Can't run Geweke test")
pass
try:
max_acl = np.unique(np.max(get_param_acorr(core)))[0]
print(
f"\t Max autocorrelation length: {max_acl}, Effective sample size: {core.chain.shape[0]/max_acl}"
)
except:
print("\t Can't run Autocorrelation test")
pass
print("")
def summary_comparison(psr_name, core, par_sigma={}, selection="all"):
"""Makes comparison table of the form:
Par Name | Old Value | New Value | Difference | Old Sigma | New Sigma
TODO: allow for selection of subparameters"""
pd.set_option("max_rows", None)
plot_params = get_param_groups(core, selection=selection)
summary_dict = {}
for pnames, title in zip(plot_params["par"], plot_params["title"]):
if "timing" in pnames:
if isinstance(core, TimingCore):
param_vals = core.get_param(pnames, tm_convert=True, to_burn=True)
elif isinstance(core, Core):
param_vals = core.get_param(pnames, to_burn=True)
summary_dict[title] = {}
summary_dict[title]["new_val"] = np.median(param_vals)
summary_dict[title]["new_sigma"] = np.std(param_vals)
if title in core.tm_pars_orig:
summary_dict[title]["old_val"] = core.tm_pars_orig[title][0]
summary_dict[title]["old_sigma"] = core.tm_pars_orig[title][1]
summary_dict[title]["difference"] = (
summary_dict[title]["new_val"] - core.tm_pars_orig[title][0]
)
if abs(summary_dict[title]["difference"]) > core.tm_pars_orig[title][1]:
summary_dict[title]["big"] = True
else:
summary_dict[title]["big"] = False
if summary_dict[title]["new_sigma"] < summary_dict[title]["old_sigma"]:
summary_dict[title]["constrained"] = True
else:
summary_dict[title]["constrained"] = False
else:
summary_dict[title]["old_val"] = "-"
summary_dict[title]["old_sigma"] = "-"
summary_dict[title]["difference"] = "-"
summary_dict[title]["big"] = "-"
summary_dict[title]["constrained"] = "-"
return pd.DataFrame(
np.asarray(
[
[x for x in summary_dict.keys()],
[summary_dict[x]["old_val"] for x in summary_dict.keys()],
[summary_dict[x]["new_val"] for x in summary_dict.keys()],
[summary_dict[x]["difference"] for x in summary_dict.keys()],
[summary_dict[x]["old_sigma"] for x in summary_dict.keys()],
[summary_dict[x]["new_sigma"] for x in summary_dict.keys()],
[summary_dict[x]["big"] for x in summary_dict.keys()],
[summary_dict[x]["constrained"] for x in summary_dict.keys()],
]
).T,
columns=[
"Parameter",
"Old Value",
"New Median Value",
"Difference",
"Old Sigma",
"New Std Dev",
">1 sigma change?",
"More Constrained?",
],
)
def residual_comparison(
t2pulsar, core, use_mean_median_map="median", use_tm_pars_orig=False
):
"""Used to compare old residuals to new residuals."""
core_titles = get_titles(t2pulsar.name, core)
core_timing_dict_unscaled = OrderedDict()
if use_mean_median_map == "map":
map_idx_e_e = np.argmax(core.get_param("lnpost", to_burn=True))
elif use_mean_median_map not in ["map", "median", "mean"]:
raise ValueError(
"use_mean_median_map can only be either 'map','median', or 'mean"
)
for par in core.params:
unscaled_param = core.get_param(par, to_burn=True, tm_convert=True)
if use_mean_median_map == "map":
core_timing_dict_unscaled[par] = unscaled_param[map_idx_e_e]
elif use_mean_median_map == "mean":
core_timing_dict_unscaled[par] = np.mean(unscaled_param)
elif use_mean_median_map == "median":
core_timing_dict_unscaled[par] = np.median(unscaled_param)
core_timing_dict = deepcopy(core_timing_dict_unscaled)
if use_tm_pars_orig:
for p in core_timing_dict.keys():
if "timing" in p:
core_timing_dict.update(
{p: np.double(core.tm_pars_orig[p.split("_")[-1]][0])}
)
chain_tm_params_orig = deepcopy(core.tm_pars_orig)
chain_tm_delay_kwargs = {}
for par in t2pulsar.pars():
if par == "SINI" and "COSI" in core.tm_pars_orig.keys():
sin_val, sin_err, _ = chain_tm_params_orig[par]
val = np.longdouble(np.sqrt(1 - sin_val**2))
err = np.longdouble(np.sqrt((np.abs(sin_val / val)) ** 2 * sin_err**2))
chain_tm_params_orig["COSI"] = [val, err, "physical"]
chain_tm_delay_kwargs["COSI"] = core_timing_dict[
core.params[core_titles.index("COSI")]
]
elif par in core.tm_pars_orig.keys():
chain_tm_params_orig[par][-1] = "physical"
chain_tm_delay_kwargs[par] = core_timing_dict[
core.params[core_titles.index(par)]
]
else:
print(f"{par} not in t2pulsar pars")
tm_delay(t2pulsar, chain_tm_params_orig, chain_tm_delay_kwargs)
plt.show()
def refit_errs(psr, tm_params_orig):
# Check to see if nan or inf in pulsar parameter errors.
# The refit will populate the incorrect errors, but sometimes
# changes the values by too much, which is why it is done in this order.
orig_vals = {p: v for p, v in zip(psr.t2pulsar.pars(), psr.t2pulsar.vals())}
orig_errs = {p: e for p, e in zip(psr.t2pulsar.pars(), psr.t2pulsar.errs())}
if np.any(np.isnan(psr.t2pulsar.errs())) or np.any(
[err == 0.0 for err in psr.t2pulsar.errs()]
):
eidxs = np.where(
np.logical_or(np.isnan(psr.t2pulsar.errs()), psr.t2pulsar.errs() == 0.0)
)[0]
psr.t2pulsar.fit()
for idx in eidxs:
par = psr.t2pulsar.pars()[idx]
print(par, np.longdouble(psr.t2pulsar.errs()[idx]))
tm_params_orig[par][1] = np.longdouble(psr.t2pulsar.errs()[idx])
psr.t2pulsar.vals(orig_vals)
psr.t2pulsar.errs(orig_errs)
def reorder_columns(e_e_chaindir, outdir):
chain_e_e = pd.read_csv(
e_e_chaindir + "/chain_1.0.txt", sep="\t", dtype=float, header=None
)
switched_chain = chain_e_e[[0, 3, 1, 4, 2, 5, 6, 7, 8, 9, 10, 11, 12]]
np.savetxt(outdir + "/chain_1.txt", switched_chain.values, delimiter="\t")
def get_new_PAL2_params(psr_name, core):
new_PAL2_params = []
for par in core.params:
if "efac" in par:
new_par = psr_name + "_" + par.split("efac-")[-1] + "_efac"
elif "jitter" in par:
new_par = psr_name + "_" + par.split("jitter_q-")[-1] + "_log10_ecorr"
elif "equad" in par:
new_par = psr_name + "_" + par.split("equad-")[-1] + "_log10_equad"
elif par in ["lnpost", "lnlike", "chain_accept", "pt_chain_accept"]:
new_par = par
else:
new_par = psr_name + "_timing_model_" + par
new_PAL2_params.append(new_par)
return new_PAL2_params
def get_titles(psr_name, core):
titles = []
for core_param in core.params:
if "timing" in core_param.split("_"):
if "DMX" in core_param.split("_"):
titles.append(("_").join(core_param.split("_")[-2:]))
else:
titles.append(core_param.split("_")[-1])
else:
if psr_name in core_param.split("_"):
titles.append((" ").join(core_param.split("_")[1:]))
else:
titles.append(core_param)
"""
else:
unparams=['lnpost','lnlike','chain_accept','pt_chain_accept']
for com_par in params:
if (
com_par
not in core.params
):
unparams.append(com_par)
for ncom_par in unparams:
if ncom_par in params:
del titles[params.index(ncom_par)]
del params[
params.index(ncom_par)
]
"""
return titles
def get_common_params_titles(psr_name, core_list, exclude=True):
common_params = []
common_titles = []
for core in core_list:
if len(common_params) == 0:
for core_param in core.params:
common_params.append(core_param)
if "timing" in core_param.split("_"):
if "DMX" in core_param.split("_"):
common_titles.append(("_").join(core_param.split("_")[-2:]))
else:
common_titles.append(core_param.split("_")[-1])
else:
if psr_name in core_param.split("_"):
common_titles.append((" ").join(core_param.split("_")[1:]))
else:
common_titles.append(core_param)
else:
if exclude:
uncommon_params = [
"lnpost",
"lnlike",
"chain_accept",
"pt_chain_accept",
]
else:
uncommon_params = ["chain_accept", "pt_chain_accept"]
for com_par in common_params:
if com_par not in core.params:
uncommon_params.append(com_par)
for ncom_par in uncommon_params:
if ncom_par in common_params:
del common_titles[common_params.index(ncom_par)]
del common_params[common_params.index(ncom_par)]
return common_params, common_titles
def get_other_param_overlap(psr_name, core_list):
"""Returns a dictionary of params with list of indices for corresponding core in core_list"""
boring_params = ["lnpost", "lnlike", "chain_accept", "pt_chain_accept"]
common_params_all, _ = get_common_params_titles(psr_name, core_list, exclude=False)
com_par_dict = defaultdict(list)
for j, core in enumerate(core_list):
for param in core.params:
if param not in common_params_all + boring_params:
com_par_dict[param].append(j)
return com_par_dict
def plot_all_param_overlap(
psr_name,
core_list,
core_list_legend=None,
com_par_dict=None,
exclude=True,
real_tm_pars=True,
conf_int=None,
close=True,
par_sigma={},
ncols=3,
hist_kwargs={},
fig_kwargs={},
):
if not core_list_legend:
core_list_legend = []
for core in core_list:
core_list_legend.append(core.label)
hist_core_list_kwargs = {
"hist": True,
"ncols": ncols,
"title_y": 1.4,
"hist_kwargs": hist_kwargs,
"linewidth": 3.0,
}
if "suptitle" not in fig_kwargs.keys():
suptitle = f"{psr_name} Mass Plots"
else:
suptitle = fig_kwargs["suptitle"]
if "suptitlefontsize" not in fig_kwargs.keys():
suptitlefontsize = 24
else:
suptitlefontsize = fig_kwargs["suptitlefontsize"]
if "suptitleloc" not in fig_kwargs.keys():
suptitleloc = (0.25, 1.05)
else:
suptitleloc = fig_kwargs["suptitleloc"]
if "legendloc" not in fig_kwargs.keys():
legendloc = (0.45, 0.97)
else:
legendloc = fig_kwargs["legendloc"]
if "legendfontsize" not in fig_kwargs.keys():
legendfontsize = 12
else:
legendfontsize = fig_kwargs["legendfontsize"]
if "colors" not in fig_kwargs.keys():
colors = [f"C{ii}" for ii in range(len(core_list_legend))]
else:
colors = fig_kwargs["colors"]
if "wspace" not in fig_kwargs.keys():
wspace = 0.1
else:
wspace = fig_kwargs["wspace"]
if "hspace" not in fig_kwargs.keys():
hspace = 0.2
else:
hspace = fig_kwargs["hspace"]
common_params_all, common_titles_all = get_common_params_titles(
psr_name, core_list, exclude=exclude
)
hist_core_list_kwargs["title_y"] = 1.0 + 0.025 * len(core_list)
if len(core_list) < 3:
y = 0.98 - 0.01 * len(core_list)
hist_core_list_kwargs["title_y"] = 1.0 + 0.02 * len(core_list)
elif len(core_list) >= 3 and len(core_list) < 5:
y = 0.95 - 0.01 * len(core_list)
# hist_core_list_kwargs['title_y'] = 1.+.05*len(core_list)
elif len(core_list) >= 3 and len(core_list) < 10:
y = 0.95 - 0.01 * len(core_list)
# hist_core_list_kwargs['title_y'] = 1.+.025*len(core_list)
else:
y = 0.95 - 0.01 * len(core_list)
# hist_core_list_kwargs['title_y'] = 1.+.05*len(core_list)
if close:
dg.plot_chains(
core_list,
suptitle=suptitle,
pars=common_params_all,
titles=common_titles_all,
real_tm_pars=real_tm_pars,
show=False,
close=False,
**hist_core_list_kwargs,
)
if conf_int or par_sigma:
fig = plt.gcf()
allaxes = fig.get_axes()
for ax in allaxes:
splt_key = ax.get_title()
if par_sigma:
if splt_key in par_sigma:
val = par_sigma[splt_key][0]
err = par_sigma[splt_key][1]
fill_space_x = np.linspace(val - err, val + err, 20)
ax.fill_between(
fill_space_x, ax.get_ylim()[1], color="grey", alpha=0.2
)
ax.axvline(val, color="k", linestyle="--")
elif splt_key == "COSI" and "SINI" in par_sigma:
sin_val, sin_err, _ = par_sigma["SINI"]
val = np.longdouble(np.sqrt(1 - sin_val**2))
err = np.longdouble(
np.sqrt((np.abs(sin_val / val)) ** 2 * sin_err**2)
)
fill_space_x = np.linspace(val - err, val + err, 20)
ax.fill_between(
fill_space_x, ax.get_ylim()[1], color="grey", alpha=0.2
)
ax.axvline(val, color="k", linestyle="--")
if conf_int:
if isinstance(conf_int, (float, int)):
if conf_int < 1.0 or conf_int > 99.0:
raise ValueError("conf_int must be between 1 and 99")
else:
raise ValueError("conf_int must be an int or float")
for i, core in enumerate(core_list):
# elif splt_key == 'COSI' and 'SINI' in par_sigma:
for com_par, com_title in zip(
common_params_all, common_titles_all
):
if splt_key == com_title:
low, up = core.get_param_confint(
com_par, interval=conf_int
)
ax.fill_between(
[low, up],
ax.get_ylim()[1],
color=f"C{i}",
alpha=0.1,
)
else:
fig = plt.gcf()
patches = []
for jj, lab in enumerate(core_list_legend):
patches.append(
mpl.patches.Patch(color=colors[jj], label=lab)
) # .split(":")[-1]))
fig.legend(handles=patches, loc=legendloc, fontsize=legendfontsize)
fig.subplots_adjust(wspace=wspace, hspace=hspace)
plt.suptitle(
suptitle,
fontsize=suptitlefontsize,
x=suptitleloc[0],
y=suptitleloc[1],
)
plt.show()
plt.close()
else:
dg.plot_chains(
core_list,
suptitle=psr_name,
pars=common_params_all,
titles=common_titles_all,
legend_labels=core_list_legend,
legend_loc=(0.0, y),
real_tm_pars=real_tm_pars,
**hist_core_list_kwargs,
)
def plot_other_param_overlap(
psr_name,
core_list,
core_list_legend=None,
com_par_dict=None,
real_tm_pars=True,
close=False,
par_sigma={},
):
if not com_par_dict:
com_par_dict = get_other_param_overlap(psr_name, core_list)
if not core_list_legend:
core_list_legend = []
for core in core_list:
core_list_legend.append(core.label)
hist_core_list_kwargs = {
"hist": True,
"ncols": 1,
"title_y": 1.4,
"hist_kwargs": dict(fill=False),
"linewidth": 3.0,
}
plotted_cosi = False
for key, vals in com_par_dict.items():
if close:
if "SINI" in key or "COSI" in key:
if not plotted_cosi:
if (
"SINI" in key
and ("_").join(key.split("_")[:-1] + ["COSI"])
in com_par_dict.keys()
):
cosi_chains = []
cosi_chains_labels = []
for c in vals:
gpar_kwargs = dg._get_gpar_kwargs(
core_list[c], real_tm_pars
)
cosi_chains.append(
np.sqrt(
1 - core_list[c].get_param(key, **gpar_kwargs) ** 2
)
)
cosi_chains_labels.append(core_list_legend[c])
for c in com_par_dict[
("_").join(key.split("_")[:-1] + ["COSI"])
]:
gpar_kwargs = dg._get_gpar_kwargs(
core_list[c], real_tm_pars
)
cosi_chains.append(
core_list[c].get_param("COSI", **gpar_kwargs)
)
cosi_chains_labels.append(core_list_legend[c])
elif (
"COSI" in key
and ("_").join(key.split("_")[:-1] + ["SINI"])
in com_par_dict.keys()
):
cosi_chains_labels = []
cosi_chains = []
for c in vals:
gpar_kwargs = dg._get_gpar_kwargs(
core_list[c], real_tm_pars
)
cosi_chains.append(
core_list[c].get_param(key, **gpar_kwargs)
)
cosi_chains_labels.append(core_list_legend[c])
for c in com_par_dict[
("_").join(key.split("_")[:-1] + ["SINI"])
]:
gpar_kwargs = dg._get_gpar_kwargs(
core_list[c], real_tm_pars
)
cosi_chains.append(
np.sqrt(
1
- core_list[c].get_param("SINI", **gpar_kwargs) ** 2
)
)
cosi_chains_labels.append(core_list_legend[c])
fig = plt.figure(figsize=[15, 4])
axis = fig.add_subplot(1, 1, 1)
for i, chain in enumerate(cosi_chains):
plt.hist(
chain,
bins=40,
density=True,
log=False,
linestyle="-",
histtype="step",
linewidth=hist_core_list_kwargs["linewidth"],
label=cosi_chains_labels[i],
)
plt.legend()
plt.title("COSI")
else:
hist_core_list_kwargs["title_y"] = 1.0 + 0.05 * len(core_list)
y = 0.95 - 0.03 * len(core_list)
dg.plot_chains(
[core_list[c] for c in vals],
suptitle=psr_name,
pars=[key],
legend_labels=[core_list_legend[c] for c in vals],
legend_loc=(0.0, y),
real_tm_pars=real_tm_pars,
show=False,
close=False,
**hist_core_list_kwargs,
)
if par_sigma:
splt_key = key.split("_")[-1]
if splt_key == "COSI" or splt_key == "SINI" and "SINI" in par_sigma:
if not plotted_cosi:
sin_val, sin_err, _ = par_sigma["SINI"]
val = np.longdouble(np.sqrt(1 - sin_val**2))
err = np.longdouble(
np.sqrt((np.abs(sin_val / val)) ** 2 * sin_err**2)
)
fill_space_x = np.linspace(val - err, val + err, 20)
plt.fill_between(
fill_space_x,
plt.gca().get_ylim()[1],
color="grey",
alpha=0.2,
)
plt.axvline(val, color="k", linestyle="--")
plotted_cosi = True
else:
if splt_key in par_sigma:
val = par_sigma[splt_key][0]
err = par_sigma[splt_key][1]
fill_space_x = np.linspace(val - err, val + err, 20)
plt.fill_between(
fill_space_x,
plt.gca().get_ylim()[1],
color="grey",
alpha=0.2,
)
plt.axvline(val, color="k", linestyle="--")
plt.show()
plt.close()
else:
hist_core_list_kwargs["title_y"] = 1.0 + 0.05 * len(core_list)
y = 0.95 - 0.03 * len(core_list)
dg.plot_chains(
[core_list[c] for c in vals],
suptitle=psr_name,
pars=[key],
legend_labels=[core_list_legend[c] for c in vals],
legend_loc=(0.0, y),
real_tm_pars=real_tm_pars,
**hist_core_list_kwargs,
)
print("")
def get_fancy_labels(labels, overline=False):
fancy_labels = []
for lab in labels:
if lab == "A1":
fancy_labels.append(r"$x-\overline{x}$ (lt-s)")
elif lab == "EPS1":
fancy_labels.append(r"$\epsilon_{1}-\overline{\epsilon_{1}}$")
elif lab == "EPS2":
fancy_labels.append(r"$\epsilon_{2}-\overline{\epsilon_{2}}$")
elif lab == "M2":
fancy_labels.append(r"$m_{\mathrm{c}}-\overline{m_{\mathrm{c}}}$")
elif lab == "COSI":
fancy_labels.append(r"$\mathrm{cos}i-\overline{\mathrm{cos}i}$")
# fancy_labels.append(r'$\mathrm{cos}i$')
elif lab == "PB":
fancy_labels.append(r"$P_{\mathrm{b}}-\overline{P_{\mathrm{b}}}$")
# fancy_labels.append(r'$P_{\mathrm{b}}-\overline{P_{\mathrm{b}}}$ (days)')
elif lab == "TASC":
fancy_labels.append(r"$T_{\mathrm{asc}}-\overline{T_{\mathrm{asc}}}$")
# fancy_labels.append(r'$T_{\mathrm{asc}}-\overline{T_{\mathrm{asc}}}$ (MJD)')
elif lab == "ELONG":
fancy_labels.append(r"$\lambda-\overline{\lambda}$")
# fancy_labels.append(r'$\lambda-\overline{\lambda}$ (degrees)')
elif lab == "ELAT":
fancy_labels.append(r"$\beta-\overline{\beta}$")
# fancy_labels.append(r'$\beta-\overline{\beta}$ (degrees)')
elif lab == "PMELONG":
fancy_labels.append(r"$\mu_{\lambda}-\overline{\mu_{\lambda}}$")
# fancy_labels.append(r'$\mu_{\lambda}-\overline{\mu_{\lambda}}$ (mas/yr)')
elif lab == "PMELAT":
fancy_labels.append(r"$\mu_{\beta}-\overline{\mu_{\beta}}$")
# fancy_labels.append(r'$\mu_{\beta}-\overline{\mu_{\beta}}$ (mas/yr)')
elif lab == "F0":
fancy_labels.append(r"$\nu-\overline{\nu}$")
# fancy_labels.append(r'$\nu-\overline{\nu}~(\mathrm{s}^{-1})$')
elif lab == "F1":
fancy_labels.append(r"$\dot{\nu}-\overline{\dot{\nu}}$")
# fancy_labels.append(r'$\dot{\nu}-\overline{\dot{\nu}}~(\mathrm{s}^{-2})$')
elif lab == "PX":
# fancy_labels.append(r'$\pi-\overline{\pi}$ (mas)')
fancy_labels.append(r"$\pi$ (mas)")
elif "efac" in lab:
fancy_labels.append(r"EFAC")
elif "equad" in lab:
fancy_labels.append(r"$\mathrm{log}_{10}$EQUAD")
elif "ecorr" in lab:
fancy_labels.append(r"$\mathrm{log}_{10}$ECORR")
else:
fancy_labels.append(lab)
return fancy_labels
def fancy_plot_all_param_overlap(
psr_name,
core_list,
core_list_legend=None,
com_par_dict=None,
exclude=True,
par_sigma={},
conf_int=False,
preliminary=True,
ncols=4,
real_tm_pars=True,
selection="all",
hist_kwargs={},
fig_kwargs={},
):
if not core_list_legend:
core_list_legend = []
for core in core_list:
core_list_legend.append(core.label)
if not hist_kwargs:
hist_kwargs = {
"linewidth": 3.0,
"density": True,
"histtype": "step",
"bins": 40,
}
if "suptitle" not in fig_kwargs.keys():