Coverage for pesummary/gw/file/formats/pycbc.py: 58.5%
41 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-05-16 08:11 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-05-16 08:11 +0000
1# Licensed under an MIT style license -- see LICENSE.md
3import numpy as np
4from pesummary.gw.file.formats.base_read import GWSingleAnalysisRead
5from pesummary import conf
6from pesummary.core.file.formats.ini import read_ini
7from pycbc.inference.io import loadfile
9__author__ = ["Charlie Hoy <charlie.hoy@ligo.org>"]
11def read_pycbc(path, **kwargs):
12 """Grab the parameters and samples in a pycbc file
14 Parameters
15 ----------
16 path: str
17 path to the result file you wish to read in
18 """
19 with loadfile(path, "r") as f:
20 params = list(f["samples"].keys())
21 _samples = f.read_samples(params)
22 samples = {key: _samples[key] for key in _samples.dtype.names}
23 try:
24 from pycbc.conversions import snr_from_loglr
25 samples["network_matched_filter_snr"] = snr_from_loglr(
26 samples["loglikelihood"] - _samples.lognl
27 )
28 except AttributeError:
29 pass
30 try:
31 config = read_ini(f.read_config_file(return_cp=False).read())
32 except (KeyError, IndexError):
33 # no config file stored
34 config = None
35 extra_kwargs = {
36 "sampler": {}, "meta_data": {}, "other": dict(f.attrs)
37 }
38 try:
39 extra_kwargs["sampler"][conf.log_evidence] = np.round(
40 extra_kwargs["other"].pop("log_evidence"), 2
41 )
42 extra_kwargs["sampler"][conf.log_evidence_error] = np.round(
43 extra_kwargs["other"].pop("dlog_evidence"), 2
44 )
45 except KeyError:
46 pass
48 low_freqs = [
49 item for key, item in extra_kwargs["other"].items() if
50 "likelihood_low_freq" in key
51 ]
52 if len(low_freqs):
53 extra_kwargs["meta_data"]["f_low"] = np.min(low_freqs)
54 try:
55 extra_kwargs["meta_data"]["f_ref"] = extra_kwargs["other"].pop("f_ref")
56 except KeyError:
57 pass
59 data = {
60 "parameters": list(samples.keys()),
61 "samples": np.array([_ for _ in samples.values()]).T.tolist(),
62 "injection": None,
63 "version": None,
64 "kwargs": extra_kwargs,
65 "config": config
66 }
67 return data
70class PyCBC(GWSingleAnalysisRead):
71 """PESummary wrapper of `pycbc` (https://git.ligo.org/lscsoft/bilby). The
72 path_to_results_file argument will be passed directly to
73 `pycbc.inference.io.loadfile`. All functions therefore use `pycbc`
74 methods and requires `pycbc` to be installed.
75 """
76 def __init__(self, path_to_results_file, **kwargs):
77 super(PyCBC, self).__init__(path_to_results_file, **kwargs)
78 self.load(self._grab_data_from_pycbc_file, **kwargs)
80 def _grab_data_from_pycbc_file(self, *args, **kwargs):
81 """Load the results file using the `pycbc` library
82 """
83 return read_pycbc(*args, **kwargs)