lisaanalysistools 1.0.0__cp312-cp312-macosx_10_9_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of lisaanalysistools might be problematic. Click here for more details.

Files changed (37) hide show
  1. lisaanalysistools-1.0.0.dist-info/LICENSE +201 -0
  2. lisaanalysistools-1.0.0.dist-info/METADATA +80 -0
  3. lisaanalysistools-1.0.0.dist-info/RECORD +37 -0
  4. lisaanalysistools-1.0.0.dist-info/WHEEL +5 -0
  5. lisaanalysistools-1.0.0.dist-info/top_level.txt +2 -0
  6. lisatools/__init__.py +0 -0
  7. lisatools/_version.py +4 -0
  8. lisatools/analysiscontainer.py +438 -0
  9. lisatools/cutils/detector.cpython-312-darwin.so +0 -0
  10. lisatools/datacontainer.py +292 -0
  11. lisatools/detector.py +410 -0
  12. lisatools/diagnostic.py +976 -0
  13. lisatools/glitch.py +193 -0
  14. lisatools/sampling/__init__.py +0 -0
  15. lisatools/sampling/likelihood.py +882 -0
  16. lisatools/sampling/moves/__init__.py +0 -0
  17. lisatools/sampling/moves/gbgroupstretch.py +53 -0
  18. lisatools/sampling/moves/gbmultipletryrj.py +1287 -0
  19. lisatools/sampling/moves/gbspecialgroupstretch.py +671 -0
  20. lisatools/sampling/moves/gbspecialstretch.py +1836 -0
  21. lisatools/sampling/moves/mbhspecialmove.py +286 -0
  22. lisatools/sampling/moves/placeholder.py +16 -0
  23. lisatools/sampling/moves/skymodehop.py +110 -0
  24. lisatools/sampling/moves/specialforegroundmove.py +564 -0
  25. lisatools/sampling/prior.py +508 -0
  26. lisatools/sampling/stopping.py +320 -0
  27. lisatools/sampling/utility.py +324 -0
  28. lisatools/sensitivity.py +888 -0
  29. lisatools/sources/__init__.py +0 -0
  30. lisatools/sources/emri/__init__.py +1 -0
  31. lisatools/sources/emri/tdiwaveform.py +72 -0
  32. lisatools/stochastic.py +291 -0
  33. lisatools/utils/__init__.py +0 -0
  34. lisatools/utils/constants.py +40 -0
  35. lisatools/utils/multigpudataholder.py +730 -0
  36. lisatools/utils/pointeradjust.py +106 -0
  37. lisatools/utils/utility.py +240 -0
@@ -0,0 +1,438 @@
1
+ import warnings
2
+ from abc import ABC
3
+ from typing import Any, Tuple, Optional, List
4
+
5
+ import math
6
+ import numpy as np
7
+ from numpy.typing import ArrayLike
8
+ from scipy import interpolate
9
+ import matplotlib.pyplot as plt
10
+
11
+ try:
12
+ import cupy as cp
13
+
14
+ except (ModuleNotFoundError, ImportError):
15
+ import numpy as cp
16
+
17
+ from . import detector as lisa_models
18
+ from .utils.utility import AET, get_array_module
19
+ from .utils.constants import *
20
+ from .stochastic import (
21
+ StochasticContribution,
22
+ FittedHyperbolicTangentGalacticForeground,
23
+ )
24
+ from .datacontainer import DataResidualArray
25
+ from .sensitivity import SensitivityMatrix
26
+ from .diagnostic import (
27
+ noise_likelihood_term,
28
+ residual_full_source_and_noise_likelihood,
29
+ residual_source_likelihood_term,
30
+ inner_product,
31
+ data_signal_source_likelihood_term,
32
+ data_signal_full_source_and_noise_likelihood,
33
+ )
34
+
35
+
36
+ class AnalysisContainer:
37
+ """Combinatorial container that combines sensitivity and data information.
38
+
39
+ Args:
40
+ data_res_arr: Data / Residual / Signal array.
41
+ sens_mat: Sensitivity information.
42
+ signal_gen: Callable object that takes information through ``*args`` and ``**kwargs`` and
43
+ generates a signal in the proper channel setup employed in ``data_res_arr`` and ``sens_mat``.
44
+
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ data_res_arr: DataResidualArray,
50
+ sens_mat: SensitivityMatrix,
51
+ signal_gen: Optional[callable] = None,
52
+ ) -> None:
53
+ self.data_res_arr = data_res_arr
54
+ self.sens_mat = sens_mat
55
+
56
+ if signal_gen is not None:
57
+ self.signal_gen = signal_gen
58
+
59
+ @property
60
+ def data_res_arr(self) -> DataResidualArray:
61
+ """Data information."""
62
+ return self._data_res_arr
63
+
64
+ @data_res_arr.setter
65
+ def data_res_arr(self, data_res_arr: DataResidualArray) -> None:
66
+ """Set data."""
67
+ assert isinstance(data_res_arr, DataResidualArray)
68
+ self._data_res_arr = data_res_arr
69
+
70
+ @property
71
+ def sens_mat(self) -> SensitivityMatrix:
72
+ """Sensitivity information."""
73
+ return self._sens_mat
74
+
75
+ @sens_mat.setter
76
+ def sens_mat(self, sens_mat: SensitivityMatrix) -> None:
77
+ "Set sensitivity information."
78
+ assert isinstance(sens_mat, SensitivityMatrix)
79
+ self._sens_mat = sens_mat
80
+
81
+ @property
82
+ def signal_gen(self) -> callable:
83
+ """Signal generator."""
84
+ if not hasattr(self, "_signal_gen"):
85
+ raise ValueError(
86
+ "User must input signal_gen kwarg to use the signal generator."
87
+ )
88
+ return self._signal_gen
89
+
90
+ @signal_gen.setter
91
+ def signal_gen(self, signal_gen: callable):
92
+ """Set signal generator."""
93
+ assert hasattr(signal_gen, "__call__")
94
+ self._signal_gen = signal_gen
95
+
96
+ def loglog(self) -> Tuple[plt.Figure, plt.Axes]:
97
+ """Produce loglog plot of both source and sensitivity information.
98
+
99
+ Returns:
100
+ Matplotlib figure and axes object in a 2-tuple.
101
+
102
+ """
103
+ fig, ax = self.sens_mat.loglog(char_strain=True)
104
+ if self.sens_mat.ndim == 3:
105
+ # 3x3 most likely
106
+ for i in range(self.sens_mat.shape[0]):
107
+ for j in range(i, self.sens_mat.shape[1]):
108
+ # char strain
109
+ ax[i * self.sens_mat.shape[1] + j].loglog(
110
+ self.data_res_arr.f_arr,
111
+ self.data_res_arr.f_arr * self.data_res_arr[i],
112
+ )
113
+ ax[i * self.sens_mat.shape[1] + j].loglog(
114
+ self.data_res_arr.f_arr,
115
+ self.data_res_arr.f_arr * self.data_res_arr[j],
116
+ )
117
+ else:
118
+ for i in range(self.sens_mat.shape[0]):
119
+ ax[i].loglog(
120
+ self.data_res_arr.f_arr,
121
+ self.data_res_arr.f_arr * self.data_res_arr[i],
122
+ )
123
+ return (fig, ax)
124
+
125
+ def inner_product(self, **kwargs: dict) -> float | complex:
126
+ """Return the inner product of the current set of information
127
+
128
+ Args:
129
+ **kwargs: Inner product keyword arguments.
130
+
131
+ Returns:
132
+ Inner product value.
133
+
134
+ """
135
+ if "psd" in kwargs:
136
+ kwargs.pop("psd")
137
+
138
+ return inner_product(self.data_res_arr, self.data_res_arr, psd=self.sens_mat)
139
+
140
+ def snr(self, **kwargs: dict) -> float:
141
+ """Return the SNR of the current set of information
142
+
143
+ Args:
144
+ **kwargs: Inner product keyword arguments.
145
+
146
+ Returns:
147
+ SNR value.
148
+
149
+ """
150
+ return self.inner_product(**kwargs).real ** (1 / 2)
151
+
152
+ def template_inner_product(
153
+ self, template: DataResidualArray, **kwargs: dict
154
+ ) -> float | complex:
155
+ """Calculate the inner product of a template with the data.
156
+
157
+ Args:
158
+ template: Template signal.
159
+ **kwargs: Keyword arguments to pass to :func:`lisatools.diagnostic.inner_product`.
160
+
161
+ Returns:
162
+ Inner product value.
163
+
164
+ """
165
+ if "psd" in kwargs:
166
+ kwargs.pop("psd")
167
+
168
+ if "include_psd_info" in kwargs:
169
+ kwargs.pop("include_psd_info")
170
+
171
+ ip_val = inner_product(self.data_res_arr, template, psd=self.sens_mat, **kwargs)
172
+ return ip_val
173
+
174
+ def template_snr(
175
+ self, template: DataResidualArray, phase_maximize: bool = False, **kwargs: dict
176
+ ) -> Tuple[float, float]:
177
+ """Calculate the SNR of a template, both optimal and detected.
178
+
179
+ Args:
180
+ template: Template signal.
181
+ phase_maximize: If ``True``, maximize over an overall phase.
182
+ **kwargs: Keyword arguments to pass to :func:`lisatools.diagnostic.inner_product`.
183
+
184
+ Returns:
185
+ ``(optimal snr, detected snr)``.
186
+
187
+ """
188
+ kwargs_in = kwargs.copy()
189
+ if "psd" in kwargs:
190
+ kwargs_in.pop("psd")
191
+
192
+ if "complex" in kwargs_in:
193
+ kwargs_in.pop("complex")
194
+
195
+ # TODO: should we cache?
196
+ h_h = inner_product(template, template, psd=self.sens_mat, **kwargs_in)
197
+ non_marg_d_h = inner_product(
198
+ self.data_res_arr, template, psd=self.sens_mat, complex=True, **kwargs_in
199
+ )
200
+ d_h = np.abs(non_marg_d_h) if phase_maximize else non_marg_d_h.copy()
201
+ self.non_marg_d_h = non_marg_d_h
202
+
203
+ opt_snr = np.sqrt(h_h.real)
204
+ det_snr = d_h.real / opt_snr
205
+ return (opt_snr, det_snr)
206
+
207
+ def template_likelihood(
208
+ self,
209
+ template: DataResidualArray,
210
+ include_psd_info: bool = False,
211
+ phase_maximize: bool = False,
212
+ **kwargs: dict
213
+ ) -> float:
214
+ """Calculate the Likelihood of a template against the data.
215
+
216
+ Args:
217
+ template: Template signal.
218
+ include_psd_info: If ``True``, add the PSD term to the Likelihood value.
219
+ phase_maximize: If ``True``, maximize over an overall phase.
220
+ **kwargs: Keyword arguments to pass to :func:`lisatools.diagnostic.inner_product`.
221
+
222
+ Returns:
223
+ Likelihood value.
224
+
225
+ """
226
+ kwargs_in = kwargs.copy()
227
+ if "psd" in kwargs_in:
228
+ kwargs_in.pop("psd")
229
+
230
+ if "complex" in kwargs_in:
231
+ kwargs_in.pop("complex")
232
+
233
+ # TODO: should we cache?
234
+ d_d = inner_product(
235
+ self.data_res_arr, self.data_res_arr, psd=self.sens_mat, **kwargs_in
236
+ )
237
+ h_h = inner_product(template, template, psd=self.sens_mat, **kwargs_in)
238
+ non_marg_d_h = inner_product(
239
+ self.data_res_arr, template, psd=self.sens_mat, complex=True, **kwargs_in
240
+ )
241
+ d_h = np.abs(non_marg_d_h) if phase_maximize else non_marg_d_h.copy()
242
+ self.non_marg_d_h = non_marg_d_h
243
+ like_out = -1 / 2 * (d_d + h_h - 2 * d_h).real
244
+
245
+ if include_psd_info:
246
+ # add noise term if requested
247
+ like_out += self.likelihood(noise_only=True)
248
+
249
+ return like_out
250
+
251
+ def likelihood(
252
+ self, source_only: bool = False, noise_only: bool = False, **kwargs: dict
253
+ ) -> float | complex:
254
+ """Return the likelihood of the current arangement.
255
+
256
+ Args:
257
+ source_only: If ``True`` return the source-only Likelihood.
258
+ noise_only: If ``True``, return the noise part of the Likelihood alone.
259
+ **kwargs: Keyword arguments to pass to :func:`lisatools.diagnostic.inner_product`.
260
+
261
+ Returns:
262
+ Likelihood value.
263
+
264
+ """
265
+ if noise_only and source_only:
266
+ raise ValueError("noise_only and source only cannot both be True.")
267
+ elif noise_only:
268
+ return noise_likelihood_term(self.sens_mat)
269
+ elif source_only:
270
+ return residual_source_likelihood_term(
271
+ self.data_res_arr, self.sens_mat, **kwargs
272
+ )
273
+ else:
274
+ return residual_full_source_and_noise_likelihood(
275
+ self.data_res_arr, self.sens_mat, **kwargs
276
+ )
277
+
278
+ def _calculate_signal_operation(
279
+ self,
280
+ calc: str,
281
+ *args: ArrayLike,
282
+ source_only: bool = False,
283
+ waveform_kwargs: Optional[dict] = {},
284
+ data_res_arr_kwargs: Optional[dict] = {},
285
+ **kwargs: dict
286
+ ) -> float | complex:
287
+ """Return the likelihood of a generated signal with the data.
288
+
289
+ Args:
290
+ calc: Type of calculation to do. Options are ``"likelihood"``, ``"inner_product"``, or ``"snr"``.
291
+ *args: Arguments to waveform generating function. Must include parameters.
292
+ source_only: If ``True`` return the source-only Likelihood (leave out noise part).
293
+ waveform_kwargs: Keyword arguments to pass to waveform generator.
294
+ data_res_arr_kwargs: Keyword arguments for instantiation of :class:`DataResidualArray`.
295
+ This can be used if any transforms are desired prior to the Likelihood computation. If it is not input,
296
+ the kwargs are taken to be the same as those used to initalize ``self.data_res_arr``.
297
+ **kwargs: Keyword arguments to pass to :func:`lisatools.diagnostic.inner_product`
298
+
299
+ Returns:
300
+ Likelihood value.
301
+
302
+ """
303
+
304
+ if data_res_arr_kwargs == {}:
305
+ data_res_arr_kwargs = self.data_res_arr.init_kwargs
306
+
307
+ template = DataResidualArray(
308
+ self.signal_gen(*args, **waveform_kwargs), **data_res_arr_kwargs
309
+ )
310
+
311
+ args_2 = (template,)
312
+
313
+ if "include_psd_info" in kwargs:
314
+ assert kwargs["include_psd_info"] == (not source_only)
315
+ kwargs.pop("include_psd_info")
316
+
317
+ kwargs = dict(psd=self.sens_mat, **kwargs)
318
+
319
+ if calc == "likelihood":
320
+ kwargs["include_psd_info"] = not source_only
321
+ return self.template_likelihood(*args_2, **kwargs)
322
+ elif calc == "inner_product":
323
+ return self.template_inner_product(*args_2, **kwargs)
324
+ elif calc == "snr":
325
+ return self.template_snr(*args_2, **kwargs)
326
+ else:
327
+ raise ValueError("`calc` must be 'likelihood', 'inner_product', or 'snr'.")
328
+
329
+ def calculate_signal_likelihood(
330
+ self,
331
+ *args: ArrayLike,
332
+ source_only: bool = False,
333
+ waveform_kwargs: Optional[dict] = {},
334
+ data_res_arr_kwargs: Optional[dict] = {},
335
+ **kwargs: dict
336
+ ) -> float | complex:
337
+ """Return the likelihood of a generated signal with the data.
338
+
339
+ Args:
340
+ params: Arguments to waveform generating function. Must include parameters.
341
+ source_only: If ``True`` return the source-only Likelihood (leave out noise part).
342
+ waveform_kwargs: Keyword arguments to pass to waveform generator.
343
+ data_res_arr_kwargs: Keyword arguments for instantiation of :class:`DataResidualArray`.
344
+ This can be used if any transforms are desired prior to the Likelihood computation.
345
+ **kwargs: Keyword arguments to pass to :func:`lisatools.diagnostic.inner_product`
346
+
347
+ Returns:
348
+ Likelihood value.
349
+
350
+ """
351
+
352
+ return self._calculate_signal_operation(
353
+ "likelihood",
354
+ *args,
355
+ source_only=source_only,
356
+ waveform_kwargs=waveform_kwargs,
357
+ data_res_arr_kwargs=data_res_arr_kwargs,
358
+ **kwargs
359
+ )
360
+
361
+ def calculate_signal_inner_product(
362
+ self,
363
+ *args: ArrayLike,
364
+ source_only: bool = False,
365
+ waveform_kwargs: Optional[dict] = {},
366
+ data_res_arr_kwargs: Optional[dict] = {},
367
+ **kwargs: dict
368
+ ) -> float | complex:
369
+ """Return the inner product of a generated signal with the data.
370
+
371
+ Args:
372
+ *args: Arguments to waveform generating function. Must include parameters.
373
+ source_only: If ``True`` return the source-only Likelihood (leave out noise part).
374
+ waveform_kwargs: Keyword arguments to pass to waveform generator.
375
+ data_res_arr_kwargs: Keyword arguments for instantiation of :class:`DataResidualArray`.
376
+ This can be used if any transforms are desired prior to the Likelihood computation.
377
+ **kwargs: Keyword arguments to pass to :func:`lisatools.diagnostic.inner_product`
378
+
379
+ Returns:
380
+ Inner product value.
381
+
382
+ """
383
+
384
+ return self._calculate_signal_operation(
385
+ "inner_product",
386
+ *args,
387
+ source_only=source_only,
388
+ waveform_kwargs=waveform_kwargs,
389
+ data_res_arr_kwargs=data_res_arr_kwargs,
390
+ **kwargs
391
+ )
392
+
393
+ def calculate_signal_snr(
394
+ self,
395
+ *args: ArrayLike,
396
+ source_only: bool = False,
397
+ waveform_kwargs: Optional[dict] = {},
398
+ data_res_arr_kwargs: Optional[dict] = {},
399
+ **kwargs: dict
400
+ ) -> Tuple[float, float]:
401
+ """Return the SNR of a generated signal with the data.
402
+
403
+ Args:
404
+ *args: Arguments to waveform generating function. Must include parameters.
405
+ source_only: If ``True`` return the source-only Likelihood (leave out noise part).
406
+ waveform_kwargs: Keyword arguments to pass to waveform generator.
407
+ data_res_arr_kwargs: Keyword arguments for instantiation of :class:`DataResidualArray`.
408
+ This can be used if any transforms are desired prior to the Likelihood computation.
409
+ **kwargs: Keyword arguments to pass to :func:`lisatools.diagnostic.inner_product`
410
+
411
+ Returns:
412
+ Snr values (optimal, detected).
413
+
414
+ """
415
+
416
+ return self._calculate_signal_operation(
417
+ "snr",
418
+ *args,
419
+ source_only=source_only,
420
+ waveform_kwargs=waveform_kwargs,
421
+ data_res_arr_kwargs=data_res_arr_kwargs,
422
+ **kwargs
423
+ )
424
+
425
+ def eryn_likelihood_function(self, x, *args, **kwargs):
426
+ if x.ndim == 1:
427
+ input_vals = tuple(x) + tuple(args)
428
+ return self.calculate_signal_likelihood(*input_vals, **kwargs)
429
+ elif x.ndim == 2:
430
+ likelihood_out = np.zeros(x.shape[0])
431
+ for i in range(x.shape[0]):
432
+ input_vals = tuple(x[i]) + tuple(args)
433
+ likelihood_out[i] = self.calculate_signal_likelihood(
434
+ *input_vals, **kwargs
435
+ )
436
+
437
+ else:
438
+ raise ValueError("x must be a 1D or 2D array.")