holodeck.utils

Utility functions and tools.

References

class holodeck.utils._Modifier[source]

Bases: ABC

Base class for all types of post-processing modifiers.

Notes

  • Must be subclassed for use.

  • __call__(base) ==> modify(base)

abstract modify(base: object)[source]

Perform an in-place modification on the passed object instance.

Parameters:

base (object) – The object instance to be modified.

_abc_impl = <_abc._abc_data object>
holodeck.utils.deprecated_warn(msg, exc_info=True)[source]

Decorator for functions that will be deprecated, add warning, but still execute function.

holodeck.utils.deprecated_pass(new_func, msg='', exc_info=True)[source]

Decorator for functions that have been deprecated, warn and pass arguments to new function.

holodeck.utils.deprecated_fail(new_func, msg='', exc_info=True)[source]

Decorator for functions that have been deprecated, warn and raise error.

holodeck.utils.load_hdf5(fname, keys=None)[source]

Load data and header information from HDF5 files into dictionaries.

Parameters:
  • fname (str) – Filename to load (must be an hdf5 file).

  • keys (None or (list of str)) – Specific keys to load from the top-level of the HDF5 file. None: load all top-level keys.

Returns:

  • header (dict,) – All entries from hdf5.File.attrs, typically used for meta-data.

  • data (dict,) – All top level datasets from the hdf5 file, specifically everything returned from hdf5.File.keys().

holodeck.utils.mpi_print(*args, **kwargs)[source]
holodeck.utils.python_environment()[source]

Tries to determine the current python environment, one of: ‘jupyter’, ‘ipython’, ‘terminal’.

Returns:

Description of the current python environment, one of [‘jupter’, ‘ipython’, ‘terminal’].

Return type:

str

holodeck.utils.tqdm(*args, **kwargs)[source]

Construct a progress bar appropriately based on the current environment (script vs. notebook)

Parameters:
  • *args (All arguments are passed directory to the tqdm constructor.) –

  • **kwargs (All arguments are passed directory to the tqdm constructor.) –

Returns:

Decorated iterator that shows a progress bar.

Return type:

tqdm.tqdm_gui

holodeck.utils.get_file_size(fnames, precision=1)[source]

Return a human-readable size of a file or set of files.

Parameters:
  • fnames (str or list) – Paths to target file(s)

  • precisions (int,) – Sesired decimal precision of output

Returns:

byte_str – Human-readable size of file(s)

Return type:

str

holodeck.utils.path_name_ending(path, ending)[source]
holodeck.utils.get_subclass_instance(value, default, superclass, allow_none=False)[source]

Convert the given value into a subclass instance.

None ==> instance from default class Class ==> instance from that class instance ==> check that this is an instance of a subclass of superclass, error if not

Parameters:
  • value (object,) – Object to convert into a class instance.

  • default (class,) – Default class constructor to use if value is None.

  • superclass (class,) – Super/parent class to compare against the class instance from value or default. If the class instance is not a subclass of superclass, a ValueError is raised.

Returns:

value – Class instance that is a subclass of superclass.

Return type:

object,

:raises ValueError : if the class instance is not a subclass of superclass.:

holodeck.utils.get_git_hash(short=True) str[source]
holodeck.utils.roll_rows(arr, roll_num)[source]

Roll each row (axis=0) of the given array by an amount specified.

Parameters:
  • arr ((R, D) ndarray) – Input data to be rolled.

  • roll_num ((R,) ndarray of int) – Amount to roll each row. Must match the number of rows (axis=0) in arr.

Returns:

result – Rolled version of the input data.

Return type:

(R, D) ndarray

Example

>>> a = np.arange(12).reshape(3, 4); b = [1, -1, 2]; utils.roll_rows(a, b)
array([[ 3,  0,  1,  2],
       [ 5,  6,  7,  4],
       [10, 11,  8,  9]])
holodeck.utils.get_scatter_weights(uniform_cents, dist)[source]

Get the weights (fractional mass) that should be transferred to each bin to introduce the given scatter.

Parameters:
  • uniform_cents ((N,) ndarray) – Uniformly spaced bin-centers specifying distances in the parameter of interest (e.g. mass).

  • dist (scipy.stats._distn_infrastructure.rv_continuous_frozen instance) – Object providing a CDF function cdf(x) determining the weights for each bin. e.g. dist = sp.stats.norm(loc=0.0, scale=0.1)

Returns:

dm – Array of weights for bins with the given distances. [-N+1, -N+2, …, -2, -1, 0, +1, +2, …, +N-2, +N-1]

Return type:

(2*N - 1,) ndarray

holodeck.utils._scatter_with_weights(dens, weights, axis=0)[source]
holodeck.utils._get_rolled_weights(log_cents, dist)[source]
holodeck.utils.scatter_redistribute_densities(cents, dens, dist=None, scatter=None, axis=0)[source]

Redistribute dens across the target axis to account for scatter/variance.

Parameters:
  • cents ((N,) ndarray) – Locations of bin centers in the parameter of interest.

  • dist (scipy.stats._distn_infrastructure.rv_continuous_frozen instance) – Object providing a CDF function cdf(x) determining the weights for each bin. e.g. dist = sp.stats.norm(loc=0.0, scale=0.1)

  • dens (ndarray) – Input values to be redistributed. Must match the size of cents along axis axis.

Returns:

dens_new – Array with resitributed values. Same shape as input dens.

Return type:

ndarray

holodeck.utils.eccen_func(cent: float, width: float, size: int) ndarray[source]

Draw random values between [0.0, 1.0] with a given center and width.

This function is a bit contrived, but the norm defines the center-point of the distribution, and the std parameter determines the width of the distribution. In all cases the resulting values are only between [0.0, 1.0]. This function is typically used to draw initial random eccentricities.

Parameters:
  • cent (float,) – Specification of the center-point of the distribution. Range: positive numbers. Values norm << 1 correspond to small eccentricities, while norm >> 1 are large eccentricities, with the distribution symmetric around norm=1.0 (and eccens of 0.5).

  • width (float,) – Specification of the width of the distribution. Specifically how near or far values tend to be from the given central value (norm). Range: positive numbers. Note that the ‘width’ of the distribution depends on the norm value, in addition to std. Smaller values (typically std << 1) produce narrower distributions.

  • size (int,) – Number of samples to draw.

Returns:

eccen – Values between [0.0, 1.0] with shape given by the size parameter.

Return type:

ndarray,

holodeck.utils.frac_str(vals, prec=2)[source]

Return a string with the fraction and decimal of non-zero elements of the given array.

e.g. [0, 1, 2, 0, 0] ==> “2/5 = 4.0e-1”

Parameters:
  • vals ((N,) array_like,) – Input array to find non-zero elements of.

  • prec (int) – Decimal precision in scientific notation string.

Returns:

rv – Fraction string.

Return type:

str,

holodeck.utils.interp(xnew, xold, yold, left=nan, right=nan, xlog=True, ylog=True)[source]

Linear interpolation of the given arguments in log/lin-log/lin space.

Parameters:
  • xnew (npt.ArrayLike) – New locations (independent variable) to interpolate to.

  • xold (npt.ArrayLike) – Old locations of independent variable.

  • yold (npt.ArrayLike) – Old locations of dependent variable.

  • left (float, optional) – Fill value for locations below the domain xold.

  • right (float, optional) – Fill value for locations above the domain xold.

  • xlog (bool, optional) – Linear interpolation in the log of x values.

  • ylog (bool, optional) – Linear interpolation in the log of y values.

Returns:

y1 – Interpolated output values of the dependent variable.

Return type:

npt.ArrayLike

holodeck.utils.isnumeric(val: object) bool[source]

Test if the input value can successfully be cast to a float.

Parameters:

val (object) – Value to test.

Returns:

True if the input value can be cast to a float.

Return type:

bool

holodeck.utils.isinteger(val: object) bool[source]

Test if the input value is an integral (integer) number.

Parameters:

val (object) – Value to test.

Returns:

True if the input value is an integer number.

Return type:

bool

holodeck.utils.log_normal_base_10(mu: float, sigma: float, size: int | List[int] | None = None, shift: float = 0.0) ndarray[source]

Draw from a log-normal distribution using base-10 standard-deviation.

i.e. the sigma argument is in “dex”, or powers of ten.

Parameters:
  • mu (float) – Mean value of the distribution.

  • sigma (float) – Standard deviation in dex (i.e. powers of ten). sigma=1.0 means a standard deviation of one order of magnitude around mu.

  • size (Union[int, list[int]], optional) – Number of values to draw. Either a single integer, or a tuple of integers describing a shape.

  • shift (float, optional) –

Returns:

dist – Resulting distribution values.

Return type:

npt.ArrayLike

holodeck.utils.midpoints(vals, axis=-1, log=False)[source]
holodeck.utils.midpoints_multiax(vals, axis, log=False)[source]
holodeck.utils.minmax(vals: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], filter: bool = False) ndarray[source]

Find the minimum and maximum values in the given array.

Parameters:
  • vals (npt.ArrayLike) – Input values in which to find extrema.

  • filter (bool, optional) – Select only finite values from the input array.

Returns:

extr – Minimum and maximum values.

Return type:

(2,) np.ndarray

holodeck.utils.ndinterp(xx, xvals, yvals, xlog=False, ylog=False)[source]

Interpolate 2D data to an array of points.

xvals and yvals are (N, M) where the interpolation is done along the 1th (M) axis (i.e. interpolation is done independently for each N row. Should be generalizeable to higher dim.

Parameters:
  • xx ((T,) or (N, T) ndarray) – Target x-values to interpolate to.

  • xvals ((N, M) ndarray) – Evaluation points (x-values) of the functions to be interpolated. Interpolation is performed over the 1th (last) axis. NOTE: values must be monotonically increasing along axis=1 !

  • yvals ((N, M) ndarray) – Function values (y-values) of the function to be interpolated. Interpolation is performed over the 1th (last) axis.

Returns:

ynew – Interpolated function values, for each of N functions and T evaluation points.

Return type:

(N, T) ndarray

holodeck.utils.pta_freqs(dur=505868328.00000006, num=40, cad=None)[source]

Get Fourier frequency bin specifications for the given parameters.

Parameters:
  • dur (float,) – Total observing duration, which determines the minimum sensitive frequency, 1/dur. Typically dur should be given in units of [sec], such that the returned frequencies are in units of [1/sec] = [Hz]

  • num (int,) – Number of frequency bins. If cad is not None, then the number of frequency bins is determined by cad and the num value is disregarded.

  • cad (float or None,) – Cadence of observations, which determines the maximum sensitive frequency (i.e. the Nyquist frequency). If cad is not given, then num frequency bins are constructed.

Returns:

  • cents ((F,) ndarray) – Bin-center frequencies for F bins. The frequency bin centers are at: F_i = (i + 1.5) / dur for i between 0 and num-1. The number of frequency bins, F is the argument num, or determined by cad if it is given.

  • edges ((F+1,) ndarray) – Bin-edge frequencies for F bins, i.e. F+1 bin edges. The frequency bin edges are at: F_i = (i + 1) / dur for i between 0 and num. The number of frequency bins, F is the argument num, or determined by cad if it is given.

holodeck.utils.print_stats(stack=True, print_func=<built-in function print>, **kwargs)[source]

Print out basic properties and statistics on the input key-value array_like values.

Parameters:
  • stack (bool,) – Whether or not to print a backtrace to stdout.

  • print_func (callable,) – Function to use for returning/printing output.

  • kwargs (dict,) – Key-value pairs where values are array_like for the shape/stats to be printed.

holodeck.utils.quantile_filtered(values, percs, axis, func=<ufunc 'isfinite'>)[source]
holodeck.utils.quantiles(values, percs=None, sigmas=None, weights=None, axis=None, values_sorted=False, filter=None)[source]

Compute weighted percentiles.

NOTE: if values is a masked array, then only unmasked values are used!

Parameters:
  • values ((N,)) – input data

  • percs ((M,) scalar) – Desired quantiles of the data. Within range of [0.0, 1.0].

  • weights ((N,) or None) – Weights for each input data point in values.

  • axis (int or None,) – Axis over which to calculate quantiles.

  • values_sorted (bool) – If True, then input values are assumed to already be sorted. Otherwise they are sorted before calculating quantiles (for efficiency).

Returns:

percs – Array of quantiles of the input data.

Return type:

(M,) float

holodeck.utils.random_power(extr, pdf_index, size=1)[source]

Draw from power-law PDF with the given extrema and index.

FIX/BUG : negative extr values break pdf_index=-1 !!

Parameters:
  • extr (array_like scalar) – The minimum and maximum value of this array are used as extrema.

  • pdf_index (scalar) – The power-law index of the PDF distribution to be drawn from. Any real number is valid, positive or negative. NOTE: the numpy.random.power function uses the power-law index of the CDF, i.e. g+1

  • size (scalar) – The number of points to draw (cast to int).

  • **kwags (dict pairs) – Additional arguments passed to zcode.math_core.minmax with extr.

Returns:

rv – Array of random variables with N=`size` (default, size=1).

Return type:

(N,) scalar

holodeck.utils.rk4_step(func, x0, y0, dx, args=None, check_nan=0, check_nan_max=5)[source]

Perform a single 4th-order Runge-Kutta integration step.

holodeck.utils.stats(vals: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], percs: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, prec: int = 2, weights=None) str[source]

Return a string giving quantiles of the given input data.

Parameters:
  • vals (npt.ArrayLike,) – Input values to get quantiles of.

  • percs (npt.ArrayLike, optional) – Quantiles to calculate.

  • prec (int, optional) – Precision in scientific notation of output.

Returns:

rv – Quantiles of input formatted as a string of scientific notation values.

Return type:

str

Raises:

TypeError – raised if input data is not iterable.:

holodeck.utils.std(vals, weights)[source]

Weighted standard deviation (stdev).

See: https://www.itl.nist.gov/div898/software/dataplot/refman2/ch2/weightsd.pdf

holodeck.utils.trapz(yy: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], xx: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], axis: int = -1, cumsum: bool = True)[source]

Perform a cumulative integration along the given axis.

Parameters:
  • yy (ArrayLike of scalar,) – Input to be integrated.

  • xx (ArrayLike of scalar,) – The sample points corresponding to the yy values. This must either be shaped as * the same number of dimensions as yy, with the same length along the axis dimension, or * 1D with length matching yy[axis]

  • axis (int,) – The axis over which to integrate.

Returns:

ct – Cumulative trapezoid rule integration.

Return type:

ndarray of scalar,

holodeck.utils.trapz_loglog(yy: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], xx: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], bounds: Tuple[float, float] | None = None, axis: int = -1, dlogx: float | None = None, lntol: float = 0.01, cumsum: bool = True) _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes][source]

Calculate integral, given y = dA/dx or y = dA/dlogx w/ trapezoid rule in log-log space.

We are calculating the integral A given sets of values for y and x. To associate yy with dA/dx then dlogx = None [default], otherwise, to associate yy with dA/dlogx then dlogx = True for natural-logarithm, or dlogx = b for a logarithm of base b.

For each interval (x[i+1], x[i]), calculate the integral assuming that y is of the form,

y = a * x^gamma

Parameters:
  • yy (ndarray) –

  • xx ((X,) array_like of scalar,) –

  • bounds ((2,) array_like of scalar,) –

  • axis (int,) –

  • dlogx (scalar or None,) –

  • lntol (scalar,) –

Return type:

integ

Notes

  • When bounds are given that are not identical to input xx values, then interpolation must be performed. This can be done on the resulting cumsum’d values, or on the input integrand values. The cumsum values are not necessarily a power-law (for negative indices), and thus the interpolation is better performed on the input yy values.

  • Interpolating the cumulative-integral works very badly, instead interpolate the x/y values initially to obtain the integral at the appropriate locations.

holodeck.utils._parse_log_norm_pars(vals, size, default=None)[source]

Parse/Sanitize the parameters for a log-normal distribution.

  • () ==> (N,)

  • (2,) ==> (N,) log_normal(vals)

  • (N,) ==> (N,)

BUG: this function should probably be deprecated / removed !

Parameters:

vals (object,) –

Input can be a single value, (2,) array_like, of array_like of size size:
  • scalar : this value is broadcast to an ndarray of size size

  • (2,) array_like : these two arguments are passed to log_normal_base_10 and size samples are drawn

  • (N,) array_like : if N matches size, these values are returned.

Returns:

vals – Returned values.

Return type:

ndarray

holodeck.utils._parse_val_log10_val_pars(val, val_log10, val_units=1.0, name='value', only_one=True)[source]

Given either a parameter value, or the log10 of the value, ensure that both are set.

Parameters:
  • val (array_like or None,) – The parameter value itself in the desired units (specified by val_units).

  • val_log10 (array_like or None,) – The log10 of the parameter value in natural units.

  • val_units (array_like,) – The conversion factor from natural units (used in val_log10) to the desired units (used in val).

  • name (str,) – The name of the variable for use in error messages.

  • only_one (bool,) – Whether one, and only one, of val and val_log10 should be provided (i.e. not None).

Returns:

  • val (array_like,) – The parameter value itself in desired units. e.g. mass in grams, s.t. mass = Msol * 10^{mass_log10}

  • val_log10 (array_like,) – The log10 of the parameter value in natural units. e.g. log10 of mass in solar-masses, s.t. mass = Msol * 10^{mass_log10}

holodeck.utils._integrate_grid_differential_number(edges, dnum, freq=False)[source]

Integrate the differential number-density of binaries over the given grid (edges).

NOTE: the edges provided MUST all be in linear space, mass is converted to log10(M) and frequency is converted to ln(f). NOTE: the density dnum MUST correspond to dn/ [dlog10(M) dq dz dln(f)]

Parameters:
  • edges ((4,) iterable of ArrayLike) –

  • dnum (ndarray) –

  • freq (bool) – Whether or not to also integrate the frequency dimension.

Returns:

number – Number of binaries in each bin of mass, mass-ratio, redshift, frequency. NOTE: if freq=False, then number corresponds to dN/dln(f), the number of binaries per log-interval of frequency.

Return type:

ndarray

holodeck.utils._func_gaussian(xx, aa, mm, ss)[source]
holodeck.utils.fit_gaussian(xx, yy, guess=None)[source]

Fit a Gaussian/Normal distribution with the given initial guess of parameters.

Parameters:
  • xx (array, (N,)) –

  • yy (array, (N,)) –

  • guess (None or (3,) array of float) – Initial parameter values as starting point of fit. The values correspond to: [amplitude, mean, stdev]. If guess is None, then the maximum, mean, and stdev of the given values are used as a starting point.

Returns:

  • popt ((3,) array of float) – Best fit parameters: [amplitude, mean, stdev]

  • pcov ((3, 3) array of float) – Covariance matrix of best fit parameters.

holodeck.utils._func_line(xx, amp, slope)[source]
holodeck.utils.fit_powerlaw(xx, yy, init=[-15.0, -0.6666666666666666])[source]

Fit the given data with a power-law.

Returns:

  • log10_amp

  • plaw

holodeck.utils._func_powerlaw_psd(freqs, fref, amp, index)[source]
holodeck.utils.fit_powerlaw_psd(xx, yy, fref, init=[-15.0, -4.333333333333333])[source]
holodeck.utils.fit_powerlaw_fixed_index(xx, yy, index=-0.6666666666666666, init=[-15.0])[source]
Returns:

  • log10_amp

  • plaw

holodeck.utils._func_turnover_psd(freqs, fref, amp, gamma, fbreak, kappa)[source]
holodeck.utils.fit_turnover_psd(xx, yy, fref, init=[-16, -4.333333333333333, 9.506426344208685e-09, 2.5])[source]
Parameters:
  • xx ((F,)) – Frequencies in units of reference-frequency (e.g. 1/yr)

  • yy ((F,)) – GWB PSD

holodeck.utils.dfdt_from_dadt(dadt, sepa, mtot=None, frst_orb=None)[source]

Convert from hardening rate in separation to hardening rate in frequency.

Parameters:
  • dadt (array_like) – Hardening rate in terms of binary separation.

  • sepa (array_like) – Binary separations.

  • mtot (None or array_like) – Binary total-mass in units of [gram]. Either mtot or frst_orb must be provided.

  • frst_orb (None or array_like) – Binary rest-frame orbital-frequency in units of [1/sec]. Either mtot or frst_orb must be provided.

Returns:

  • dfdt – Hardening rate in terms of rest-frame frequency. [1/sec^2] NOTE: Has the opposite sign as dadt.

  • frst_orb – Orbital frequency, in the rest-frame. [1/sec]

holodeck.utils.mtmr_from_m1m2(m1, m2=None)[source]

Convert from primary and secondary masses into total-mass and mass-ratio.

NOTE: it doesn’t matter if m1 or m2 is the primary or secondary.

Parameters:
  • m1 (array_like,) – Mass. If this is a single value, or a 1D array, it denotes the mass of one component of a binary. It can also be shaped, (N,2) where the two elements are the two component masses.

  • m2 (None or array_like,) – If array_like, it must match the shape of m1, and corresponds to the companion mass.

Returns:

Total mass and mass-ratio. If the input values are floats, this is just shaped (2,).

Return type:

(2,N) ndarray

holodeck.utils.m1m2_from_mtmr(mt: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], mr: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes][source]

Convert from total-mass and mass-ratio to individual masses.

Parameters:
  • mt (array_like) – Total mass of the binary.

  • mr (array_like) – Mass ratio of the binary.

Returns:

Primary and secondary masses respectively. 0-primary (more massive component), 1-secondary (less massive component)

Return type:

(2,N) ndarray

holodeck.utils.frst_from_fobs(fobs, redz)[source]

Calculate rest-frame frequency from observed frequency and redshift.

Parameters:
  • fobs (array_like) – Observer-frame frequencies.

  • redz (array_like) – Redshifts.

Returns:

fobs – Rest-frame frequencies.

Return type:

array_like

holodeck.utils.fobs_from_frst(frst, redz)[source]

Calculate observed frequency from rest-frame frequency and redshift.

Parameters:
  • frst (array_like) – Rest-frame frequencies.

  • redz (array_like) – Redshifts.

Returns:

fobs – Observer-frame frequencies.

Return type:

array_like

holodeck.utils.kepler_freq_from_sepa(mass, sepa)[source]

Calculate binary orbital frequency using Kepler’s law.

Parameters:
  • mass (array_like) – Binary total mass [grams].

  • sepa (array_like) – Binary semi-major axis or separation [cm].

Returns:

freq – Binary orbital frequency [1/s].

Return type:

array_like

holodeck.utils.kepler_sepa_from_freq(mass, freq)[source]

Calculate binary separation using Kepler’s law.

Parameters:
  • mass (array_like) – Binary total mass [grams]

  • freq (array_like) – Binary orbital frequency [1/s].

Returns:

sepa – Binary semi-major axis (i.e. separation) [cm].

Return type:

array_like

holodeck.utils.rad_isco(m1, m2=0.0, factor=3.0)[source]

Inner-most Stable Circular Orbit, radius at which binaries ‘merge’.

ENH: allow single (total) mass argument. ENH: add function to calculate factor as a function of BH spin.

Parameters:
  • m1 (array_like,) – Mass of first (either) component of binary [grams].

  • m2 (array_like,) – Mass of second (other) component of binary [grams].

  • factor (float,) – Factor by which to multiple the Schwarzschild radius to define the ISCO. 3.0 for a non-spinning black-hole.

Returns:

rs – Radius of the inner-most stable circular orbit [cm].

Return type:

array_like,

holodeck.utils.frst_isco(m1, m2=0.0, **kwargs)[source]

Get rest-frame orbital frequency of ISCO orbit.

Parameters:
  • m1 (array_like, units of [gram]) – Total mass, or mass of the primary. Added together with m2 to get total mass.

  • m2 (array_like, units of [gram] or None) – Mass of secondary, or None if m1 is already total mass.

Returns:

fisco

Return type:

array_like, units of [Hz]

holodeck.utils.redz_after(time, redz=None, age=None)[source]

Calculate the redshift after the given amount of time has passed.

Parameters:
  • time (array_like in units of [sec]) – Amount of time to pass.

  • redz (None or array_like,) – Redshift of starting point after which time is added.

  • age (None or array_like, in units of [sec]) – Age of the Universe at the starting point, after which time is added.

Returns:

new_redz – Redshift of the Universe after the given amount of time.

Return type:

array_like

holodeck.utils.schwarzschild_radius(mass)[source]

Return the Schwarschild radius [cm] for the given mass [grams].

Parameters:

m1 (array_like) – Mass [grams]

Returns:

rs – Schwzrschild radius for this mass.

Return type:

array_like,

holodeck.utils.velocity_orbital(mt, mr, per=None, sepa=None)[source]
holodeck.utils._get_sepa_freq(mt, sepa, freq)[source]
holodeck.utils.lambda_factor_dlnf(frst, dfdt, redz, dcom=None)[source]

Account for the universe’s differential space-time volume for a given hardening rate.

For each binary, calculate the factor:

\[\Lambda \equiv (dVc/dz) * (dz/dt) * [dt/dln(f)]\]
, which has units of [Mpc^3]. When multiplied by a number-density [Mpc^-3], it gives the number of binaries in the Universe per log-frequency interval. This value must still be multiplied by \(\Delta \ln(f)\) to get a number of binaries across a frequency in.

Parameters:
  • frst (ArrayLike) – Binary frequency (typically rest-frame orbital frequency; but it just needs to match what’s provided in the dfdt term. Units of [1/sec].

  • dfdt (ArrayLike) – Binary hardening rate in terms of frequency (typically rest-frame orbital frequency, but it just needs to match what’s provided in frst). Units of [1/sec^2].

  • redz (ArrayLike) – Binary redshift. Dimensionless.

  • dcom (ArrayLike) – Comoving distance to binaries (for the corresponding redshift, redz). Units of [cm]. If not provided, calculated from given redz.

Returns:

lambda_fact – The differential comoving volume of the universe per log interval of binary frequency.

Return type:

ArrayLike

holodeck.utils.angs_from_sepa(sepa, dcom, redz)[source]

Calculate angular separation

Parameters:
  • sepa (ArrayLike) – Binary separation, in cm

  • dcom (ArrayLike) – Binary comoving distance, in cm

  • redz (ArrayLike) – Binary redshift

Returns:

angs – Angular separation

Return type:

ArrayLike

holodeck.utils.eddington_accretion(mass, eps=0.1)[source]

Eddington Accretion rate, \(\dot{M}_{Edd} = L_{Edd}/\epsilon c^2\).

Parameters:
  • mass (array_like of scalar) – BH Mass.

  • eps (array_like of scalar) – Efficiency parameter.

Returns:

mdot – Eddington accretion rate.

Return type:

array_like of scalar

holodeck.utils.eddington_luminosity(mass)[source]
holodeck.utils.chirp_mass(m1, m2=None)[source]

Calculate the chirp-mass of a binary.

Parameters:
  • m1 (array_like,) – Mass [grams] This can either be the mass of the primary component, if scalar or 1D array_like, or the mass of both components, if 2D array_like, shaped (N, 2).

  • m2 (None or array_like,) – Mass [grams] of the other component of the binary. If given, the shape must be broadcastable against m1.

Returns:

mc – Chirp mass [grams] of the binary.

Return type:

array_like,

holodeck.utils.chirp_mass_mtmr(mt, mr)[source]

Calculate the chirp-mass of a binary.

Parameters:
  • mt (array_like,) – Total mass [grams]. This is M = m1+m2.

  • mr (array_like,) – Mass ratio. q = m2/m1 <= 1. This is defined as the secondary (smaller) divided by the primary (larger) mass.

Returns:

mc – Chirp mass [grams] of the binary.

Return type:

array_like,

holodeck.utils.gw_char_strain_nyquist(dur_obs, hs, frst_orb, redz, dfdt_rst)[source]

GW Characteristic Strain assuming frequency bins are Nyquist sampled.

Nyquist assumption: the bin-width is equal to 1/T, for T the total observing duration.

See, e.g., [Sesana2004], Eq.35, and surrounding text. NOTE: make sure this is the correct definition of “characteristic” strain for your application!

# ! THIS FUNCTION MAY NOT BE CORRECT [LZK:2022-08-25] ! #

Parameters:
  • dur_obs (array_like,) – Duration of observations, in the observer frame, in units of [sec]. Typically this is a single float value.

  • hs (array_like,) – Strain amplitude of the source. Dimensionless.

  • frst_orb (array_like,) – Observer-frame orbital frequency, units of [1/sec].

  • redz (array_like,) – Redshift of the binary. Dimensionless.

  • dfdt_rst (array_like,) – Rate of orbital-frequency evolution of the binary, in the rest-frame. Units of [1/sec^2].

Returns:

hc – Characteristic strain of the binary.

Return type:

array_like,

holodeck.utils.gw_dedt(m1, m2, sepa, eccen)[source]

GW Eccentricity Evolution rate (de/dt) due to GW emission.

NOTE: returned value is negative.

See [Peters1964], Eq. 5.8

Parameters:
  • m1 (array_like,) – Mass of one component of the binary [grams].

  • m2 (array_like,) – Mass of other component of the binary [grams].

  • sepa (array_like,) – Binary semi-major axis (i.e. separation) [cm].

  • eccen (array_like,) – Binary orbital eccentricity.

Returns:

dedt – Rate of eccentricity change of the binary. NOTE: returned value is negative or zero.

Return type:

array_like

holodeck.utils.gw_dade(sepa, eccen)[source]

Rate of semi-major axis evolution versus eccentricity, due to GW emission (da/de).

NOTE: returned value is positive (e and a go in same direction). See [Peters1964], Eq. 5.7

Parameters:
  • sepa (array_like) – Binary semi-major axis (separation) [grams].

  • eccen (array_like) – Binary eccentricity [grams].

Returns:

dade – Rate of change of semi-major axis versus eccentricity [cm]. NOTE: returned value is positive.

Return type:

array_like

holodeck.utils.gw_freq_dist_func(nn, ee=0.0, recursive=True)[source]

GW frequency distribution function.

See [EN2007] Eq. 2.4; this function gives g(n,e).

NOTE: recursive relation fails for zero eccentricities! TODO: could choose to use non-recursive when zero eccentricities are found?

TODO: replace ee variable with eccen

Parameters:
  • nn (int,) – Number of frequency harmonic to calculate.

  • ee (array_like,) – Binary eccentricity.

Returns:

gg – GW Frequency distribution function g(n,e).

Return type:

array_like,

holodeck.utils.gw_hardening_rate_dadt(m1, m2, sepa, eccen=None)[source]

GW Hardening rate in separation (da/dt).

NOTE: returned value is negative.

See [Peters1964], Eq. 5.6

Parameters:
  • m1 (array_like,) – Mass of one component of the binary [grams].

  • m2 (array_like,) – Mass of other component of the binary [grams].

  • sepa (array_like,) – Binary semi-major axis (i.e. separation) [cm].

  • eccen (None or array_like,) – Binary orbital eccentricity. Treated as zero if None.

Returns:

dadt – Binary hardening rate [cm/s] due to GW emission.

Return type:

array_like,

holodeck.utils.gw_hardening_rate_dfdt(m1, m2, frst_orb, eccen=None)[source]

GW Hardening rate in frequency (df/dt).

Parameters:
  • m1 (array_like) – Mass of one component of each binary [grams].

  • m2 (array_like) – Mass of other component of each binary [grams].

  • freq_orb (array_like) – Rest frame orbital frequency of each binary [1/s].

  • eccen (array_like, optional) – Eccentricity of each binary.

Returns:

dfdt – Hardening rate in terms of frequency for each binary [1/s^2].

Return type:

array_like,

holodeck.utils.gw_hardening_timescale_freq(mchirp, frst)[source]

GW Hardening timescale in terms of frequency (not separation).

tau = f_r / (df_r / dt), e.g. [EN2007] Eq.2.9

Parameters:
  • mchirp (array_like,) – Chirp mass in [grams]

  • frst (array_like,) – Rest-frame orbital frequency [1/s].

Returns:

tau – GW hardening timescale defined w.r.t. orbital frequency [sec].

Return type:

array_like,

holodeck.utils.gw_lum_circ(mchirp, freq_orb_rest)[source]

Calculate the GW luminosity of a circular binary.

[EN2007] Eq. 2.2

Parameters:
  • mchirp (array_like,) – Binary chirp mass [grams].

  • freq_orb_rest (array_like,) – Rest-frame binary orbital frequency [1/s].

Returns:

lgw_circ – GW Luminosity [erg/s].

Return type:

array_like,

holodeck.utils.gw_strain_source(mchirp, dcom, freq_rest_orb)[source]

GW Strain from a single source in a circular orbit.

For reference, see: * [Sesana2004] Eq.36 : they use f_r to denote rest-frame GW-frequency. * [Enoki2004] Eq.5.

Parameters:
  • mchirp (array_like,) – Binary chirp mass [grams].

  • dcom (array_like,) – Comoving distance to source [cm].

  • freq_orb_rest (array_like,) – Rest-frame binary orbital frequency [1/s].

Returns:

hs – GW Strain (not characteristic strain).

Return type:

array_like,

holodeck.utils.sep_to_merge_in_time(m1, m2, time)[source]

The initial separation required to merge within the given time.

See: [Peters1964]

Parameters:
  • m1 (array_like,) – Mass of one component of the binary [grams].

  • m2 (array_like,) – Mass of other component of the binary [grams].

  • time (array_like,) – The duration of time of interest [sec].

Returns:

Initial binary separation [cm].

Return type:

array_like

holodeck.utils.time_to_merge_at_sep(m1, m2, sepa)[source]

The time required to merge starting from the given initial separation.

See: [Peters1964].

Parameters:
  • m1 (array_like,) – Mass of one component of the binary [grams].

  • m2 (array_like,) – Mass of other component of the binary [grams].

  • sepa (array_like,) – Binary semi-major axis (i.e. separation) [cm].

Returns:

Duration of time for binary to coalesce [sec].

Return type:

array_like

holodeck.utils.gamma_psd_to_strain(gamma_psd)[source]
holodeck.utils.gamma_strain_to_psd(gamma_strain)[source]
holodeck.utils.gamma_strain_to_omega(gamma_strain)[source]
holodeck.utils.char_strain_to_psd(freqs, hc)[source]
Parameters:
  • freqs (array_like) – Frequencies of interest in [1/sec]. Note: these should NOT be in units of reference frequency, but in units of [Hz] = [1/sec].

  • hc (array_like) – Characteristic strain.

Returns:

psd – Power spectral density of gravitational waves.

Return type:

array_like

holodeck.utils.psd_to_char_strain(freqs, psd)[source]
holodeck.utils.char_strain_to_rho(freqs, hc, tspan)[source]
holodeck.utils.rho_to_char_strain(freqs, rho, tspan)[source]
holodeck.utils.char_strain_to_strain_amp(hc, fc, df)[source]

Calculate the strain amplitude of single sources given their characteristic strains.

Parameters:
  • hc (array_like) – Characteristic strain of the single sources.

  • fc (array_like) – Observed orbital frequency bin centers.

  • df (array_like) – Observed orbital frequency bin widths.

Returns:

hs – Strain amplitude of the single sources.

Return type:

(F,R,L)

holodeck.utils._gw_ecc_func(eccen)[source]

GW Hardening rate eccentricitiy dependence F(e).

See [Peters1964] Eq. 5.6, or [EN2007] Eq. 2.3

Parameters:

eccen (array_like,) – Binary orbital eccentricity [].

Returns:

fe – Eccentricity-dependence term of GW emission [].

Return type:

array_like

holodeck.utils._array_args(*args)[source]
holodeck.utils.scatter_redistribute(cents, dist, dens, axis=0)[source]
holodeck.utils.nyquist_freqs(dur, cad)[source]

DEPRECATED. Use holodeck.utils.pta_freqs instead.