Coverage for pesummary/core/file/formats/dingo.py: 78.5%

79 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2026-01-15 17:49 +0000

1# Licensed under an MIT style license -- see LICENSE.md 

2 

3import numpy as np 

4from pesummary.core.file.formats.base_read import SingleAnalysisRead 

5from pesummary.core.file.formats.bilby import _bilby_prior_dict_to_pesummary_samples_dict 

6from pesummary import conf 

7from pesummary.utils.utils import logger 

8 

9__author__ = [ 

10 "Stephen Green <stephen.green@ligo.org>", 

11 "Nihar Gupte <nihar.gupte@ligo.org>", 

12] 

13 

14 

15def _load_dingo(path): 

16 """Wrapper for `dingo.gw.result.Result` 

17 

18 Parameters 

19 ---------- 

20 path: str 

21 path to the dingo result file you wish to load 

22 """ 

23 from dingo.gw.result import Result 

24 

25 return Result(file_name=path) 

26 

27 

28# TODO: Set up for complex parameters (but first enable output of complex SNR from Dingo) 

29 

30 

31def read_dingo( 

32 path, disable_prior=False, nsamples_for_prior=None, _dingo_class=None, **kwargs 

33): 

34 """Grab the parameters and samples in a dingo file 

35 

36 Parameters 

37 ---------- 

38 path: str 

39 path to the result file you wish to read in 

40 disable_prior: Bool, optional 

41 if True, do not collect prior samples from the `bilby` result file. 

42 Default False 

43 nsamples_for_prior: int, optional 

44 number of samples to draw from the analytic priors 

45 """ 

46 if _dingo_class is None: 

47 _dingo_class = Dingo 

48 dingo_object = _load_dingo(path) 

49 posterior = dingo_object.get_pesummary_samples(num_processes=kwargs.get("num_processes", 1)) 

50 parameters = list(posterior.keys()) 

51 samples = posterior.to_numpy() 

52 injection = dingo_object.injection_parameters 

53 if injection is None: 

54 injection = {i: j for i, j in zip(parameters, [float("nan")] * len(parameters))} 

55 else: 

56 for i in parameters: 

57 if i not in injection.keys(): 

58 injection[i] = float("nan") 

59 

60 try: 

61 extra_kwargs = _dingo_class.grab_extra_kwargs(dingo_object) 

62 except Exception: 

63 extra_kwargs = {"sampler": {}, "meta_data": {}} 

64 extra_kwargs["sampler"]["nsamples"] = len(samples) 

65 if "weights" in dingo_object.samples: 

66 extra_kwargs["sampler"]["pe_algorithm"] = "dingo-is" 

67 else: 

68 extra_kwargs["sampler"]["pe_algorithm"] = "dingo" 

69 try: 

70 version = dingo_object.version 

71 except Exception as e: 

72 version = None 

73 

74 data = { 

75 "parameters": parameters, 

76 "samples": samples.tolist(), 

77 "injection": injection, 

78 "version": version, 

79 "kwargs": extra_kwargs, 

80 } 

81 if not disable_prior: 

82 logger.debug("Drawing prior samples from dingo result file") 

83 if nsamples_for_prior is None: 

84 nsamples_for_prior = len(samples) 

85 prior_samples = Dingo.grab_priors(dingo_object, nsamples=nsamples_for_prior) 

86 data["prior"] = {"samples": prior_samples} 

87 if len(prior_samples): 

88 data["prior"]["analytic"] = prior_samples.analytic 

89 else: 

90 try: 

91 _prior = dingo_object.pesummary_prior 

92 data["prior"] = { 

93 "samples": {}, 

94 "analytic": {key: str(item) for key, item in _prior.items()}, 

95 } 

96 except (AttributeError, KeyError): 

97 pass 

98 return data 

99 

100 

101def prior_samples_from_dingo_object(dingo_object, nsamples=5000, **kwargs): 

102 """Return a dict of prior samples from a `dingo.core.result.Result` 

103 object 

104 

105 Parameters 

106 ---------- 

107 dingo_object: dingo.gw.result.Result 

108 a dingo.core.result.Result object you wish to draw prior samples from 

109 nsamples: int, optional 

110 number of samples to draw from a prior file. Default 5000 

111 """ 

112 samples = dingo_object.pesummary_prior.sample(size=nsamples) 

113 return _bilby_prior_dict_to_pesummary_samples_dict( 

114 samples, prior=dingo_object.pesummary_prior 

115 ) 

116 

117 

118class Dingo(SingleAnalysisRead): 

119 """PESummary wrapper of `dingo` (https://github.com/dingo-gw/dingo). The 

120 path_to_results_file argument will be passed directly to 

121 `bilby.gw.result.Result`. All functions therefore use `dingo` 

122 methods and requires `dingo` to be installed. 

123 

124 Parameters 

125 ---------- 

126 path_to_results_file: str 

127 path to the results file that you wish to read in with `dingo`. 

128 disable_prior: Bool, optional 

129 if True, do not collect prior samples from the `dingo` result file. 

130 Default False 

131 remove_nan_likelihood_samples: Bool, optional 

132 if True, remove samples which have log_likelihood='nan'. Default True 

133 

134 Attributes 

135 ---------- 

136 parameters: list 

137 list of parameters stored in the result file 

138 samples: 2d list 

139 list of samples stored in the result file 

140 samples_dict: dict 

141 dictionary of samples stored in the result file keyed by parameters 

142 input_version: str 

143 version of the result file passed. 

144 extra_kwargs: dict 

145 dictionary of kwargs that were extracted from the result file 

146 injection_parameters: dict 

147 dictionary of injection parameters extracted from the result file 

148 prior: dict 

149 dictionary of prior samples keyed by parameters. The prior functions 

150 are evaluated for 5000 samples. 

151 pe_algorithm: str 

152 name of the algorithm used to generate the posterior samples 

153 

154 Methods 

155 ------- 

156 to_dat: 

157 save the posterior samples to a .dat file 

158 to_latex_table: 

159 convert the posterior samples to a latex table 

160 generate_latex_macros: 

161 generate a set of latex macros for the stored posterior samples 

162 """ 

163 

164 def __init__(self, path_to_results_file, **kwargs): 

165 super().__init__(path_to_results_file, **kwargs) 

166 self.load(self._grab_data_from_dingo_file, **kwargs) 

167 

168 @staticmethod 

169 def grab_priors(dingo_object, nsamples=5000): 

170 """Draw samples from the prior functions stored in the dingo object""" 

171 try: 

172 return prior_samples_from_dingo_object(dingo_object, nsamples=nsamples) 

173 except Exception as e: 

174 logger.info("Failed to draw prior samples because {}".format(e)) 

175 return {} 

176 

177 @staticmethod 

178 def grab_extra_kwargs(dingo_object): 

179 """Grab any additional information stored in the dingo object""" 

180 f = dingo_object 

181 kwargs = { 

182 "sampler": {}, 

183 "meta_data": {}, 

184 "event_metadata": f.event_metadata, 

185 "other": f.metadata, 

186 } 

187 if f.log_evidence: 

188 kwargs["sampler"][conf.log_evidence] = np.round(f.log_evidence, 4) 

189 if f.log_evidence_std: 

190 kwargs["sampler"][conf.log_evidence_error] = np.round(f.log_evidence_std, 4) 

191 if f.log_bayes_factor: 

192 kwargs["sampler"][conf.log_bayes_factor] = np.round(f.log_bayes_factor, 4) 

193 if f.log_noise_evidence: 

194 kwargs["sampler"][conf.log_noise_evidence] = np.round(f.log_noise_evidence, 4) 

195 return kwargs 

196 

197 @staticmethod 

198 def _grab_data_from_dingo_file(path, **kwargs): 

199 """Load the results file using the `dingo` library""" 

200 return read_dingo(path, **kwargs)