pycbc package

Subpackages

Submodules

pycbc.bin_utils module

class pycbc.bin_utils.BinnedArray(bins, array=None, dtype='double')[source]

Bases: object

A convenience wrapper, using the NDBins class to provide access to the elements of an array object. Technical reasons preclude providing a subclass of the array object, so the array data is made available as the “array” attribute of this class.

Examples:

Note that even for 1 dimensional arrays the index must be a tuple.

>>> x = BinnedArray(NDBins((LinearBins(0, 10, 5),)))
>>> x.array
array([ 0.,  0.,  0.,  0.,  0.])
>>> x[0,] += 1
>>> x[0.5,] += 1
>>> x.array
array([ 2.,  0.,  0.,  0.,  0.])
>>> x.argmax()
(1.0,)

Note the relationship between the binning limits, the bin centres, and the co-ordinates of the BinnedArray

>>> x = BinnedArray(NDBins((LinearBins(-0.5, 1.5, 2),     LinearBins(-0.5, 1.5, 2))))
>>> x.bins.centres()
(array([ 0.,  1.]), array([ 0.,  1.]))
>>> x[0, 0] = 0
>>> x[0, 1] = 1
>>> x[1, 0] = 2
>>> x[1, 1] = 4
>>> x.array
array([[ 0.,  1.],
       [ 2.,  4.]])
>>> x[0, 0]
0.0
>>> x[0, 1]
1.0
>>> x[1, 0]
2.0
>>> x[1, 1]
4.0
>>> x.argmin()
(0.0, 0.0)
>>> x.argmax()
(1.0, 1.0)
argmax()[source]

Return the co-ordinates of the bin centre containing the maximum value. Same as numpy.argmax(), converting the indexes to bin co-ordinates.

argmin()[source]

Return the co-ordinates of the bin centre containing the minimum value. Same as numpy.argmin(), converting the indexes to bin co-ordinates.

centres()[source]

Return a tuple of arrays containing the bin centres for each dimension.

copy()[source]

Return a copy of the BinnedArray. The .bins attribute is shared with the original.

logregularize(epsilon=5e-324)[source]

Find bins <= 0, and set them to epsilon, This has the effect of allowing the logarithm of the array to be evaluated without error.

class pycbc.bin_utils.BinnedRatios(bins, dtype='double')[source]

Bases: object

Like BinnedArray, but provides a numerator array and a denominator array. The incnumerator() method increments a bin in the numerator by the given weight, and the incdenominator() method increments a bin in the denominator by the given weight. There are no methods provided for setting or decrementing either, but the they are accessible as the numerator and denominator attributes, which are both BinnedArray objects.

bins()[source]
centres()[source]

Return a tuple of arrays containing the bin centres for each dimension.

incdenominator(coords, weight=1)[source]

Add weight to the denominator bin at coords.

incnumerator(coords, weight=1)[source]

Add weight to the numerator bin at coords.

logregularize(epsilon=5e-324)[source]

Find bins in the denominator that are 0, and set them to 1, while setting the corresponding bin in the numerator to float epsilon. This has the effect of allowing the logarithm of the ratio array to be evaluated without error.

ratio()[source]

Compute and return the array of ratios.

regularize()[source]

Find bins in the denominator that are 0, and set them to 1. Presumably the corresponding bin in the numerator is also 0, so this has the effect of allowing the ratio array to be evaluated without error, returning zeros in those bins that have had no weight added to them.

class pycbc.bin_utils.Bins(minv, maxv, n)[source]

Bases: object

Parent class for 1-dimensional binnings.

Not intended to be used directly, but to be subclassed for use in real bins classes.

centres()[source]

Return an array containing the locations of the bin centres.

lower()[source]

Return an array containing the locations of the lower boundaries of the bins.

upper()[source]

Return an array containing the locations of the upper boundaries of the bins.

class pycbc.bin_utils.IrregularBins(boundaries)[source]

Bases: Bins

Bins with arbitrary, irregular spacing. We only require strict monotonicity of the bin boundaries. N boundaries define N-1 bins.

Example:

>>> x = IrregularBins([0.0, 11.0, 15.0, numpy.inf])
>>> len(x)
3
>>> x[1]
0
>>> x[1.5]
0
>>> x[13]
1
>>> x[25]
2
>>> x[4:17]
slice(0, 3, None)
>>> IrregularBins([0.0, 15.0, 11.0])
Traceback (most recent call last):
    ...
ValueError: non-monotonic boundaries provided
>>> y = IrregularBins([0.0, 11.0, 15.0, numpy.inf])
>>> x == y
True
centres()[source]

Return an array containing the locations of the bin centres.

lower()[source]

Return an array containing the locations of the lower boundaries of the bins.

upper()[source]

Return an array containing the locations of the upper boundaries of the bins.

class pycbc.bin_utils.LinearBins(minv, maxv, n)[source]

Bases: Bins

Linearly-spaced bins. There are n bins of equal size, the first bin starts on the lower bound and the last bin ends on the upper bound inclusively.

Example:

>>> x = LinearBins(1.0, 25.0, 3)
>>> x.lower()
array([  1.,   9.,  17.])
>>> x.upper()
array([  9.,  17.,  25.])
>>> x.centres()
array([  5.,  13.,  21.])
>>> x[1]
0
>>> x[1.5]
0
>>> x[10]
1
>>> x[25]
2
>>> x[0:27]
Traceback (most recent call last):
    ...
IndexError: 0
>>> x[1:25]
slice(0, 3, None)
>>> x[:25]
slice(0, 3, None)
>>> x[10:16.9]
slice(1, 2, None)
>>> x[10:17]
slice(1, 3, None)
>>> x[10:]
slice(1, 3, None)
centres()[source]

Return an array containing the locations of the bin centres.

lower()[source]

Return an array containing the locations of the lower boundaries of the bins.

upper()[source]

Return an array containing the locations of the upper boundaries of the bins.

class pycbc.bin_utils.LinearPlusOverflowBins(minv, maxv, n)[source]

Bases: Bins

Linearly-spaced bins with overflow at the edges.

There are n-2 bins of equal size. The bin 1 starts on the lower bound and bin n-2 ends on the upper bound. Bins 0 and n-1 are overflow going from -infinity to the lower bound and from the upper bound to +infinity respectively. Must have n >= 3.

Example:

>>> x = LinearPlusOverflowBins(1.0, 25.0, 5)
>>> x.centres()
array([-inf,   5.,  13.,  21.,  inf])
>>> x.lower()
array([-inf,   1.,   9.,  17.,  25.])
>>> x.upper()
array([  1.,   9.,  17.,  25.,  inf])
>>> x[float("-inf")]
0
>>> x[0]
0
>>> x[1]
1
>>> x[10]
2
>>> x[24.99999999]
3
>>> x[25]
4
>>> x[100]
4
>>> x[float("+inf")]
4
>>> x[float("-inf"):9]
slice(0, 3, None)
>>> x[9:float("+inf")]
slice(2, 5, None)
centres()[source]

Return an array containing the locations of the bin centres.

lower()[source]

Return an array containing the locations of the lower boundaries of the bins.

upper()[source]

Return an array containing the locations of the upper boundaries of the bins.

class pycbc.bin_utils.LogarithmicBins(minv, maxv, n)[source]

Bases: Bins

Logarithmically-spaced bins.

There are n bins, each of whose upper and lower bounds differ by the same factor. The first bin starts on the lower bound, and the last bin ends on the upper bound inclusively.

Example:

>>> x = LogarithmicBins(1.0, 25.0, 3)
>>> x[1]
0
>>> x[5]
1
>>> x[25]
2
centres()[source]

Return an array containing the locations of the bin centres.

lower()[source]

Return an array containing the locations of the lower boundaries of the bins.

upper()[source]

Return an array containing the locations of the upper boundaries of the bins.

class pycbc.bin_utils.LogarithmicPlusOverflowBins(minv, maxv, n)[source]

Bases: Bins

Logarithmically-spaced bins plus one bin at each end that goes to zero and positive infinity respectively. There are n-2 bins each of whose upper and lower bounds differ by the same factor. Bin 1 starts on the lower bound, and bin n-2 ends on the upper bound inclusively. Bins 0 and n-1 are overflow bins extending from 0 to the lower bound and from the upper bound to +infinity respectively. Must have n >= 3.

Example:

>>> x = LogarithmicPlusOverflowBins(1.0, 25.0, 5)
>>> x[0]
0
>>> x[1]
1
>>> x[5]
2
>>> x[24.999]
3
>>> x[25]
4
>>> x[100]
4
>>> x.lower()
array([ 0.   ,  1.        ,  2.92401774,  8.54987973, 25.      ])
>>> x.upper()
array([ 1.   ,  2.92401774,  8.54987973, 25.        ,       inf])
>>> x.centres()
array([ 0.   ,  1.70997595,  5.        , 14.62008869,       inf])
centres()[source]

Return an array containing the locations of the bin centres.

lower()[source]

Return an array containing the locations of the lower boundaries of the bins.

upper()[source]

Return an array containing the locations of the upper boundaries of the bins.

class pycbc.bin_utils.NDBins(*args)[source]

Bases: tuple

Multi-dimensional co-ordinate binning. An instance of this object is used to convert a tuple of co-ordinates into a tuple of bin indices. This can be used to allow the contents of an array object to be accessed with real-valued coordinates.

NDBins is a subclass of the tuple builtin, and is initialized with an iterable of instances of subclasses of Bins. Each Bins subclass instance describes the binning to apply in the corresponding co-ordinate direction, and the number of them sets the dimensions of the binning.

Example:

>>> x = NDBins((LinearBins(1, 25, 3), LogarithmicBins(1, 25, 3)))
>>> x[1, 1]
(0, 0)
>>> x[1.5, 1]
(0, 0)
>>> x[10, 1]
(1, 0)
>>> x[1, 5]
(0, 1)
>>> x[1, 1:5]
(0, slice(0, 2, None))
>>> x.centres()
(array([ 5., 13., 21.]), array([ 1.70997595,  5.        , 14.62008869]))

Note that the co-ordinates to be converted must be a tuple, even if it is only a 1-dimensional co-ordinate.

centres()[source]

Return a tuple of arrays, where each array contains the locations of the bin centres for the corresponding dimension.

lower()[source]

Return a tuple of arrays, where each array contains the locations of the lower boundaries of the bins in the corresponding dimension.

upper()[source]

Return a tuple of arrays, where each array contains the locations of the upper boundaries of the bins in the corresponding dimension.

pycbc.boundaries module

This modules provides utilities for manipulating parameter boundaries. Namely, classes are offered that will map values to a specified domain using either cyclic boundaries or reflected boundaries.

class pycbc.boundaries.Bounds(min_bound=-inf, max_bound=inf, btype_min='closed', btype_max='open', cyclic=False)[source]

Bases: object

Creates and stores bounds using the given values.

The type of boundaries used can be set using the btype_(min|max) parameters. These arguments set what kind of boundary is used at the minimum and maximum bounds. Specifically, if btype_min (btype_max) is set to:

  • “open”: the minimum (maximum) boundary will be an instance of OpenBound. This means that a value must be > (<) the bound for it to be considered within the bounds.

  • “closed”: the minimum (maximum) boundary will be an instance of ClosedBound. This means that a value must be >= (<=) the bound for it to be considered within the bounds.

  • “reflected”: the minimum (maximum) boundary will be an isntance of ReflectedBound. This means that a value will be reflected to the right (left) if apply_conditions is used on the value. For more details see apply_conditions.

If the cyclic keyword is set to True, then apply_conditions will cause values to be wrapped around to the minimum (maximum) bound if the value is > (<=) the maximum (minimum) bound. For more details see apply_conditions.

Values can be checked whether or not they occur within the bounds using in; e.g., 6 in bounds. This is done without applying any boundary conditions. To apply conditions, then check whether the value is in bounds, use the contains_conditioned method.

The default is for the minimum bound to be “closed” and the maximum bound to be “open”, i.e., a right-open interval.

Parameters:
  • min_bound ({-numpy.inf, float}) – The value of the lower bound. Default is -inf.

  • max_bound ({numpy.inf, float}) – The value of the upper bound. Default is inf.

  • btype_min ({'open', string}) – The type of the lower bound; options are “closed”, “open”, or “reflected”. Default is “closed”.

  • btype_min – The type of the lower bound; options are “closed”, “open”, or “reflected”. Default is “open”.

  • cyclic ({False, bool}) – Whether or not to make the bounds cyclic; default is False. If True, both the minimum and maximum bounds must be finite.

Examples

Create a right-open interval between -1 and 1 and test whether various values are within them: >>> bounds = Bounds(-1., 1.) >>> -1 in bounds True >>> 0 in bounds True >>> 1 in bounds False

Create an open interval between -1 and 1 and test the same values: >>> bounds = Bounds(-1, 1, btype_min=”open”) >>> -1 in bounds False >>> 0 in bounds True >>> 1 in bounds False

Create cyclic bounds between -1 and 1 and plot the effect of conditioning on points between -10 and 10: >>> bounds = Bounds(-1, 1, cyclic=True) >>> x = numpy.linspace(-10, 10, num=1000) >>> conditioned_x = bounds.apply_conditions(x) >>> fig = pyplot.figure() >>> ax = fig.add_subplot(111) >>> ax.plot(x, x, c=’b’, lw=2, label=’input’) >>> ax.plot(conditioned_x, x, c=’r’, lw=1) >>> ax.vlines([-1., 1.], x.min(), x.max(), color=’k’, linestyle=’–‘) >>> ax.set_title(‘cyclic bounds between x=-1,1’) >>> fig.show()

Create a reflected bound at -1 and plot the effect of conditioning: >>> bounds = Bounds(-1, 1, btype_min=’reflected’) >>> x = numpy.linspace(-10, 10, num=1000) >>> conditioned_x = bounds.apply_conditions(x) >>> fig = pyplot.figure() >>> ax = fig.add_subplot(111) >>> ax.plot(x, x, c=’b’, lw=2, label=’input’) >>> ax.plot(conditioned_x, x, c=’r’, lw=1) >>> ax.vlines([-1., 1.], x.min(), x.max(), color=’k’, linestyle=’–‘) >>> ax.set_title(‘reflected right at x=-1’) >>> fig.show()

Create a reflected bound at 1 and plot the effect of conditioning: >>> bounds = Bounds(-1, 1, btype_max=’reflected’) >>> x = numpy.linspace(-10, 10, num=1000) >>> conditioned_x = bounds.apply_conditions(x) >>> fig = pyplot.figure() >>> ax = fig.add_subplot(111) >>> ax.plot(x, x, c=’b’, lw=2, label=’input’) >>> ax.plot(conditioned_x, x, c=’r’, lw=1) >>> ax.vlines([-1., 1.], x.min(), x.max(), color=’k’, linestyle=’–‘) >>> ax.set_title(‘reflected left at x=1’) >>> fig.show()

Create reflected bounds at -1 and 1 and plot the effect of conditioning: >>> bounds = Bounds(-1, 1, btype_min=’reflected’, btype_max=’reflected’) >>> x = numpy.linspace(-10, 10, num=1000) >>> conditioned_x = bounds.apply_conditions(x) >>> fig = pyplot.figure() >>> ax = fig.add_subplot(111) >>> ax.plot(x, x, c=’b’, lw=2, label=’input’) >>> ax.plot(conditioned_x, x, c=’r’, lw=1) >>> ax.vlines([-1., 1.], x.min(), x.max(), color=’k’, linestyle=’–‘) >>> ax.set_title(‘reflected betewen x=-1,1’) >>> fig.show()

apply_conditions(value)[source]

Applies any boundary conditions to the given value.

The value is manipulated according based on the following conditions:

  • If self.cyclic is True then value is wrapped around to the minimum (maximum) bound if value is >= self.max (< self.min) bound. For example, if the minimum and maximum bounds are 0, 2*pi and value = 5*pi, then the returned value will be pi.

  • If self.min is a reflected boundary then value will be reflected to the right if it is < self.min. For example, if self.min = 10 and value = 3, then the returned value will be 17.

  • If self.max is a reflected boundary then value will be reflected to the left if it is > self.max. For example, if self.max = 20 and value = 27, then the returned value will be 13.

  • If self.min and self.max are both reflected boundaries, then value will be reflected between the two boundaries until it falls within the bounds. The first reflection occurs off of the maximum boundary. For example, if self.min = 10, self.max = 20, and value = 42, the returned value will be 18 ( the first reflection yields -2, the second 22, and the last 18).

  • If neither bounds are reflected and cyclic is False, then the value is just returned as-is.

Parameters:

value (float) – The value to apply the conditions to.

Returns:

The value after the conditions are applied; see above for details.

Return type:

float

contains_conditioned(value)[source]

Runs apply_conditions on the given value before testing whether it is in bounds. Note that if cyclic is True, or both bounds are reflected, than this will always return True.

Parameters:

value (float) – The value to test.

Returns:

Whether or not the value is within the bounds after the boundary conditions are applied.

Return type:

bool

property cyclic

Whether the bounds are cyclic or not.

Type:

bool

property max

The maximum bound

Type:

_bounds instance

property min

The minimum bound

Type:

_bounds instance

class pycbc.boundaries.ClosedBound(x=0, /)[source]

Bases: _Bound

Sets larger and smaller functions to be >= and <=, respectively.

larger(other)[source]

A function to determine whether or not other is larger than the bound. This raises a NotImplementedError; classes that inherit from this must define it.

name = 'closed'
smaller(other)[source]

A function to determine whether or not other is smaller than the bound. This raises a NotImplementedError; classes that inherit from this must define it.

class pycbc.boundaries.OpenBound(x=0, /)[source]

Bases: _Bound

Sets larger and smaller functions to be > and <, respectively.

larger(other)[source]

Returns True if other is >, False otherwise

name = 'open'
smaller(other)[source]

Returns True if other is <, False otherwise.

class pycbc.boundaries.ReflectedBound(x=0, /)[source]

Bases: ClosedBound

Inherits from ClosedBound, adding reflection functions.

name = 'reflected'
reflect(value)[source]
reflect_left(value)[source]

Only reflects the value if is > self.

reflect_right(value)[source]

Only reflects the value if is < self.

pycbc.boundaries.apply_cyclic(value, bounds)[source]

Given a value, applies cyclic boundary conditions between the minimum and maximum bounds.

Parameters:
  • value (float) – The value to apply the cyclic conditions to.

  • bounds (Bounds instance) – Boundaries to use for applying cyclic conditions.

Returns:

The value after the cyclic bounds are applied.

Return type:

float

pycbc.boundaries.reflect_well(value, bounds)[source]

Given some boundaries, reflects the value until it falls within both boundaries. This is done iteratively, reflecting left off of the boundaries.max, then right off of the boundaries.min, etc.

Parameters:
  • value (float) – The value to apply the reflected boundaries to.

  • bounds (Bounds instance) – Boundaries to reflect between. Both bounds.min and bounds.max must be instances of ReflectedBound, otherwise an AttributeError is raised.

Returns:

The value after being reflected between the two bounds.

Return type:

float

pycbc.conversions module

This module provides a library of functions that calculate waveform parameters from other parameters. All exposed functions in this module’s namespace return one parameter given a set of inputs.

pycbc.conversions.chi_a(mass1, mass2, spin1z, spin2z)[source]

Returns the aligned mass-weighted spin difference from mass1, mass2, spin1z, and spin2z.

pycbc.conversions.chi_eff(mass1, mass2, spin1z, spin2z)[source]

Returns the effective spin from mass1, mass2, spin1z, and spin2z.

pycbc.conversions.chi_eff_from_spherical(mass1, mass2, spin1_a, spin1_polar, spin2_a, spin2_polar)[source]

Returns the effective spin using spins in spherical coordinates.

pycbc.conversions.chi_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y)[source]

Returns the effective precession spin from mass1, mass2, spin1x, spin1y, spin2x, and spin2y.

pycbc.conversions.chi_p_from_spherical(mass1, mass2, spin1_a, spin1_azimuthal, spin1_polar, spin2_a, spin2_azimuthal, spin2_polar)[source]

Returns the effective precession spin using spins in spherical coordinates.

pycbc.conversions.chi_p_from_xi1_xi2(xi1, xi2)[source]

Returns effective precession spin from xi1 and xi2.

pycbc.conversions.chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)[source]

Returns the in-plane spin from mass1, mass2, and xi2 for the secondary mass.

pycbc.conversions.chi_perp_from_spinx_spiny(spinx, spiny)[source]

Returns the in-plane spin from the x/y components of the spin.

pycbc.conversions.chirp_distance(dist, mchirp, ref_mass=1.4)[source]

Returns the chirp distance given the luminosity distance and chirp mass.

pycbc.conversions.det_tc(detector_name, ra, dec, tc, ref_frame='geocentric', relative=False)[source]

Returns the coalescence time of a signal in the given detector.

Parameters:
  • detector_name (string) – The name of the detector, e.g., ‘H1’.

  • ra (float) – The right ascension of the signal, in radians.

  • dec (float) – The declination of the signal, in radians.

  • tc (float) – The GPS time of the coalescence of the signal in the ref_frame.

  • ref_frame ({'geocentric', string}) – The reference frame that the given coalescence time is defined in. May specify ‘geocentric’, or a detector name; default is ‘geocentric’.

Returns:

The GPS time of the coalescence in detector detector_name.

Return type:

float

pycbc.conversions.dquadmon_from_lambda(lambdav)[source]

Return the quadrupole moment of a neutron star given its lambda

We use the relations defined here. https://arxiv.org/pdf/1302.4499.pdf. Note that the convention we use is that:

\[\mathrm{dquadmon} = \bar{Q} - 1.\]

Where \(\bar{Q}\) (dimensionless) is the reduced quadrupole moment.

pycbc.conversions.eta_from_mass1_mass2(mass1, mass2)[source]

Returns the symmetric mass ratio from mass1 and mass2.

pycbc.conversions.eta_from_q(q)[source]

Returns the symmetric mass ratio from the given mass ratio.

This is given by:

\[\eta = \frac{q}{(1+q)^2}.\]

Note that the mass ratio may be either < 1 or > 1.

pycbc.conversions.eta_from_tau0_tau3(tau0, tau3, f_lower)[source]

Returns symmetric mass ratio from \(\tau_0, \tau_3\).

pycbc.conversions.final_mass_from_f0_tau(f0, tau, l=2, m=2)[source]

Returns the final mass (in solar masses) based on the given frequency and damping time.

Note

Currently, only (l,m) = (2,2), (3,3), (4,4), (2,1) are supported. Any other indices will raise a KeyError.

Parameters:
  • f0 (float or array) – Frequency of the QNM (in Hz).

  • tau (float or array) – Damping time of the QNM (in seconds).

  • l (int, optional) – l-index of the harmonic. Default is 2.

  • m (int, optional) – m-index of the harmonic. Default is 2.

Returns:

The mass of the final black hole. If the combination of frequency and damping times give an unphysical result, numpy.nan will be returned.

Return type:

float or array

pycbc.conversions.final_mass_from_initial(mass1, mass2, spin1x=0.0, spin1y=0.0, spin1z=0.0, spin2x=0.0, spin2y=0.0, spin2z=0.0, approximant='SEOBNRv4PHM', f_ref=-1)[source]

Estimates the final mass from the given initial parameters.

This uses the fits used by either the NRSur7dq4 or EOBNR models for converting from initial parameters to final, depending on the approximant argument.

Parameters:
  • mass1 (float) – The mass of one of the components, in solar masses.

  • mass2 (float) – The mass of the other component, in solar masses.

  • spin1x (float, optional) – The dimensionless x-component of the spin of mass1. Default is 0.

  • spin1y (float, optional) – The dimensionless y-component of the spin of mass1. Default is 0.

  • spin1z (float, optional) – The dimensionless z-component of the spin of mass1. Default is 0.

  • spin2x (float, optional) – The dimensionless x-component of the spin of mass2. Default is 0.

  • spin2y (float, optional) – The dimensionless y-component of the spin of mass2. Default is 0.

  • spin2z (float, optional) – The dimensionless z-component of the spin of mass2. Default is 0.

  • approximant (str, optional) – The waveform approximant to use for the fit function. If “NRSur7dq4”, the NRSur7dq4Remnant fit in lalsimulation will be used. If “SEOBNRv4”, the XLALSimIMREOBFinalMassSpin function in lalsimulation will be used. Otherwise, XLALSimIMREOBFinalMassSpinPrec from lalsimulation will be used, with the approximant name passed as the approximant in that function (“SEOBNRv4PHM” will work with this function). Default is “SEOBNRv4PHM”.

  • f_ref (float, optional) – The reference frequency for the spins. Only used by the NRSur7dq4 fit. Default (-1) will use the default reference frequency for the approximant.

Returns:

The final mass, in solar masses.

Return type:

float

pycbc.conversions.final_spin_from_f0_tau(f0, tau, l=2, m=2)[source]

Returns the final spin based on the given frequency and damping time.

Note

Currently, only (l,m) = (2,2), (3,3), (4,4), (2,1) are supported. Any other indices will raise a KeyError.

Parameters:
  • f0 (float or array) – Frequency of the QNM (in Hz).

  • tau (float or array) – Damping time of the QNM (in seconds).

  • l (int, optional) – l-index of the harmonic. Default is 2.

  • m (int, optional) – m-index of the harmonic. Default is 2.

Returns:

The spin of the final black hole. If the combination of frequency and damping times give an unphysical result, numpy.nan will be returned.

Return type:

float or array

pycbc.conversions.final_spin_from_initial(mass1, mass2, spin1x=0.0, spin1y=0.0, spin1z=0.0, spin2x=0.0, spin2y=0.0, spin2z=0.0, approximant='SEOBNRv4PHM', f_ref=-1)[source]

Estimates the final spin from the given initial parameters.

This uses the fits used by either the NRSur7dq4 or EOBNR models for converting from initial parameters to final, depending on the approximant argument.

Parameters:
  • mass1 (float) – The mass of one of the components, in solar masses.

  • mass2 (float) – The mass of the other component, in solar masses.

  • spin1x (float, optional) – The dimensionless x-component of the spin of mass1. Default is 0.

  • spin1y (float, optional) – The dimensionless y-component of the spin of mass1. Default is 0.

  • spin1z (float, optional) – The dimensionless z-component of the spin of mass1. Default is 0.

  • spin2x (float, optional) – The dimensionless x-component of the spin of mass2. Default is 0.

  • spin2y (float, optional) – The dimensionless y-component of the spin of mass2. Default is 0.

  • spin2z (float, optional) – The dimensionless z-component of the spin of mass2. Default is 0.

  • approximant (str, optional) – The waveform approximant to use for the fit function. If “NRSur7dq4”, the NRSur7dq4Remnant fit in lalsimulation will be used. If “SEOBNRv4”, the XLALSimIMREOBFinalMassSpin function in lalsimulation will be used. Otherwise, XLALSimIMREOBFinalMassSpinPrec from lalsimulation will be used, with the approximant name passed as the approximant in that function (“SEOBNRv4PHM” will work with this function). Default is “SEOBNRv4PHM”.

  • f_ref (float, optional) – The reference frequency for the spins. Only used by the NRSur7dq4 fit. Default (-1) will use the default reference frequency for the approximant.

Returns:

The dimensionless final spin.

Return type:

float

pycbc.conversions.freq_from_final_mass_spin(final_mass, final_spin, l=2, m=2, n=0)[source]

Returns QNM frequency for the given mass and spin and mode.

Parameters:
  • final_mass (float or array) – Mass of the black hole (in solar masses).

  • final_spin (float or array) – Dimensionless spin of the final black hole.

  • l (int or array, optional) – l-index of the harmonic. Default is 2.

  • m (int or array, optional) – m-index of the harmonic. Default is 2.

  • n (int or array) – Overtone(s) to generate, where n=0 is the fundamental mode. Default is 0.

Returns:

The frequency of the QNM(s), in Hz.

Return type:

float or array

pycbc.conversions.freqlmn_from_other_lmn(f0, tau, current_l, current_m, new_l, new_m)[source]

Returns the QNM frequency (in Hz) of a chosen new (l,m) mode from the given current (l,m) mode.

Parameters:
  • f0 (float or array) – Frequency of the current QNM (in Hz).

  • tau (float or array) – Damping time of the current QNM (in seconds).

  • current_l (int, optional) – l-index of the current QNM.

  • current_m (int, optional) – m-index of the current QNM.

  • new_l (int, optional) – l-index of the new QNM to convert to.

  • new_m (int, optional) – m-index of the new QNM to convert to.

Returns:

The frequency of the new (l, m) QNM mode. If the combination of frequency and damping time provided for the current (l, m) QNM mode correspond to an unphysical Kerr black hole mass and/or spin, numpy.nan will be returned.

Return type:

float or array

pycbc.conversions.invq_from_mass1_mass2(mass1, mass2)[source]

Returns the inverse mass ratio m2/m1, where m1 >= m2.

pycbc.conversions.lambda_from_mass_tov_file(mass, tov_file, distance=0.0)[source]

Return the lambda parameter(s) corresponding to the input mass(es) interpolating from the mass-Lambda data for a particular EOS read in from an ASCII file.

pycbc.conversions.lambda_tilde(mass1, mass2, lambda1, lambda2)[source]

The effective lambda parameter

The mass-weighted dominant effective lambda parameter defined in https://journals.aps.org/prd/pdf/10.1103/PhysRevD.91.043002

pycbc.conversions.mass1_from_mass2_eta(mass2, eta, force_real=True)[source]

Returns the primary mass from the secondary mass and symmetric mass ratio.

pycbc.conversions.mass1_from_mchirp_eta(mchirp, eta)[source]

Returns the primary mass from the chirp mass and symmetric mass ratio.

pycbc.conversions.mass1_from_mchirp_q(mchirp, q)[source]

Returns the primary mass from the given chirp mass and mass ratio.

pycbc.conversions.mass1_from_mtotal_eta(mtotal, eta)[source]

Returns the primary mass from the total mass and symmetric mass ratio.

pycbc.conversions.mass1_from_mtotal_q(mtotal, q)[source]

Returns a component mass from the given total mass and mass ratio.

If the mass ratio q is >= 1, the returned mass will be the primary (heavier) mass. If q < 1, the returned mass will be the secondary (lighter) mass.

pycbc.conversions.mass1_from_tau0_tau3(tau0, tau3, f_lower)[source]

Returns the primary mass from the given \(\tau_0, \tau_3\).

pycbc.conversions.mass2_from_mass1_eta(mass1, eta, force_real=True)[source]

Returns the secondary mass from the primary mass and symmetric mass ratio.

pycbc.conversions.mass2_from_mchirp_eta(mchirp, eta)[source]

Returns the primary mass from the chirp mass and symmetric mass ratio.

pycbc.conversions.mass2_from_mchirp_q(mchirp, q)[source]

Returns the secondary mass from the given chirp mass and mass ratio.

pycbc.conversions.mass2_from_mtotal_eta(mtotal, eta)[source]

Returns the secondary mass from the total mass and symmetric mass ratio.

pycbc.conversions.mass2_from_mtotal_q(mtotal, q)[source]

Returns a component mass from the given total mass and mass ratio.

If the mass ratio q is >= 1, the returned mass will be the secondary (lighter) mass. If q < 1, the returned mass will be the primary (heavier) mass.

pycbc.conversions.mass2_from_tau0_tau3(tau0, tau3, f_lower)[source]

Returns the secondary mass from the given \(\tau_0, \tau_3\).

pycbc.conversions.mchirp_from_mass1_mass2(mass1, mass2)[source]

Returns the chirp mass from mass1 and mass2.

pycbc.conversions.mchirp_from_tau0(tau0, f_lower)[source]

Returns chirp mass from \(\tau_0\) and the given frequency.

pycbc.conversions.mtotal_from_mass1_mass2(mass1, mass2)[source]

Returns the total mass from mass1 and mass2.

pycbc.conversions.mtotal_from_mchirp_eta(mchirp, eta)[source]

Returns the total mass from the chirp mass and symmetric mass ratio.

pycbc.conversions.mtotal_from_tau0_tau3(tau0, tau3, f_lower, in_seconds=False)[source]

Returns total mass from \(\tau_0, \tau_3\).

pycbc.conversions.nltides_gw_phase_diff_isco(f_low, f0, amplitude, n, m1, m2)[source]

Calculate the gravitational-wave phase shift bwtween f_low and f_isco due to non-linear tides.

Parameters:
  • f_low (float) – Frequency from which to compute phase. If the other arguments are passed as numpy arrays then the value of f_low is duplicated for all elements in the array

  • f0 (float or numpy.array) – Frequency that NL effects switch on

  • amplitude (float or numpy.array) – Amplitude of effect

  • n (float or numpy.array) – Growth dependence of effect

  • m1 (float or numpy.array) – Mass of component 1

  • m2 (float or numpy.array) – Mass of component 2

Returns:

delta_phi – Phase in radians

Return type:

float or numpy.array

pycbc.conversions.optimal_dec_from_detector(detector_name, tc)[source]

For a given detector and GPS time, return the optimal orientation (directly overhead of the detector) in declination.

Parameters:
  • detector_name (string) – The name of the detector, e.g., ‘H1’.

  • tc (float) – The GPS time of the coalescence of the signal in the ref_frame.

Returns:

The declination of the signal, in radians.

Return type:

float

pycbc.conversions.optimal_ra_from_detector(detector_name, tc)[source]

For a given detector and GPS time, return the optimal orientation (directly overhead of the detector) in right ascension.

Parameters:
  • detector_name (string) – The name of the detector, e.g., ‘H1’.

  • tc (float) – The GPS time of the coalescence of the signal in the ref_frame.

Returns:

The declination of the signal, in radians.

Return type:

float

pycbc.conversions.phi1_from_phi_a_phi_s(phi_a, phi_s)[source]

Returns the angle between the x-component axis and the in-plane spin for the primary mass from phi_s and phi_a.

pycbc.conversions.phi2_from_phi_a_phi_s(phi_a, phi_s)[source]

Returns the angle between the x-component axis and the in-plane spin for the secondary mass from phi_s and phi_a.

pycbc.conversions.phi_a(mass1, mass2, spin1x, spin1y, spin2x, spin2y)[source]

Returns the angle between the in-plane perpendicular spins.

pycbc.conversions.phi_from_spinx_spiny(spinx, spiny)[source]

Returns the angle between the x-component axis and the in-plane spin.

pycbc.conversions.phi_s(spin1x, spin1y, spin2x, spin2y)[source]

Returns the sum of the in-plane perpendicular spins.

pycbc.conversions.primary_mass(mass1, mass2)[source]

Returns the larger of mass1 and mass2 (p = primary).

pycbc.conversions.primary_spin(mass1, mass2, spin1, spin2)[source]

Returns the dimensionless spin of the primary mass.

pycbc.conversions.primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)[source]

Returns the effective precession spin argument for the larger mass.

pycbc.conversions.q_from_mass1_mass2(mass1, mass2)[source]

Returns the mass ratio m1/m2, where m1 >= m2.

pycbc.conversions.remnant_mass_from_mass1_mass2_cartesian_spin_eos(mass1, mass2, spin1x=0.0, spin1y=0.0, spin1z=0.0, eos='2H', spin2x=0.0, spin2y=0.0, spin2z=0.0, swap_companions=False, ns_bh_mass_boundary=None, extrapolate=False)[source]

Function that determines the remnant disk mass of an NS-BH system using the fit to numerical-relativity results discussed in Foucart, Hinderer & Nissanke, PRD 98, 081501(R) (2018). The BH spin may be misaligned with the orbital angular momentum. In such cases the ISSO is approximated following the approach of Stone, Loeb & Berger, PRD 87, 084053 (2013), which was originally devised for a previous NS-BH remnant mass fit of Foucart, PRD 86, 124007 (2012). Note: NS spin is assumed to be 0!

Parameters:
  • mass1 (float) – The mass of the black hole, in solar masses.

  • mass2 (float) – The mass of the neutron star, in solar masses.

  • spin1x (float, optional) – The dimensionless x-component of the spin of mass1. Default = 0.

  • spin1y (float, optional) – The dimensionless y-component of the spin of mass1. Default = 0.

  • spin1z (float, optional) – The dimensionless z-component of the spin of mass1. Default = 0.

  • eos (str, optional) – Name of the equation of state being adopted. Default is ‘2H’.

  • spin2x (float, optional) – The dimensionless x-component of the spin of mass2. Default = 0.

  • spin2y (float, optional) – The dimensionless y-component of the spin of mass2. Default = 0.

  • spin2z (float, optional) – The dimensionless z-component of the spin of mass2. Default = 0.

  • swap_companions (boolean, optional) – If mass2 > mass1, swap mass and spin of object 1 and 2 prior to applying the fitting formula (otherwise fail). Default is False.

  • ns_bh_mass_boundary (float, optional) – If mass2 is greater than this value, the neutron star is effectively treated as a black hole and the returned value is 0. For consistency with the eos, set this to the maximum mass allowed by the eos; set a lower value for a more stringent cut. Default is None.

  • extrapolate (boolean, optional) – Invoke extrapolation of NS baryonic mass and NS compactness in scipy.interpolate.interp1d at low masses. If ns_bh_mass_boundary is provided, it is applied at high masses, otherwise the equation of state prescribes the maximum possible mass2. Default is False.

Returns:

remnant_mass – The remnant mass in solar masses

Return type:

float

pycbc.conversions.remnant_mass_from_mass1_mass2_spherical_spin_eos(mass1, mass2, spin1_a=0.0, spin1_polar=0.0, eos='2H', spin2_a=0.0, spin2_polar=0.0, swap_companions=False, ns_bh_mass_boundary=None, extrapolate=False)[source]

Function that determines the remnant disk mass of an NS-BH system using the fit to numerical-relativity results discussed in Foucart, Hinderer & Nissanke, PRD 98, 081501(R) (2018). The BH spin may be misaligned with the orbital angular momentum. In such cases the ISSO is approximated following the approach of Stone, Loeb & Berger, PRD 87, 084053 (2013), which was originally devised for a previous NS-BH remnant mass fit of Foucart, PRD 86, 124007 (2012). Note: The NS spin does not play any role in this fit!

Parameters:
  • mass1 (float) – The mass of the black hole, in solar masses.

  • mass2 (float) – The mass of the neutron star, in solar masses.

  • spin1_a (float, optional) – The dimensionless magnitude of the spin of mass1. Default = 0.

  • spin1_polar (float, optional) – The tilt angle of the spin of mass1. Default = 0 (aligned w L).

  • eos (str, optional) – Name of the equation of state being adopted. Default is ‘2H’.

  • spin2_a (float, optional) – The dimensionless magnitude of the spin of mass2. Default = 0.

  • spin2_polar (float, optional) – The tilt angle of the spin of mass2. Default = 0 (aligned w L).

  • swap_companions (boolean, optional) – If mass2 > mass1, swap mass and spin of object 1 and 2 prior to applying the fitting formula (otherwise fail). Default is False.

  • ns_bh_mass_boundary (float, optional) – If mass2 is greater than this value, the neutron star is effectively treated as a black hole and the returned value is 0. For consistency with the eos, set this to the maximum mass allowed by the eos; set a lower value for a more stringent cut. Default is None.

  • extrapolate (boolean, optional) – Invoke extrapolation of NS baryonic mass and NS compactness in scipy.interpolate.interp1d at low masses. If ns_bh_mass_boundary is provided, it is applied at high masses, otherwise the equation of state prescribes the maximum possible mass2. Default is False.

Returns:

remnant_mass – The remnant mass in solar masses

Return type:

float

pycbc.conversions.secondary_mass(mass1, mass2)[source]

Returns the smaller of mass1 and mass2 (s = secondary).

pycbc.conversions.secondary_spin(mass1, mass2, spin1, spin2)[source]

Returns the dimensionless spin of the secondary mass.

pycbc.conversions.secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)[source]

Returns the effective precession spin argument for the smaller mass.

pycbc.conversions.snr_from_loglr(loglr)[source]

Returns SNR computed from the given log likelihood ratio(s). This is defined as sqrt(2*loglr).If the log likelihood ratio is < 0, returns 0.

Parameters:

loglr (array or float) – The log likelihood ratio(s) to evaluate.

Returns:

The SNRs computed from the log likelihood ratios.

Return type:

array or float

pycbc.conversions.spin1x_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s)[source]

Returns x-component spin for primary mass.

pycbc.conversions.spin1y_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s)[source]

Returns y-component spin for primary mass.

pycbc.conversions.spin1z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a)[source]

Returns spin1z.

pycbc.conversions.spin2x_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s)[source]

Returns x-component spin for secondary mass.

pycbc.conversions.spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s)[source]

Returns y-component spin for secondary mass.

pycbc.conversions.spin2z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a)[source]

Returns spin2z.

pycbc.conversions.spin_from_pulsar_freq(mass, radius, freq)[source]

Returns the dimensionless spin of a pulsar.

Assumes the pulsar is a solid sphere when computing the moment of inertia.

Parameters:
  • mass (float) – The mass of the pulsar, in solar masses.

  • radius (float) – The assumed radius of the pulsar, in kilometers.

  • freq (float) – The spin frequency of the pulsar, in Hz.

pycbc.conversions.tau0_from_mass1_mass2(mass1, mass2, f_lower)[source]

Returns \(\tau_0\) from the component masses and given frequency.

pycbc.conversions.tau0_from_mchirp(mchirp, f_lower)[source]

Returns \(\tau_0\) from the chirp mass and the given frequency.

pycbc.conversions.tau0_from_mtotal_eta(mtotal, eta, f_lower)[source]

Returns \(\tau_0\) from the total mass, symmetric mass ratio, and the given frequency.

pycbc.conversions.tau3_from_mass1_mass2(mass1, mass2, f_lower)[source]

Returns \(\tau_3\) from the component masses and given frequency.

pycbc.conversions.tau3_from_mtotal_eta(mtotal, eta, f_lower)[source]

Returns \(\tau_0\) from the total mass, symmetric mass ratio, and the given frequency.

pycbc.conversions.tau_from_final_mass_spin(final_mass, final_spin, l=2, m=2, n=0)[source]

Returns QNM damping time for the given mass and spin and mode.

Parameters:
  • final_mass (float or array) – Mass of the black hole (in solar masses).

  • final_spin (float or array) – Dimensionless spin of the final black hole.

  • l (int or array, optional) – l-index of the harmonic. Default is 2.

  • m (int or array, optional) – m-index of the harmonic. Default is 2.

  • n (int or array) – Overtone(s) to generate, where n=0 is the fundamental mode. Default is 0.

Returns:

The damping time of the QNM(s), in seconds.

Return type:

float or array

pycbc.conversions.taulmn_from_other_lmn(f0, tau, current_l, current_m, new_l, new_m)[source]

Returns the QNM damping time (in seconds) of a chosen new (l,m) mode from the given current (l,m) mode.

Parameters:
  • f0 (float or array) – Frequency of the current QNM (in Hz).

  • tau (float or array) – Damping time of the current QNM (in seconds).

  • current_l (int, optional) – l-index of the current QNM.

  • current_m (int, optional) – m-index of the current QNM.

  • new_l (int, optional) – l-index of the new QNM to convert to.

  • new_m (int, optional) – m-index of the new QNM to convert to.

Returns:

The daming time of the new (l, m) QNM mode. If the combination of frequency and damping time provided for the current (l, m) QNM mode correspond to an unphysical Kerr black hole mass and/or spin, numpy.nan will be returned.

Return type:

float or array

pycbc.conversions.xi1_from_spin1x_spin1y(spin1x, spin1y)[source]

Returns the effective precession spin argument for the larger mass. This function assumes it’s given spins of the primary mass.

pycbc.conversions.xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spin2x, spin2y)[source]

Returns the effective precession spin argument for the smaller mass. This function assumes it’s given spins of the secondary mass.

pycbc.cosmology module

This modules provides functions for computing cosmological quantities, such as redshift. This is mostly a wrapper around astropy.cosmology.

Note: in all functions, distance is short hand for luminosity_distance. Any other distance measure is explicitly named; e.g., comoving_distance.

pycbc.cosmology.cosmological_quantity_from_redshift(z, quantity, strip_unit=True, **kwargs)[source]

Returns the value of a cosmological quantity (e.g., age) at a redshift.

Parameters:
  • z (float) – The redshift.

  • quantity (str) – The name of the quantity to get. The name may be any attribute of astropy.cosmology.FlatLambdaCDM.

  • strip_unit (bool, optional) – Just return the value of the quantity, sans units. Default is True.

  • **kwargs – All other keyword args are passed to get_cosmology() to select a cosmology. If none provided, will use DEFAULT_COSMOLOGY.

Returns:

The value of the quantity at the requested value. If strip_unit is True, will return the value. Otherwise, will return the value with units.

Return type:

float or astropy.units.quantity

pycbc.cosmology.distance_from_comoving_volume(vc, interp=True, **kwargs)[source]

Returns the luminosity distance from the given comoving volume.

Parameters:
  • vc (float) – The comoving volume, in units of cubed Mpc.

  • interp (bool, optional) – If true, this will setup an interpolator between distance and comoving volume the first time this function is called. This is useful when making many successive calls to this function (such as when using this function in a transform for parameter estimation). However, setting up the interpolator the first time takes O(10)s of seconds. If you will only be making a single call to this function, or will only run it on an array with < ~100000 elements, it is faster to not use the interpolator (i.e., set interp=False). Default is True.

  • **kwargs – All other keyword args are passed to get_cosmology() to select a cosmology. If none provided, will use DEFAULT_COSMOLOGY.

Returns:

The luminosity distance at the given comoving volume.

Return type:

float

pycbc.cosmology.redshift(distance, **kwargs)[source]

Returns the redshift associated with the given luminosity distance.

If the requested cosmology is one of the pre-defined ones in astropy.cosmology.parameters.available, DistToZ is used to provide a fast interpolation. This takes a few seconds to setup on the first call.

Parameters:
  • distance (float) – The luminosity distance, in Mpc.

  • **kwargs – All other keyword args are passed to get_cosmology() to select a cosmology. If none provided, will use DEFAULT_COSMOLOGY.

Returns:

The redshift corresponding to the given distance.

Return type:

float

pycbc.cosmology.redshift_from_comoving_volume(vc, interp=True, **kwargs)[source]

Returns the redshift from the given comoving volume.

Parameters:
  • vc (float) – The comoving volume, in units of cubed Mpc.

  • interp (bool, optional) – If true, this will setup an interpolator between redshift and comoving volume the first time this function is called. This is useful when making many successive calls to this function (and is necessary when using this function in a transform when doing parameter estimation). However, setting up the interpolator the first time takes O(10)s of seconds. If you will only be making a single call to this function, or will only run it on an array with < ~100000 elements, it is faster to not use the interpolator (i.e., set interp=False). Default is True.

  • **kwargs – All other keyword args are passed to get_cosmology() to select a cosmology. If none provided, will use DEFAULT_COSMOLOGY.

Returns:

The redshift at the given comoving volume.

Return type:

float

pycbc.detector module

This module provides utilities for calculating detector responses and timing between observatories.

class pycbc.detector.Detector(detector_name, reference_time=1126259462.0)[source]

Bases: object

A gravitational wave detector

antenna_pattern(right_ascension, declination, polarization, t_gps, frequency=0, polarization_type='tensor')[source]

Return the detector response.

Parameters:
  • right_ascension (float or numpy.ndarray) – The right ascension of the source

  • declination (float or numpy.ndarray) – The declination of the source

  • polarization (float or numpy.ndarray) – The polarization angle of the source

  • polarization_type (string flag: Tensor, Vector or Scalar) – The gravitational wave polarizations. Default: ‘Tensor’

Returns:

  • fplus(default) or fx or fb (float or numpy.ndarray) – The plus or vector-x or breathing polarization factor for this sky location / orientation

  • fcross(default) or fy or fl (float or numpy.ndarray) – The cross or vector-y or longitudnal polarization factor for this sky location / orientation

effective_distance(distance, ra, dec, pol, time, inclination)[source]

Distance scaled to account for amplitude factors

The effective distance of the source. This scales the distance so that the amplitude is equal to a source which is optimally oriented with respect to the detector. For fixed detector-frame intrinsic parameters this is a measure of the expected signal strength.

Parameters:
  • distance (float) – Source luminosity distance in megaparsecs

  • ra (float) – The right ascension in radians

  • dec (float) – The declination in radians

  • pol (float) – Polarization angle of the gravitational wave in radians

  • time (float) – GPS time in seconds

  • inclination – The inclination of the binary’s orbital plane

Returns:

eff_dist – The effective distance of the source

Return type:

float

get_icrs_pos()[source]

Transforms GCRS frame to ICRS frame

Returns:

loc – ICRS coordinates in cartesian system

Return type:

numpy.ndarray shape (3,1) units: AU

gmst_estimate(gps_time)[source]
lal()[source]

Return lal data type detector instance

light_travel_time_to_detector(det)[source]

Return the light travel time from this detector :param det: The other detector to determine the light travel time to. :type det: Detector

Returns:

time – The light travel time in seconds

Return type:

float

optimal_orientation(t_gps)[source]
Return the optimal orientation in right ascension and declination

for a given GPS time.

Parameters:

t_gps (float) – Time in gps seconds

Returns:

  • ra (float) – Right ascension that is optimally oriented for the detector

  • dec (float) – Declination that is optimally oriented for the detector

project_wave(hp, hc, ra, dec, polarization, method='lal', reference_time=None)[source]

Return the strain of a waveform as measured by the detector. Apply the time shift for the given detector relative to the assumed geocentric frame and apply the antenna patterns to the plus and cross polarizations.

Parameters:
  • hp (pycbc.types.TimeSeries) – Plus polarization of the GW

  • hc (pycbc.types.TimeSeries) – Cross polarization of the GW

  • ra (float) – Right ascension of source location

  • dec (float) – Declination of source location

  • polarization (float) – Polarization angle of the source

  • method ({'lal', 'constant', 'vary_polarization'}) – The method to use for projecting the polarizations into the detector frame. Default is ‘lal’.

  • reference_time (float, Optional) – The time to use as, a reference for some methods of projection. Used by ‘constant’ and ‘vary_polarization’ methods. Uses average time if not provided.

set_gmst_reference()[source]
time_delay_from_detector(other_detector, right_ascension, declination, t_gps)[source]

Return the time delay from the given to detector for a signal with the given sky location; i.e. return t1 - t2 where t1 is the arrival time in this detector and t2 is the arrival time in the other detector. Note that this would return the same value as time_delay_from_earth_center if other_detector was geocentric. :param other_detector: A detector instance. :type other_detector: detector.Detector :param right_ascension: The right ascension (in rad) of the signal. :type right_ascension: float :param declination: The declination (in rad) of the signal. :type declination: float :param t_gps: The GPS time (in s) of the signal. :type t_gps: float

Returns:

The arrival time difference between the detectors.

Return type:

float

time_delay_from_earth_center(right_ascension, declination, t_gps)[source]

Return the time delay from the earth center

time_delay_from_location(other_location, right_ascension, declination, t_gps)[source]

Return the time delay from the given location to detector for a signal with the given sky location In other words return t1 - t2 where t1 is the arrival time in this detector and t2 is the arrival time in the other location.

Parameters:
  • other_location (numpy.ndarray of coordinates) – A detector instance.

  • right_ascension (float) – The right ascension (in rad) of the signal.

  • declination (float) – The declination (in rad) of the signal.

  • t_gps (float) – The GPS time (in s) of the signal.

Returns:

The arrival time difference between the detectors.

Return type:

float

class pycbc.detector.LISA[source]

Bases: object

For LISA detector

get_gcrs_pos(location)[source]

Transforms ICRS frame to GCRS frame

Parameters:

loc (numpy.ndarray shape (3,1) units: AU) – Cartesian Coordinates of the location in ICRS frame

Returns:

loc – GCRS coordinates in cartesian system

Return type:

numpy.ndarray shape (3,1) units: meters

get_pos(ref_time)[source]

Return the position of LISA detector for a given reference time :param ref_time: :type ref_time: numpy.ScalarType

Returns:

location – Returns the position of all 3 sattelites with each row correspoding to a single axis.

Return type:

numpy.ndarray of shape (3,3)

time_delay_from_detector(det, right_ascension, declination, t_gps)[source]

Return the time delay from the LISA detector for a signal with the given sky location in ICRS frame; i.e. return t1 - t2 where t1 is the arrival time in this detector and t2 is the arrival time in the other detector.

Parameters:
  • other_detector (detector.Detector) – A detector instance.

  • right_ascension (float) – The right ascension (in rad) of the signal.

  • declination (float) – The declination (in rad) of the signal.

  • t_gps (float) – The GPS time (in s) of the signal.

Returns:

The arrival time difference between the detectors.

Return type:

numpy.ndarray

time_delay_from_earth_center(right_ascension, declination, t_gps)[source]

Return the time delay from the earth center in ICRS frame

time_delay_from_location(other_location, right_ascension, declination, t_gps)[source]

Return the time delay from the LISA detector to detector for a signal with the given sky location. In other words return t1 - t2 where t1 is the arrival time in this detector and t2 is the arrival time in the other location. Units(AU)

Parameters:
  • other_location (numpy.ndarray of coordinates in ICRS frame) – A detector instance.

  • right_ascension (float) – The right ascension (in rad) of the signal.

  • declination (float) – The declination (in rad) of the signal.

  • t_gps (float) – The GPS time (in s) of the signal.

Returns:

The arrival time difference between the detectors.

Return type:

numpy.ndarray

pycbc.detector.add_detector_on_earth(name, longitude, latitude, yangle=0, xangle=None, height=0, xlength=4000, ylength=4000)[source]

Add a new detector on the earth

Parameters:
  • name (str) – two-letter name to identify the detector

  • longitude (float) – Longitude in radians using geodetic coordinates of the detector

  • latitude (float) – Latitude in radians using geodetic coordinates of the detector

  • yangle (float) – Azimuthal angle of the y-arm (angle drawn from pointing north)

  • xangle (float) – Azimuthal angle of the x-arm (angle drawn from point north). If not set we assume a right angle detector following the right-hand rule.

  • height (float) – The height in meters of the detector above the standard reference ellipsoidal earth

pycbc.detector.get_available_detectors()[source]

List the available detectors

pycbc.detector.get_available_lal_detectors()[source]

Return list of detectors known in the currently sourced lalsuite. This function will query lalsuite about which detectors are known to lalsuite. Detectors are identified by a two character string e.g. ‘K1’, but also by a longer, and clearer name, e.g. KAGRA. This function returns both. As LAL doesn’t really expose this functionality we have to make some assumptions about how this information is stored in LAL. Therefore while we hope this function will work correctly, it’s possible it will need updating in the future. Better if lal would expose this information properly.

pycbc.detector.gmst_accurate(gps_time)[source]
pycbc.detector.load_detector_config(config_files)[source]

Add custom detectors from a configuration file

Parameters:

config_files (str or list of strs) – The config file(s) which specify new detectors

pycbc.detector.overhead_antenna_pattern(right_ascension, declination, polarization)[source]

Return the antenna pattern factors F+ and Fx as a function of sky location and polarization angle for a hypothetical interferometer located at the north pole. Angles are in radians. Declinations of ±π/2 correspond to the normal to the detector plane (i.e. overhead and underneath) while the point with zero right ascension and declination is the direction of one of the interferometer arms. :param right_ascension: :type right_ascension: float :param declination: :type declination: float :param polarization: :type polarization: float

Returns:

  • f_plus (float)

  • f_cros (float)

pycbc.detector.ppdets(ifos, separator=', ')[source]

Pretty-print a list (or set) of detectors: return a string listing the given detectors alphabetically and separated by the given string (comma by default).

pycbc.detector.single_arm_frequency_response(f, n, arm_length)[source]

The relative amplitude factor of the arm response due to signal delay. This is relevant where the long-wavelength approximation no longer applies)

pycbc.dq module

Utilities to query archival instrument status information of gravitational-wave detectors from public sources and/or dqsegdb.

pycbc.dq.parse_flag_str(flag_str)[source]

Parse a dq flag query string

Parameters:

flag_str (str) – String to be parsed

Returns:

  • flags (list of strings) – List of reduced name strings which can be passed to lower level query commands

  • signs (dict) – Dict of bools indicating if the flag should add positively to the segmentlist

  • ifos (dict) – Ifo specified for the given flag

  • bounds (dict) – The boundary of a given flag

  • padding (dict) – Any padding that should be applied to the segments for a given flag

pycbc.dq.parse_veto_definer(veto_def_filename, ifos)[source]

Parse a veto definer file from the filename and return a dictionary indexed by ifo and veto definer category level.

Parameters:
  • veto_def_filename (str) – The path to the veto definer file

  • ifos (str) – The list of ifos for which we require information from the veto definer file

Returns:

parsed_definition – Returns a dictionary first indexed by ifo, then category level, and finally a list of veto definitions.

Return type:

dict

pycbc.dq.query_cumulative_flags(ifo, segment_names, start_time, end_time, source='any', server='https://segments.ligo.org', veto_definer=None, bounds=None, padding=None, override_ifos=None, cache=False)[source]

Return the times where any flag is active

Parameters:
  • ifo (string or dict) – The interferometer to query (H1, L1). If a dict, an element for each flag name must be provided.

  • segment_name (list of strings) – The status flag to query from GWOSC.

  • start_time (int) – The starting gps time to begin querying from GWOSC

  • end_time (int) – The end gps time of the query

  • source (str, Optional) – Choice between “GWOSC” or “dqsegdb”. If dqsegdb, the server option may also be given. The default is to try GWOSC first then try dqsegdb.

  • server (str, Optional) – The server path. Only used with dqsegdb atm.

  • veto_definer (str, Optional) – The path to a veto definer to define groups of flags which themselves define a set of segments.

  • bounds (dict, Optional) – Dict containing start-end tuples keyed by the flag name which indicate places which should have a distinct time period to be active.

  • padding (dict, Optional) – Dict keyed by the flag name. Each element is a tuple

  • (start_pad

  • boundaries. (end_pad) which indicates how to change the segment) –

  • override_ifos (dict, Optional) – A dict keyed by flag_name to override the ifo option on a per flag basis.

Returns:

segments – List of segments

Return type:

ligo.segments.segmentlist

pycbc.dq.query_dqsegdb2(detector, flag_name, start_time, end_time, server)[source]

Utility function for better error reporting when calling dqsegdb2.

pycbc.dq.query_flag(ifo, segment_name, start_time, end_time, source='any', server='https://segments.ligo.org', veto_definer=None, cache=False)[source]

Return the times where the flag is active

Parameters:
  • ifo (string) – The interferometer to query (H1, L1).

  • segment_name (string) – The status flag to query from GWOSC.

  • start_time (int) – The starting gps time to begin querying from GWOSC

  • end_time (int) – The end gps time of the query

  • source (str, Optional) – Choice between “GWOSC” or “dqsegdb”. If dqsegdb, the server option may also be given. The default is to try GWOSC first then try dqsegdb.

  • server (str, Optional) – The server path. Only used with dqsegdb atm.

  • veto_definer (str, Optional) – The path to a veto definer to define groups of flags which themselves define a set of segments.

  • cache (bool) – If true cache the query. Default is not to cache

Returns:

segments – List of segments

Return type:

ligo.segments.segmentlist

pycbc.dq.query_str(ifo, flag_str, start_time, end_time, source='any', server='https://segments.ligo.org', veto_definer=None)[source]

Query for flags based on a special str syntax

Parameters:
  • ifo (str) – The ifo to query for (may be overridden in syntax)

  • flag_str (str) – Specification of how to do the query. Ex. +H1:DATA:1<-8,8>[0,100000000] would return H1 time for the DATA available flag with version 1. It would then apply an 8 second padding and only return times within the chosen range 0,1000000000.

  • start_time (int) – The start gps time. May be overridden for individual flags with the flag str bounds syntax

  • end_time (int) – The end gps time. May be overridden for individual flags with the flag str bounds syntax

  • source (str, Optional) – Choice between “GWOSC” or “dqsegdb”. If dqsegdb, the server option may also be given. The default is to try GWOSC first then try dqsegdb.

  • server (str, Optional) – The server path. Only used with dqsegdb atm.

  • veto_definer (str, Optional) – The path to a veto definer to define groups of flags which themselves define a set of segments.

Returns:

segs – A list of segments corresponding to the flag query string

Return type:

segmentlist

pycbc.libutils module

This module provides a simple interface for loading a shared library via ctypes, allowing it to be specified in an OS-independent way and searched for preferentially according to the paths that pkg-config specifies.

pycbc.libutils.get_ctypes_library(libname, packages, mode=0)[source]

This function takes a library name, specified in architecture-independent fashion (i.e. omitting any prefix such as ‘lib’ or suffix such as ‘so’ or ‘dylib’ or version number) and a list of packages that may provide that library, and according first to LD_LIBRARY_PATH, then the results of pkg-config, and falling back to the system search path, will try to return a CDLL ctypes object. If ‘mode’ is given it will be used when loading the library.

pycbc.libutils.get_libpath_from_dirlist(libname, dirs)[source]

This function tries to find the architecture-independent library given by libname in the first available directory in the list dirs. ‘Architecture-independent’ means omitting any prefix such as ‘lib’ or suffix such as ‘so’ or ‘dylib’ or version number. Within the first directory in which a matching pattern can be found, the lexicographically first such file is returned, as a string giving the full path name. The only supported OSes at the moment are posix and mac, and this function does not attempt to determine which is being run. So if for some reason your directory has both ‘.so’ and ‘.dylib’ libraries, who knows what will happen. If the library cannot be found, None is returned.

pycbc.libutils.import_optional(library_name)[source]

Try to import library but and return stub if not found

Parameters:

library_name (str) – The name of the python library to import

Returns:

library – Either returns the library if importing is sucessful or it returns a stub which raises an import error and message when accessed.

Return type:

library or stub

pycbc.libutils.pkg_config(pkg_libraries)[source]

Use pkg-config to query for the location of libraries, library directories, and header directories

Parameters:

pkg_libries (list) – A list of packages as strings

Returns:

libraries(list), library_dirs(list), include_dirs(list)

pycbc.libutils.pkg_config_check_exists(package)[source]
pycbc.libutils.pkg_config_header_strings(pkg_libraries)[source]

Returns a list of header strings that could be passed to a compiler

pycbc.libutils.pkg_config_libdirs(packages)[source]

Returns a list of all library paths that pkg-config says should be included when linking against the list of packages given as ‘packages’. An empty return list means that the package may be found in the standard system locations, irrespective of pkg-config.

pycbc.mchirp_area module

Functions to compute the area corresponding to different CBC on the m1 & m2 plane when given a central mchirp value and uncertainty. It also includes a function that calculates the source frame when given the detector frame mass and redshift.

pycbc.mchirp_area.calc_areas(trig_mc_det, mass_limits, mass_bdary, z, mass_gap, mass_gap_separate)[source]

Computes the area inside the lines of the second component mass as a function of the first component mass for the two extreme values of mchirp: mchirp +/- mchirp_uncertainty, for each region of the source classifying diagram.

pycbc.mchirp_area.calc_probabilities(mchirp, snr, eff_distance, src_args)[source]

Computes the different probabilities that a candidate event belongs to each CBC source category taking as arguments the chirp mass, the coincident SNR and the effective distance, and estimating the chirp mass uncertainty, the luminosity distance (and its uncertainty) and the redshift (and its uncertainty). Probability is estimated to be directly proportional to the area of the corresponding CBC region.

pycbc.mchirp_area.from_cli(args, parser)[source]
pycbc.mchirp_area.get_area(trig_mc, lim_h1, lim_h2, lim_v1, lim_v2)[source]

Returns the area under the chirp mass contour in a region of the m1-m2 plane (m1 > m2).

Parameters:
  • trig_mc (sequence of two values) – first represents central estimate of mchirp in source frame, second its uncertainty

  • lim_h1 (floats or the string 'diagonal') – upper and lower horizontal limits of the region (limits on m2)

  • lim_h2 (floats or the string 'diagonal') – upper and lower horizontal limits of the region (limits on m2)

  • lim_v1 (floats) – right and left vertical limits of the region (limits on m1)

  • lim_v2 (floats) – right and left vertical limits of the region (limits on m1)

Returns:

area

Return type:

float

pycbc.mchirp_area.insert_args(parser)[source]
pycbc.mchirp_area.intmc(mc, x_min, x_max)[source]

Returns the integral of m2 over m1 between x_min and x_max, assuming that mchirp is fixed.

pycbc.mchirp_area.redshift_estimation(distance, distance_std, lal_cosmology)[source]

Takes values of distance and its uncertainty and returns a dictionary with estimates of the redshift and its uncertainty. If the argument ‘lal_cosmology’ is True, it uses Planck15 cosmology model as defined in lalsuite instead of the astropy default. Constants for lal_cosmology taken from Planck15_lal_cosmology() in https://git.ligo.org/lscsoft/pesummary/-/blob/master/pesummary/gw/ cosmology.py.

pycbc.mchirp_area.src_mass_from_z_det_mass(z, del_z, mdet, del_mdet)[source]

Takes values of redshift, redshift uncertainty, detector mass and its uncertainty and computes the source mass and its uncertainty.

pycbc.opt module

This module defines optimization flags and determines hardware features that some other modules and packages may use in addition to some optimized utilities.

class pycbc.opt.LimitedSizeDict(*args, **kwds)[source]

Bases: OrderedDict

Fixed sized dict for FIFO caching

pycbc.opt.getconf(confvar)[source]
pycbc.opt.insert_optimization_option_group(parser)[source]

Adds the options used to specify optimization-specific options.

Parameters:

parser (object) – OptionParser instance

pycbc.opt.verify_optimization_options(opt, parser)[source]

Parses the CLI options, verifies that they are consistent and reasonable, and acts on them if they are

Parameters:
  • opt (object) – Result of parsing the CLI with OptionParser, or any object with the required attributes

  • parser (object) – OptionParser instance.

pycbc.pnutils module

This module contains convenience pN functions. This includes calculating conversions between quantities.

pycbc.pnutils.A0(f_lower)[source]

used in calculating chirp times: see Cokelaer, arxiv.org:0706.4437 appendix 1, also lalinspiral/python/sbank/tau0tau3.py

pycbc.pnutils.A3(f_lower)[source]

another parameter used for chirp times

pycbc.pnutils.chirp_distance(dist, mchirp, ref_mass=1.4)[source]
pycbc.pnutils.energy(v, mass1, mass2, s1z=0, s2z=0, phase_order=-1, spin_order=-1)[source]
pycbc.pnutils.energy_coefficients(m1, m2, s1z=0, s2z=0, phase_order=-1, spin_order=-1)[source]

Return the energy coefficients. This assumes that the system has aligned spins only.

pycbc.pnutils.eta_mass1_to_mass2(eta, mass1, return_mass_heavier=False, force_real=True)[source]

This function takes values for eta and one component mass and returns the second component mass. Similar to mchirp_mass1_to_mass2 this requires finding the roots of a quadratic equation. Basically:

eta m2^2 + (2 eta - 1)m1 m2 + eta m1^2 = 0

This has two solutions which correspond to mass1 being the heavier mass or it being the lighter mass. By default the value corresponding to mass1 > mass2 is returned. Use the return_mass_heavier kwarg to invert this behaviour.

pycbc.pnutils.f_BKLISCO(m1, m2)[source]

Mass ratio dependent ISCO derived from estimates of the final spin of a merged black hole in a paper by Buonanno, Kidder, Lehner (arXiv:0709.3839). See also arxiv:0801.4297v2 eq.(5)

Parameters:
  • m1 (float or numpy.array) – First component mass in solar mass units

  • m2 (float or numpy.array) – Second component mass in solar mass units

Returns:

f – Frequency in Hz

Return type:

float or numpy.array

pycbc.pnutils.f_ERD(M)[source]

Effective RingDown frequency studied in Pan et al. (arXiv:0704.1964) found to give good fit between stationary-phase templates and numerical relativity waveforms [NB equal-mass & nonspinning!] Equal to 1.07*omega_220/2*pi

Parameters:

M (float or numpy.array) – Total mass in solar mass units

Returns:

f – Frequency in Hz

Return type:

float or numpy.array

pycbc.pnutils.f_FRD(m1, m2)[source]

Fundamental RingDown frequency calculated from the Berti, Cardoso and Will (gr-qc/0512160) value for the omega_220 QNM frequency using mass-ratio dependent fits to the final BH mass and spin from Buonanno et al. (arXiv:0706.3732) : see also InspiralBankGeneration.c

Parameters:
  • m1 (float or numpy.array) – First component mass in solar mass units

  • m2 (float or numpy.array) – Second component mass in solar mass units

Returns:

f – Frequency in Hz

Return type:

float or numpy.array

pycbc.pnutils.f_LRD(m1, m2)[source]

Lorentzian RingDown frequency = 1.2*FRD which captures part of the Lorentzian tail from the decay of the QNMs

Parameters:
  • m1 (float or numpy.array) – First component mass in solar mass units

  • m2 (float or numpy.array) – Second component mass in solar mass units

Returns:

f – Frequency in Hz

Return type:

float or numpy.array

pycbc.pnutils.f_LightRing(M)[source]

Gravitational wave frequency corresponding to the light-ring orbit, equal to 1/(3**(3/2) pi M) : see InspiralBankGeneration.c

Parameters:

M (float or numpy.array) – Total mass in solar mass units

Returns:

f – Frequency in Hz

Return type:

float or numpy.array

pycbc.pnutils.f_SchwarzISCO(M)[source]

Innermost stable circular orbit (ISCO) for a test particle orbiting a Schwarzschild black hole

Parameters:

M (float or numpy.array) – Total mass in solar mass units

Returns:

f – Frequency in Hz

Return type:

float or numpy.array

pycbc.pnutils.frequency_cutoff_from_name(name, m1, m2, s1z, s2z)[source]

Returns the result of evaluating the frequency cutoff function specified by ‘name’ on a template with given parameters.

Parameters:
  • name (string) – Name of the cutoff function

  • m1 (float or numpy.array) – First component mass in solar masses

  • m2 (float or numpy.array) – Second component mass in solar masses

  • s1z (float or numpy.array) – First component dimensionless spin S_1/m_1^2 projected onto L

  • s2z (float or numpy.array) – Second component dimensionless spin S_2/m_2^2 projected onto L

Returns:

f – Frequency in Hz

Return type:

float or numpy.array

pycbc.pnutils.frequency_to_velocity(f, M)[source]
pycbc.pnutils.get_beta_sigma_from_aligned_spins(eta, spin1z, spin2z)[source]

Calculate the various PN spin combinations from the masses and spins. See <http://arxiv.org/pdf/0810.5336v3.pdf>.

Parameters:
  • eta (float or numpy.array) – Symmetric mass ratio of the input system(s)

  • spin1z (float or numpy.array) – Spin(s) parallel to the orbit of the heaviest body(ies)

  • spin2z (float or numpy.array) – Spin(s) parallel to the orbit of the smallest body(ies)

Returns:

  • beta (float or numpy.array) – The 1.5PN spin combination

  • sigma (float or numpy.array) – The 2PN spin combination

  • gamma (float or numpy.array) – The 2.5PN spin combination

  • chis (float or numpy.array) – (spin1z + spin2z) / 2.

pycbc.pnutils.get_final_freq(approx, m1, m2, s1z, s2z)[source]

Returns the final (highest) frequency for a given approximant using given template parameters.

NOTE: TaylorTx and TaylorFx are currently all given an ISCO cutoff !!

Parameters:
  • approx (string) – Name of the approximant e.g. ‘EOBNRv2’

  • m1 (float or numpy.array) – First component mass in solar masses

  • m2 (float or numpy.array) – Second component mass in solar masses

  • s1z (float or numpy.array) – First component dimensionless spin S_1/m_1^2 projected onto L

  • s2z (float or numpy.array) – Second component dimensionless spin S_2/m_2^2 projected onto L

Returns:

f – Frequency in Hz

Return type:

float or numpy.array

pycbc.pnutils.get_freq(freqfunc, m1, m2, s1z, s2z)[source]

Returns the LALSimulation function which evaluates the frequency for the given frequency function and template parameters.

Parameters:
  • freqfunc (string) – Name of the frequency function to use, e.g., ‘fEOBNRv2RD’

  • m1 (float or numpy.array) – First component mass in solar masses

  • m2 (float or numpy.array) – Second component mass in solar masses

  • s1z (float or numpy.array) – First component dimensionless spin S_1/m_1^2 projected onto L

  • s2z (float or numpy.array) – Second component dimensionless spin S_2/m_2^2 projected onto L

Returns:

f – Frequency in Hz

Return type:

float or numpy.array

pycbc.pnutils.get_inspiral_tf(tc, mass1, mass2, spin1, spin2, f_low, n_points=100, pn_2order=7, approximant='TaylorF2')[source]

Compute the time-frequency evolution of an inspiral signal.

Return a tuple of time and frequency vectors tracking the evolution of an inspiral signal in the time-frequency plane.

pycbc.pnutils.hybridEnergy(v, m1, m2, chi1, chi2, qm1, qm2)[source]

Return hybrid MECO energy.

Return the hybrid energy [eq. (6)] whose minimum defines the hybrid MECO up to 3.5PN (including the 3PN spin-spin)

Parameters:
  • m1 (float) – Mass of the primary object in solar masses.

  • m2 (float) – Mass of the secondary object in solar masses.

  • chi1 (float) – Dimensionless spin of the primary object.

  • chi2 (float) – Dimensionless spin of the secondary object.

  • qm1 (float) – Quadrupole-monopole term of the primary object (1 for black holes).

  • qm2 (float) – Quadrupole-monopole term of the secondary object (1 for black holes).

Returns:

h_E – The hybrid energy as a function of v

Return type:

float

pycbc.pnutils.hybrid_meco_frequency(m1, m2, chi1, chi2, qm1=None, qm2=None)[source]

Return the frequency of the hybrid MECO

Parameters:
  • m1 (float) – Mass of the primary object in solar masses.

  • m2 (float) – Mass of the secondary object in solar masses.

  • chi1 (float) – Dimensionless spin of the primary object.

  • chi2 (float) – Dimensionless spin of the secondary object.

  • qm1 ({None, float}, optional) – Quadrupole-monopole term of the primary object (1 for black holes). If None, will be set to qm1 = 1.

  • qm2 ({None, float}, optional) – Quadrupole-monopole term of the secondary object (1 for black holes). If None, will be set to qm2 = 1.

Returns:

f – The frequency (in Hz) of the hybrid MECO

Return type:

float

pycbc.pnutils.hybrid_meco_velocity(m1, m2, chi1, chi2, qm1=None, qm2=None)[source]

Return the velocity of the hybrid MECO

Parameters:
  • m1 (float) – Mass of the primary object in solar masses.

  • m2 (float) – Mass of the secondary object in solar masses.

  • chi1 (float) – Dimensionless spin of the primary object.

  • chi2 (float) – Dimensionless spin of the secondary object.

  • qm1 ({None, float}, optional) – Quadrupole-monopole term of the primary object (1 for black holes). If None, will be set to qm1 = 1.

  • qm2 ({None, float}, optional) – Quadrupole-monopole term of the secondary object (1 for black holes). If None, will be set to qm2 = 1.

Returns:

v – The velocity (dimensionless) of the hybrid MECO

Return type:

float

pycbc.pnutils.jframe_to_l0frame(mass1, mass2, f_ref, phiref=0.0, thetajn=0.0, phijl=0.0, spin1_a=0.0, spin2_a=0.0, spin1_polar=0.0, spin2_polar=0.0, spin12_deltaphi=0.0)[source]

Converts J-frame parameters into L0 frame.

Parameters:
  • mass1 (float) – The mass of the first component object in the binary (in solar masses)

  • mass2 (float) – The mass of the second component object in the binary (in solar masses)

  • f_ref (float) – The reference frequency.

  • thetajn (float) – Angle between the line of sight and the total angular momentume J.

  • phijl (float) – Azimuthal angle of L on its cone about J.

  • spin1_a (float) – The dimensionless spin magnitude \(|\vec{{s}}_1/m^2_1|\).

  • spin2_a (float) – The dimensionless spin magnitude \(|\vec{{s}}_2/m^2_2|\).

  • spin1_polar (float) – Angle between L and the spin magnitude of the larger object.

  • spin2_polar (float) – Angle betwen L and the spin magnitude of the smaller object.

  • spin12_deltaphi (float) – Difference between the azimuthal angles of the spin of the larger object (S1) and the spin of the smaller object (S2).

Returns:

Dictionary of:

  • inclinationfloat

    Inclination (rad), defined as the angle between the orbital angular momentum L and the line-of-sight at the reference frequency.

  • spin1xfloat

    The x component of the first binary component’s dimensionless spin.

  • spin1yfloat

    The y component of the first binary component’s dimensionless spin.

  • spin1zfloat

    The z component of the first binary component’s dimensionless spin.

  • spin2xfloat

    The x component of the second binary component’s dimensionless spin.

  • spin2yfloat

    The y component of the second binary component’s dimensionless spin.

  • spin2zfloat

    The z component of the second binary component’s dimensionless spin.

Return type:

dict

pycbc.pnutils.kerr_lightring(v, chi)[source]

Return the function whose first root defines the Kerr light ring

pycbc.pnutils.kerr_lightring_velocity(chi)[source]

Return the velocity at the Kerr light ring

pycbc.pnutils.l0frame_to_jframe(mass1, mass2, f_ref, phiref=0.0, inclination=0.0, spin1x=0.0, spin1y=0.0, spin1z=0.0, spin2x=0.0, spin2y=0.0, spin2z=0.0)[source]

Converts L0-frame parameters to J-frame.

Parameters:
  • mass1 (float) – The mass of the first component object in the binary (in solar masses)

  • mass2 (float) – The mass of the second component object in the binary (in solar masses)

  • f_ref (float) – The reference frequency.

  • phiref (float) – The orbital phase at f_ref.

  • inclination (float) – Inclination (rad), defined as the angle between the orbital angular momentum L and the line-of-sight at the reference frequency.

  • spin1x (float) – The x component of the first binary component’s dimensionless spin.

  • spin1y (float) – The y component of the first binary component’s dimensionless spin.

  • spin1z (float) – The z component of the first binary component’s dimensionless spin.

  • spin2x (float) – The x component of the second binary component’s dimensionless spin.

  • spin2y (float) – The y component of the second binary component’s dimensionless spin.

  • spin2z (float) – The z component of the second binary component’s dimensionless spin.

Returns:

Dictionary of:

  • thetajnfloat

    Angle between the line of sight and the total angular momentume J.

  • phijlfloat

    Azimuthal angle of L on its cone about J.

  • spin1_afloat

    The dimensionless spin magnitude \(|\vec{{s}}_1/m^2_1|\).

  • spin2_afloat

    The dimensionless spin magnitude \(|\vec{{s}}_2/m^2_2|\).

  • spin1_polarfloat

    Angle between L and the spin magnitude of the larger object.

  • spin2_polarfloat

    Angle betwen L and the spin magnitude of the smaller object.

  • spin12_deltaphifloat

    Difference between the azimuthal angles of the spin of the larger object (S1) and the spin of the smaller object (S2).

Return type:

dict

pycbc.pnutils.mass1_mass2_spin1z_spin2z_to_beta_sigma_gamma(mass1, mass2, spin1z, spin2z)[source]
pycbc.pnutils.mass1_mass2_to_mchirp_eta(mass1, mass2)[source]
pycbc.pnutils.mass1_mass2_to_mtotal_eta(mass1, mass2)[source]
pycbc.pnutils.mass1_mass2_to_tau0_tau3(mass1, mass2, f_lower)[source]
pycbc.pnutils.mchirp_eta_to_mass1_mass2(m_chirp, eta)[source]
pycbc.pnutils.mchirp_mass1_to_mass2(mchirp, mass1)[source]

This function takes a value of mchirp and one component mass and returns the second component mass. As this is a cubic equation this requires finding the roots and returning the one that is real. Basically it can be shown that:

m2^3 - a(m2 + m1) = 0

where

a = Mc^5 / m1^3

this has 3 solutions but only one will be real.

pycbc.pnutils.mchirp_q_to_mass1_mass2(mchirp, q)[source]

This function takes a value of mchirp and the mass ratio mass1/mass2 and returns the two component masses.

The map from q to eta is

eta = (mass1*mass2)/(mass1+mass2)**2 = (q)/(1+q)**2

Then we can map from (mchirp,eta) to (mass1,mass2).

pycbc.pnutils.meco2(m1, m2, s1z=0, s2z=0, phase_order=-1, spin_order=-1)[source]
pycbc.pnutils.meco_velocity(m1, m2, chi1, chi2)[source]

Returns the velocity of the minimum energy cutoff for 3.5pN (2.5pN spin)

Parameters:
  • m1 (float) – First component mass in solar masses

  • m2 (float) – Second component mass in solar masses

  • chi1 (float) – First component dimensionless spin S_1/m_1^2 projected onto L

  • chi2 (float) – Second component dimensionless spin S_2/m_2^2 projected onto L

Returns:

v – Velocity (dimensionless)

Return type:

float

pycbc.pnutils.megaparsecs_to_meters(distance)[source]
pycbc.pnutils.mtotal_eta_to_mass1_mass2(m_total, eta)[source]
pycbc.pnutils.nearest_larger_binary_number(input_len)[source]

Return the nearest binary number larger than input_len.

pycbc.pnutils.parsecs_to_meters(distance)[source]
pycbc.pnutils.solar_mass_to_kg(solar_masses)[source]
pycbc.pnutils.t2_cutoff_frequency(m1, m2, chi1, chi2)[source]
pycbc.pnutils.t2_cutoff_velocity(m1, m2, chi1, chi2)[source]
pycbc.pnutils.t4_cutoff_velocity(m1, m2, chi1, chi2)

Returns the velocity of the minimum energy cutoff for 3.5pN (2.5pN spin)

Parameters:
  • m1 (float) – First component mass in solar masses

  • m2 (float) – Second component mass in solar masses

  • chi1 (float) – First component dimensionless spin S_1/m_1^2 projected onto L

  • chi2 (float) – Second component dimensionless spin S_2/m_2^2 projected onto L

Returns:

v – Velocity (dimensionless)

Return type:

float

pycbc.pnutils.tau0_tau3_to_mass1_mass2(tau0, tau3, f_lower)[source]
pycbc.pnutils.tau0_tau3_to_mtotal_eta(tau0, tau3, f_lower)[source]
pycbc.pnutils.velocity_to_frequency(v, M)[source]

pycbc.pool module

Tools for creating pools of worker processes

class pycbc.pool.BroadcastPool(processes=None, initializer=None, initargs=(), **kwds)[source]

Bases: Pool

Multiprocessing pool with a broadcast method

allmap(fcn, args)[source]

Do a function call on every worker with different arguments

Parameters:
  • fcn (funtion) – Function to call.

  • args (tuple) – The arguments for Pool.map

broadcast(fcn, args)[source]

Do a function call on every worker.

Parameters:
  • fcn (funtion) – Function to call.

  • args (tuple) – The arguments for Pool.map

map(func, items, chunksize=None)[source]

Catch keyboard interuppts to allow the pool to exit cleanly.

Parameters:
  • func (function) – Function to call

  • items (list of tuples) – Arguments to pass

  • chunksize (int, Optional) – Number of calls for each process to handle at once

class pycbc.pool.SinglePool[source]

Bases: object

broadcast(fcn, args)[source]
imap(f, items)
map(f, items)[source]
pycbc.pool.choose_pool(processes, mpi=False)[source]

Get processing pool

pycbc.pool.is_main_process()[source]

Check if this is the main control process and may handle one time tasks

pycbc.pool.use_mpi(require_mpi=False, log=True)[source]

Get whether MPI is enabled and if so the current size and rank

pycbc.rate module

pycbc.rate.compute_efficiency(f_dist, m_dist, dbins)[source]

Compute the efficiency as a function of distance for the given sets of found and missed injection distances. Note that injections that do not fit into any dbin get lost :(

pycbc.rate.compute_lower_limit(mu_in, post, alpha=0.9)[source]

Returns the lower limit mu_low of confidence level alpha for a posterior distribution post on the given parameter mu. The posterior need not be normalized.

pycbc.rate.compute_upper_limit(mu_in, post, alpha=0.9)[source]

Returns the upper limit mu_high of confidence level alpha for a posterior distribution post on the given parameter mu. The posterior need not be normalized.

pycbc.rate.compute_volume_vs_mass(found, missed, mass_bins, bin_type, dbins=None)[source]

Compute the average luminosity an experiment was sensitive to

Assumes that luminosity is uniformly distributed in space. Input is the sets of found and missed injections.

pycbc.rate.confidence_interval_min_width(mu, post, alpha=0.9)[source]

Returns the minimal-width confidence interval [mu_low, mu_high] of confidence level alpha for a posterior distribution post on the parameter mu.

pycbc.rate.filter_injections_by_mass(injs, mbins, bin_num, bin_type, bin_num2=None)[source]

For a given set of injections (sim_inspiral rows), return the subset of injections that fall within the given mass range.

pycbc.rate.hpd_coverage(mu, pdf, thresh)[source]

Integrates a pdf over mu taking only bins where the mean over the bin is above a given threshold This gives the coverage of the HPD interval for the given threshold.

pycbc.rate.hpd_credible_interval(mu_in, post, alpha=0.9, tolerance=0.001)[source]

Returns the minimum and maximum rate values of the HPD (Highest Posterior Density) credible interval for a posterior post defined at the sample values mu_in. Samples need not be uniformly spaced and posterior need not be normalized.

Will not return a correct credible interval if the posterior is multimodal and the correct interval is not contiguous; in this case will over-cover by including the whole range from minimum to maximum mu.

pycbc.rate.hpd_threshold(mu_in, post, alpha, tol)[source]

For a PDF post over samples mu_in, find a density threshold such that the region having higher density has coverage of at least alpha, and less than alpha plus a given tolerance.

pycbc.rate.integral_element(mu, pdf)[source]

Returns an array of elements of the integrand dP = p(mu) dmu for a density p(mu) defined at sample values mu ; samples need not be equally spaced. Uses a simple trapezium rule. Number of dP elements is 1 - (number of mu samples).

pycbc.rate.integrate_efficiency(dbins, eff, err=0, logbins=False)[source]
pycbc.rate.mean_efficiency_volume(found, missed, dbins)[source]
pycbc.rate.normalize_pdf(mu, pofmu)[source]

Takes a function pofmu defined at rate sample values mu and normalizes it to be a suitable pdf. Both mu and pofmu must be arrays or lists of the same length.

pycbc.scheme module

This modules provides python contexts that set the default behavior for PyCBC objects.

class pycbc.scheme.CPUScheme(num_threads=1)[source]

Bases: Scheme

class pycbc.scheme.CUDAScheme(device_num=0)[source]

Bases: Scheme

Context that sets PyCBC objects to use a CUDA processing scheme.

class pycbc.scheme.ChooseBySchemeDict[source]

Bases: dict

This class represents a dictionary whose purpose is to chose objects based on their processing scheme. The keys are intended to be processing schemes.

class pycbc.scheme.DefaultScheme(num_threads=1)[source]

Bases: CPUScheme

class pycbc.scheme.MKLScheme(num_threads=1)[source]

Bases: CPUScheme

class pycbc.scheme.NumpyScheme(num_threads=1)[source]

Bases: CPUScheme

class pycbc.scheme.Scheme[source]

Bases: object

Context that sets PyCBC objects to use CPU processing.

pycbc.scheme.clean_cuda(context)[source]
pycbc.scheme.cpuonly(func)[source]
pycbc.scheme.current_prefix()[source]
pycbc.scheme.from_cli(opt)[source]

Parses the command line options and returns a precessing scheme.

Parameters:

opt (object) – Result of parsing the CLI with OptionParser, or any object with the required attributes.

Returns:

ctx – Returns the requested processing scheme.

Return type:

Scheme

pycbc.scheme.insert_processing_option_group(parser)[source]

Adds the options used to choose a processing scheme. This should be used if your program supports the ability to select the processing scheme.

Parameters:

parser (object) – OptionParser instance

pycbc.scheme.register_clean_cuda(function)[source]
pycbc.scheme.schemed(prefix)[source]
pycbc.scheme.verify_processing_options(opt, parser)[source]
Parses the processing scheme options and verifies that they are

reasonable.

Parameters:
  • opt (object) – Result of parsing the CLI with OptionParser, or any object with the required attributes.

  • parser (object) – OptionParser instance.

pycbc.sensitivity module

This module contains utilities for calculating search sensitivity

pycbc.sensitivity.chirp_volume_montecarlo(found_d, missed_d, found_mchirp, missed_mchirp, distribution_param, distribution, limits_param, min_param, max_param)[source]
pycbc.sensitivity.compute_search_efficiency_in_bins(found, total, ndbins, sim_to_bins_function=<function <lambda>>)[source]

Calculate search efficiency in the given ndbins.

The first dimension of ndbins must be bins over injected distance. sim_to_bins_function must map an object to a tuple indexing the ndbins.

pycbc.sensitivity.compute_search_volume_in_bins(found, total, ndbins, sim_to_bins_function)[source]

Calculate search sensitive volume by integrating efficiency in distance bins

No cosmological corrections are applied: flat space is assumed. The first dimension of ndbins must be bins over injected distance. sim_to_bins_function must maps an object to a tuple indexing the ndbins.

pycbc.sensitivity.volume_binned_pylal(f_dist, m_dist, bins=15)[source]

Compute the sensitive volume using a distance binned efficiency estimate

Parameters:
  • f_dist (numpy.ndarray) – The distances of found injections

  • m_dist (numpy.ndarray) – The distances of missed injections

Returns:

  • volume (float) – Volume estimate

  • volume_error (float) – The standard error in the volume

pycbc.sensitivity.volume_montecarlo(found_d, missed_d, found_mchirp, missed_mchirp, distribution_param, distribution, limits_param, min_param=None, max_param=None)[source]

Compute sensitive volume and standard error via direct Monte Carlo integral

Injections should be made over a range of distances such that sensitive volume due to signals closer than D_min is negligible, and efficiency at distances above D_max is negligible TODO : Replace this function by Collin’s formula given in Usman et al. ? OR get that coded as a new function?

Parameters:
  • found_d (numpy.ndarray) – The distances of found injections

  • missed_d (numpy.ndarray) – The distances of missed injections

  • found_mchirp (numpy.ndarray) – Chirp mass of found injections

  • missed_mchirp (numpy.ndarray) – Chirp mass of missed injections

  • distribution_param (string) – Parameter D of the injections used to generate a distribution over distance, may be ‘distance’, ‘chirp_distance’.

  • distribution (string) – form of the distribution over the parameter, may be ‘log’ (uniform in log D) ‘uniform’ (uniform in D) ‘distancesquared’ (uniform in D**2) ‘volume’ (uniform in D**3)

  • limits_param (string) – Parameter Dlim specifying limits inside which injections were made may be ‘distance’, ‘chirp distance’

  • min_param (float) – minimum value of Dlim at which injections were made; only used for log distribution, then if None the minimum actually injected value will be used

  • max_param (float) – maximum value of Dlim out to which injections were made; if None the maximum actually injected value will be used

Returns:

  • volume (float) – Volume estimate

  • volume_error (float) – The standard error in the volume

pycbc.sensitivity.volume_shell(f_dist, m_dist)[source]

Compute the sensitive volume using sum over spherical shells.

Parameters:
  • f_dist (numpy.ndarray) – The distances of found injections

  • m_dist (numpy.ndarray) – The distances of missed injections

Returns:

  • volume (float) – Volume estimate

  • volume_error (float) – The standard error in the volume

pycbc.sensitivity.volume_to_distance_with_errors(vol, vol_err)[source]

Return the distance and standard deviation upper and lower bounds

Parameters:
Returns:

  • dist (float)

  • ehigh (float)

  • elow (float)

pycbc.transforms module

This modules provides classes and functions for transforming parameters.

class pycbc.transforms.AlignTotalSpin[source]

Bases: BaseTransform

Converts angles from total angular momentum J frame to orbital angular momentum L (waveform) frame

name = 'align_total_spin'
transform(maps)[source]

Rigidly rotate binary so that the total angular momentum has the given inclination (iota) instead of the orbital angular momentum. Return the new inclination, s1, and s2. s1 and s2 are dimensionless spin. Note: the spins are assumed to be given in the frame defined by the orbital angular momentum.

class pycbc.transforms.AlignedMassSpinToCartesianSpin[source]

Bases: BaseTransform

Converts mass-weighted spins to cartesian z-axis spins.

inverse

alias of CartesianSpinToAlignedMassSpin

inverse_transform(maps)[source]

This function transforms from component masses and cartesian spins to mass-weighted spin parameters aligned with the angular momentum.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

name = 'aligned_mass_spin_to_cartesian_spin'
transform(maps)[source]

This function transforms from aligned mass-weighted spins to cartesian spins aligned along the z-axis.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.BaseTransform[source]

Bases: object

A base class for transforming between two sets of parameters.

static format_output(old_maps, new_maps)[source]

This function takes the returned dict from transform and converts it to the same datatype as the input.

Parameters:
  • old_maps ({FieldArray, dict}) – The mapping object to add new maps to.

  • new_maps (dict) – A dict with key as parameter name and value is numpy.array.

Returns:

The old_maps object with new keys from new_maps.

Return type:

{FieldArray, dict}

classmethod from_config(cp, section, outputs, skip_opts=None, additional_opts=None)[source]

Initializes a transform from the given section.

Parameters:
  • cp (pycbc.workflow.WorkflowConfigParser) – A parsed configuration file that contains the transform options.

  • section (str) – Name of the section in the configuration file.

  • outputs (str) – The names of the parameters that are output by this transformation, separated by VARARGS_DELIM. These must appear in the “tag” part of the section header.

  • skip_opts (list, optional) – Do not read options in the given list.

  • additional_opts (dict, optional) – Any additional arguments to pass to the class. If an option is provided that also exists in the config file, the value provided will be used instead of being read from the file.

Returns:

An instance of the class.

Return type:

cls

inverse = None
inverse_jacobian(maps)[source]

The Jacobian for the outputs to inputs transformation.

inverse_transform(maps)[source]

The inverse conversions of transform. This function transforms from outputs to inputs.

jacobian(maps)[source]

The Jacobian for the inputs to outputs transformation.

name = None
transform(maps)[source]

This function transforms from inputs to outputs.

class pycbc.transforms.CartesianSpin1ToSphericalSpin1[source]

Bases: CartesianToSpherical

The inverse of SphericalSpin1ToCartesianSpin1.

Deprecation Warning: This will be removed in a future update. Use CartesianToSpherical with spin-parameter names passed in instead.

name = 'cartesian_spin_1_to_spherical_spin_1'
class pycbc.transforms.CartesianSpin2ToSphericalSpin2[source]

Bases: CartesianToSpherical

The inverse of SphericalSpin2ToCartesianSpin2.

Deprecation Warning: This will be removed in a future update. Use CartesianToSpherical with spin-parameter names passed in instead.

name = 'cartesian_spin_2_to_spherical_spin_2'
class pycbc.transforms.CartesianSpinToAlignedMassSpin[source]

Bases: AlignedMassSpinToCartesianSpin

The inverse of AlignedMassSpinToCartesianSpin.

inverse

alias of AlignedMassSpinToCartesianSpin

inverse_jacobian(maps)

The Jacobian for the inputs to outputs transformation.

inverse_transform(maps)

This function transforms from aligned mass-weighted spins to cartesian spins aligned along the z-axis.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)

The Jacobian for the outputs to inputs transformation.

name = 'cartesian_spin_to_aligned_mass_spin'
transform(maps)

This function transforms from component masses and cartesian spins to mass-weighted spin parameters aligned with the angular momentum.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.CartesianSpinToChiP[source]

Bases: BaseTransform

Converts cartesian spins to chi_p.

name = 'cartesian_spin_to_chi_p'
transform(maps)[source]

This function transforms from component masses and caretsian spins to chi_p.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.CartesianSpinToPrecessionMassSpin[source]

Bases: PrecessionMassSpinToCartesianSpin

The inverse of PrecessionMassSpinToCartesianSpin.

inverse

alias of PrecessionMassSpinToCartesianSpin

inverse_jacobian(maps)

The Jacobian for the inputs to outputs transformation.

inverse_transform(maps)

This function transforms from mass-weighted spins to caretsian spins in the x-y plane.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)

The Jacobian for the outputs to inputs transformation.

name = 'cartesian_spin_to_precession_mass_spin'
transform(maps)

This function transforms from component masses and cartesian spins to mass-weighted spin parameters perpendicular with the angular momentum.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.CartesianToSpherical(*args)[source]

Bases: SphericalToCartesian

Converts spherical coordinates to cartesian.

Parameters:
  • x (str) – The name of the x parameter.

  • y (str) – The name of the y parameter.

  • z (str) – The name of the z parameter.

  • radial (str) – The name of the radial parameter.

  • azimuthal (str) – The name of the azimuthal angle parameter.

  • polar (str) – The name of the polar angle parameter.

inverse

alias of SphericalToCartesian

inverse_jacobian(maps)

The Jacobian for the inputs to outputs transformation.

inverse_transform(maps)

This function transforms from spherical to cartesian spins.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.SphericalToCartesian('x', 'y', 'z',
                                        'a', 'phi', 'theta')
>>> t.transform({'a': numpy.array([0.1]), 'phi': numpy.array([0.1]),
                'theta': numpy.array([0.1])})
    {'a': array([ 0.1]), 'phi': array([ 0.1]), 'theta': array([ 0.1]),
     'x': array([ 0.00993347]), 'y': array([ 0.00099667]),
     'z': array([ 0.09950042])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)

The Jacobian for the outputs to inputs transformation.

name = 'cartesian_to_spherical'
transform(maps)

This function transforms from cartesian to spherical spins.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.ChiPToCartesianSpin[source]

Bases: CartesianSpinToChiP

The inverse of CartesianSpinToChiP.

inverse

alias of CartesianSpinToChiP

inverse_jacobian(maps)

The Jacobian for the inputs to outputs transformation.

inverse_transform(maps)

This function transforms from component masses and caretsian spins to chi_p.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)

The Jacobian for the outputs to inputs transformation.

name = 'cartesian_spin_to_chi_p'
transform(maps)

The inverse conversions of transform. This function transforms from outputs to inputs.

class pycbc.transforms.ChirpDistanceToDistance(ref_mass=1.4)[source]

Bases: BaseTransform

Converts chirp distance to luminosity distance, given the chirp mass.

inverse

alias of DistanceToChirpDistance

inverse_jacobian(maps)[source]

Returns the Jacobian for transforming luminosity distance to chirp distance, given the chirp mass.

inverse_transform(maps)[source]

This function transforms from luminosity distance to chirp distance, given the chirp mass.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy as np
>>> from pycbc import transforms
>>> t = transforms.ChirpDistanceToDistance()
>>> t.inverse_transform({'distance': np.array([40.]), 'mchirp': np.array([1.2])})
{'distance': array([ 40.]), 'chirp_distance': array([ 40.52073522]), 'mchirp': array([ 1.2])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)[source]

Returns the Jacobian for transforming chirp distance to luminosity distance, given the chirp mass.

name = 'chirp_distance_to_distance'
transform(maps)[source]

This function transforms from chirp distance to luminosity distance, given the chirp mass.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy as np
>>> from pycbc import transforms
>>> t = transforms.ChirpDistanceToDistance()
>>> t.transform({'chirp_distance': np.array([40.]), 'mchirp': np.array([1.2])})
{'mchirp': array([ 1.2]), 'chirp_distance': array([ 40.]), 'distance': array([ 39.48595679])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.CustomTransform(input_args, output_args, transform_functions, jacobian=None)[source]

Bases: BaseTransform

Allows for any transform to be defined.

Parameters:
  • input_args ((list of) str) – The names of the input parameters.

  • output_args ((list of) str) – The names of the output parameters.

  • transform_functions (dict) – Dictionary mapping input args to a string giving a function call; e.g., {'q': 'q_from_mass1_mass2(mass1, mass2)'}.

  • jacobian (str, optional) – String giving a jacobian function. The function must be in terms of the input arguments.

Examples

Create a custom transform that converts mass1, mass2 to mtotal, q:

>>> t = transforms.CustomTransform(['mass1', 'mass2'], ['mtotal', 'q'], {'mtotal': 'mass1+mass2', 'q': 'mass1/mass2'}, '(mass1 + mass2) / mass2**2')

Evaluate a pair of masses:

>>> t.transform({'mass1': 10., 'mass2': 5.})
{'mass1': 10.0, 'mass2': 5.0, 'mtotal': 15.0, 'q': 2.0}

The Jacobian for the same pair of masses:

>>> t.jacobian({'mass1': 10., 'mass2': 5.})
0.59999999999999998
classmethod from_config(cp, section, outputs)[source]

Loads a CustomTransform from the given config file.

Example section:

[{section}-outvar1+outvar2]
name = custom
inputs = inputvar1, inputvar2
outvar1 = func1(inputs)
outvar2 = func2(inputs)
jacobian = func(inputs)
jacobian(maps)[source]

The Jacobian for the inputs to outputs transformation.

name = 'custom'
transform(maps)[source]

Applies the transform functions to the given maps object.

Parameters:

maps (dict, or FieldArray) –

Returns:

A map object containing the transformed variables, along with the original variables. The type of the output will be the same as the input.

Return type:

dict or FieldArray

class pycbc.transforms.CustomTransformMultiOutputs(input_args, output_args, transform_functions, jacobian=None)[source]

Bases: CustomTransform

Allows for any transform to be defined. Based on CustomTransform, but also supports multi-returning value functions.

Parameters:
  • input_args ((list of) str) – The names of the input parameters.

  • output_args ((list of) str) – The names of the output parameters.

  • transform_functions (dict) – Dictionary mapping input args to a string giving a function call; e.g., {'q': 'q_from_mass1_mass2(mass1, mass2)'}.

  • jacobian (str, optional) – String giving a jacobian function. The function must be in terms of the input arguments.

classmethod from_config(cp, section, outputs)[source]

Loads a CustomTransformMultiOutputs from the given config file.

Example section:

[{section}-outvar1+outvar2]
name = custom_multi
inputs = inputvar1, inputvar2
outvar1, outvar2 = func1(inputs)
jacobian = func2(inputs)
name = 'custom_multi'
transform(maps)[source]

Applies the transform functions to the given maps object. :param maps: :type maps: dict, or FieldArray

Returns:

A map object containing the transformed variables, along with the original variables. The type of the output will be the same as the input.

Return type:

dict or FieldArray

class pycbc.transforms.DistanceToChirpDistance(ref_mass=1.4)[source]

Bases: ChirpDistanceToDistance

The inverse of ChirpDistanceToDistance.

inverse

alias of ChirpDistanceToDistance

inverse_jacobian(maps)

Returns the Jacobian for transforming chirp distance to luminosity distance, given the chirp mass.

inverse_transform(maps)

This function transforms from chirp distance to luminosity distance, given the chirp mass.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy as np
>>> from pycbc import transforms
>>> t = transforms.ChirpDistanceToDistance()
>>> t.transform({'chirp_distance': np.array([40.]), 'mchirp': np.array([1.2])})
{'mchirp': array([ 1.2]), 'chirp_distance': array([ 40.]), 'distance': array([ 39.48595679])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)

Returns the Jacobian for transforming luminosity distance to chirp distance, given the chirp mass.

name = 'distance_to_chirp_distance'
transform(maps)

This function transforms from luminosity distance to chirp distance, given the chirp mass.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy as np
>>> from pycbc import transforms
>>> t = transforms.ChirpDistanceToDistance()
>>> t.inverse_transform({'distance': np.array([40.]), 'mchirp': np.array([1.2])})
{'distance': array([ 40.]), 'chirp_distance': array([ 40.52073522]), 'mchirp': array([ 1.2])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.DistanceToRedshift[source]

Bases: BaseTransform

Converts distance to redshift.

inverse = None
name = 'distance_to_redshift'
transform(maps)[source]

This function transforms from distance to redshift.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.DistanceToRedshift()
>>> t.transform({'distance': numpy.array([1000])})
    {'distance': array([1000]), 'redshift': 0.19650987609144363}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.Exponent(inputvar, outputvar)[source]

Bases: Log

Applies an exponent transform to an inputvar parameter.

This is the inverse of the log transform.

Parameters:
  • inputvar (str) – The name of the parameter to transform.

  • outputvar (str) – The name of the transformed parameter.

inverse

alias of Log

inverse_jacobian(maps)

Computes the Jacobian of \(y = \log(x)\).

This is:

\[\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{1}{x}.\]
Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

The value of the jacobian at the given point(s).

Return type:

float

inverse_transform(maps)

Computes \(\log(x)\).

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

out – A map between the transformed variable name and value(s), along with the original variable name and value(s).

Return type:

dict or FieldArray

jacobian(maps)

Computes the Jacobian of \(y = e^{x}\).

This is:

\[\frac{\mathrm{d}y}{\mathrm{d}x} = e^{x}.\]
Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

The value of the jacobian at the given point(s).

Return type:

float

name = 'exponent'
transform(maps)

Computes \(y = e^{x}\).

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

out – A map between the transformed variable name and value(s), along with the original variable name and value(s).

Return type:

dict or FieldArray

class pycbc.transforms.GEOToLISA(tc_lisa_param=None, longitude_lisa_param=None, latitude_lisa_param=None, polarization_lisa_param=None, tc_geo_param=None, longitude_geo_param=None, latitude_geo_param=None, polarization_geo_param=None)[source]

Bases: LISAToGEO

The inverse of LISAToGEO.

inverse

alias of LISAToGEO

inverse_transform(maps)

This function transforms arrival time, sky localization, and polarization angle in the LISA frame to the corresponding values in the geocentric frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

name = 'geo_to_lisa'
transform(maps)

This function transforms arrival time, sky localization, and polarization angle in the geocentric frame to the corresponding values in the LISA frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.GEOToSSB(tc_geo_param=None, longitude_geo_param=None, latitude_geo_param=None, polarization_geo_param=None, tc_ssb_param=None, longitude_ssb_param=None, latitude_ssb_param=None, polarization_ssb_param=None)[source]

Bases: BaseTransform

Converts arrival time, sky localization, and polarization angle in the geocentric frame to the corresponding values in the SSB frame.

default_params_name = {'default_latitude_geo': 'dec', 'default_latitude_ssb': 'eclipticlatitude', 'default_longitude_geo': 'ra', 'default_longitude_ssb': 'eclipticlongitude', 'default_polarization_geo': 'polarization', 'default_polarization_ssb': 'polarization', 'default_tc_geo': 'tc', 'default_tc_ssb': 'tc'}
classmethod from_config(cp, section, outputs)[source]

Initializes a transform from the given section.

Parameters:
  • cp (pycbc.workflow.WorkflowConfigParser) – A parsed configuration file that contains the transform options.

  • section (str) – Name of the section in the configuration file.

  • outputs (str) – The names of the parameters that are output by this transformation, separated by VARARGS_DELIM. These must appear in the “tag” part of the section header.

  • skip_opts (list, optional) – Do not read options in the given list.

  • additional_opts (dict, optional) – Any additional arguments to pass to the class. If an option is provided that also exists in the config file, the value provided will be used instead of being read from the file.

Returns:

An instance of the class.

Return type:

cls

inverse

alias of SSBToGEO

inverse_transform(maps)[source]

This function transforms arrival time, sky localization, and polarization angle in the SSB frame to the corresponding values in the geocentric frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

name = 'geo_to_ssb'
transform(maps)[source]

This function transforms arrival time, sky localization, and polarization angle in the geocentric frame to the corresponding values in the SSB frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.LISAToGEO(tc_lisa_param=None, longitude_lisa_param=None, latitude_lisa_param=None, polarization_lisa_param=None, tc_geo_param=None, longitude_geo_param=None, latitude_geo_param=None, polarization_geo_param=None)[source]

Bases: BaseTransform

Converts arrival time, sky localization, and polarization angle in the LISA frame to the corresponding values in the geocentric frame.

default_params_name = {'default_latitude_geo': 'dec', 'default_latitude_lisa': 'eclipticlatitude', 'default_longitude_geo': 'ra', 'default_longitude_lisa': 'eclipticlongitude', 'default_polarization_geo': 'polarization', 'default_polarization_lisa': 'polarization', 'default_tc_geo': 'tc', 'default_tc_lisa': 'tc'}
classmethod from_config(cp, section, outputs)[source]

Initializes a transform from the given section.

Parameters:
  • cp (pycbc.workflow.WorkflowConfigParser) – A parsed configuration file that contains the transform options.

  • section (str) – Name of the section in the configuration file.

  • outputs (str) – The names of the parameters that are output by this transformation, separated by VARARGS_DELIM. These must appear in the “tag” part of the section header.

  • skip_opts (list, optional) – Do not read options in the given list.

  • additional_opts (dict, optional) – Any additional arguments to pass to the class. If an option is provided that also exists in the config file, the value provided will be used instead of being read from the file.

Returns:

An instance of the class.

Return type:

cls

inverse

alias of GEOToLISA

inverse_transform(maps)[source]

This function transforms arrival time, sky localization, and polarization angle in the geocentric frame to the corresponding values in the LISA frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

name = 'lisa_to_geo'
transform(maps)[source]

This function transforms arrival time, sky localization, and polarization angle in the LISA frame to the corresponding values in the geocentric frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.LISAToSSB(tc_lisa_param=None, longitude_lisa_param=None, latitude_lisa_param=None, polarization_lisa_param=None, tc_ssb_param=None, longitude_ssb_param=None, latitude_ssb_param=None, polarization_ssb_param=None)[source]

Bases: BaseTransform

Converts arrival time, sky localization, and polarization angle in the LISA frame to the corresponding values in the SSB frame.

default_params_name = {'default_latitude_lisa': 'eclipticlatitude', 'default_latitude_ssb': 'eclipticlatitude', 'default_longitude_lisa': 'eclipticlongitude', 'default_longitude_ssb': 'eclipticlongitude', 'default_polarization_lisa': 'polarization', 'default_polarization_ssb': 'polarization', 'default_tc_lisa': 'tc', 'default_tc_ssb': 'tc'}
classmethod from_config(cp, section, outputs)[source]

Initializes a transform from the given section.

Parameters:
  • cp (pycbc.workflow.WorkflowConfigParser) – A parsed configuration file that contains the transform options.

  • section (str) – Name of the section in the configuration file.

  • outputs (str) – The names of the parameters that are output by this transformation, separated by VARARGS_DELIM. These must appear in the “tag” part of the section header.

  • skip_opts (list, optional) – Do not read options in the given list.

  • additional_opts (dict, optional) – Any additional arguments to pass to the class. If an option is provided that also exists in the config file, the value provided will be used instead of being read from the file.

Returns:

An instance of the class.

Return type:

cls

inverse

alias of SSBToLISA

inverse_transform(maps)[source]

This function transforms arrival time, sky localization, and polarization angle in the SSB frame to the corresponding values in the LISA frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

name = 'lisa_to_ssb'
transform(maps)[source]

This function transforms arrival time, sky localization, and polarization angle in the LISA frame to the corresponding values in the SSB frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.LambdaFromMultipleTOVFiles(mass_param, lambda_param, map_file, distance=None, redshift_mass=True, file_columns=None)[source]

Bases: BaseTransform

Uses multiple equation of states.

Parameters:
  • mass_param (str) – The name of the mass parameter to transform.

  • lambda_param (str) – The name of the tidal deformability parameter that mass_param is to be converted to interpolating from the data in the mass-Lambda file.

  • mass_lambda_file (str) – Path of the mass-Lambda data file. The first column in the data file should contain mass values, and the second column Lambda values.

  • distance (float, optional) – The distance (in Mpc) of the source. Used to redshift the mass. If None, then a distance must be provided to the transform.

  • file_columns (list of str, optional) – The names and order of columns in the mass_lambda_file. Must contain at least ‘mass’ and ‘lambda’. If not provided, will assume the order is (‘radius’, ‘mass’, ‘lambda’).

property distance

Returns the fixed distance to transform mass samples from detector to source frame if one is specified.

classmethod from_config(cp, section, outputs)[source]

Initializes a transform from the given section.

Parameters:
  • cp (pycbc.workflow.WorkflowConfigParser) – A parsed configuration file that contains the transform options.

  • section (str) – Name of the section in the configuration file.

  • outputs (str) – The names of the parameters that are output by this transformation, separated by VARARGS_DELIM. These must appear in the “tag” part of the section header.

  • skip_opts (list, optional) – Do not read options in the given list.

  • additional_opts (dict, optional) – Any additional arguments to pass to the class. If an option is provided that also exists in the config file, the value provided will be used instead of being read from the file.

Returns:

An instance of the class.

Return type:

cls

get_eos(eos_index)[source]

Gets the EOS for the given index.

If the index is not in range returns None.

property lambda_param

Returns the output lambda parameter.

property map_file

Returns the mass data read from the mass-Lambda data file for an EOS.

property mass_param

Returns the input mass parameter.

name = 'lambda_from_multiple_tov_files'
transform(maps)[source]

Transforms mass value and eos index into a lambda value

class pycbc.transforms.LambdaFromTOVFile(mass_param, lambda_param, mass_lambda_file, distance=None, redshift_mass=True, file_columns=None)[source]

Bases: BaseTransform

Transforms mass values corresponding to Lambda values for a given EOS interpolating from the mass-Lambda data for that EOS read in from an external ASCII file.

The interpolation of the mass-Lambda data is a one-dimensional piecewise linear interpolation. If the redshift_mass keyword argument is True (the default), the mass values to be transformed are assumed to be detector frame masses. In that case, a distance should be provided along with the mass for transformation to the source frame mass before the Lambda values are extracted from the interpolation. If the transform is read in from a config file, an example code block would be:

[{section}-lambda1]
name = lambda_from_tov_file
mass_param = mass1
lambda_param = lambda1
distance = 40
mass_lambda_file = {filepath}

If this transform is used in a parameter estimation analysis where distance is a variable parameter, the distance to be used will vary with each draw. In that case, the example code block will be:

[{section}-lambda1]
name = lambda_from_tov_file
mass_param = mass1
lambda_param = lambda1
mass_lambda_file = filepath

If your prior is in terms of the source-frame masses (srcmass), then you can shut off the redshifting by adding do-not-redshift-mass to the config file. In this case you do not need to worry about a distance. Example:

[{section}-lambda1]
name = lambda_from_tov_file
mass_param = srcmass1
lambda_param = lambda1
mass_lambda_file = filepath
do-not-redshift-mass =
Parameters:
  • mass_param (str) – The name of the mass parameter to transform.

  • lambda_param (str) – The name of the tidal deformability parameter that mass_param is to be converted to interpolating from the data in the mass-Lambda file.

  • mass_lambda_file (str) – Path of the mass-Lambda data file. The first column in the data file should contain mass values, and the second column Lambda values.

  • distance (float, optional) – The distance (in Mpc) of the source. Used to redshift the mass. Needed if redshift_mass is True and no distance parameter exists If None, then a distance must be provided to the transform.

  • redshift_mass (bool, optional) – Redshift the mass parameters when computing the lambdas. Default is False.

  • file_columns (list of str, optional) – The names and order of columns in the mass_lambda_file. Must contain at least ‘mass’ and ‘lambda’. If not provided, will assume the order is (‘mass’, ‘lambda’).

property data
property distance

Returns the fixed distance to transform mass samples from detector to source frame if one is specified.

classmethod from_config(cp, section, outputs)[source]

Initializes a transform from the given section.

Parameters:
  • cp (pycbc.workflow.WorkflowConfigParser) – A parsed configuration file that contains the transform options.

  • section (str) – Name of the section in the configuration file.

  • outputs (str) – The names of the parameters that are output by this transformation, separated by VARARGS_DELIM. These must appear in the “tag” part of the section header.

  • skip_opts (list, optional) – Do not read options in the given list.

  • additional_opts (dict, optional) – Any additional arguments to pass to the class. If an option is provided that also exists in the config file, the value provided will be used instead of being read from the file.

Returns:

An instance of the class.

Return type:

cls

property lambda_data

Returns the Lambda data read from the mass-Lambda data file for an EOS.

static lambda_from_tov_data(m_src, mass_data, lambda_data)[source]

Returns Lambda corresponding to a given mass interpolating from the TOV data.

Parameters:
  • m (float) – Value of the mass.

  • mass_data (array) – Mass array from the Lambda-M curve of an EOS.

  • lambda_data (array) – Lambda array from the Lambda-M curve of an EOS.

Returns:

lambdav – The Lambda corresponding to the mass m for the EOS considered.

Return type:

float

property lambda_param

Returns the output lambda parameter.

property mass_data

Returns the mass data read from the mass-Lambda data file for an EOS.

property mass_param

Returns the input mass parameter.

name = 'lambda_from_tov_file'
transform(maps)[source]

Computes the transformation of mass to Lambda.

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

out – A map between the transformed variable name and value(s), along with the original variable name and value(s).

Return type:

dict or FieldArray

class pycbc.transforms.Log(inputvar, outputvar)[source]

Bases: BaseTransform

Applies a log transform from an inputvar parameter to an outputvar parameter. This is the inverse of the exponent transform.

Parameters:
  • inputvar (str) – The name of the parameter to transform.

  • outputvar (str) – The name of the transformed parameter.

property inputvar

Returns the input parameter.

inverse

alias of Exponent

inverse_jacobian(maps)[source]

Computes the Jacobian of \(y = e^{x}\).

This is:

\[\frac{\mathrm{d}y}{\mathrm{d}x} = e^{x}.\]
Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

The value of the jacobian at the given point(s).

Return type:

float

inverse_transform(maps)[source]

Computes \(y = e^{x}\).

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

out – A map between the transformed variable name and value(s), along with the original variable name and value(s).

Return type:

dict or FieldArray

jacobian(maps)[source]

Computes the Jacobian of \(y = \log(x)\).

This is:

\[\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{1}{x}.\]
Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

The value of the jacobian at the given point(s).

Return type:

float

name = 'log'
property outputvar

Returns the output parameter.

transform(maps)[source]

Computes \(\log(x)\).

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

out – A map between the transformed variable name and value(s), along with the original variable name and value(s).

Return type:

dict or FieldArray

class pycbc.transforms.Logistic(inputvar, outputvar, codomain=(0.0, 1.0))[source]

Bases: Logit

Applies a logistic transform from an input parameter to an output parameter. This is the inverse of the logit transform.

Typically, the output of the logistic function has range \(\in [0,1)\). However, the codomain argument can be used to expand this to any finite real interval.

Parameters:
  • inputvar (str) – The name of the parameter to transform.

  • outputvar (str) – The name of the transformed parameter.

  • frange (tuple or distributions.bounds.Bounds, optional) – The range of the output parameter. Can be any finite interval. Default is (0., 1.).

property bounds

Returns the range of the output parameter.

classmethod from_config(cp, section, outputs, skip_opts=None, additional_opts=None)[source]

Initializes a Logistic transform from the given section.

The section must specify an input and output variable name. The codomain of the output may be specified using min-{output}, max-{output}. Example:

[{section}-q]
name = logistic
inputvar = logitq
outputvar = q
min-q = 1
max-q = 8
Parameters:
  • cp (pycbc.workflow.WorkflowConfigParser) – A parsed configuration file that contains the transform options.

  • section (str) – Name of the section in the configuration file.

  • outputs (str) – The names of the parameters that are output by this transformation, separated by VARARGS_DELIM. These must appear in the “tag” part of the section header.

  • skip_opts (list, optional) – Do not read options in the given list.

  • additional_opts (dict, optional) – Any additional arguments to pass to the class. If an option is provided that also exists in the config file, the value provided will be used instead of being read from the file.

Returns:

An instance of the class.

Return type:

cls

inverse

alias of Logit

inverse_jacobian(maps)

Computes the Jacobian of \(y = \mathrm{logit}(x; a,b)\).

This is:

\[\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{b -a}{(x-a)(b-x)},\]

where \(x \in (a, b)\).

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

The value of the jacobian at the given point(s).

Return type:

float

inverse_transform(maps)

Computes \(\mathrm{logit}(x; a, b)\).

The domain \(a, b\) of \(x\) are given by the class’s bounds.

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

out – A map between the transformed variable name and value(s), along with the original variable name and value(s).

Return type:

dict or FieldArray

jacobian(maps)

Computes the Jacobian of \(y = \mathrm{logistic}(x; a,b)\).

This is:

\[\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{e^x (b-a)}{(1+e^y)^2},\]

where \(y \in (a, b)\).

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

The value of the jacobian at the given point(s).

Return type:

float

name = 'logistic'
transform(maps)

Computes \(y = \mathrm{logistic}(x; a,b)\).

The codomain \(a, b\) of \(y\) are given by the class’s bounds.

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

out – A map between the transformed variable name and value(s), along with the original variable name and value(s).

Return type:

dict or FieldArray

class pycbc.transforms.Logit(inputvar, outputvar, domain=(0.0, 1.0))[source]

Bases: BaseTransform

Applies a logit transform from an inputvar parameter to an outputvar parameter. This is the inverse of the logistic transform.

Typically, the input of the logit function is assumed to have domain \(\in (0, 1)\). However, the domain argument can be used to expand this to any finite real interval.

Parameters:
  • inputvar (str) – The name of the parameter to transform.

  • outputvar (str) – The name of the transformed parameter.

  • domain (tuple or distributions.bounds.Bounds, optional) – The domain of the input parameter. Can be any finite interval. Default is (0., 1.).

property bounds

Returns the domain of the input parameter.

classmethod from_config(cp, section, outputs, skip_opts=None, additional_opts=None)[source]

Initializes a Logit transform from the given section.

The section must specify an input and output variable name. The domain of the input may be specified using min-{input}, max-{input}. Example:

[{section}-logitq]
name = logit
inputvar = q
outputvar = logitq
min-q = 1
max-q = 8
Parameters:
  • cp (pycbc.workflow.WorkflowConfigParser) – A parsed configuration file that contains the transform options.

  • section (str) – Name of the section in the configuration file.

  • outputs (str) – The names of the parameters that are output by this transformation, separated by VARARGS_DELIM. These must appear in the “tag” part of the section header.

  • skip_opts (list, optional) – Do not read options in the given list.

  • additional_opts (dict, optional) – Any additional arguments to pass to the class. If an option is provided that also exists in the config file, the value provided will be used instead of being read from the file.

Returns:

An instance of the class.

Return type:

cls

property inputvar

Returns the input parameter.

inverse

alias of Logistic

inverse_jacobian(maps)[source]

Computes the Jacobian of \(y = \mathrm{logistic}(x; a,b)\).

This is:

\[\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{e^x (b-a)}{(1+e^y)^2},\]

where \(y \in (a, b)\).

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

The value of the jacobian at the given point(s).

Return type:

float

inverse_transform(maps)[source]

Computes \(y = \mathrm{logistic}(x; a,b)\).

The codomain \(a, b\) of \(y\) are given by the class’s bounds.

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

out – A map between the transformed variable name and value(s), along with the original variable name and value(s).

Return type:

dict or FieldArray

jacobian(maps)[source]

Computes the Jacobian of \(y = \mathrm{logit}(x; a,b)\).

This is:

\[\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{b -a}{(x-a)(b-x)},\]

where \(x \in (a, b)\).

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

The value of the jacobian at the given point(s).

Return type:

float

static logistic(x, a=0.0, b=1.0)[source]

Computes the logistic function with range \(\in (a, b)\).

This is given by:

\[\mathrm{logistic}(x; a, b) = \frac{a + b e^x}{1 + e^x}.\]

Note that this is also the inverse of the logit function with domain \((a, b)\).

Parameters:
  • x (float) – The value to evaluate.

  • a (float, optional) – The minimum bound of the range of the logistic function. Default is 0.

  • b (float, optional) – The maximum bound of the range of the logistic function. Default is 1.

Returns:

The logistic of x.

Return type:

float

static logit(x, a=0.0, b=1.0)[source]

Computes the logit function with domain \(x \in (a, b)\).

This is given by:

\[\mathrm{logit}(x; a, b) = \log\left(\frac{x-a}{b-x}\right).\]

Note that this is also the inverse of the logistic function with range \((a, b)\).

Parameters:
  • x (float) – The value to evaluate.

  • a (float, optional) – The minimum bound of the domain of x. Default is 0.

  • b (float, optional) – The maximum bound of the domain of x. Default is 1.

Returns:

The logit of x.

Return type:

float

name = 'logit'
property outputvar

Returns the output parameter.

transform(maps)[source]

Computes \(\mathrm{logit}(x; a, b)\).

The domain \(a, b\) of \(x\) are given by the class’s bounds.

Parameters:

maps (dict or FieldArray) – A dictionary or FieldArray which provides a map between the parameter name of the variable to transform and its value(s).

Returns:

out – A map between the transformed variable name and value(s), along with the original variable name and value(s).

Return type:

dict or FieldArray

class pycbc.transforms.Mass1Mass2ToMchirpEta[source]

Bases: MchirpEtaToMass1Mass2

The inverse of MchirpEtaToMass1Mass2.

inverse

alias of MchirpEtaToMass1Mass2

inverse_jacobian(maps)

Returns the Jacobian for transforming mchirp and eta to mass1 and mass2.

inverse_transform(maps)

This function transforms from chirp mass and symmetric mass ratio to component masses.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpEtaToMass1Mass2()
>>> t.transform({'mchirp': numpy.array([10.]), 'eta': numpy.array([0.25])})
{'mass1': array([ 16.4375183]), 'mass2': array([ 8.21875915]),
 'mchirp': array([ 10.]), 'eta': array([ 0.25])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)

Returns the Jacobian for transforming mass1 and mass2 to mchirp and eta.

name = 'mass1_mass2_to_mchirp_eta'
transform(maps)

This function transforms from component masses to chirp mass and symmetric mass ratio.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.inverse_transform({'mass1': numpy.array([8.2]), 'mass2': numpy.array([8.2])})
    {'mass1': array([ 8.2]), 'mass2': array([ 8.2]),
     'mchirp': array([ 9.97717521]), 'eta': 0.25}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.Mass1Mass2ToMchirpQ(mass1_param=None, mass2_param=None, mchirp_param=None, q_param=None)[source]

Bases: MchirpQToMass1Mass2

The inverse of MchirpQToMass1Mass2.

inverse

alias of MchirpQToMass1Mass2

inverse_jacobian(maps)

Returns the Jacobian for transforming mchirp and q to mass1 and mass2.

inverse_transform(maps)

This function transforms from chirp mass and mass ratio to component masses.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.transform({'mchirp': numpy.array([10.]), 'q': numpy.array([2.])})
{'mass1': array([ 16.4375183]), 'mass2': array([ 8.21875915]),
 'mchirp': array([ 10.]), 'q': array([ 2.])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)

Returns the Jacobian for transforming mass1 and mass2 to mchirp and q.

name = 'mass1_mass2_to_mchirp_q'
transform(maps)

This function transforms from component masses to chirp mass and mass ratio.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.inverse_transform({'mass1': numpy.array([16.4]), 'mass2': numpy.array([8.2])})
    {'mass1': array([ 16.4]), 'mass2': array([ 8.2]),
     'mchirp': array([ 9.97717521]), 'q': 2.0}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.MchirpEtaToMass1Mass2[source]

Bases: BaseTransform

Converts chirp mass and symmetric mass ratio to component masses.

inverse_jacobian(maps)[source]

Returns the Jacobian for transforming mass1 and mass2 to mchirp and eta.

inverse_transform(maps)[source]

This function transforms from component masses to chirp mass and symmetric mass ratio.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.inverse_transform({'mass1': numpy.array([8.2]), 'mass2': numpy.array([8.2])})
    {'mass1': array([ 8.2]), 'mass2': array([ 8.2]),
     'mchirp': array([ 9.97717521]), 'eta': 0.25}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)[source]

Returns the Jacobian for transforming mchirp and eta to mass1 and mass2.

name = 'mchirp_eta_to_mass1_mass2'
transform(maps)[source]

This function transforms from chirp mass and symmetric mass ratio to component masses.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpEtaToMass1Mass2()
>>> t.transform({'mchirp': numpy.array([10.]), 'eta': numpy.array([0.25])})
{'mass1': array([ 16.4375183]), 'mass2': array([ 8.21875915]),
 'mchirp': array([ 10.]), 'eta': array([ 0.25])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.MchirpQToMass1Mass2(mass1_param=None, mass2_param=None, mchirp_param=None, q_param=None)[source]

Bases: BaseTransform

Converts chirp mass and mass ratio to component masses.

inverse

alias of Mass1Mass2ToMchirpQ

inverse_jacobian(maps)[source]

Returns the Jacobian for transforming mass1 and mass2 to mchirp and q.

inverse_transform(maps)[source]

This function transforms from component masses to chirp mass and mass ratio.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.inverse_transform({'mass1': numpy.array([16.4]), 'mass2': numpy.array([8.2])})
    {'mass1': array([ 16.4]), 'mass2': array([ 8.2]),
     'mchirp': array([ 9.97717521]), 'q': 2.0}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

jacobian(maps)[source]

Returns the Jacobian for transforming mchirp and q to mass1 and mass2.

name = 'mchirp_q_to_mass1_mass2'
transform(maps)[source]

This function transforms from chirp mass and mass ratio to component masses.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.MchirpQToMass1Mass2()
>>> t.transform({'mchirp': numpy.array([10.]), 'q': numpy.array([2.])})
{'mass1': array([ 16.4375183]), 'mass2': array([ 8.21875915]),
 'mchirp': array([ 10.]), 'q': array([ 2.])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.PrecessionMassSpinToCartesianSpin[source]

Bases: BaseTransform

Converts mass-weighted spins to cartesian x-y plane spins.

inverse

alias of CartesianSpinToPrecessionMassSpin

inverse_transform(maps)[source]

This function transforms from component masses and cartesian spins to mass-weighted spin parameters perpendicular with the angular momentum.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

name = 'precession_mass_spin_to_cartesian_spin'
transform(maps)[source]

This function transforms from mass-weighted spins to caretsian spins in the x-y plane.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.SSBToGEO(tc_geo_param=None, longitude_geo_param=None, latitude_geo_param=None, polarization_geo_param=None, tc_ssb_param=None, longitude_ssb_param=None, latitude_ssb_param=None, polarization_ssb_param=None)[source]

Bases: GEOToSSB

The inverse of GEOToSSB.

inverse

alias of GEOToSSB

inverse_transform(maps)

This function transforms arrival time, sky localization, and polarization angle in the geocentric frame to the corresponding values in the SSB frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

name = 'ssb_to_geo'
transform(maps)

This function transforms arrival time, sky localization, and polarization angle in the SSB frame to the corresponding values in the geocentric frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.SSBToLISA(tc_lisa_param=None, longitude_lisa_param=None, latitude_lisa_param=None, polarization_lisa_param=None, tc_ssb_param=None, longitude_ssb_param=None, latitude_ssb_param=None, polarization_ssb_param=None)[source]

Bases: LISAToSSB

The inverse of LISAToSSB.

inverse

alias of LISAToSSB

inverse_transform(maps)

This function transforms arrival time, sky localization, and polarization angle in the LISA frame to the corresponding values in the SSB frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

name = 'ssb_to_lisa'
transform(maps)

This function transforms arrival time, sky localization, and polarization angle in the SSB frame to the corresponding values in the LISA frame.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

class pycbc.transforms.SphericalSpin1ToCartesianSpin1[source]

Bases: SphericalToCartesian

Converts spherical spin parameters (radial and two angles) to catesian spin parameters. This class only transforms spsins for the first component mass.

Deprecation Warning: This will be removed in a future update. Use SphericalToCartesian with spin-parameter names passed in instead.

inverse

alias of CartesianSpin1ToSphericalSpin1

name = 'spherical_spin_1_to_cartesian_spin_1'
class pycbc.transforms.SphericalSpin2ToCartesianSpin2[source]

Bases: SphericalToCartesian

Converts spherical spin parameters (radial and two angles) to catesian spin parameters. This class only transforms spsins for the first component mass.

Deprecation Warning: This will be removed in a future update. Use SphericalToCartesian with spin-parameter names passed in instead.

inverse

alias of CartesianSpin2ToSphericalSpin2

name = 'spherical_spin_2_to_cartesian_spin_2'
class pycbc.transforms.SphericalToCartesian(x, y, z, radial, azimuthal, polar)[source]

Bases: BaseTransform

Converts spherical coordinates to cartesian.

Parameters:
  • x (str) – The name of the x parameter.

  • y (str) – The name of the y parameter.

  • z (str) – The name of the z parameter.

  • radial (str) – The name of the radial parameter.

  • azimuthal (str) – The name of the azimuthal angle parameter.

  • polar (str) – The name of the polar angle parameter.

inverse

alias of CartesianToSpherical

inverse_transform(maps)[source]

This function transforms from cartesian to spherical spins.

Parameters:

maps (a mapping object) –

Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

name = 'spherical_to_cartesian'
transform(maps)[source]

This function transforms from spherical to cartesian spins.

Parameters:

maps (a mapping object) –

Examples

Convert a dict of numpy.array:

>>> import numpy
>>> from pycbc import transforms
>>> t = transforms.SphericalToCartesian('x', 'y', 'z',
                                        'a', 'phi', 'theta')
>>> t.transform({'a': numpy.array([0.1]), 'phi': numpy.array([0.1]),
                'theta': numpy.array([0.1])})
    {'a': array([ 0.1]), 'phi': array([ 0.1]), 'theta': array([ 0.1]),
     'x': array([ 0.00993347]), 'y': array([ 0.00099667]),
     'z': array([ 0.09950042])}
Returns:

out – A dict with key as parameter name and value as numpy.array or float of transformed values.

Return type:

dict

pycbc.transforms.apply_transforms(samples, transforms, inverse=False)[source]

Applies a list of BaseTransform instances on a mapping object.

Parameters:
  • samples ({FieldArray, dict}) – Mapping object to apply transforms to.

  • transforms (list) – List of BaseTransform instances to apply. Nested transforms are assumed to be in order for forward transforms.

  • inverse (bool, optional) – Apply inverse transforms. In this case transforms will be applied in the opposite order. Default is False.

Returns:

samples – Mapping object with transforms applied. Same type as input.

Return type:

{FieldArray, dict}

pycbc.transforms.compute_jacobian(samples, transforms, inverse=False)[source]

Computes the jacobian of the list of transforms at the given sample points.

Parameters:
  • samples ({FieldArray, dict}) – Mapping object specifying points at which to compute jacobians.

  • transforms (list) – List of BaseTransform instances to apply. Nested transforms are assumed to be in order for forward transforms.

  • inverse (bool, optional) – Compute inverse jacobians. Default is False.

Returns:

The product of the jacobians of all fo the transforms.

Return type:

float

pycbc.transforms.get_common_cbc_transforms(requested_params, variable_args, valid_params=None)[source]

Determines if any additional parameters from the InferenceFile are needed to get derived parameters that user has asked for.

First it will try to add any base parameters that are required to calculate the derived parameters. Then it will add any sampling parameters that are required to calculate the base parameters needed.

Parameters:
  • requested_params (list) – List of parameters that user wants.

  • variable_args (list) – List of parameters that InferenceFile has.

  • valid_params (list) – List of parameters that can be accepted.

Returns:

  • requested_params (list) – Updated list of parameters that user wants.

  • all_c (list) – List of BaseTransforms to apply.

pycbc.transforms.order_transforms(transforms)[source]

Orders transforms to ensure proper chaining.

For example, if transforms = [B, A, C], and A produces outputs needed by B, the transforms will be re-rorderd to [A, B, C].

Parameters:
  • transforms (list) – List of transform instances to order.

  • Outputs

  • -------

  • list – List of transformed ordered such that forward transforms can be carried out without error.

pycbc.transforms.read_transforms_from_config(cp, section='transforms')[source]

Returns a list of PyCBC transform instances for a section in the given configuration file.

If the transforms are nested (i.e., the output of one transform is the input of another), the returned list will be sorted by the order of the nests.

Parameters:
  • cp (WorflowConfigParser) – An open config file to read.

  • section ({"transforms", string}) – Prefix on section names from which to retrieve the transforms.

Returns:

A list of the parsed transforms.

Return type:

list

pycbc.version module

Module contents

PyCBC contains a toolkit for CBC gravitational wave analysis

class pycbc.LogFormatter(fmt=None, datefmt=None, style='%', validate=True)[source]

Bases: Formatter

Format the logging appropriately This will return the log time in the ISO 6801 standard, but with millisecond precision https://en.wikipedia.org/wiki/ISO_8601 e.g. 2022-11-18T09:53:01.554+00:00

converter()

timestamp[, tz] -> tz’s local time from POSIX timestamp.

formatTime(record, datefmt=None)[source]

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

pycbc.add_common_pycbc_options(parser)[source]

Common utility to add standard options to each PyCBC executable.

Parameters:

parser (argparse.ArgumentParser) – The argument parser to which the options will be added

pycbc.gps_now()[source]

Return the current GPS time as a float using Astropy.

pycbc.init_logging(verbose=False, format='%(asctime)s %(levelname)s : %(message)s')[source]

Common utility for setting up logging in PyCBC.

Installs a signal handler such that verbosity can be activated at run-time by sending a SIGUSR1 to the process.

Parameters:
  • verbose (bool or int, optional) – What level to set the verbosity level to. Accepts either a boolean or an integer representing the level to set. If True/False will set to logging.INFO/logging.WARN. For higher logging levels, pass an integer representing the level to set. (1 = INFO, 2 = DEBUG).

  • format (str, optional) – The format to use for logging messages.

pycbc.makedir(path)[source]

Make the analysis directory path and any parent directories that don’t already exist. Will do nothing if path already exists.

pycbc.random_string(stringLength=10)[source]

Generate a random string of fixed length