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: pycbc.bin_utils.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: pycbc.bin_utils.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: pycbc.bin_utils.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: pycbc.bin_utils.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: pycbc.bin_utils.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[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.
min

The minimum bound.

Type:_Bound instance
max

The maximum bound.

Type:_Bound instance
cyclic

Whether the bounds are cyclic or not.

Type:bool

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
cyclic
max
min
class pycbc.boundaries.ClosedBound[source]

Bases: pycbc.boundaries._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[source]

Bases: pycbc.boundaries._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[source]

Bases: pycbc.boundaries.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 modules 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.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.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.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.primary_mass(mass1, mass2)[source]

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

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

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

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

Returns the total mass from mass1 and mass2.

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

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

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

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

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

Returns the symmetric mass ratio from mass1 and mass2.

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

Returns the chirp mass from mass1 and mass2.

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.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.mass1_from_mtotal_eta(mtotal, eta)[source]

Returns the primary mass from the total mass and symmetric 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.mtotal_from_mchirp_eta(mchirp, eta)[source]

Returns the total mass from the chirp 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.mass2_from_mchirp_eta(mchirp, eta)[source]

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

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.mass1_from_mass2_eta(mass2, eta, force_real=True)[source]

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

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.mass1_from_mchirp_q(mchirp, q)[source]

Returns the primary mass from the given chirp mass and 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.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_mtotal_eta(mtotal, eta, f_lower)[source]

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

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

Returns \(\tau_0\) from the component masses and 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.mtotal_from_tau0_tau3(tau0, tau3, f_lower, in_seconds=False)[source]

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

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

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

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_tau0_tau3(tau0, tau3, f_lower)[source]

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

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

Returns the dimensionless spin of the primary mass.

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

Returns the dimensionless spin of the secondary mass.

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

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

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_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y)[source]

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

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

Returns the angle between the in-plane perpendicular spins.

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

Returns the sum of the in-plane perpendicular spins.

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

Returns the effective precession spin argument for the larger mass.

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

Returns the effective precession spin argument for the smaller mass.

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.conversions.chi_perp_from_spinx_spiny(spinx, spiny)[source]

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

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_p_from_xi1_xi2(xi1, xi2)[source]

Returns effective precession spin from xi1 and xi2.

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

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

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.spin1z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a)[source]

Returns spin1z.

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

Returns spin2z.

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.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.chirp_distance(dist, mchirp, ref_mass=1.4)[source]

Returns the chirp distance given the luminosity distance and chirp 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.freq_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1)[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.
  • nmodes (int, optional) – The number of overtones to generate. Default is 1.
Returns:

The frequency of the QNM(s), in Hz. If only a single mode is requested (and mass, spin, l, and m are not arrays), this will be a float. If multiple modes requested, will be an array with shape [input shape x] nmodes, where input shape is the broadcasted shape of the inputs.

Return type:

float or array

pycbc.conversions.tau_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1)[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.
  • nmodes (int, optional) – The number of overtones to generate. Default is 1.
Returns:

The damping time of the QNM(s), in seconds. If only a single mode is requested (and mass, spin, l, and m are not arrays), this will be a float. If multiple modes requested, will be an array with shape [input shape x] nmodes, where input shape is the broadcasted shape of the inputs.

Return type:

float or array

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_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='SEOBNRv4')[source]

Estimates the final mass from the given initial parameters.

This uses the fits used by the EOBNR models for converting from initial parameters to final. Which version used can be controlled by 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. Default is “SEOBNRv4”.
Returns:

The final mass, in solar masses.

Return type:

float

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='SEOBNRv4')[source]

Estimates the final spin from the given initial parameters.

This uses the fits used by the EOBNR models for converting from initial parameters to final. Which version used can be controlled by 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. Default is “SEOBNRv4”.
Returns:

The dimensionless final spin.

Return type:

float

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_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.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.coordinates module

Coordinate transformations.

pycbc.coordinates.cartesian_to_spherical_rho(x, y, z)[source]

Calculates the magnitude in spherical coordinates from Cartesian coordinates.

Parameters:
  • x ({numpy.array, float}) – X-coordinate.
  • y ({numpy.array, float}) – Y-coordinate.
  • z ({numpy.array, float}) – Z-coordinate.
Returns:

rho – The radial amplitude.

Return type:

{numpy.array, float}

pycbc.coordinates.cartesian_to_spherical_azimuthal(x, y)[source]

Calculates the azimuthal angle in spherical coordinates from Cartesian coordinates. The azimuthal angle is in [0,2*pi].

Parameters:
  • x ({numpy.array, float}) – X-coordinate.
  • y ({numpy.array, float}) – Y-coordinate.
Returns:

phi – The azimuthal angle.

Return type:

{numpy.array, float}

pycbc.coordinates.cartesian_to_spherical_polar(x, y, z)[source]

Calculates the polar angle in spherical coordinates from Cartesian coordinates. The polar angle is in [0,pi].

Parameters:
  • x ({numpy.array, float}) – X-coordinate.
  • y ({numpy.array, float}) – Y-coordinate.
  • z ({numpy.array, float}) – Z-coordinate.
Returns:

theta – The polar angle.

Return type:

{numpy.array, float}

pycbc.coordinates.cartesian_to_spherical(x, y, z)[source]

Maps cartesian coordinates (x,y,z) to spherical coordinates (rho,phi,theta) where phi is in [0,2*pi] and theta is in [0,pi].

Parameters:
  • x ({numpy.array, float}) – X-coordinate.
  • y ({numpy.array, float}) – Y-coordinate.
  • z ({numpy.array, float}) – Z-coordinate.
Returns:

  • rho ({numpy.array, float}) – The radial amplitude.
  • phi ({numpy.array, float}) – The azimuthal angle.
  • theta ({numpy.array, float}) – The polar angle.

pycbc.coordinates.spherical_to_cartesian(rho, phi, theta)[source]

Maps spherical coordinates (rho,phi,theta) to cartesian coordinates (x,y,z) where phi is in [0,2*pi] and theta is in [0,pi].

Parameters:
  • rho ({numpy.array, float}) – The radial amplitude.
  • phi ({numpy.array, float}) – The azimuthal angle.
  • theta ({numpy.array, float}) – The polar angle.
Returns:

  • x ({numpy.array, float}) – X-coordinate.
  • y ({numpy.array, float}) – Y-coordinate.
  • z ({numpy.array, float}) – Z-coordinate.

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.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, **kwargs)[source]

Returns the redshift from the given comoving volume.

Parameters:
  • vc (float) – The comoving volume, in units of cubed 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 at the given comoving volume.

Return type:

float

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

Returns the luminosity distance from the given comoving volume.

Parameters:
  • vc (float) – The comoving volume, in units of cubed Mpc.
  • **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.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.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)[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
Returns:

  • fplus (float or numpy.ndarray) – The plus polarization factor for this sky location / orientation
  • fcross (float or numpy.ndarray) – The cross polarization factor for this sky location / orientation

gmst_estimate(gps_time)[source]
light_travel_time_to_detector(det)[source]

Return the light travel time from this detector

Parameters:det (Detector) – The other detector to determine the light travel time to.
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, longitude, latitude, polarization)[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.

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.

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:

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

pycbc.detector.effective_distance(distance, inclination, f_plus, f_cross)[source]
pycbc.detector.get_available_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.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.

Parameters:
  • right_ascension (float) –
  • declination (float) –
  • polarization (float) –
Returns:

  • f_plus (float)
  • f_cros (float)

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='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 LOSC.
  • start_time (int) – The starting gps time to begin querying from LOSC
  • 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
  • end_pad) which indicates how to change the segment boundaries. ((start_pad,) –
  • 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:

glue.segments.segmentlist

pycbc.dq.query_flag(ifo, segment_name, start_time, end_time, source='any', server='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 LOSC.
  • start_time (int) – The starting gps time to begin querying from LOSC
  • 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:

glue.segments.segmentlist

pycbc.dq.query_str(ifo, flag_str, start_time, end_time, source='any', server='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=None)[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.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)[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.intmc(mc, x_min, x_max)[source]

Returns the integral of mchange between the minimum and maximum values of a component mass taking mchirp as an argument.

pycbc.mchirp_area.mchange(x, mc)[source]

Returns a component mass as a function of mchirp and the other component mass.

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: collections.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 LALSimulation function which evaluates 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.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.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: multiprocessing.pool.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]
map(f, items)[source]
pycbc.pool.choose_pool(processes, mpi=False)[source]
pycbc.pool.is_main_process()[source]

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

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: pycbc.scheme.Scheme

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

Bases: pycbc.scheme.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: pycbc.scheme.CPUScheme

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

Bases: pycbc.scheme.CPUScheme

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

Bases: pycbc.scheme.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(fn, *args, **kwds)[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.AlignedMassSpinToCartesianSpin[source]

Bases: pycbc.transforms.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: pycbc.transforms.SphericalSpin1ToCartesianSpin1

The inverse of SphericalSpin1ToCartesianSpin1.

inverse

alias of SphericalSpin1ToCartesianSpin1

inverse_jacobian(maps)

The Jacobian for the inputs to outputs transformation.

inverse_transform(maps)[source]

This function transforms from spherical to cartesian 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
jacobian(maps)

The Jacobian for the outputs to inputs transformation.

name = 'cartesian_spin_1_to_spherical_spin_1'
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
class pycbc.transforms.CartesianSpin2ToSphericalSpin2[source]

Bases: pycbc.transforms.CartesianSpin1ToSphericalSpin1

The inverse of SphericalSpin2ToCartesianSpin2.

inverse

alias of SphericalSpin2ToCartesianSpin2

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

Bases: pycbc.transforms.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: pycbc.transforms.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: pycbc.transforms.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.ChiPToCartesianSpin[source]

Bases: pycbc.transforms.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: pycbc.transforms.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: pycbc.transforms.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.DistanceToChirpDistance(ref_mass=1.4)[source]

Bases: pycbc.transforms.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: pycbc.transforms.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: pycbc.transforms.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.LambdaFromMultipleTOVFiles(mass_param, lambda_param, map_file, distance=None, file_columns=None)[source]

Bases: pycbc.transforms.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’).
distance

Returns the fixed distance to transform mass samples from detector to source frame if one is specified.

get_eos(eos_index)[source]

Gets the EOS for the given index.

If the index is not in range returns None.

lambda_param

Returns the output lambda parameter.

map_file

Returns the mass data read from the mass-Lambda data file for an EOS.

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, file_columns=None)[source]

Bases: pycbc.transforms.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. The mass values to be transformed are assumed to be detector frame masses, so 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 mass value inputted is in the source frame, then provide distance=0. 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
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 (‘mass’, ‘lambda’).
data
distance

Returns the fixed distance to transform mass samples from detector to source frame if one is specified.

lambda_data

Returns the Lambda data read from the mass-Lambda data file for an EOS.

static lambda_from_tov_data(m, d, mass_data, lambda_data)[source]

Returns Lambda corresponding to a given mass interpolating from the TOV data.

Parameters:
  • m (float) – Value of the mass.
  • d (float) – Value of distance.
  • 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

lambda_param

Returns the output lambda parameter.

mass_data

Returns the mass data read from the mass-Lambda data file for an EOS.

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: pycbc.transforms.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.
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'
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: pycbc.transforms.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.).
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: pycbc.transforms.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.).
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

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'
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: pycbc.transforms.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[source]

Bases: pycbc.transforms.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: pycbc.transforms.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[source]

Bases: pycbc.transforms.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: pycbc.transforms.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.SphericalSpin1ToCartesianSpin1[source]

Bases: pycbc.transforms.BaseTransform

Converts spherical spin parameters (magnitude and two angles) to catesian spin parameters. This class only transforms spsins for the first component mass.

inverse

alias of CartesianSpin1ToSphericalSpin1

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_spin_1_to_cartesian_spin_1'
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.SphericalSpin1ToCartesianSpin1()
>>> t.transform({'spin1_a': numpy.array([0.1]), 'spin1_azimuthal': numpy.array([0.1]), 'spin1_polar': numpy.array([0.1])})
    {'spin1_a': array([ 0.1]), 'spin1_azimuthal': array([ 0.1]), 'spin1_polar': array([ 0.1]),
     'spin2x': array([ 0.00993347]), 'spin2y': array([ 0.00099667]), 'spin2z': 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
class pycbc.transforms.SphericalSpin2ToCartesianSpin2[source]

Bases: pycbc.transforms.SphericalSpin1ToCartesianSpin1

Converts spherical spin parameters (magnitude and two angles) to cartesian spin parameters. This class only transforms spins for the second component mass.

inverse

alias of CartesianSpin2ToSphericalSpin2

name = 'spherical_spin_2_to_cartesian_spin_2'
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

pycbc.init_logging(verbose=False, format='%(asctime)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.

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