-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnltm_plot_utils_v5.py
2196 lines (1990 loc) · 85.2 KB
/
nltm_plot_utils_v5.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 matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import astropy.units as u
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
from pint.residuals import Residuals
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):
"""Strips the parfile for the dmx values to be used in an Advanced Noise Modeling Run
:param parfile: the parameter file to be stripped
"""
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):
"""Separate version of getting the maximum a posteriori from a `la_forge` core
:param core: `la_forge` core object
:param params: the parameters for which to get the MAP values
:param to_burn: whether to shorten the chain to exclude early samples
"""
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(psr, tm_params_orig, new_params, plot=True):
"""
Compute difference in residuals due to perturbed timing model.
:param psr: enterprise pulsar object
:param tm_params_orig: dictionary of TM parameter tuples, (val, err)
:param new_params: dictionary of new TM parameter tuples, (val, err)
:param plot: Whether to plot the delay or return the delay
"""
if hasattr(psr, "model"):
residuals = Residuals(psr.pint_toas, psr.model)
elif hasattr(psr, "t2pulsar"):
residuals = np.longdouble(psr.t2pulsar.residuals())
else:
raise ValueError(
"Enterprise pulsar must keep either pint or t2pulsar. Use either drop_t2pulsar=False or drop_pintpsr=False when initializing the enterprise pulsar."
)
# 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]
)
if hasattr(psr, "model"):
new_model = deepcopy(psr.model)
# Set values to new sampled values
new_model.set_param_values(tm_params_rescaled)
# Get new residuals
# new_res = np.longdouble(Residuals(psr.pint_toas, new_model).resids_value)
new_res = Residuals(psr.pint_toas, new_model)
if plot:
plotres_pint(psr, new_res, residuals)
elif hasattr(psr, "t2pulsar"):
# Set values to new sampled values
psr.t2pulsar.vals(tm_params_rescaled)
# Get new residuals
new_res = np.longdouble(psr.t2pulsar.residuals())
# Set values back to originals
psr.t2pulsar.vals(orig_params)
if plot:
plotres_t2(psr, new_res)
else:
raise ValueError(
"Enterprise pulsar must keep either pint or t2pulsar. Use either drop_t2pulsar=False or drop_pintpsr=False when initializing the enterprise pulsar."
)
if not plot:
# Return the time-series for the pulsar
return new_res[psr.isort], psr.residuals
def plotres_pint(psr, new_res, old_res, **kwargs):
"""Used to compare different sets of residuals from a pint pulsar
:param psr: an `enterprise` pulsar with the `PINT` pulsar object retained
:param new_res: the new residuals, post-run
:param old_res: the old residuals, generally from the parfile parameters
"""
kwargs.get("alpha", 0.5)
plt.errorbar(
old_res.toas.get_mjds().value,
old_res.resids.to(u.us).value,
yerr=old_res.toas.get_errors().to(u.us).value,
fmt="x",
label="Old Residuals",
**kwargs,
)
plt.errorbar(
new_res.toas.get_mjds().value,
new_res.resids.to(u.us).value,
yerr=new_res.toas.get_errors().to(u.us).value,
fmt="+",
label="New Residuals",
**kwargs,
)
meannewres = np.sqrt(np.mean(new_res.resids.to(u.us) ** 2))
meanoldres = np.sqrt(np.mean(old_res.resids.to(u.us) ** 2))
plt.legend()
plt.xlabel(r"MJD")
plt.ylabel(r"res [$\mu s$]")
plt.title(
rf"{psr.name}: RMS, Old Res = {meanoldres.value:.3f} $\mu s$, New Res = {meannewres.value:.3f} $\mu s$"
)
plt.grid()
def plotres_t2(psr, new_res, **kwargs):
"""Used to compare different sets of residuals from a T2 pulsar
:param psr: an `enterprise` pulsar with the `TEMPO2` pulsar object retained
:param new_res: the new residuals, post-run
"""
kwargs.get("alpha", 0.5)
plt.errorbar(
(psr.toas * u.s).to("d").value,
(psr.residuals * u.s).to("us").value,
yerr=(psr.toaerrs * u.s).to("us").value,
fmt="x",
label="Old Residuals",
**kwargs,
)
plt.errorbar(
(psr.toas * u.s).to("d").value,
(new_res[psr.isort] * u.s).to("us").value,
yerr=(psr.toaerrs * u.s).to("us").value,
fmt="+",
label="New Residuals",
**kwargs,
)
meannewres = np.sqrt(np.mean((new_res * u.s).to("us") ** 2))
meanoldres = np.sqrt(np.mean((psr.residuals * u.s).to("us") ** 2))
plt.legend()
plt.xlabel(r"MJD")
plt.ylabel(r"res [$\mu s$]")
plt.title(
rf"{psr.name}: RMS, Old Res = {meanoldres.value:.3f} $\mu s$, New Res = {meannewres.value:.3f} $\mu s$"
)
plt.grid()
def residual_comparison(
psr,
core,
use_mean_median_map="median",
):
"""Used to compare old residuals to new residuals.
:param psr: `enterprise` pulsar object with either `PINT` or `libstempo` pulsar retained
:param core: `la_forge` core object
:param use_mean_median_map: {"median","mean","map"} determines which values from posteriors to take
as values in the residual calculation
"""
core_titles = get_titles(psr.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 psr.fitpars:
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():
if par in core_titles:
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 directly sampled. Using parfile value.")
chain_tm_params_orig[par][-1] = "normalized"
chain_tm_delay_kwargs[par] = 0.0
else:
print(f"{par} not in psr pars")
tm_delay(psr, chain_tm_params_orig, chain_tm_delay_kwargs)
plt.show()
def check_convergence(core_list):
"""Checks chain convergence using Gelman-Rubin split R-hat statistic (Vehtari et al. 2019),
a geweke test, and the auto-correlation
:param core_list: list of `la_forge` core objects
"""
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, selection="all"):
"""Makes comparison table of the form:
Par Name | Old Value | New Value | Difference | Old Sigma | New Sigma
:param psr_name: str, Name of the pulsar to be looked at
:param core: `la_forge` core object
:param selection: str, Used to select various groups of parameters:
see `get_param_groups` for details
"""
# TODO: allow for selection of subparameters
pd.set_option("display.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)
summary_dict[title]["new_sigma"] = np.max(
np.abs(
core.get_param_credint(pnames, interval=68, onesided=False)
- summary_dict[title]["new_val"]
)
)
summary_dict[title]["rounded_new_sigma"] = np.round(
summary_dict[title]["new_sigma"],
-int(np.floor(np.log10(np.abs(summary_dict[title]["new_sigma"])))),
)
summary_dict[title]["rounded_new_val"] = np.round(
summary_dict[title]["new_val"],
-int(np.floor(np.log10(np.abs(summary_dict[title]["new_sigma"])))),
)
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]["rounded_old_sigma"] = np.round(
summary_dict[title]["old_sigma"],
-int(np.floor(np.log10(np.abs(summary_dict[title]["old_sigma"])))),
)
summary_dict[title]["rounded_old_val"] = np.round(
summary_dict[title]["old_val"],
-int(np.floor(np.log10(np.abs(summary_dict[title]["old_sigma"])))),
)
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"] = "-"
summary_dict[title]["rounded_old_val"] = "-"
summary_dict[title]["rounded_old_sigma"] = "-"
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]["rounded_old_val"] for x in summary_dict.keys()],
[summary_dict[x]["rounded_old_sigma"] for x in summary_dict.keys()],
[summary_dict[x]["rounded_new_val"] for x in summary_dict.keys()],
[summary_dict[x]["rounded_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 Sigma",
"Rounded Old Value",
"Rounded Old Sigma",
"Rounded New Value",
"Rounded New Sigma",
">1 sigma change?",
"More Constrained?",
],
)
def refit_errs(psr, tm_params_orig):
"""Checks to see if nan or inf in pulsar parameter errors.
:param psr: `enterprise` pulsar object with either `PINT` or `libstempo` pulsar retained
:param tm_params_orig: original timing model parameters (usually from parfile)
Notes: 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):
"""reorders chain columns
:param e_e_chaindir: path to chain to be reordered
:param outdir: path to output directory
"""
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):
"""Renames PAL2 parameters old naming scheme
:param psr_name: Name of the pulsar
:param core: `la_forge` core object
"""
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_dmgp_timescales(psr_name, core, ci_int = 68.3):
plot_params = get_param_groups(core, selection="dm_chrom")
lower_q = (100 - ci_int) / 2
for dm_par in plot_params["par"]:
if "ell" in dm_par:
if isinstance(core, TimingCore):
plot_params["conv_med_val"].append(
f"{np.median(10**core.get_param(dm_par,tm_convert=True))} days"
)
plot_params["conv_CI"].append(
[f"{np.percentile(10**core.get_param(dm_par,tm_convert=True),q=lower_q)} days, lower",
f"{np.percentile(10**core.get_param(dm_par,tm_convert=True),q=100-lower_q)} days, higher"]
)
else:
plot_params["conv_med_val"].append(
f"{np.median(10**core.get_param(dm_par))} days"
)
plot_params["conv_CI"].append(
[f"{np.percentile(10**core.get_param(dm_par),q=lower_q)} days, lower",
f"{np.percentile(10**core.get_param(dm_par),q=100-lower_q)} days, higher"]
)
elif "log10_p" in dm_par:
if isinstance(core, TimingCore):
plot_params["conv_med_val"].append(
f"{np.median(10**core.get_param(dm_par,tm_convert=True)*3.16e7/86400)} days"
)
plot_params["conv_CI"].append(
[f"{np.percentile(10**core.get_param(dm_par,tm_convert=True)*3.16e7/86400,q=lower_q)} days, lower",
f"{np.percentile(10**core.get_param(dm_par,tm_convert=True)*3.16e7/86400,q=100-lower_q)} days, higher"]
)
else:
plot_params["conv_med_val"].append(
f"{np.median(10**core.get_param(dm_par)*3.16e7/86400)} days"
)
plot_params["conv_CI"].append(
[f"{np.percentile(10**core.get_param(dm_par)*3.16e7/86400,q=lower_q)} days, lower",
f"{np.percentile(10**core.get_param(dm_par)*3.16e7/86400,q=100-lower_q)} days, higher"]
)
elif "n_earth" in dm_par:
if isinstance(core, TimingCore):
plot_params["conv_med_val"].append(
f"{np.median(core.get_param(dm_par,tm_convert=True))} SW electron density"
)
plot_params["conv_CI"].append(
[f"{np.percentile(core.get_param(dm_par,tm_convert=True),q=lower_q)} SW electron density, lower",
f"{np.percentile(core.get_param(dm_par,tm_convert=True),q=100-lower_q)} SW electron density, higher"]
)
else:
plot_params["conv_med_val"].append(
f"{np.median(core.get_param(dm_par))} SW electron density"
)
plot_params["conv_CI"].append(
[f"{np.percentile(core.get_param(dm_par),q=lower_q)} SW electron density, lower",
f"{np.percentile(core.get_param(dm_par),q=100-lower_q)} SW electron density, higher"]
)
else:
if isinstance(core, TimingCore):
if "log10" in dm_par:
new_val = 10**core.get_param(dm_par,tm_convert=True)
else:
new_val = core.get_param(dm_par,tm_convert=True)
plot_params["conv_med_val"].append(
f"{np.median(new_val)}"
)
plot_params["conv_CI"].append(
[f"{np.percentile(new_val,q=lower_q)} lower",
f"{np.percentile(new_val,q=100-lower_q)} higher"]
)
else:
if "log10" in dm_par:
new_val = 10**core.get_param(dm_par)
else:
new_val = core.get_param(dm_par)
plot_params["conv_med_val"].append(
f"{np.median(new_val)}"
)
plot_params["conv_CI"].append(
[f"{np.percentile(new_val,q=lower_q)} lower",
f"{np.percentile(new_val,q=100-lower_q)} higher"]
)
return plot_params
def get_titles(psr_name, core):
"""Get titles for timing model parameters
:param psr_name: Name of the pulsar
:param core: `la_forge` core object
"""
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)
return titles
def get_common_params_titles(psr_name, core_list, exclude=True):
"""Renames gets common parameters and titles
:param psr_name: Name of the pulsar
:param core_list: list of `la_forge` core objects
:param exclude: exclude ["lnpost","lnlike","chain_accept","pt_chain_accept",]
"""
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):
"""Gets a dictionary of params with list of indices for corresponding core in core_list
:param psr_name: Name of the pulsar
:param core_list: list of `la_forge` core objects
"""
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,
exclude=True,
real_tm_pars=True,
conf_int=None,
close=True,
par_sigma={},
ncols=3,
hist_kwargs={},
fig_kwargs={},
**kwargs,
):
"""Plots common parameters between cores in core_list
:param psr_name: Name of the pulsar
:param core_list: list of `la_forge` core objects
:param core_list_legend: list of labels corresponding to core_list
:param exclude: excludes ["lnpost","lnlike","chain_accept","pt_chain_accept",]
:param real_tm_pars: Whether to plot scaled or unscaled Timing Model parameters
:param conf_int: float shades confidence interval region can be float between 0 and 1
:param close: Whether to close the figure after displaying
:param par_sigma: the error dictionary from the parfile of the form: {par_name:(val,err,'physical')}
:param ncols: number of columns to plot
:param hist_kwargs: kwargs for the histograms
:param fig_kwargs: general figure kwargs
"""
if not core_list_legend:
core_list_legend = []
for core in core_list:
core_list_legend.append(core.label)
linestyles = kwargs.get("linestyles", ["-" for x in core_list])
suptitle = fig_kwargs.get("suptitle", f"{psr_name} Comparison Plots")
labelfontsize = fig_kwargs.get("labelfontsize", 18)
titlefontsize = fig_kwargs.get("titlefontsize", 16)
suptitlefontsize = fig_kwargs.get("suptitlefontsize", 24)
suptitleloc = fig_kwargs.get("suptitleloc", (0.35, 0.94))
legendloc = fig_kwargs.get("legendloc", (0.45, 0.97))
legendfontsize = fig_kwargs.get("legendfontsize", 12)
colors = fig_kwargs.get("colors", [f"C{ii}" for ii in range(len(core_list_legend))])
wspace = fig_kwargs.get("wspace", 0.1)
hspace = fig_kwargs.get("hspace", 0.4)
figsize = fig_kwargs.get("figsize", (15, 10))
hist_core_list_kwargs = {
"hist": True,
"ncols": ncols,
"title_y": 1.4,
"hist_kwargs": hist_kwargs,
"linewidth": 3.0,
"linestyle": linestyles,
}
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 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)
gls_fill = ax.fill_between(
fill_space_x, ax.get_ylim()[1], color="grey", alpha=0.2
)
gls_line = 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)
gls_fill = ax.fill_between(
fill_space_x, ax.get_ylim()[1], color="grey", alpha=0.2
)
gls_line = 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_credint(
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()
if par_sigma:
patches.append(gls_line)
patches.append(gls_fill)
patches = []
for jj, lab in enumerate(core_list_legend):
patches.append(
mpl.patches.Patch(
color=colors[jj],
linestyle=linestyles[jj],
fill=False,
label=lab,
linewidth=3,
)
) # .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,
real_tm_pars=True,
close=True,
selection="all",
par_sigma={},
hist_kwargs={},
**kwargs,
):
"""Plots non-common parameters between cores in core_list
:param psr_name: Name of the pulsar
:param core_list: list of `la_forge` core objects
:param core_list_legend: list of labels corresponding to core_list
:param real_tm_pars: Whether to plot scaled or unscaled Timing Model parameters
:param close: Whether to close the figure after displaying
:param selection: str, Used to select various groups of parameters:
see `get_param_groups` for details
:param par_sigma: the error dictionary from the parfile of the form: {par_name:(val,err,'physical')}
:param hist_kwargs: kwargs for the histograms
"""
linestyles = kwargs.get("linestyles", ["-" for x in core_list])
legendloc = kwargs.get("legendloc", (0.0, 0.95 - 0.03 * len(core_list)))
title_y = kwargs.get("title_y", 1.0 + 0.05 * len(core_list))
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": title_y,
"hist_kwargs": hist_kwargs,
"linewidth": 3.0,
"linestyle": linestyles,
}
selected_params = []
for c_l in core_list:
tmp_selected_params = get_param_groups(c_l, selection=selection)
for tsp in tmp_selected_params["par"]:
if tsp not in selected_params:
selected_params.append(tsp)
plotted_cosi = False
for key, vals in com_par_dict.items():
if key in selected_params:
if close:
# hist_core_list_kwargs["title_y"] = 1.0 + 0.05 * 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=legendloc,
real_tm_pars=real_tm_pars,
show=False,
close=False,
**hist_core_list_kwargs,
)
if par_sigma:
fig = plt.gcf()
allaxes = fig.get_axes()
for ax in allaxes:
full_key = ax.get_title()
splt_key = full_key.split("_")
if "DMX" in splt_key:
par_key = ("_").join(splt_key[-2:])
else:
par_key = splt_key[-1]
if par_key in par_sigma:
val = par_sigma[par_key][0]
err = par_sigma[par_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
)