API reference¶
Data module¶
Utilities for handling and manipulating strain data from gravitational-wave detectors.
- class ringdown.data.AutoCovariance(*args, delta_t=None, ifo=None, attrs=None, **kwargs)¶
Bases:
TimeSeriesContains and manipulates autocovariance functions, a special kind of
TimeSeries.- property cholesky: ndarray¶
Cholesky factor \(L\) of covariance matrix \(C = L^TL\).
- compute_snr(x, y=None) float¶
Efficiently compute the signal-to_noise ratio \(\mathrm{SNR} = \left\langle x \mid y \right\rangle / \sqrt{\left\langle x \mid x \right\rangle}\), where the inner product is defined by \(\left\langle x \mid y \right\rangle \equiv x_i C^{-1}_{ij} y_j\). This is internally computed using Cholesky factors to speed up the computation.
If x is a signal and y is noisy data, then this is the matched filter SNR; if both of them are a template, then this is the optimal SNR.
- Parameters:
x (array) – target time series.
y (array) – reference time series. Defaults to x.
- Returns:
snr – signal-to-noise ratio
- Return type:
float
- classmethod from_data(d, n=None, delta_t=None, method='fd', **kws)¶
Estimate
AutoCovariancefrom time domain data using Welch’s method by default.- Parameters:
d (Data, array) – data time series.
n (int) – length of output ACF. Defaults to
len(d).delta_t (float) – time-sample spacing, necessary if d is a simple array with no associated timing information. Defaults to d.delta_t if d is
Data.method (str) – whether to use Welch’s method (
'fd'), or simply auto-correlate the data ('td'). The latter is highly discouraged and will result in a warning. Defaults to fd.**kws – additional keyword arguments passed to
PowerSpectrum.fom_data().
- Returns:
acf – estimate of the autocovariance function.
- Return type:
- inner_product(x, y=None) complex¶
Compute the noise weighterd inner product between x and y defined by \(\left\langle x \mid y \right\rangle \equiv x_i C^{-1}_{ij} y_j\).
- Parameters:
x (array) – target time series.
y (array) – reference time series. Defaults to x.
- Returns:
snr – signal-to-noise ratio
- Return type:
float
- property matrix: ndarray¶
Covariance matrix built from ACF, \(C_{ij} = \rho(|i-j|)\).
- to_psd() PowerSpectrum¶
Returns corresponding
PowerSpectrum, obtained by Fourier transforming ACF.- Returns:
psd – power spectral density.
- Return type:
- whiten(data) Data | TimeSeries | ndarray¶
Whiten stretch of data using ACF.
- Parameters:
data (array, TimeSeries) – unwhitened data.
- Returns:
w_data – whitened data.
- Return type:
Data | TimeSeries | array
- class ringdown.data.Data(*args, ifo=None, attrs=None, **kwargs)¶
Bases:
TimeSeriesContainer for time-domain strain data from a given GW detector.
- ifo¶
detector identifier (e.g., ‘H1’ for LIGO Hanford).
- Type:
str
- attrs¶
optional additional information, e.g., to identify data provenance.
- Type:
dict
- condition(t0: float | None = None, ds: int | None = None, f_min: float | None = None, f_max: float | None = None, trim: float = 0.25, digital_filter: bool = True, remove_mean: bool = True, decimate_kws: dict | None = None, slice_left: float | None = None, slice_right: float | None = None)¶
Condition data.
- Parameters:
t0 (float) – target time to be preserved after downsampling.
ds (int) – decimation factor for downsampling.
f_min (float) – lower frequency for high passing.
f_max (float) – higher frequency for low passing.
trim (float) – fraction of data to trim from edges after conditioning, to avoid spectral issues if filtering (default 0.25).
digital_filter (bool) – apply digital antialiasing filter by discarding Fourier components higher than Nyquist; otherwise, filter through
scipy.signal.decimate().(default True).remove_mean (bool) – explicitly remove mean from time series after conditioning (default True).
decimate_kws (dict) – options for decimation function.
slice_left (float) – number of seconds before t0 to slice the strain data, e.g. to avoid NaNs
slice_right (float) – number of seconds after t0 to slice the strain data, e.g. to avoid NaNs
- Returns:
cond_data – conditioned data object.
- Return type:
- property detector: <MagicMock id='139050237477568'>¶
lalobject containing detector information.
- classmethod from_psd(psd: PowerSpectrum, **kws)¶
Generate data from a given PSD.
- Parameters:
psd (PowerSpectrum) – power spectral density.
- Returns:
data – time series data.
- Return type:
- get_acf(**kws)¶
Estimate ACF from data, see
AutoCovariance.from_data().
- get_psd(**kws)¶
Estimate PSD from data, see
PowerSpectrum.from_data().
- class ringdown.data.FrequencySeries(data=None, index=None, dtype: Dtype | None = None, name=None, copy: bool | None = None, fastpath: bool | lib.NoDefault = <no_default>)¶
Bases:
SeriesA container for frequency domain data based on pandas.Series; the index should contain frequency stamps for uniformly-sampled data.
- property delta_f: float¶
Fourier frequency spacing.
- property delta_t: float¶
Sampling time interval.
- property duration: float¶
Time series duration (time spanned between first and last samples).
- property f_samp: float¶
Sampling frequency (1/delta_t).
- property freq: Index¶
Frequency stamps.
- interpolate_to_index(freq: ndarray | None = None, delta_f: float | None = None, f_min: float | None = None, f_max: float | None = None, log: bool = False, force: bool = False, **kws)¶
Interpolate the
FrequencySeriesto new index. Inherits fromSeries.interpolate_to_index().If no frequency arguments are specified, it will interpolate to a a frequency array with the same span as the original, but enforcing uniform spacing based on the difference between the first two frequency samples.
- Parameters:
freq (list or numpy array or pd.Series) – array of frequency bins to label the new frequencies
delta_f (float) – frequency steps of the new interpolated signal
f_min (float) – instead of an array of frequencies, one can provide the starting frequency
f_min, the highest frequencyf_maxand the frequency spacingdelta_f.f_max (float) – max frequency of the new interpolated signal
log (bool) – interpolate in log-log space [EXPERIMENTAL] (default False)
- Returns:
new_series – interpolated series
- Return type:
- to_time_series(epoch=0.0)¶
Inverse Fourier transform frequency series to time series.
- Returns:
time_series – time series.
- Return type:
- class ringdown.data.PowerSpectrum(*args, delta_f=None, ifo=None, attrs=None, fill_power_of_two=True, enforce_uniform_spacing=True, **kwargs)¶
Bases:
FrequencySeriesContains and manipulates power spectral densities, a special kind of
FrequencySeries.- compute_snr(x: FrequencySeries, y: FrequencySeries | None = None, f_min: float | None = None, f_max: float | None = None) float¶
Efficiently compute the signal-to_noise ratio \(\mathrm{SNR} = \left\langle x \mid y \right\rangle / \sqrt{\left\langle x \mid x \right\rangle}\), where the inner product is defined by \(\left\langle x \mid y \right\rangle \equiv 4 \Delta f \Re \sum x_i y_i / S_i\).
If x is a signal and y is noisy data, then this is the matched filter SNR; if both of them are a template, then this is the optimal SNR (default).
- Parameters:
x (array) – target frequency series.
y (array) – reference frequency series. Defaults to x.
- Returns:
snr – signal-to-noise ratio
- Return type:
float
- draw_noise_fd(freq: ndarray | None = None, delta_f: float | None = None, f_min: float | None = None, f_max: float | None = None, prng: int | Generator | None = None, **kws)¶
Draw Fourier-domain noise from the PSD, with variance consistent with the LIGO definition of the PSD (cf. GW likelihood), namely
\[\tilde{h}(f) \sim \mathcal{N}(0, \sqrt{\frac{S(f)}{4\Delta f}\]where the covariance matrix is diagonal, and \(\Delta f = 1/T\) is the PSD.
Can specify a frequency array or frequency range and spacing to which interpolate or extrapolate the PSD.
Other keyword arguments are passed to the interpolation rutine
PowerSpectrum.interpolate_to_index().- Parameters:
freq (array) – frequencies over which to draw noise (default to PSD index).
delta_f (float) – frequency spacing; can be used to create
freqif not provided).f_min (float) – minimum frequency to draw noise.
f_max (float) – maximum frequency to draw noise.
prng (int, np.random.Generator) – random number generator.
kws (dict) – additional keyword arguments passed to
PowerSpectrum.interpolate_to_index().
- Returns:
noise – noise realization.
- Return type:
- draw_noise_td(duration: float | None = None, f_samp: float | None = None, delta_t: float | None = None, f_min: float | None = None, f_max: float | None = None, delta_f: float | None = None, epoch=0.0, **kws)¶
Draw time-domain noise from the PSD.
Duration and sampling rate are determined from the PSD if not provided. If a frequency range is provided, the PSD is interpolated/extrapolated to that range before drawing the noise.
Additional keyword arguments are passed to
PowerSpectrum.draw_noise_fd().- Parameters:
duration (float) – duration of the time series (provide this argument or delta_f).
f_samp (float) – sampling frequency (provide this argument or f_high which will be half of f_samp; alternatively, f_samp will be determined from delta_t).
delta_t (float) – time step (provide this argument or f_samp or f_high).
f_min (float) – minimum frequency to draw noise.
f_max (float) – maximum frequency to draw noise.
delta_f (float) – frequency step (provide this argument or duration)
epoch (float) – initial time of the time series.
kws (dict) – additional keyword arguments passed to
PowerSpectrum.draw_noise_fd().
- Returns:
noise – noise realization.
- Return type:
- fill_low_frequencies(f_min: float = 0.0, fill_value: float | None = None, **kws) PowerSpectrum¶
Complete low frequencies in power spectrum, extending all the way down to f_min, which defaults to 0. If fill_value is not provided, it will be set to 10 times the maximum PSD value.
If f_min is not below the lowest frequency in the PSD, nothing is done and the PSD is returned as is.
Additional arguments are passed to
PowerSpectrum.interpolate_to_index().- Parameters:
f_min (float) – lower frequency threshold.
fill_value (float) – value with which to patch PSD below f_min.
kws (**) – additional keyword arguments passed to
PowerSpectrum.interpolate_to_index().
- Returns:
psd – power spectrum with low frequencies completed.
- Return type:
- fill_power_of_two() None¶
Ensure that the power spectrum is complete up to the next power of two frequency.
- classmethod from_data(data: Data | ndarray, f_min: float | None = None, f_max: float | None = None, fill_value: float | tuple | None = None, **kws)¶
Estimate
PowerSpectrumfrom time domain data using Welch’s method.- Parameters:
data (Data, array) – data time series.
f_min (float, None) – optional lower frequency at which to taper PSD via
PowerSpectrum.patch(). Defaults to None (i.e., no patching).f_max (float, None) – optional higher frequency at which to taper PSD via
PowerSpectrum.patch(). Defaults to None (i.e., no patching).fill_value (float, tuple, None) – value with which to patch PSD; if a tuple, then these
(psd_low, psd_high)values are used at the low and high ends respectively; if a float, the same value is used in both ends; if None, will patch with 10x the maximum PSD value in the respective patched region.**kws – additional keyword arguments passed to
scipy.signal.Welch().
- Returns:
psd – power specturm estimate.
- Return type:
- classmethod from_lalsimulation(func: str | Callable, freq: ndarray | None = None, f_min: float = 0, f_max: float | None = None, delta_f: float | None = None, fill_value: float | None = None, **kws)¶
Obtain
PowerSpectrumfrom LALSimulation function.- Parameters:
func (str, builtin_function_or_method) – LALSimulation PSD function, or name thereof (e.g.,
SimNoisePSDaLIGOZeroDetHighPower).freq (array) – frequencies over which to evaluate PSD.
f_min (float) – lower frequency threshold for padding: PSD will be patched below this value.
delta_f (float) – frequency spacing (required if
freqis not provided).fill_value (float) – value with which to patch PSD below
f_min.**kw – additional arguments passed to padding function
PowerSpectrum.patch().
- Returns:
psd – power spectrum frequency series.
- Return type:
- gate(max_dynamic_range=10, inplace=False)¶
Gate PSD to avoid numerical issues.
- Parameters:
max_dynamic_range (float) – maximum dynamic range in decades to allow in the PSD.
- Returns:
psd – gated power spectrum.
- Return type:
- inner_product(x: FrequencySeries, y: FrequencySeries | None = None, f_min: float | None = None, f_max: float | None = None) complex¶
Compute the noise weighterd inner product between x and y defined by \(\left\langle x \mid y \right\rangle \equiv 4 \Delta f \Re \sum x_i y_i / S_i\).
- Parameters:
x (array) – target frequency series.
y (array) – reference frequency series. Defaults to x.
f_min (float) – lower frequency bound (default derived from x)
f_max (float) – upper frequency bound (default derived from x)
- Returns:
snr – signal-to-noise ratio
- Return type:
float
- patch(f_min, f_max=None, patch_level=None, in_place=False, fill_value=None)¶
Modify PSD at low or high frequencies so that it patches to a constant.
- Parameters:
f_min (float) – low frequency threshold.
f_max (float) – high frequency threshold (def., None).
patch_level (float,tuple) – value with which to patch PSD; if a tuple, then these
(psd_low, psd_high)values are used at the low and high ends respectively; if a float, the same value is used in both ends; if None, will patch with 10x the maximum PSD value in the respective patched region.fill_value (float) – an alias for patch level for consistency with interp1d
in_place (bool) – modify PSD in place; otherwise, returns copy. Defaults to False.
- Returns:
psd – returns PSD only if not
in_place.- Return type:
PowerSpectrum, None
- to_acf()¶
Return cyclic ACF corresponding to PSD obtained by inverse Fourier transforming.
- Returns:
acf – autocovariance function.
- Return type:
- class ringdown.data.Series(data=None, index=None, dtype: Dtype | None = None, name=None, copy: bool | None = None, fastpath: bool | lib.NoDefault = <no_default>)¶
Bases:
SeriesA wrapper of
pandas.Serieswith some additional functionality.- classmethod fetch(channel: str, start: float | None = None, end: float | None = None, t0: float | None = None, seglen: float | None = None, frametype: str | None = None, **kws)¶
Download open data or discover data using NDS2 (requires GWpy).
Uses GWpy’s
gwpy.timeseries.TimeSeries.fetch_open_data()orgwpy.timeseries.TimeSeries.get()to download data. If channel is ‘GWOSC’, then it will download open data from GWOSC; otherwise, it will attempt to discover remote or local data using NDS2.- Parameters:
channel (str) – channel name or ‘GWOSC’ for public data.
start (float) – start GPS time.
end (float) – end GPS time.
t0 (float) – center time of segment to fetch (alternative to start and end).
seglen (float) – length of segment to fetch (alternative to start and end).
frametype (str) – specify frame type to facilitate NDS frame discovery.
**kws – additional keyword arguments passed to GWpy’s fetch function.
- Returns:
series – series downloaded from GWOSC or NDS.
- Return type:
- interpolate_to_index(new_index, **kwargs)¶
Reinterpolate the
Seriesto new index.Makes use of
scipy.interpolate.interp1d()to which additional arguments are passed (by default{'kind': 'cubic', 'fill_value': 0, 'bounds_error': False})
- classmethod load(path: str | None = None, channel: str | None = None, **kws)¶
Universal load function to read data from disk or discover GWOSC/NDS data using GWpy.
Only one of path or channel can be provided. If a path is provided, it will attempt to read the data from disk using
Series.read(); if channel is provided, it will attempt to discover and fetch the data usingSeries.fetch(), which leverages GWpy’s NDS2 interface.A special case of the latter is when channel is ‘GWOSC’ (case insensitive); if so, it will download open data from GWOSC.
- Parameters:
path (str) – path to file, or None if fetching remote data
channel (str) – channel name or ‘GWOSC’ for public data (case insensitive)
**kws – additional keyword arguments passed to
Series.read()orSeries.fetch().
- classmethod read(path: str, kind: str | None = None, channel: str | None = None, **kws)¶
Load data from disk.
If
kindis gwosc assumes input is an strain HDF5 file downloaded from GWOSC. Ifkindis frame and the keyword channel is given, then attempt to load the given path(s) using gwpy’s frame file reading. Otherwise, it is a wrapper aroundpandas.read_hdf()orpandas.read_csv()functions, forkind = 'hdf'orkind = 'csv'.If
kindisNone, guesses filetype from extension.- Parameters:
path (str) – path to file, or None if fetching remote data.
kind (str) – kind of file to load: gwsoc, hdf or csv.
channel (str) – channel name to use when reading GW frame files (not required otherwise).
- Returns:
series – series loaded from disk
- Return type:
- class ringdown.data.TimeSeries(data=None, index=None, dtype: Dtype | None = None, name=None, copy: bool | None = None, fastpath: bool | lib.NoDefault = <no_default>)¶
Bases:
SeriesA container for time series data based on pandas.Series; the index should contain time stamps for uniformly-sampled data.
- property delta_f: float¶
Fourier frequency spacing.
- property delta_t: float¶
Sampling time interval.
- property duration: float¶
Time series duration (time spanned between first and last samples).
- property epoch: float¶
Time of first sample.
- property f_samp: float¶
Sampling frequency (1/delta_t).
- interpolate_to_index(time=None, t0=None, duration=None, delta_t=None, fsamp=None, **kws)¶
Reinterpolate the
TimeSeriesto new index. Inherits fromSeries.interpolate_to_index().- Parameters:
time (list or numpy array or pd.Series) – new times over which to interpolate
t0 (float) – instead of an array of times, one can provide the start time
t0the duration and sample rate. If these andtimeare provided then the duration and sampling rate are taken from thetimearray, settingt0to be the original oneduration (float) – duration of the new interpolated signal
fsamp (float) – sample rate of the new interpolated signal
- Returns:
new_series – interpolated series
- Return type:
- property time: Index¶
Time stamps.
- to_frequency_series()¶
Fourier transform time series to frequency series.
- Returns:
freq_series – frequency series.
- Return type:
Fit module¶
Module defining the core Fit class.
- class ringdown.fit.Fit(modes=None, strain_scale='auto', imr_result=None, **kws)¶
Bases:
objectA ringdown fit. Contains all the information required to setup and run a ringdown inference analysis, as well as to manipulate the result.
Example usage:
import ringdown as rd fit = rd.Fit(modes=[(1,-2,2,2,0), (1,-2,2,2,1)]) fit.load_data('{i}-{i}1_GWOSC_16KHZ_R1-1126259447-32.hdf5', ifos=['H1', 'L1'], kind='gwosc') fit.set_target(1126259462.4083147, ra=1.95, dec=-1.27, psi=0.82, duration=0.05) fit.condition_data(ds=8) fit.update_model(a_scale_max=1e-21, m_min=50, m_max=150, cosi=-1) fit.run()
- data¶
dictionary containing data, indexed by detector name.
- Type:
dict
- acfs¶
dictionary containing autocovariance functions corresponding to data, if already computed.
- Type:
dict
- start_times¶
target truncation time for each detector.
- Type:
dict
- antenna_patterns¶
dictionary of tuples (Fp, Fc) with plus and cross antenna patterns for each detector (only applicable depending on model).
- Type:
dict
- target¶
information about truncation time at geocenter and, if applicable, source right ascension, declination and polarization angle.
- Type:
- result¶
if model has been run, arviz object containing fit result
- Type:
Result, arviz.data.inference_data.InferenceData
- prior¶
if model prior has been run, arviz object containing prior
- Type:
Result, arviz.data.inference_data.InferenceData
- modes¶
if applicable, list of (p, s, l, m, n) tuples identifying modes to be fit (else, None).
- Type:
list
- n_modes¶
number of modes to be fit.
- Type:
int
- ifos¶
list of detector names.
- Type:
list
- t0¶
target geocenter start time.
- Type:
float
- sky¶
tuple with source right ascension, declination and polarization angle.
- Type:
tuple
- analysis_data¶
dictionary of truncated analysis data that will be fed to the sampler.
- Type:
dict
- info¶
information that can be used to reproduce a fit (e.g., data provenance, or conditioning options), stored as dictionary of dictionaries whose outer (inner) keys will be interpreted as sections (options) when creating a configuration file through
Fit.to_config().- Type:
dict
- injections¶
dictionary containing injected signals, indexed by detector name.
- Type:
dict
- imr_result¶
reference IMR posterior, if one has been loaded.
- Type:
Result, arviz.data.inference_data.InferenceData
- auto_scale¶
whether to automatically scale strain data when sampling using single precision.
- Type:
bool
- add_data(data, time=None, ifo=None, acf=None)¶
Add data to fit.
- Parameters:
data (array,Data) – time series to be added.
time (array) – array of time stamps (only required if data is not
ringdown.data.Data).ifo (str) – interferometer key (optional).
acf (array,AutoCovariance) – autocovariance series corresponding to these data (optional).
- add_imr_result(imr_result: DataFrame | dict | ndarray, **kws) None¶
Add reference inspiral-merger-ringdown (IMR) result to fit.
- Parameters:
imr_result (pd.DataFrame, dict, np.ndarray) – IMR result data, either as a DataFrame, dictionary, or array.
approximant (str) – approximant used in IMR result.
reference_frequency (float) – reference frequency of IMR result.
psds (dict) – dictionary of power spectral densities for each detector.
- property analysis_data: dict¶
Slice of data to be analyzed for each detector. Extracted from
Fit.databased on information in analysis targetFit.target.
- property analysis_injections: dict¶
Slice of injection to be analyzed for each detector. Extracted from
Fit.conditioned_injectionsbased on information in analysis targetFit.target.
- property analysis_times: dict¶
Time arrays for analysis data.
- property antenna_patterns¶
- property attrs¶
- property cholesky_factors¶
Cholesky factors of ACFs for each detector.
- compute_acfs(shared=False, ifos=None, **kws)¶
Compute ACFs for all data sets in Fit.data.
- Parameters:
shared (bool) – specifies if all IFOs are to share a single ACF, in which case the ACF is only computed once from the data of the first IFO (useful for simulated data) (default False)
ifos (list) – specific set of IFOs for which to compute ACF, otherwise computes it for all
constructor (extra kwargs are passed to ACF)
- compute_injected_snrs(optimal=True, network=True) dict | float¶
Return a dictionary of injected SNRs for each detector.
- Parameters:
optimal (bool) – if True, return optimal SNRs (def. True); otherwise return matched filter SNRs.
network (bool) – if True, return total network SNR (def. True).
- Returns:
snrs – dictionary of SNRs for each detector if network=False, otherwise the total network SNR.
- Return type:
dict | float
- condition_data(preserve_acfs: bool = False, silent: bool = False, **kwargs)¶
Condition data for all detectors by calling
ringdown.data.Data.condition(). Docstring for that function below.The preserve_acfs argument determines whether to preserve original ACFs in fit after conditioning (default False).
The silent argument determines whether to suppress warnings.
Condition data.
- Parameters:
t0 (float) – target time to be preserved after downsampling.
ds (int) – decimation factor for downsampling.
f_min (float) – lower frequency for high passing.
f_max (float) – higher frequency for low passing.
trim (float) – fraction of data to trim from edges after conditioning, to avoid spectral issues if filtering (default 0.25).
digital_filter (bool) – apply digital antialiasing filter by discarding Fourier components higher than Nyquist; otherwise, filter through
scipy.signal.decimate().(default True).remove_mean (bool) – explicitly remove mean from time series after conditioning (default True).
decimate_kws (dict) – options for decimation function.
slice_left (float) – number of seconds before t0 to slice the strain data, e.g. to avoid NaNs
slice_right (float) – number of seconds after t0 to slice the strain data, e.g. to avoid NaNs
- Returns:
cond_data – conditioned data object.
- Return type:
- property conditioned_injections: dict¶
Conditioned injections, if available.
- copy()¶
Produce a deep copy of this Fit object.
- Returns:
fit_copy – deep copy of Fit.
- Return type:
- property delta_t: float¶
Time step of data series.
- property duration: float¶
Analysis duration in the units of time presumed by the
Fit.dataandFit.acfsobjects (usually seconds). Defined as \(T = N\times\Delta t\), where \(N\) is the number of analysis samples (n_analyze) and \(\Delta t\) is the time sample spacing.
- fake_data(ifos: list[str] | str | None = None, psds: dict[str, str | PowerSpectrum] | None = None, duration: float | None = None, delta_t: float | None = None, freq: float | None = None, f_samp: float | None = None, f_min: float | None = None, f_max: float | None = None, delta_f: float | None = None, t0: float | None = None, epoch: float | None = None, prng: int | Generator | None = None, psd_kws: dict | None = None, record_acfs: bool = False, **kws)¶
Generate synthetic data for a given set of interferometers.
If PSDs are provided, draws time-domain data from PSDs using
ringdown.data.PowerSpectrum.draw_noise_td(). If no PSDs are provided, initializes empty data arrays with specified time stamps.- Parameters:
ifos (list) – list of detector keys (e.g.,
['H1', 'L1']); also accepts a single string if adding a single detector.psds (dict) – dictionary of PSDs indexed by interferometer keys, or: (1) PSD string replacement pattern, e.g.,
'path/to/{ifo}-PSD.txt'where ifo will be replaced by the detector key (e.g., H1 for LIGO Hanford); (2) name of a PSD function available in LALSimulation.duration (float) – duration of data segment (default None); not required if PSD is provided.
delta_t (float) – time step of data (default None).
freq (float) – frequency array to create PSD (default None).
f_samp (float) – sampling frequency of data (default None).
f_min (float) – minimum frequency of data (default None).
f_max (float) – maximum frequency of data (default None).
delta_f (float) – frequency step of PSD (default None).
t0 (float) – time of data segment center (default None); if not provided, the target time will be used if available.
epoch (float) – time of data segment start (default None); if not provided, will be set based on t0 or target time.
prng (int, np.random.Generator) – random number generator seed or object (default None).
psd_kws (dict) – additional keyword arguments passed to PSD constructor.
record_acfs (bool) – record ACFs for this data (default False).
**kws – additional keyword arguments passed to
ringdown.data.Data.draw_noise_td().
- classmethod from_config(config_input: str | ConfigParser, no_cond: bool = False, result: str | None = None)¶
Creates a
Fitinstance from a configuration file.Has the ability to load and condition data, as well as to inject a simulated signal and to compute or load ACFs. Does not run the fit automatically.
Can initialize a fit from an IMR result, if the ‘imr’ section contains a path to an IMR result file and the ‘initialize_fit’ option is set to True.
- Parameters:
config_input (str, configparser.ConfigParser) – path to config file on disk, or preloaded
configparser.ConfigParserno_cond (bool) – option to ignore conditioning
- Returns:
fit – Ringdown
Fitobject.- Return type:
- classmethod from_imr_result(imr: IMRResult | str, advance_target_by_mass: float | None = None, reference_mass: float | None = None, load_data: bool = True, load_acfs: bool = True, condition: bool = True, set_target: bool = True, update_model: bool = True, duration: float | bool = 'auto', data_kws: dict | None = None, peak_kws: dict | None = None, acf_kws: dict | None = None, prior_kws: dict | None = None, psds: dict | None = None, approximant: str | None = None, reference_frequency: float | None = None, prng: int | Generator | None = None, **kws)¶
Create a new Fit object from an IMR result.
- get_templates(signal_buffer='auto', **kws)¶
Produce templates at each detector for a given set of parameters. Can be used to generate waveforms from model samples, or a full coalescence.
This is a wrapper around
ringdown.waveforms.get_detector_signals().- Parameters:
signal_buffer (float, str) – span of time around target for which to evaluate polarizations, to avoid doing so over a very long time array (for speed). By default,
signal_buffer='auto'sets this to a multiple of the analysis duration; otherwise this should be a float, or inf for no signal_buffer. (see docs forringdown.waveforms.Ringdown.from_parameters(); this option has no effect for coalescence signals)**kws – arguments passed to
ringdown.waveforms.get_detector_signals().
- Returns:
waveforms – dictionary of
Datawaveforms for each detector.- Return type:
dict
- property has_acfs: bool¶
Whether ACFs have been computed or loaded with
Fit.load_acfs().
- property has_data: bool¶
Whether data has been loaded with
Fit.load_data().
- property has_imr_result: bool¶
Whether an IMR result has been loaded with
Fit.add_imr_result().
- property has_injections: bool¶
Whether injections have been added with
Fit.inject().
- property has_target: bool¶
Whether an analysis target has been set with
Fit.set_target().
- property ifos: list¶
Instruments to be analyzed.
- inject(no_noise=False, **kws) None¶
Add simulated signal to data, and records it in
Fit.injections.Warning
This method overwrites data stored in in
Fit.data.Arguments are passed to
Fit.get_templates().- Parameters:
no_noise (bool) – if true, replaces data with injection, instead of adding the two. (def. False)
- property injection_parameters: dict | Parameters¶
Injection parameters, if available.
- load_acfs(path=None, ifos=None, from_psd=False, from_imr_result=False, **kws)¶
Load autocovariances from disk. Can read in a PSD, instead of an ACF, if using the from_psd argument.
Additional arguments are passed to
ringdown.data.AutoCovariance.read()(or,ringdown.data.PowerSpectrum.read()iffrom_psd).- Parameters:
path (dict, str) – dictionary of ACF paths indexed by interferometer keys, or path string replacement pattern, e.g.,
'path/to/acf_{i}_{ifo}.dat'where i and ifo will be respectively replaced by the first letter and key for each detector listed in ifos (e.g., H and H1 for LIGO Hanford).ifos (list) – list of detector keys (e.g.,
['H1', 'L1']), not required if path_input is a dictionary.from_psd (bool) – read in a PSD and convert to ACF.
- load_data(path: str | None = None, ifos: list[str] | None = None, channel: dict[str] | None = None, frametype: dict[str] | None = None, slide: dict[float] | None = None, **kws)¶
Load data from disk.
Additional arguments are passed to
ringdown.data.Data.load().If a seglen argument is provided (e.g., to fetch data from GWOSC), the segment will be assumed to be centered on a GPS time t0, which (if not provided) defaults to the target time
Fit.t0(if t0 is not provided and no target was set, an error will be raised).- Parameters:
path (dict, str) – dictionary of data paths indexed by interferometer keys, or path string replacement pattern, e.g.,
'path/to/{i}-{ifo}_GWOSC_16KHZ_R1-1126259447-32.hdf5'where i and ifo will be respectively replaced by the first letter and key for each detector listed in ifos (e.g., H and H1 for LIGO Hanford).ifos (list) – list of detector keys (e.g.,
['H1', 'L1']), not required if path_input is a dictionary.channel (dict, str) – dictionary of channel names indexed by interferometer keys, or channel name string replacement pattern, e.g.,
'{ifo}:GWOSC-16KHZ_R1_STRAIN'where i and ifo will be respectively replaced by the first letter and key for each detector listed in ifos (e.g., H and H1 for LIGO Hanford). Only used when kind = ‘frame’.frametype (dict, str) – dictionary of frame types indexed by interferometer keys, or frame type string replacement pattern, e.g., ‘H1_HOFT_C00’, with same replacement rules as for channel and path. Only used when kind = ‘discover’.
slide (dict) – optional dictionary of time slides to apply to each detector, e.g.,
{'H1': 0.1, 'L1': -0.05}; if provided, the data of each detector will be rolled by an integer number of samples closest to the requested time shift, i.e.,np.roll(data, int(slide / delta_t).
- property model_settings: dict¶
Prior options as currently set.
- property n_analyze: int¶
Number of data points included in analysis for each detector.
- property n_modes: int¶
Number of damped sinusoids to be included in template.
- property psds: dict¶
Dictionary of power spectral densities for each detector, derived from ACFs.
- property raw_data: dict¶
- reset(preserve_conditioning=False)¶
Reset all priors and results, but keep data and target information.
- run(prior: bool = False, predictive: bool = True, store_h_det: bool = False, store_h_det_mode: bool = True, store_residuals: bool = False, rescale_strain: bool = True, suppress_warnings: bool = True, min_ess: int | None = None, prng: ArrayImpl | int | None = None, validation_enabled: bool = False, **kwargs)¶
Fit model.
Additional keyword arguments not listed below are passed to the sampler with the following defaults when sampling:
{‘dense_mass’: True, ‘num_warmup’: 1000, ‘num_samples’: 1000, ‘num_chains’: 4}
See docs for
numpyro.infer.NUTS()andnumpyro.infer.MCMC()to see all available options.- Parameters:
prior (bool) – whether to sample the prior (def. False).
predictive (bool) – draw secondary quantities from the posterior predictive after runtime (def. True).
store_h_det (bool) – store detector templates in result (def. False).
store_h_det_mode (bool) – store individual-mode templates in result (def. True).
store_residuals (bool) – compute whitened residuals point-wise (def. False).
rescale_strain (bool) – rescale strain-like quantites by strain_scale, if strain was rescaled before running, as could be the case when using float32 (def. True).
suppress_warnings (bool) – suppress some sampler warnings (def. True).
min_ess (number) – if given, keep re-running the sampling with longer chains until the minimum effective sample size exceeds min_ess (def. None).
validation_enabled (bool) – if True, run with numpyro.validation_enabled() to get verbose error messages
return_model (bool) – returns numpyro model instead of running it (def. False).
**kwargs – arguments passed to sampler.
- property run_input: list¶
Arguments to be passed to model function at runtime: [times, strains, ls, fp, fc].
- set_modes(modes: int | list[tuple[int, int, int, int, int]])¶
Establish list of modes to include in analysis template.
Modes can be an integer, in which case n arbitrary damped sinusoids will be fit.
- Modes identified by their (p, s, l, m, n) indices, where:
p is 1 for prograde modes, and -1 for retrograde modes;
s is the spin-weight (-2 for gravitational waves);
l is the azimuthal quantum number;
m is the magnetic quantum number;
n is the overtone number.
See
ringdown.indexing.ModeIndexList.- Parameters:
modes (list) – list of tuples with quasinormal mode (p, s, l, m, n) numbers.
- set_strain_scale(scale)¶
- set_target(t0: float | dict | None = None, ra: float | None = None, dec: float | None = None, psi: float | None = None, duration: float | None = None, reference_ifo: str | None = None, antenna_patterns: dict | None = None, target: Target | None = None, force: bool = False)¶
Establish truncation target, stored to self.target.
Provide a targeted analysis start time t0 to serve as beginning of truncated analysis segment; this will be compared against timestamps in fit.data objects so that the closest sample to t0 is preserved after conditioning and taken as the first sample of the analysis segment.
Important
If the model accepts multiple detectors, t0 is assumed to be defined at geocenter; truncation time at individual detectors will be determined based on specified sky location.
The source sky location and orientation can be specified by the ra, dec, and psi arguments. These are use to both determine the truncation time at different detectors, as well as to compute the corresponding antenna patterns. Specifying a sky location is only required if the model can handle data from multiple detectors.
The argument duration specifies the length of the analysis segment in the unit of time used to index the data (e.g., s). Based on the sampling rate, this argument is used to compute the number of samples to be included in the segment, beginning from the first sample identified from t0.
Alternatively, the n_analyze argument can be specified directly. If neither duration nor n_analyze are provided, the duration will be set based on the shortest available data series in the Fit object.
Warning
Failing to explicitly specify duration or n_analyze risks inadvertently extremely long analysis segments, with correspondingly long run times.
- Parameters:
t0 (float, dict) – target time (at geocenter for a detector network, if no reference_ifo is specified), or a dictionary of start times.
ra (float) – source right ascension (rad).
dec (float) – source declination (rad).
psi (float) – source polarization angle (rad).
duration (float) – analysis segment length in seconds, or time unit indexing data (overrides n_analyze).
antenna_patterns (dict) – dictionary with tuples for plus and cross antenna patterns for each detector {ifo: (Fp, Fc)} (optional)
reference_ifo (str) – if specified, use this detector as reference for delays and antenna patterns, otherwise assume t0 defined at geocenter.
- set_tone_sequence(nmode, p=1, s=-2, l=2, m=2)¶
Set template modes to be a sequence of overtones with a given angular structure.
To set an arbitrary set of modes, use
Fit.set_modes()- Parameters:
nmode (int) – number of tones (nmode=1 includes only fundamental mode).
p (int) – prograde (p=1) vs retrograde (p=-1) flag.
s (int) – spin-weight.
l (int) – azimuthal quantum number.
m (int) – magnetic quantum number.
- property settings¶
- property start_indices: dict¶
Locations of first samples in
Fit.datato be included in the ringdown analysis for each detector.
- property start_times¶
- property strain_scale¶
- property t0: float¶
Target truncation time (defined at geocenter if model accepts multiple detectors).
- property times: dict¶
Dictionary of analysis segment start times for each detector.
- to_config(path=None)¶
Create configuration file to reproduce this fit by calling
Fit.from_config().Note
This will only result in a working configuration file if all data provenance information is available in
Fit.info. This field is automatically populated if theFit.load_data()method is used to add data to fit.- Parameters:
path (str) – optional destination path for configuration file.
- Returns:
config – configuration file object.
- Return type:
- to_json(indent=4, **kws)¶
- update_info(section: str, **kws) None¶
Update fit information stored in
Fit.info, e.g., data provenance or injection properties. If creating a config file throughFit.to_config(), section will operate as a name for a section with options determined by the keyword arguments passed here.Keyword arguments are stored as “options” for the given section, e.g.,:
fit.update_info('data', path='path/to/{ifo}-data.h5')
adds an entry to
fit.infolike:{'data': {'path': 'path/to/{ifo}-data.h5')}}
- Parameters:
section (str) – name of information category, e.g., data, injection, condition.
- update_model(**kws)¶
Set or modify prior options or other model settings. For example,
fit.update_model(a_scale_max=1e-21)sets the a_scale_max parameter to 1e-21.Valid arguments for the selected model can be found in
Fit.valid_model_settings.
- update_prior(*args, **kwargs)¶
- property valid_model_settings: list¶
Valid prior parameters for the selected model. These can be set through
Fit.update_model().
- whiten(datas: dict) dict¶
Return whiten data for all detectors using ACFs stored in
Fit.acfs.See also
ringdown.data.AutoCovariance.whiten().- Parameters:
datas (dict) – dictionary of data to be whitened for each detector.
- Returns:
whitened_datas – dictionary of
ringdown.data.Datawith whitened data for each detector.- Return type:
dict
- property whitened_analysis_data: dict¶
Whitened analysis data for each detector.
- class ringdown.fit.FitSequence(*args, target_collection=None, **kws)¶
Bases:
FitA sequence of ringdown fits of the same model to the same data at different times. Contains the same information as a single Fit object, with the addition of a target_collection attribute that stores multiple Target objects that are looped over at runtime.
Example usage:
import ringdown as rd fit = rd.Fit(modes=[(1,-2,2,2,0), (1,-2,2,2,1)]) fit.load_data('{i}-{i}1_GWOSC_16KHZ_R1-1126259447-32.hdf5', ifos=['H1', 'L1'], kind='gwosc') fit.set_target_collection( t0_ref=1126259462.4083147, m_ref=70, t0_start=0, t0_end=5, t0_step=1, ra=1.95, dec=-1.27, psi=0.82, duration=0.05 ) fit.condition_data(ds=8) fit.update_model(a_scale_max=1e-21, m_min=50, m_max=150, cosi=-1) fit.run()
- static format_output_path(path_template: str, t0: float) str¶
Get the output path for a target time based on a template string.
- classmethod from_config(config_input: str | dict, no_cond: bool = False, **kws)¶
Create a FitSequence object from a configuration file or dictionary. See Fit.from_config for additional keyword arguments.
This supports creating a FitSequence based on an IMR result. In this case, the configuration file should include an imr section with settings for the IMR result. The pipe section can include targetting entries pointing to the IMR result (e.g., t0-ref = imr); see the docs for TargetCollection.from_config for more information.
If no_cond is True, conditioning options in the configuration file will be ignored. HOWEVER, conditioning may still be applied if the Fit is being initialized from an IMR result. To prevent this, set condition = False in the IMR section of the configuration file.
- Parameters:
config_input (str, dict) – path to configuration file or dictionary.
no_cond (bool) – if True, will ignore condition section in config; data may still be conditioned if initializing from IMR result.
**kws – additional keyword arguments passed to FitSequence constructor.
- Returns:
fit – FitSequence object.
- Return type:
- property results¶
An alias for the result attribute.
- run(predictive: bool = True, store_h_det: bool = False, store_h_det_mode: bool = True, store_residuals: bool = False, rescale_strain: bool = True, suppress_warnings: bool = True, min_ess: int | None = None, prng: ArrayImpl | int | None = None, validation_enabled: bool = False, individual_progress_bars: bool = False, recondition: bool = True, output_path: str | None = None, **kwargs)¶
Run the sequence of fits iteratively.
The options are the same as for Fit.run, with the addition of a recondition argument that specifies whether to recondition the data to each target before running the fit.
There is also an output_path argument that allows for saving results to disk as they are produced. This argument should be a path string with a * placeholder that will be replaced by the target time, e.g. output_path=’results/*/result.nc’.
- Parameters:
predictive (bool) – if True, compute predictive posterior samples.
store_h_det (bool) – if True, store detector-frame strain in results.
store_h_det_mode (bool) – if True, store mode-frame strain in results.
store_residuals (bool) – if True, store residuals in results.
rescale_strain (bool) – if True, rescale strain by amplitude scale factor.
suppress_warnings (bool) – if True, suppress warnings during run.
min_ess (int) – minimum effective sample size required for each target.
prng (int, np.random.Generator) – random number generator seed or object.
validation_enabled (bool) – if True, enable validation checks during run.
individual_progress_bars (bool) – if True, show individual progress bars for each target.
recondition (bool) – if True, recondition data to each target before running.
output_path (str) – path to save results to, with {} replaced by target time.
**kwargs – additional keyword arguments passed to Fit.run.
- set_target_collection(*args, **kws)¶
Set a collection of targets for the fit sequence. All arguments are passed to TargetCollection.construct, whose docs are included below.
Construct a collection of targets from a set of keyword arguments. There are three ways to specify the start times:
1- listing the times explicitly 2- listing time differences with respect to a reference time 3- providing start, stop, step instructions to construct start times (potentially relative to a reference time)
Time steps/differences can be specified in seconds or M, if a reference mass is provided (in solar masses).
Accepted arguments to set target time are: - t0_list: list of start times - t0_delta_list: list of time differences with respect to a reference - t0_ref: reference time to be used for time differences - t0_start, t0_stop, t0_step: start, stop, step instructions
Additional arguments can be provided to specify the sky location and duration of the analysis.
- Parameters:
reference_mass (float, None) – reference mass in solar masses to use for time steps.
info (dict, None) – dictionary of additional information to store with the collection.
kws (dict) – keyword arguments to specify target times and sky locations.
- Returns:
targets – collection of target objects.
- Return type:
- property targets¶
An alias for the target_collection attribute.
Model module¶
Module defining the probabilistic model (likelihood and prior) for ringdown data.
- ringdown.model.get_arviz(sampler, modes: list | None = None, ifos: list | None = None, injections: list | None = None, epoch: list | None = None, scale: list | None = None, attrs: dict | None = None, store_data: bool = True)¶
Convert a numpyro sampler to an arviz dataset.
- Parameters:
sampler (numpyro.MCMC) – The sampler to convert after running.
modes (None or array_like) – Coordinates of modes to include in the dataset; if None, then all modes are included and indexed by integers.
ifos (None or array_like) – The ifos to include in the dataset. If None, then all ifos are included.
injections (None or array_like) – The injections to include in the dataset. If None, then no injections are included.
epoch (None or array_like) – The epoch of each ifo. If None, then all epochs are set to zero.
scale (None or float) – The scale of the strain. If None, then the scale is set to one.
attrs (None or dict) – Attributes to include in the arviz dataset.
record_data (bool) – Whether to record the observed data and auxiliary quantities in the arviz dataset.
- Returns:
dataset – The arviz dataset.
- Return type:
arviz.InferenceData
- ringdown.model.make_model(modes: int | list[int, int, int, int], a_scale_max: float, marginalized: bool = True, m_min: float | None = None, m_max: float | None = None, chi_min: float = 0.0, chi_max: float = 0.99, cosi_min: float | None = None, cosi_max: float | None = None, cosi: float | None = None, df_min: None | float | list[None | float] = None, df_max: None | float | list[None | float] = None, dg_min: None | float | list[None | float] = None, dg_max: None | float | list[None | float] = None, f_min: None | float | list[float] = None, f_max: None | float | list[float] = None, g_min: None | float | list[float] = None, g_max: None | float | list[float] = None, flat_amplitude_prior: bool = False, mode_ordering: None | str = None, single_polarization: bool = False, prior: bool = False, predictive: bool = False, store_h_det: bool = False, store_h_det_mode: bool = False)¶
- Parameters:
modes (int or list[tuple]) – If integer, the number of damped sinusoids to use. If list of tuples, each entry should be of the form (p, s, ell, m), where p is 1 for prograde -1 for retrograde; s is the spin weight (-2 for the usual GW modes); and ell and m refer to the usual angular numbers.
a_scale_max (float) – The maximum value of the amplitude scale parameter. This is used to define the prior on the amplitude scale parameter.
marginalized (bool) – Whether or not to marginalize over the quadrature amplitudes analytically.
m_min (float) – The minimum mass of the black hole in solar masses.
m_max (float) – The maximum mass of the black hole in solar masses.
chi_min (float) – The minimum dimensionless spin of the black hole.
chi_max (float) – The maximum dimensionless spin of the black hole.
cosi_min (float or None) – The minimum inclination angle to the angular orbital momentum of the black hole.
cosi_max (float or None) – The maximum inclination angle to the angular orbital momentum of the black hole.
cosi (float or None) – The inclination angle to the angular orbital momentum of the black hole. If not None, then cosi_min and cosi_max are ignored and the value of cosi is fixed.
df_min (None or float or list[None or float]) – The minimum fractional deviation from the GR frequency. If a list then it should have the same length as modes.
df_max (None or float or list[None or float]) – The maximum fractional deviation from the GR frequency. If a list, then it should have the same length as modes.
dg_min (None or float or list[None or float]) – The minimum fractional deviation from the GR damping rate. If a list, then it should have the same length as modes.
dg_max (None or float or list[None or float]) – The maximum fractional deviation from the GR damping rate. If a list, then it should have the same length as modes.
flat_amplitude_prior (bool) – Whether or not to impose a flat prior on the amplitude scale parameter. This is only relevant if marginalized is False.
mode_ordering (None or str) – Relevant to the case where modes is an integer, and the model consists of arbitrary damped sinusoids. If None, then the frequencies and damping rates are only constrained by the bounds f_min, f_max, g_min, and g_max. If ‘f’, then the frequencies are constrained to be in increasing order; if ‘g’, then the damping rates are constrained to be in increasing order.
single_polarization (bool) – if true, assumes a single, linear polarization: either plus or cross, with theta = 0. This should only be used for testing in simulated data for a single detector! (default: False)
prior (bool) – Whether or not to compute the likelihood. If True, then the likelihood is not computed, and the model is used for prior predictive sampling.
predictive (bool) – Whether to generate the quadrature amplitudes when marginalized=True.
store_h_det (bool) – Whether to store the detector-frame waveform in the model.
store_h_det_mode (bool) – Whether to store the mode-by-mode detector-frame waveform in the model.
- Returns:
model – A model function that can be used with numpyro to sample from the posterior distribution of the ringdown parameters.
- Return type:
function
- ringdown.model.rd_design_matrix(ts, f, gamma, Fp, Fc, Ascales, aligned=False, YpYc=None, single_polarization=False)¶
Construct the design matrix for a generic ringdown model.
For each detector, this is a matrix whose rows are the cosine and sine basis functions for the damped sinusoids that make up the ringdown model; the columns are times.
There are four quadratures per mode \((F_+ \cos\omega t, F_+ \sin\omega t, F_\times \cos\omega t, F_\times \sin\omega t)\), so that the design matrix has shape
(nifo, nt, nquads*nmode), i.e.,:[ [ # [0:nmode] are the plus cosine quadratures Fp * exp(-gamma_0*t_0) * cos(omega_0*t_0), Fp * exp(-gamma_1*t_0) * cos(omega_1*t_0), ..., # [nmode:2*nmode] are the plus sine quadratures Fp * exp(-gamma_0*t_0) * sin(omega_0*t_0), Fp * exp(-gamma_1*t_0) * sin(omega_1*t_0), ..., # [2*nmode:3*nmode] are the cross cosine quadratures Fc * exp(-gamma_0*t_0) * cos(omega_0*t_0), Fc * exp(-gamma_1*t_0) * cos(omega_1*t_0), ..., # [3*nmode:4*nmode] are the cross sine quadratures Fc * exp(-gamma_0*t_0) * sin(omega_0*t_0), Fc * exp(-gamma_1*t_0) * sin(omega_1*t_0), ... ], [ Fp * exp(-gamma_0*t_1) * cos(omega_0*t_1), Fp * exp(-gamma_1*t_1) * cos(omega_1*t_1), ..., Fp * exp(-gamma_0*t_1) * sin(omega_0*t_1), Fp * exp(-gamma_1*t_1) * sin(omega_1*t_1), ..., Fc * exp(-gamma_0*t_1) * cos(omega_0*t_1), Fc * exp(-gamma_1*t_1) * cos(omega_1*t_1), ..., Fc * exp(-gamma_0*t_1) * sin(omega_0*t_1), Fc * exp(-gamma_1*t_1) * sin(omega_1*t_1), ... ], ... ]
For the aligned model we have that, for each \((\ell, m)\) mode and suppressing the exponential decay,
\[ \begin{align}\begin{aligned}\begin{split}h_+ = A_{\ell m} Y_{\ell m}^+ \cos(\omega_{\ell m} t - \phi_{\ell m}) \\\end{split}\\h_\times = A_{\ell m} Y_{\ell m}^\times \sin(\omega_{\ell m} t - \phi_{\ell m})\end{aligned}\end{align} \]This means that the quadratures are:
\[\begin{split}x_+ = A_{\ell m} Y_{\ell m}^+ \cos\phi_{\ell m} \\ y_+ = A_{\ell m} Y_{\ell m}^+ \sin\phi_{\ell m} \\ x_\times = - A_{\ell m} Y_{\ell m}^\times \sin\phi_{\ell m} \\ y_\times = A_{\ell m} Y_{\ell m}^\times \cos\phi_{\ell m}\end{split}\]We want to combine these four quadratures into two. To do this, note that the overall signal at a given detector looks like:
\[h = A_{\ell m} \left( F_+ Y_{\ell m}^+ \cos\phi_{\ell m} - F_\times Y_{\ell m}^\times \sin\phi_{\ell m} \right) \cos(\omega_{\ell m} t) + A_{\ell m} \left( F_+ Y_{\ell m}^+ \sin\phi_{\ell m} + F_\times Y_{\ell m}^\times \cos\phi_{\ell m} \right) \sin(\omega_{\ell m} t)\]where \(F_+\) and \(F_\times\) are the plus and cross polarization antenna patterns.
We want to sum the cosine and sine columns to get the right linear combination per the equation above. The right linear combination becomes apparent if we write the above as in inner product:
\[h = (x, y) \cdot M\]where \(x = A_{\ell m} \cos \phi_{\ell m}\) and \(y = A_{\ell m} \sin \phi_{\ell m}\) while \(M\) is the matrix
\[\begin{split}M = \begin{pmatrix} F_+ Y_{\ell m}^+ \cos\omega t + F_\times Y_{\ell m}^\times \sin\omega t \\ F_+ Y_{\ell m}^+ \sin\omega t + F_\times Y_{\ell m}^\times \sin\omega t \\ \end{pmatrix}\end{split}\]This function effects that summation to return a design matrix corresponding to two quadratures.
- Parameters:
ts (array_like) – The times at which to evaluate the design matrix; shape
(nifo, nt).f (array_like) – The frequencies of the damped sinusoids; shape
(nmode,).gamma (array_like) – The damping rates of the damped sinusoids; shape
(nmode,).Fp (array_like) – The plus polarization coefficients; shape
(nifo,).Fc (array_like) – The cross polarization coefficients; shape
(nifo,).Ascales (array_like) – The amplitude scales of the damped sinusoids; shape
(nmode,).
- Returns:
design_matrix – The design matrix; shape (nifo, nt, nquads*nmode).
- Return type:
array_like
Result module¶
Module defining the core Result class.
- class ringdown.result.Result(*args, config=None, produce_h_det=True, **kwargs)¶
Bases:
InferenceDataResult from a ringdown fit.
- property a_scale_max: float¶
Maximum amplitude scale assumed in the analysis.
- amplitude_significance(kind='quantile') Series¶
Compute a measure of support for non-vanishing mode amplitudes.
If kind is ‘quantile’, the output is the quantile of the amplitude distribution at zero, computed using the HPD.
If kind is ‘zscore’, translates the quantile into a z-score using the standard normal distribution.
- Parameters:
kind (str) – method to compute significance, ‘quantile’ or ‘zscore’ (def., ‘quantile’)
- Returns:
p – p-value of the amplitude of the signal.
- Return type:
pd.Series
- property analysis_data¶
Same as observed_strain but in dict format as in Fit
- property cholesky_factors: ndarray¶
Cholesky L factors used in analysis.
- compute_posterior_snrs(optimal: bool = True, network: bool = False, cumulative: bool = False) ndarray¶
Efficiently computes signal-to-noise ratios from posterior samples, reproducing the computation internally carried out by the sampler.
Depending on the
optimalargument, returns either the optimal SNR:snr_opt = sqrt(dot(template, template))
or the matched filter SNR:
snr_mf = dot(data, template) / snr_opt
- Parameters:
optimal (bool) – return optimal SNR, instead of matched filter SNR (def.,
True)network (bool) – return network SNR, instead of individual-detector SNRs (def.,
False)cumulative (bool) – return cumulative SNR, instead of instantaneous SNR (def.,
False)
- Returns:
snrs – stacked array of SNRs; if
cumulative = False, the shape is(samples,)ifnetwork = True, or(ifo, samples)otherwise; ifcumulative = True, the shape is(time, samples)ifnetwork = True, or(ifo, time, samples)otherwise; the number of samples equals the number of chains times the number of draws.- Return type:
array
- property config: dict[str, dict[str, str]]¶
Configuration dictionary for the result. Entries represent sections of the configuration file.
- property default_label_format: dict¶
Default formatting options for DataFrames.
- draw_sample(idx: int | tuple[int, int] | dict = None, map: bool = False, prng: Generator = None, seed: int = None) tuple[int, dict]¶
Draw a sample from the posterior.
- Parameters:
idx (int, dict, or tuple) – index of sample to draw; if an integer, it is the index of the sample in the stacked samples; if a tuple, it is the (chain, draw) index of the sample in the posterior; if a dictionary, it is the index of the sample with keys corresponding to the dimensions of the posterior (chains, draws); (def., None)
map (bool) – return maximum-probability sample; otherwise, returns random draw (def., False)
prng (numpy.random.Generator) – random number generator (optional)
seed (int) – seed to initialize new random number generator (optional)
- Returns:
i (int) – location of draw in stacked samples (i.e., samples obtained by calling
posterior.stack(sample=('chain', 'draw')))pars (xarray.core.dataset.DataVariables) – object containing drawn parameters (can be treated as dict)
- draw_strain_sample(idx: int | None = None, map: bool = False, ifo: str | None = None, mode: str | tuple | ModeIndex | bytes | None = None, prng: int | Generator | None = None, seed: int | None = None) dict[Data] | Data¶
Get a sample of the strain reconstruction.
- property epoch¶
Epoch for detector times; corresponds to fit.start_times
- property ess: float¶
Minimum effective sample size for all parameters in the result.
- classmethod from_netcdf(*args, config=None, **kwargs) Result¶
Initialize object from a netcdf file.
Expects that the file will have groups, each of which can be loaded by xarray. By default, the datasets of the InferenceData object will be lazily loaded instead of being loaded into memory. This behaviour is regulated by the value of
az.rcParams["data.load"].- Parameters:
filename (str) – location of netcdf file
engine ({"h5netcdf", "netcdf4"}, default "h5netcdf") – Library used to read the netcdf file.
group_kwargs (dict of {str: dict}, optional) – Keyword arguments to be passed into each call of
xarray.open_dataset(). The keys of the higher level should be group names or regex matching group names, the inner dicts re passed toopen_datasetThis feature is currently experimental.regex (bool, default False) – Specifies where regex search should be used to extend the keyword arguments. This feature is currently experimental.
base_group (str, default "/") – The group in the netCDF file where the InferenceData is stored. By default, assumes that the file only contains an InferenceData object.
- Return type:
InferenceData
- classmethod from_zarr(*args, **kwargs)¶
Initialize object from a zarr store or path.
Expects that the zarr store will have groups, each of which can be loaded by xarray. By default, the datasets of the InferenceData object will be lazily loaded instead of being loaded into memory. This behaviour is regulated by the value of
az.rcParams["data.load"].- Parameters:
store (MutableMapping or zarr.hierarchy.Group or str.) – Zarr storage class or path to desired Store.
- Return type:
InferenceData object
References
- get_fit(**kwargs)¶
Get a Fit object from the result.
- get_mode_parameter_dataframe(nsamp: int | None = None, ignore_index: bool = False, prng: int | Generator | None = None, **kws) DataFrame¶
Get a DataFrame of parameter samples drawn from the posterior, with columns for different modes.
This is similar to
get_parameter_dataframe(), but splits the parameters for each mode into unique columns, rather than stacking them and labeling the modes through a mode column.- Parameters:
nsamp (int) – number of samples to draw from the posterior (optional).
ignore_index (bool) – reset index rather than showing location in original samples (def., False).
prng (numpy.random.Generator | int) – random number generator or seed (optional).
**kws (dict) – additional keyword arguments to pass to the get_label method of
qnms.ParameterLabel.
- Returns:
df – DataFrame of parameter samples.
- Return type:
pandas.DataFrame
- get_parameter_dataframe(nsamp: int | None = None, prng: int | Generator = None, ignore_index=False, **kws) DataFrame¶
Get a DataFrame of parameter samples drawn from the posterior.
The columns correspond to parameters and the index to the sample, which can be used to locate this row in the Result.stacked_samples. If ignore_index, the index will be reset rather than showing the location in the original set of samples.
The parameters are labeled using the qnms.ParameterLabel class.
- Parameters:
nsamp (int) – number of samples to draw from the posterior (optional).
prng (numpy.random.Generator | int) – random number generator or seed (optional).
ignore_index (bool) – reset index rather than showing location in original samples (def., False).
**kws (dict) – additional keyword arguments to pass to the get_label method of
qnms.ParameterLabel.
- get_parameter_key_map(modes: bool = True, **kws) dict¶
Get a dictionary of parameter labels for the result.
- get_single_mode_dataframe(mode: str | tuple | ModeIndex | bytes, *args, **kws) DataFrame¶
Get a DataFrame of parameter samples drawn from the posterior for a specific mode.
- Parameters:
mode (str, tuple, ModeIndex, or bytes) – mode to extract.
*args (list) – additional arguments to pass to
get_mode_parameter_dataframe().**kws (dict) – additional keyword arguments to pass to the get_mode_label method of
qnms.ParameterLabel.
- get_strain_quantile(q: float, ifo: str = None, mode: str | tuple | ModeIndex | bytes = None) dict[Data] | Data¶
Get the quantile of the strain reconstruction.
- Parameters:
q (float) – quantile to compute
ifo (str) – detector to extract (optional)
mode (str, tuple, ModeIndex, or bytes) – mode to extract (optional)
- Returns:
h – dictionary of strain reconstructions, with keys corresponding to detector names, or a single data object if
ifois not provided- Return type:
- property h_det¶
Alias for posterior.h_det, in case this is not already present, it gets computed from individual modes.
- property h_det_mode¶
Alias for posterior.h_det_mode, in case this is not already present, it gets computed from the sum of all modes.
- property has_imr_result: bool¶
Check if an IMR result is loaded.
- property ifos: list¶
Detectors used in analysis.
- imr_consistency(coords: str = 'mchi', ndraw_rd: int | None = None, ndraw_imr: int | None = 1000, prng: int | Generator | None = None, kde_kws: dict | None = None) ndarray¶
Computes credible levels (CLs) at which each IMR sample is found relative to the ringdown posterior, returning a distribution of CLs.
The comparison is done in coordinates specified by the
coordsargument (NOTE: only ‘mchi’ currently supported).- Parameters:
coords (str) – coordinates to use for comparison (def., ‘mchi’), currently only ‘mchi’ is supported.
ndraw_rd (int) – number of RD samples to draw (def., all samples)
ndraw_imr (int) – number of IMR samples to draw (def., 1000)
prng (numpy.random.Generator) – random number generator or seed (optional)
kde_kws (dict) – additional keyword arguments to pass to gaussian_kde
- Returns:
qs – distribution of CLs at which each IMR sample is found relative to the ringdown posterior.
- Return type:
array
- imr_consistency_summary(coords: str = 'mchi', imr_weight: str = 'rd', ndraw_rd: int | None = None, ndraw_imr: int | None = 1000, imr_cl: float = 0.9, prng: int | Generator | None = None, kde_kws: dict | None = None) float¶
Compute ringdown credible level that fully encompasses certain IMR credible level specified, or that encompasses a certain fraction of IMR samples.
If imr_weight is ‘imr’, the output is the smallest credible level of the RD posterior that encompasses the entirety of the IMR credible level specified by imr_cl.
If imr_weight is ‘rd’, the output is the ringdown credible level that encompasses imr_cl of the IMR samples.
- Parameters:
coords (str) – coordinates to use for comparison (def., ‘mchi’)
imr_weight (str) – distribution to use to define the IMR credible level, ‘imr’ or ‘rd’ (def., ‘rd’)
ndraw_rd (int) – number of RD samples to draw (def., all samples)
ndraw_imr (int) – number of IMR samples to draw (def., 1000)
imr_cl (float) – IMR credible level (def., 0.9)
prng (numpy.random.Generator) – random number generator or seed (optional)
kde_kws (dict) – additional keyword arguments to pass to gaussian_kde
- Returns:
q – credible of the RD posterior that fully encompasses the IMR credible level specified by imr_cl.
- Return type:
float
- property imr_result: IMRResult¶
Reference IMR result.
- property info: dict[str, dict[str, str]]¶
Alias for config.
- property log_likelihood_timeseries¶
Compute the likelihood timeseries for the posterior samples.
- Returns:
likelihoods – array of likelihoods, with shape
(time, samples,); the number of samples equals the number of chains times the number of draws.- Return type:
array
- property loo: ELPDData¶
Returns a leave-one-out estimate of the predictive accuracy of the model.
See https://arxiv.org/abs/1507.04544 for definitions and discussion, including discussion of the ‘Pareto stabilization’ algorithm for reducing the variance of the leave-one-out estimate. The LOO is an estimate of the expected log predictive density (log of the likelihood evaluated on hypothetical data from a replication of the observation averaged over the posterior) of the model; larger LOO values indicate higher predictive accuracy (i.e. explanatory power) for the model.
- property modes: list | None¶
Modes used in analysis.
- property n_analyze: int¶
Number of samples in the analysis.
- property observed_strain¶
- plot_mass_spin(ndraw: int = 500, imr: bool = True, joint_kws: dict | None = None, marginal_kws: dict | None = None, imr_kws: dict | None = None, df_kws: dict | None = None, prng: int | Generator | None = None, palette=None, dropna: bool = False, height: float = 6, ratio: float = 5, space: float = 0.2, xlim: tuple | None = None, ylim: tuple | None = (0, 1), marginal_ticks: bool = False, x_min: float | None = None, x_max: float | None = None, y_min: float | None = 0, y_max: float | None = 1, engine: str = 'auto', **kws) None¶
Plot the mass-spin distribution for the collection. Based on seaborn’s jointplot but with the ability to use a truncated KDE (1D and 2D), controlled by the x_min, x_max, y_min, and y_max arguments.
- Parameters:
ndraw (int) – number of samples to draw from the posterior (optional).
imr (bool) – plot IMR samples (def., True).
joint_kws (dict) – keyword arguments to pass to the kdeplot method for the joint distribution (optional).
marginal_kws (dict) – keyword arguments to pass to the kdeplot method for the marginal distributions (optional).
imr_kws (dict) – keyword arguments plot IMR result, accepts: color, linewidth and linestyle.
df_kws (dict) – keyword arguments to pass to the get_parameter_dataframe method (optional).
prng (numpy.random.Generator | int) – random number generator or seed (optional).
palette (str) – color palette for hue variable (optional).
dropna (bool) – drop NaN values from DataFrame (def., False).
height (float) – height of the plot (def., 6).
ratio (float) – aspect ratio of the plot (def., 5).
space (float) – space between axes (def., 0.2).
xlim (tuple) – x-axis limits (optional).
ylim (tuple) – y-axis limits (def., (0, 1)).
marginal_ticks (bool) – show ticks on marginal plots (def., False).
x_min (float) – minimum mass value for KDE truncation (optional).
x_max (float) – maximum mass value for KDE truncation (optional).
y_min (float) – minimum spin value for KDE truncation (optional).
y_max (float) – maximum spin value for KDE truncation (optional).
**kws (dict) – additional keyword arguments to pass to the joint plot.
- Returns:
grid (seaborn.JointGrid) – joint plot object.
df_rd (pandas.DataFrame) – DataFrame of parameter samples drawn from the posterior
- plot_trace(var_names: list[str] = ['a'], compact: bool = True, *args, **kwargs)¶
Alias for
arviz.plot_trace().
- resample_to_uniform_amplitude(nsamp: int | None = None, prng: int | Generator | None = None) Result¶
Reweight the posterior to a uniform amplitude prior.
The “primal” posterior has a density \(p(a, a_{\rm scale}) = N(a; 0, a_{\rm scale}) 1/a_{\rm scale max}\). The target posterior we want has a density \(p(a, a_{\rm scale}) \propto \frac{1}{|a|^{n-1}} \frac{1}{a_{\rm scale max}}\) for \(n\) quadratures.
Therefore the importance weighs are
\[w = \frac{1}{|a|^{n-1} N(a; 0, a_{\rm scale})}\]WARNING: this method can be unstable unless you have an extremely large number of samples; we do not recommend it when the model has more than 2 quadratures (as in the z-parity symmetric models).
- Parameters:
nsamp (int) – number of samples to draw from the posterior (optional, defaults to all samples).
prng (numpy.random.Generator | int) – random number generator or seed (optional).
- Returns:
new_result – result with samples reweighted to a uniform amplitude prior; posterior will have stacked chains and draws.
- Return type:
- rescale_strain(scale=None) None¶
Autoscale the strain data in the result.
- property sample_times¶
Sample times for the analysis; corresponds to fit.analysis_data[i].time.
- set_dataframe_parameters(parameters: list[str]) None¶
Set the parameters to be included in DataFrames derived from this result.
- set_imr_result(imr_result: IMRResult) None¶
- property stacked_samples¶
Stacked samples for all parameters in the result.
- property start_times: dict¶
Same as epoch but in dict format as in Fit
- property strain_scale: float¶
Scale factor for strain data.
- property t0: float | None¶
Reference time for the analysis.
- property templates: StrainStack¶
Templates corresponding to each posterior sample, as were seen by the sampler.
Dimensions will be
(ifo, time, sample).Corresponding whitened templates can be obtained from posterior by doing:
result.h_det.stack(sample=('chain', 'draw'))
- update_default_label_format(**kws) None¶
Update the default formatting options for DataFrames.
- property waic: ELPDData¶
Returns the ‘widely applicable information criterion’ predictive accuracy metric for the fit.
See https://arxiv.org/abs/1507.04544 for definitions and discussion. A larger WAIC indicates that the model has better predictive accuarcy on the fitted data set.
- whiten(datas: dict | ndarray) dict | ndarray¶
Whiten data using the Cholesky factors from the analysis.
- Parameters:
datas (dict | np.ndarray) – data to whiten; if a dictionary, the keys should correspond to the detectors used in the analysis.
- Returns:
wds – whitened data; if a dictionary, the keys correspond to the detectors used in the analysis.
- Return type:
dict | np.ndarray
- property whitened_data: ndarray¶
Whitened data used in the analysis.
- property whitened_residuals: ndarray¶
Whitened residuals from the analysis.
- property whitened_templates: ndarray¶
Whitened templates corresponding to each posterior sample, as were seen by the sampler.
Dimensions will be
(ifo, time, sample).Corresponding unwhitened templates can be obtained from posterior by doing:
result.h_det.stack(sample=('chain', 'draw'))
- class ringdown.result.ResultCollection(results: list | None = None, index: list | None = None, reference_mass: float | None = None, reference_time: float | None = None)¶
Bases:
MultiIndexCollectionCollection of results from ringdown fits.
- amplitude_significance(simplified_index: bool = True, **kws) DataFrame¶
Compute the significance for non-vanishing mode amplitudes for each result in the collection.
See
Result.amplitude_significance()for details.- Parameters:
**kws (dict) – additional keyword arguments to pass to the amplitude_significance method of each result
- Returns:
p – DataFrame of amplitude significance for each result.
- Return type:
pd.DataFrame
- compute_imr_snrs(**kws) ndarray¶
Compute the IMR SNRs for each result in the collection. See
IMRResult.compute_ringdown_snrs()for details.Returns an array of shape (n_collection, n_ifo, n_samples) if network is False, and (n_collection, n_samples) if network is True.
- compute_imr_snrs_by_t0(optimal: bool = True, network: bool = False, cumulative: bool = False, approximate: bool = True, progress: bool = False, **kws) ndarray¶
- compute_posterior_snrs(**kws) ndarray¶
Compute the posterior SNRs for each result in the collection. See
Result.compute_posterior_snrs()for details.Returns an array of shape (n_collection, n_ifo, n_samples) if network is False, and (n_collection, n_samples) if network is True.
- classmethod from_netcdf(path_input: str | list, index: list = None, config: str | list | None = None, progress: bool = True, **kws)¶
Load a collection of results from NetCDF files.
- Parameters:
path_input (str or list) – template path to NetCDF file or list of paths; if a string, expected to be a template like path/to/many/files/*.nc or path/to/many/files/{}.nc where {} or * is replaced by the index, or used to glob for files.
index (list) – list of indices for the results; if not provided, will be inferred from the paths of found files.
config (str or list) – template path to configuration file or list of paths; if a string, expected to be a template like path/to/many/files/*.ini or path/to/many/files/{}.ini where {} or * is replaced by the index, or used to glob for files.
progress (bool) – show progress bar (def., True)
**kws (dict) – additional keyword arguments to pass to the constructor, like reference_mass or reference_time
- get_mode_parameter_dataframe(ndraw: int | None = None, index_label: str = None, split_index: bool = False, t0: bool = False, reference_mass: bool | float | None = None, draw_kws: dict | None = None, **kws) DataFrame¶
Get a combined parameter DataFrame of mode parameter samples for all results in the collection, with a new index column identifying provenance of each sample. One column per parameter, with a mode-indexing column.
- Parameters:
ndraw (int) – number of samples to draw from each result (optional)
index_label (str) – name of provenance column (def., ‘run’)
split_index (bool) – split tuple index into multiple columns (def., False)
t0 (bool) – include reference time in DataFrame (def., False)
reference_mass (bool or float) – mass in solar masses used to label time steps if including t0; if provided ‘t0m’ will be used instead of ‘t0’ (optional) so that the time is unit of mass rather than seconds.
draw_kws (dict) – keyword arguments to pass to the sample method when drawing random samples from each result (optional)
**kws (dict) – additional keyword arguments to pass to the get_mode_parameter_dataframe method of each result
- get_parameter_dataframe(ndraw: int | None = None, index_label: str = None, split_index: bool = False, t0: bool = False, reference_mass: bool | float | None = None, draw_kws: dict | None = None, progress: bool = False, **kws) DataFrame¶
Get a combined DataFrame of parameter samples for all results in the collection, with a new index column identifying provenance of each sample.
- Parameters:
ndraw (int) – number of samples to draw from each result (optional)
index_label (str) – name of provenance column (def., ‘run’)
split_index (bool) – split tuple index into multiple columns (def., False)
t0 (bool) – include reference time in DataFrame (def., False)
reference_mass (bool or float) – mass in solar masses used to label time steps if including t0; if provided ‘t0m’ will be used instead of ‘t0’ (optional) so that the time is unit of mass rather than seconds.
draw_kws (dict) – keyword arguments to pass to the sample method when drawing random samples from each result (optional)
progress (bool) – show progress bar (def., False)
**kws (dict) – additional keyword arguments to pass to the get_parameter_dataframe method of each result
- get_t0s(reference_mass: float | bool | None = None, reference_time: float | None = None, decimals: int | None = None) ndarray¶
Get analysis start times for the collection.
- Parameters:
reference_mass (float or bool) – reference mass to use for time labeling; if True, use the reference mass of the targets; if False, do not use a reference mass and return time as recorded (def., None)
reference_time (float) – reference time to use for time labeling (def., 0)
decimals (int) – number of decimal places to round the times to (optional)
- Returns:
t0s – array of analysis start times.
- Return type:
np.ndarray
- property has_imr_result: bool¶
Check if the collection has an IMR result.
- imr_consistency(*args, progress=False, **kwargs) DataFrame¶
Compute the IMR consistency for the collection. See
Result.imr_consistency()for details.
- imr_consistency_summary(*args, progress: bool = False, simplify_index: bool = True, **kws) Series¶
Compute the IMR consistency summary for each element in the collection.
See
Result.imr_consistency_summary()for details.- Parameters:
progress (bool) – show progress bar (def., False)
simplify_index (bool) – simplify the index to a single column (def., True)
**kws (dict) – additional keyword arguments to pass to the imr consistency_summary method of each result
- Returns:
q – summary of IMR consistency for each result in the collection
- Return type:
pd.Series
- property imr_result: IMRResult¶
Reference IMR result
- plot_mass_spin(ndraw: int = 500, imr: bool = True, joint_kws: dict | None = None, marginal_kws: dict | None = None, imr_kws: dict | None = None, df_kws: dict | None = None, prng: int | Generator | None = None, index_label: str = None, hue: str = None, palette=None, hue_norm=None, dropna: bool = False, height: float = 6, ratio: float = 5, space: float = 0.2, xlim: tuple | None = None, ylim: tuple | None = (0, 1), marginal_ticks: bool = False, x_min: float | None = None, x_max: float | None = None, y_min: float | None = 0, y_max: float | None = 1, **kws) None¶
Plot the mass-spin distribution for the collection. Based on seaborn’s jointplot but with the ability to use a truncated KDE (1D and 2D), controlled by the x_min, x_max, y_min, and y_max arguments.
- Parameters:
ndraw (int) – number of samples to draw from the posterior (optional).
imr (bool) – plot IMR samples (def., True).
joint_kws (dict) – keyword arguments to pass to the kdeplot method for the joint distribution (optional).
marginal_kws (dict) – keyword arguments to pass to the kdeplot method for the marginal distributions (optional).
imr_kws (dict) – keyword arguments plot IMR result, accepts: color, linewidth and linestyle.
df_kws (dict) – keyword arguments to pass to the get_parameter_dataframe method (optional).
prng (numpy.random.Generator | int) – random number generator or seed (optional).
index_label (str) – label for the index column in the DataFrame (optional).
hue (str) – alias for index_label (optional).
palette (str) – color palette for hue variable (optional).
hue_norm (tuple) – normalization tuple for hue variable (optional).
dropna (bool) – drop NaN values from DataFrame (def., False).
height (float) – height of the plot (def., 6).
ratio (float) – aspect ratio of the plot (def., 5).
space (float) – space between axes (def., 0.2).
xlim (tuple) – x-axis limits (optional).
ylim (tuple) – y-axis limits (def., (0, 1)).
marginal_ticks (bool) – show ticks on marginal plots (def., False).
x_min (float) – minimum mass value for KDE truncation (optional).
x_max (float) – maximum mass value for KDE truncation (optional).
y_min (float) – minimum spin value for KDE truncation (optional).
y_max (float) – maximum spin value for KDE truncation (optional).
**kws (dict) – additional keyword arguments to pass to the joint plot.
- Returns:
grid (seaborn.JointGrid) – joint plot object.
df_rd (pandas.DataFrame) – DataFrame of parameter samples drawn from the posterior
- property reference_mass: float | None¶
Reference mass in solar masses used for time-step labeling.
- property reference_time: float | None¶
Reference time used for time-step labeling.
- reindex_by_t0(reference_mass: bool | float | None = None, reference_time: float | None = None, decimals: int | None = None) None¶
Reindex the collection by the analysis start time.
- set_imr_result(imr_result: IMRResult) None¶
Set the reference IMR result for the collection.
- Parameters:
imr_result (IMRResult) – IMR result to set as reference.
- set_reference_mass(reference_mass: float | None) None¶
Set the reference mass for the collection.
- set_reference_time(reference_time: float | None) None¶
Set the reference time for the collection.
- property simplified_index: list¶
Simplified index for the collection, with unit-lenght tuples converted to standalone items.
- property targets: TargetCollection¶
Targets associated with the results in the collection.
- thin(n: int, start_loc: int = 0) ResultCollection¶
Thin the collection by taking every `n`th result.
- Parameters:
n (int) – number of results to skip between each result.
start_loc (int) – starting location in the collection to thin from (def., 0).
- Returns:
new_collection – thinned collection.
- Return type:
- to_netcdf(paths: str | None = None, **kws) None¶
Save the collection of results to NetCDF files.
- Parameters:
paths (str) – template path to NetCDF file or list of paths; if a string, expected to be a template like path/to/many/files/*.nc or path/to/many/files/{}.nc where {} or * is replaced by the index value.
**kws (dict) – additional keyword arguments to pass to the to_netcdf method of each result
- update_default_label_format(**kws) None¶
Update the default formatting options for DataFrames.
Waveforms module¶
Utilities for generating and handling gravitational-wave templates.
- class ringdown.waveforms.Coalescence(*args, modes=None, **kwargs)¶
Bases:
SignalAn inspiral-merger-ringdown signal from a compact binary coalescence.
- classmethod from_parameters(time, model=None, approximant=None, ell_max=None, single_mode=None, window=0.125, manual_epoch=False, subsample_placement=False, **kws)¶
Construct coalescence waveform from compact-binary parameters.
Additional keyword arguments are passed to
Parametersto construct the input forls.SimInspiralChooseTDWaveform(). This should include masses, spins, inclination, refrence phase, reference frequency, minimum frequency, and trigger time.In order to reproduce waveform placement for time-domain waveforms as carried out by
LALInference, use manual_epoch = False. Otherwise, will place waveform such that the empirical peak of the waveform envelope falls on the specified trigger time. If subsample_placement, the peak is identified via quadratic sub-sample interpolation and the waveform is shifted in the Fourier domain so that the interpolated peak falls on a sample (this option necessarily reduces performance).By default, a one-sided Tukey window with a ramp up of \(\alpha = 0.125\) is applied to the left-hand side of the signal. This means that frequencies below \(\approx 1/\left(\alpha \times T\right)\) will be corrupted, where \(T\) is the intrinsic duration of the waveform as determined by f_low. This behavior is turned off if window is 0 or False, but at risk of having a sharp turn on of time-domain waveforms in band (this should be safe for frequency-domain waveforms).
(Note that an estimate on \(T\) can be obtained through
XLALSimInspiralChirpTimeBound(f_min, m1, m2, S1z, S2z).)- Parameters:
time (array) – time array over which to evaluate waveform.
model (str) – name of waveform approximant (e.g., “NRSur7dq4”).
approximant (str) – alias for model.
ell_max (int) – highest angular harmonic
ellmode to include, defined in the coprecessing frame per the convention inherited from LALSimulation Defaults to None, which includes all available modes.single_mode (tuple) – single
(ell, m)spherical mode to include, e.g.,(2, 2); includes both left and right handed contributions, i.e.,(l, m)and(l, -m). Defaults to None, which includes all available modes.window (float, bool) – window signal from the left to avoid sharp turn ons in time-domain approximants; numerical value is interpreted as fraction of time for
tukey()window ramp up. Defaults to 0.125.manual_epoch (bool) – align waveform based on empirically found waveform peak (i.e., peak of \(h_+^2 + h_\times^2\)), not the epoch reported by approximant. Defaults to False.
subsample_placement (bool) – if
manual_epoch, find waveform peak using quadratic subsample interpolation; else, find maximum of waveform envelope in samples. Defaults to False.kws – additional keyword arguments passed to
Parameters.
- Returns:
h – compact binary coalescence signal.
- Return type:
- get_invariant_peak_time(ell_max=None, force=False)¶
Compute time of the peak of the invariant strain \(H^2\), which is defined as
\[H^2(t) \equiv \sum_{\ell m} H_{\ell m}^2(t)\]where \(H_{\ell m}(t)\) are the coefficients associated with the spherical harmonic factors \({}_{-2} Y_{\ell m}\) in the strain, namely
\[h(t) = \sum_{\ell m} H_{\ell m}(t) {}_{-2} Y_{\ell m}\]Note
This currently only works with some time domain approximants (e.g., NRSur7dq4), as it relies on
ls.SimInspiralChooseTDModes().- Parameters:
ell_max (int) – maximum \(\ell\) to include in the computation of the peak
force (bool) – redo the computation ignoring cached results
- Returns:
t_peak – peak time of the invariant strain
- Return type:
float
- class ringdown.waveforms.Parameters(mass_1: float, mass_2: float, spin_1x: float = 0, spin_1y: float = 0, spin_1z: float = 0, spin_2x: float = 0, spin_2y: float = 0, spin_2z: float = 0, luminosity_distance: float = None, iota: float = 0, phase: float = 0, long_asc_nodes: float = 0, eccentricity: float = 0, mean_per_ano: float = 0, f_low: float = 20, f_ref: float = 20, psi: float = 0, ra: float = None, dec: float = None, trigger_time: float = 0)¶
Bases:
objectContainer for CBC parameters.
Spin information is encoded in Cartesian components (LALSimulation convention).
- property chirp_mass¶
mathcal{M}_c = left(m_1 m_2right)^{3/5}/ left(m_1 + m_2right)^{1/5}.
- Type:
Chirp mass
- Type:
math
- compute_remnant_mchi(model: str = 'NRSur7dq4Remnant', solar_masses=True) tuple¶
Estimate remnant mass and spin using a remnant model.
- Parameters:
model (str) – name of remnant model to use (default: ‘NRSur7dq4Remnant’)
- Returns:
mf (float) – remnant mass.
chif (float) – remnant dimensionless spin magnitude.
- classmethod construct(**kws)¶
- property cos_iota¶
Cosine of the Newtonian inclination at reference frequency.
- dec: float = None¶
- eccentricity: float = 0¶
- property extrinsic¶
Extrinsic parameters.
- f_low: float = 20¶
- f_ref: float = 20¶
- property final_mass¶
- property final_mass_seconds¶
- property final_mass_si¶
- property final_spin¶
- get_choosetdmodes_args(delta_t)¶
Construct input for
ls.SimInspiralChooseTDModes().- Parameters:
delta_t (float) – time spacing for waveform array
- Returns:
args – list of arguments ready for
ls.SimInspiralChooseTDModes()- Return type:
list
- get_choosetdwaveform_args(delta_t)¶
Construct input for
ls.SimInspiralChooseTDWaveform().- Parameters:
delta_t (float) – time spacing for waveform array
- Returns:
args – list of arguments ready for
ls.SimInspiralChooseTDWaveform()- Return type:
list
- property intrinsic¶
Intrinsic parameters.
- iota: float = 0¶
- items(*args, **kwargs)¶
- keys(*args, **kwargs)¶
- long_asc_nodes: float = 0¶
- luminosity_distance: float = None¶
- property luminosity_distance_si¶
Luminosity distance in meters.
- mass_1: float¶
- property mass_1_si¶
First component mass in kg.
- mass_2: float¶
- property mass_2_si¶
Second component mass in kg.
- property mass_ratio¶
Mass ratio \(q = m_2/m_1\) for \(m_1 \geq m_2\).
- mean_per_ano: float = 0¶
- phase: float = 0¶
- psi: float = 0¶
- ra: float = None¶
- property spin_1¶
3D dimensionless spin for first component.
- property spin_1_mag¶
Dimensionless spin magnitude for first component.
- spin_1x: float = 0¶
- spin_1y: float = 0¶
- spin_1z: float = 0¶
- property spin_2¶
3D dimensionless spin for second component.
- property spin_2_mag¶
Dimensionless spin magnitude for second component.
- spin_2x: float = 0¶
- spin_2y: float = 0¶
- spin_2z: float = 0¶
- to_dict() dict¶
- property total_mass¶
Total mass in solar masses, \(M = m_1 + m_2\).
- trigger_time: float = 0¶
- values(*args, **kwargs)¶
- class ringdown.waveforms.Ringdown(*args, modes=None, **kwargs)¶
Bases:
Signal- static complex_mode(time: ndarray, omega: float | ndarray, gamma: float | ndarray, a: float | ndarray, ellip: float | ndarray, theta: float | ndarray, phi: float | ndarray) ndarray¶
Compute complex-valued ringdown mode waveform, as given by Eq. (8) in Isi & Farr (2021), namely
\[h = \frac{1}{2} A e^{-t \gamma}*\left((1 + \epsilon) e^{-i(\omega t - \phi_p)} + (1 - \epsilon) e^{i (\omega*t + \phi_m)}\right)\]where \(\phi_p = \phi - \theta\) and \(\phi_m = -(\phi + \theta)\).
- Parameters:
time (array) – time array [t].
omega (float) – angular frequency of the mode [1/t].
gamma (float) – damping rate of the mode [1/t].
a (float) – amplitude of the mode.
ellip (float) – ellipticity of the mode.
theta (float) – angle of ellipse in \(h_+,h_\times\) space, in radians.
phi (float) – phase angle in radians.
- Returns:
h – complex-valued waveform.
- Return type:
array
- classmethod from_parameters(time: array, t0: float = 0, signal_buffer: float = inf, two_sided: bool = True, df_pre: float = 0, dtau_pre: float = 0, mode_isel: float = None, **kws)¶
Create injection: a sinusoid up to t0, then a damped sinusoid. The (A_pre, df_pre, dtau_pre) parameters can extend the damped sinusoid backwards into a sinusoid or a ring-up, to produce a ring-up. Can incorporate several modes, if (A, phi0, f, tau) are 1D.
- Parameters:
time (array) – time array [t].
t0 (float) – ringdown model start time.
signal_buffer (float) – window of time around t0 over which to evaluate model (default np.inf, the full time segment).
two_sided (bool) – whether to include a ring-up in times preceding t0 (default True).
df_pre (float) – frequency shift for ring-up (default 0).
dtau_pre (float) – damping shift for ring-up (default 0).
mode_isel (list, int) – index or indices of modes to include in template; if None includes all modes (default).
- get_mode_parameters(mode)¶
- get_parameter(k, *args, **kwargs)¶
Get parameter k from
Signal.parameters.- Parameters:
k (str) – parameter key.
- Returns:
value – parameter value.
- Return type:
any
- property n_modes¶
- class ringdown.waveforms.Signal(*args, parameters=None, **kwargs)¶
Bases:
TimeSeriesBase class for gravitational wave signals, with methods for projection onto detectors and signal processing.
- classmethod from_parameters(*args, **kwargs) Signal¶
Produce a gravitational wave from parameters, for either a full compact binary coalescence, or the ringdown alone.
Input is passed to the corresponding constructor method, depending on the model specified in arguments. Assumes signal is ringdown by default.
- Parameters:
*args – arguments passed to constructor.
**kwargs – keyword arguments passed to constructor.
- Returns:
signal – subclass of signal.
- Return type:
- get_parameter(k: str, *args)¶
Get parameter k from
Signal.parameters.- Parameters:
k (str) – parameter key.
- Returns:
value – parameter value.
- Return type:
any
- property peak_time¶
Empirical estimate of the time of waveform envelope peak, \(\max\left(h_+^2 + h_\times^2\right)\), obtained through quadratic sub-sample interpolation.
- plot(ax=None, envelope: bool = False)¶
Plot the series’ plus and cross components. Remember that the value of this timeseries is
h = hp - 1j*hc.- Parameters:
ax (matplotlib.pyplot.Axes, None) – axis on which to plot, or None to create a new figure.
envelope (bool) – plot the envelope of the waveform, \(|h|\), as a dashed line.
- project(ifo: str | None = None, t0: float | None = None, antenna_patterns: tuple | None = None, delay: float | str | None = None, ra: float | None = None, dec: float | None = None, psi: float | None = None, fd_shift: bool = False, interpolate: bool = False)¶
Project waveform onto detector, multiplying by antenna patterns and shifting by time-of-flight delay (if required).
- Parameters:
ifo (str) – name of detector onto which to project signal, used to compute antenna_patterns and delay, if not provided explicitly.
t0 (float) – trigger time used to compute antenna_patterns and delay, if not provided explicitly; if projecting from ifo name, assumes this is GPS time. Defaults to
Signal.t0.antenna_patterns (tuple[float]) – tuple of floats with plus and cross antenna pattern values (Fp, Fc); computed based on ifo and sky location if not given.
delay (float, str) – numerical delay by which to shift signal, or
'geocent'to indicate delay is to be computed relative to geocenter for detector specified by ifo. Defaults to 0, which results in no time shift.ra (float) – source right ascension (rad), only used if projecting based on detector name.
dec (float) – source declination (rad), only used if projecting based on detector name.
psi (float) – source polarization angle (rad), only if projecting based on detector name.
fd_shift (bool) – time shift signal in the Fourier domain, if time shifting at all (determined by delay argument). Defaults to False.
interpolate (bool) – use cubic subsample signal interpolation when shifting in the time domain (fd_shift = False); otherwise, rolls by number of samples closest to delay. Defaults to False.
- Returns:
data – signal projected onto detector.
- Return type:
- property t0¶
Reference time t0, or alias, from
Signal.parameters. Valid aliases are: [‘geocent_time’, ‘trigger_time’, ‘triggertime’, ‘tc’, ‘tgps_geo’, ‘tgps_geocent’, ‘t0’].
- ringdown.waveforms.get_delay(ifo: str, t0: <MagicMock name='mock.__ror__()' id='139049793062288'>, ra: float, dec: float, reference: str = 'geocent')¶
Compute time-of-flight delay from geocenter to detector, or between detectors.
- Parameters:
ifo (str) – detector prefix.
t0 (float, LIGOTimeGPS) – reference time.
ra (float) – right ascension (rad).
dec (float) – declination (rad).
reference (str) – reference for time-of-flight delay; can be either
'geocent'to compute delay from geocenter to detector, or the prefix of another detector to compute delay between detectors.
- Returns:
dt – time-of-flight delay.
- Return type:
float
- ringdown.waveforms.get_detector_signals(times: dict | ndarray | None = None, ifos: list | None = None, antenna_patterns: dict | None = None, trigger_times: dict | None = None, t0_default: float | None = None, fast_projection: bool = False, **kws)¶
Produce templates at each detector for a given set of parameters. Can be used to generate waveforms from model samples, or to obtain IMR injections.
Additional keyword arguments are passed to
Signal.from_parameters()andSignal.project().- Parameters:
times (dict, array) – a dictionary with time stamps for each detector, or a single array of time stamps to be shared by all detectors.
ifos (list) – list of detector names, only required if times is a single array.
antenna_patterns (dict, None) – optional dictionary of tuples with plus and cross antenna patterns for each detector, (Fp, Fc); if not given, computed from sky location provided in keyword arguments.
trigger_times (dict, None) – dictionary of arrival-times at each detector; computed from sky location and reference trigger time if not given.
t0_default (float) – optional default trigger time, to be used if no other valid trigger time argument is provided in keyword arguments.
fast_projection (bool) – if true, evaluates polarization functions only once using the time array of the first interferometer and then projects onto each detector by time shifting; otherwise, evaluates polarizations for each detector, ensuring that there are no off-by-one alignment errors. (Def. False)
**kws – arguments passed to
Signal.from_parameters()and/orSignal.project().
- Returns:
sdict – dictionary of
Datawaveforms for each detector.- Return type:
dict
QNMs module¶
- class ringdown.qnms.KerrMode(*args, **kwargs)¶
Bases:
objectA Kerr quasinormal mode.
- property coefficients¶
- static compute_coefficients(mode, **kws)¶
- fgamma(chi, m_msun=None, approx=False)¶
- ftau(chi, m_msun=None, approx=False)¶
- ringdown.qnms.get_ftau(M, chi, n, l=2, m=2)¶
Get the frequency and damping time of a Kerr quasinormal mode.
This is a wrapper around the package qnm.
- Parameters:
M (float) – Black hole mass in solar masses.
chi (float) – Dimensionless spin parameter.
n (int) – Overtone number.
l (int) – Spherical harmonic index (def. 2)
m (int) – Azimuthal harmonic index (def. 2)
- Returns:
f (float) – Frequency of the mode in Hz.
tau (float) – Damping time of the mode in seconds.
Indexing module¶
- class ringdown.indexing.GenericIndex(i: int)¶
Bases:
ModeIndexGeneric mode index for non-harmonic modes (a wrapper around an integer).
- classmethod construct(i)¶
- get_coordinate()¶
- get_label(**kws)¶
- i: int¶
- property is_prograde¶
- class ringdown.indexing.ModeIndex¶
Bases:
ABCAbstract class to construct mode indices. Use the construct method to create a mode index object from a string, tuple, or other object.
- as_dict()¶
- classmethod construct(*mode)¶
- abstract get_coordinate()¶
- abstract get_label(**kws)¶
- abstract property is_prograde¶
- class ringdown.indexing.ModeIndexList(indices=None)¶
Bases:
object- get_coordinates()¶
- get_labels(**kws)¶
- index(x)¶
- property is_generic¶
- property n_modes¶
- property value¶
- ringdown.indexing.get_mode_coordinate(mode, **kws)¶
- ringdown.indexing.get_mode_label(mode, **kws)¶
Target module¶
Module defining the core Target class.
- class ringdown.target.DetectorTarget(detector_times: dict | None = None, antenna_patterns: dict | None = None, duration: float = 0)¶
Bases:
TargetTarget for a ringdown analysis defined from explicit detector times and antenna patterns, rather than a sky location and a geocenter time.
- antenna_patterns: dict | None = None¶
- classmethod construct(detector_times: dict | float | list, antenna_patterns: dict | list[tuple[float]] | tuple[float, float], ifos: list | str = None, duration: float = 0.0)¶
Create a target object from a set of detector times and antenna patterns.
The preferred input is two dictionaries of detector times and antenna pattern (Fp, Fc) tuples indexed by interferometer name. Alternatively, lists of values can be provided for both detector_times and antenna_patterns to be indexed by a list of interferometer names ifo.
If a single time is provided, it will be used for all detectors. If a single tuple is provided for antenna patterns, it will be used if only a single detector was specified through ifos.
If no detector names are specified as either keys of antenna_patterns or the ifos argument, then will assume a single detector named None.
- detector_times: dict | None = None¶
- duration: float = 0¶
- get_antenna_patterns(ifo) tuple[float, float]¶
- get_detector_time(ifo) float¶
- property sky: tuple[None]¶
Sky location is (None, None, None)
- property t0: None¶
Geocenter reference time is None
- class ringdown.target.SkyTarget(geocenter_time: <MagicMock name='mock.__ror__().__or__()' id='139049800055360'> = None, ra: float | None = None, dec: float | None = None, psi: float | None = None, duration: float = 0)¶
Bases:
TargetSky location target for a ringdown analysis.
- classmethod construct(t0: float, ra: float, dec: float, psi: float, reference_ifo: str | None = None, duration: float = 0.0, **kws)¶
Create a sky location from a reference time, either a specific detector or geocenter.
- Parameters:
t0 (float) – detector time.
ra (float) – source right ascension.
dec (float) – source declination.
psi (float) – source polarization angle.
reference_ifo (str, None) – detector name, or None for geocenter (default None)
duration (float) – analysis duration (default 0.)
- Returns:
sky – a target object.
- Return type:
- dec: float | None = None¶
- duration: float = 0¶
- geocenter_time: <MagicMock name='mock.__ror__().__or__()' id='139049800055360'> = None¶
- get_antenna_patterns(ifo) tuple[float, float]¶
Compute antenna patterns based on sky location.
- Parameters:
ifos (list) – list of detector names.
- Returns:
antenna_patterns – dictionary of antenna patterns.
- Return type:
dict
- get_detector_time(ifo) float¶
Compute detector times based on sky location.
- Parameters:
ifo (list) – detector name.
- Returns:
times – time for specified detector.
- Return type:
float
- psi: float | None = None¶
- ra: float | None = None¶
- property settings: dict¶
Return a dictionary of settings for the target.
- property sky: tuple[float | None]¶
Return sky location as a tuple (ra, dec, psi).
- property t0: float | None¶
Alias for time_geocenter.
- class ringdown.target.Target¶
Bases:
ABCAbstract class to define a target for a ringdown analysis. A target can be defined either by a sky location or by detector times and antenna patterns. Use the construct method to create a target object from a dictionary or keyword arguments.
- as_dict() dict¶
- static construct(t0: float | dict, ra: float | None = None, dec: float | None = None, psi: float | None = None, reference_ifo: str | None = None, antenna_patterns: dict | None = None, **kws)¶
Create a target object from a dictionary or keyword arguments. The source sky location and orientation can be specified by the ra, dec, and psi arguments. These are use to both determine the truncation time at different detectors, as well as to compute the corresponding antenna patterns.
Alternatively, analysis times and antenna patterns can be specified directly for each detector. In this case, the t0 argument should be a dictionary with detector names as keys and start times as values.
Cannot simultaneously provide both sky location and detector times.
- Parameters:
t0 (float, dict) – start time for the analysis, either a single time or a dictionary of times for each detector.
ra (float, None) – source right ascension.
dec (float, None) – source declination.
psi (float, None) – source polarization angle.
reference_ifo (str, None) – detector name for time reference, or None for geocenter (default None)
antenna_patterns (dict, None) – dictionary of antenna patterns for each detector, or None to compute from sky location.
- duration: float¶
- abstract get_antenna_patterns(ifo) tuple[float, float] | None¶
- get_antenna_patterns_dict(ifos) dict¶
- abstract get_detector_time(ifo) float | None¶
- get_detector_times_dict(ifos) dict¶
- property has_sky: bool¶
- property is_set: bool¶
- property settings: dict¶
- abstract property sky: tuple[float | None]¶
- abstract property t0: float | None¶
- class ringdown.target.TargetCollection(targets: list | None = None, index=None, reference_mass=None, reference_time=None, info=None)¶
Bases:
MultiIndexCollectionCollection of targets for a ringdown analysis. The collection can be initialized with a list of Target objects, or by specifying the start times and sky locations for each target. The collection can also store a reference time to label start times, as well as a reference mass (in solar masses) to label time steps in units of mass. The collection can be indexed by start times, and can provide time differences with respect to the reference time, or time steps in units of mass.
- classmethod construct(*args, reference_mass: float | None = None, info: dict | None = None, **kws) TargetCollection¶
Construct a collection of targets from a set of keyword arguments. There are three ways to specify the start times:
1- listing the times explicitly 2- listing time differences with respect to a reference time 3- providing start, stop, step instructions to construct start times (potentially relative to a reference time)
Time steps/differences can be specified in seconds or M, if a reference mass is provided (in solar masses).
Accepted arguments to set target time are: - t0_list: list of start times - t0_delta_list: list of time differences with respect to a reference - t0_ref: reference time to be used for time differences - t0_start, t0_stop, t0_step: start, stop, step instructions
Additional arguments can be provided to specify the sky location and duration of the analysis.
- Parameters:
reference_mass (float, None) – reference mass in solar masses to use for time steps.
info (dict, None) – dictionary of additional information to store with the collection.
kws (dict) – keyword arguments to specify target times and sky locations.
- Returns:
targets – collection of target objects.
- Return type:
- classmethod from_config(config_input, t0_sect='pipe', sky_sect='target', imr_result=None, acfs=None)¶
Create a collection of targets from a configuration file.
All arguments in the t0_sect section of the configuration file are passed to the construct method to create the target collection (see docs for construct for details), with additional special handling if an IMR result is referenced.
If any of the arguments to construct are set to ‘imr’, then attempts to derive them from IMR result: if imr_result is not provided, then the IMR section of the configuration file is used to load the IMR result.
- Parameters:
config_input (str, ConfigParser) – configuration file or dictionary.
t0_sect (str) – section of the configuration file to use for target times.
sky_sect (str) – section of the configuration file to use for sky location.
imr_result (IMRResult, None) – IMR result to use for reference values. If None, then the IMR section of the configuration file is used to load the IMR result if needed.
- Returns:
targets – collection of target objects.
- Return type:
- get(key) list | ndarray¶
Get attribute key for each target in the collection. Special keys include: - delta-t0: time differences with respect to the reference time - delta-m: time differences in units of reference mass
- Parameters:
key (str) – attribute name.
- Returns:
values – list of attribute values.
- Return type:
list
- get_antenna_patterns(ifo) list[tuple[float, float]]¶
Get antenna patterns for each target in the collection.
- get_detector_times(ifo) list[float]¶
Get detector times for each target in the collection.
- property index: list¶
Index for the collection; defaults to start times if none provided.
- property step_mass: float | None¶
Time step for the collection, in units of mass.
- property step_time: float | None¶
Time step for the collection, in seconds.
- property t0: ndarray¶
Start times for each target in the collection.
- property t0m: ndarray¶
Start times relative to the reference time in units of mass.
- property targets: list¶
List of targets in the collection.
- update_info(section: str, **kws) None¶
Update fit information stored in
TargetCollection.info
Utilities module¶
- class ringdown.utils.Bounded_1d_kde(pts, x_min=None, x_max=None, *args, **kwargs)¶
Bases:
gaussian_kdeRepresents a one-dimensional Gaussian kernel density estimator for a probability distribution function that exists on a bounded domain.
Authorship: Ben Farr, LIGO
- evaluate(pts)¶
Return an estimate of the density evaluated at the given points.
- property x_max¶
The upper bound of the x domain.
- property x_min¶
The lower bound of the x domain.
- class ringdown.utils.Bounded_2d_kde(pts, x_min=None, x_max=None, y_min=None, y_max=None, *args, **kwargs)¶
Bases:
gaussian_kdeRepresents a two-dimensional Gaussian kernel density estimator for a probability distribution function that exists on a bounded domain.
- evaluate(pts)¶
Return an estimate of the density evaluated at the given points.
- property x_max¶
The upper bound of the x domain.
- property x_min¶
The lower bound of the x domain.
- property y_max¶
The upper bound of the y domain.
- property y_min¶
The lower bound of the y domain.
- class ringdown.utils.ConfigParser(defaults=None, dict_type=<class 'dict'>, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object>, converters=<object object>)¶
Bases:
RawConfigParserConfigParser implementing interpolation.
- add_section(section)¶
Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.
- set(section, option, value=None)¶
Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.
- class ringdown.utils.MultiIndexCollection(data=None, index=None, reference_mass=None, reference_time=None, info=None)¶
Bases:
object- add(key, value)¶
- property as_dict¶
- get(key)¶
- property idx¶
- property index¶
- items()¶
- keys()¶
- property loc¶
- property reference_mass¶
Reference time relative to which to compute time differences.
- property reference_mass_seconds: float | None¶
Reference mass in units of seconds.
- property reference_time¶
Reference mass in solar masses to use for time steps in units of mass.
- reindex(new_index)¶
- set_reference_mass(reference_mass)¶
- set_reference_time(reference_time)¶
- values()¶
- ringdown.utils.docstring_parameter(*args, **kwargs)¶
- ringdown.utils.form_opt(x, key=None, **kws) str¶
Utility to format options in config.
- Parameters:
x (str, list, or dict) – The option to format.
kws (dict) – Additional keyword arguments to pass to np.array2string.
- Returns:
The formatted option.
- Return type:
str
- ringdown.utils.get_bilby_dict(d)¶
Parse bilby-style data dict string.
- ringdown.utils.get_dict_from_pattern(path, ifos=None, abspath=False)¶
- ringdown.utils.get_hdf5_value(x)¶
Attempt to parse a string as a number, dict, or list.
- ringdown.utils.get_ifo_list(config, section)¶
- ringdown.utils.get_tqdm(progress: bool = True)¶
Return the appropriate tqdm based on the execution environment.
- ringdown.utils.isp2(x)¶
Returns True if x is a power of two.
- ringdown.utils.kdeplot(x, y=None, orientation='vertical', **kws)¶
Plot a one-dimensional or two-dimensional kernel density estimate. Compatible with seaborn’s kdeplot.
- Parameters:
x (array) – samples of the variable.
y (array) – samples of the second variable, drawn jointly with x (optional).
orientation (str) – if ‘vertical’ produces a regular landscape plot; if ‘horizontal’ produces a rotated plot, in which x and y are flipped; if ‘auto’ the orientation is determined by the aspect ratio of the axes.
- ringdown.utils.literal_eval(node_or_string)¶
Evaluate an expression node or a string containing only a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
Caution: A complex expression can overflow the C stack and cause a crash.
- ringdown.utils.load_config(config_input)¶
- ringdown.utils.load_config_dict(config_input)¶
- ringdown.utils.np2(x)¶
Returns the next power of two as big as or larger than x.
- ringdown.utils.string_to_tuple(s)¶
- ringdown.utils.try_parse(x)¶
Attempt to parse a string as a number, dict, or list.