signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def tau0_from_mtotal_eta(mtotal, eta, f_lower):
<EOL>mtotal = mtotal * lal.MTSUN_SI<EOL>return _a0(f_lower) / (mtotal**(<NUM_LIT>/<NUM_LIT>) * eta)<EOL>
r"""Returns :math:`\tau_0` from the total mass, symmetric mass ratio, and the given frequency.
f16043:m26
def tau3_from_mtotal_eta(mtotal, eta, f_lower):
<EOL>mtotal = mtotal * lal.MTSUN_SI<EOL>return _a3(f_lower) / (mtotal**(<NUM_LIT>/<NUM_LIT>) * eta)<EOL>
r"""Returns :math:`\tau_0` from the total mass, symmetric mass ratio, and the given frequency.
f16043:m27
def tau0_from_mass1_mass2(mass1, mass2, f_lower):
mtotal = mass1 + mass2<EOL>eta = eta_from_mass1_mass2(mass1, mass2)<EOL>return tau0_from_mtotal_eta(mtotal, eta, f_lower)<EOL>
r"""Returns :math:`\tau_0` from the component masses and given frequency.
f16043:m28
def tau3_from_mass1_mass2(mass1, mass2, f_lower):
mtotal = mass1 + mass2<EOL>eta = eta_from_mass1_mass2(mass1, mass2)<EOL>return tau3_from_mtotal_eta(mtotal, eta, f_lower)<EOL>
r"""Returns :math:`\tau_3` from the component masses and given frequency.
f16043:m29
def mtotal_from_tau0_tau3(tau0, tau3, f_lower,<EOL>in_seconds=False):
mtotal = (tau3 / _a3(f_lower)) / (tau0 / _a0(f_lower))<EOL>if not in_seconds:<EOL><INDENT>mtotal /= lal.MTSUN_SI<EOL><DEDENT>return mtotal<EOL>
r"""Returns total mass from :math:`\tau_0, \tau_3`.
f16043:m30
def eta_from_tau0_tau3(tau0, tau3, f_lower):
mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower,<EOL>in_seconds=True)<EOL>eta = mtotal**(-<NUM_LIT>/<NUM_LIT>) * (_a3(f_lower) / tau3)<EOL>return eta<EOL>
r"""Returns symmetric mass ratio from :math:`\tau_0, \tau_3`.
f16043:m31
def mass1_from_tau0_tau3(tau0, tau3, f_lower):
mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower)<EOL>eta = eta_from_tau0_tau3(tau0, tau3, f_lower)<EOL>return mass1_from_mtotal_eta(mtotal, eta)<EOL>
r"""Returns the primary mass from the given :math:`\tau_0, \tau_3`.
f16043:m32
def mass2_from_tau0_tau3(tau0, tau3, f_lower):
mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower)<EOL>eta = eta_from_tau0_tau3(tau0, tau3, f_lower)<EOL>return mass2_from_mtotal_eta(mtotal, eta)<EOL>
r"""Returns the secondary mass from the given :math:`\tau_0, \tau_3`.
f16043:m33
def lambda_tilde(mass1, mass2, lambda1, lambda2):
m1, m2, lambda1, lambda2, input_is_array = ensurearray(<EOL>mass1, mass2, lambda1, lambda2)<EOL>lsum = lambda1 + lambda2<EOL>ldiff, _ = ensurearray(lambda1 - lambda2)<EOL>mask = m1 < m2<EOL>ldiff[mask] = -ldiff[mask]<EOL>eta = eta_from_mass1_mass2(m1, m2)<EOL>p1 = (lsum) * (<NUM_LIT:1> + <NUM_LIT> * eta - <NUM_LIT> * eta ** <NUM_LIT>)<EOL>p2 = (<NUM_LIT:1> - <NUM_LIT:4> * eta)**<NUM_LIT:0.5> * (<NUM_LIT:1> + <NUM_LIT:9> * eta - <NUM_LIT:11> * eta ** <NUM_LIT>) * (ldiff)<EOL>return formatreturn(<NUM_LIT> / <NUM_LIT> * (p1 + p2), input_is_array)<EOL>
The effective lambda parameter The mass-weighted dominant effective lambda parameter defined in https://journals.aps.org/prd/pdf/10.1103/PhysRevD.91.043002
f16043:m34
def chi_eff(mass1, mass2, spin1z, spin2z):
return (spin1z * mass1 + spin2z * mass2) / (mass1 + mass2)<EOL>
Returns the effective spin from mass1, mass2, spin1z, and spin2z.
f16043:m35
def chi_a(mass1, mass2, spin1z, spin2z):
return (spin2z * mass2 - spin1z * mass1) / (mass2 + mass1)<EOL>
Returns the aligned mass-weighted spin difference from mass1, mass2, spin1z, and spin2z.
f16043:m36
def chi_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
xi1 = secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)<EOL>xi2 = primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y)<EOL>return chi_p_from_xi1_xi2(xi1, xi2)<EOL>
Returns the effective precession spin from mass1, mass2, spin1x, spin1y, spin2x, and spin2y.
f16043:m37
def phi_a(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
phi1 = phi_from_spinx_spiny(primary_spin(mass1, mass2, spin1x, spin2x),<EOL>primary_spin(mass1, mass2, spin1y, spin2y))<EOL>phi2 = phi_from_spinx_spiny(secondary_spin(mass1, mass2, spin1x, spin2x),<EOL>secondary_spin(mass1, mass2, spin1y, spin2y))<EOL>return (phi1 - phi2) % (<NUM_LIT:2> * numpy.pi)<EOL>
Returns the angle between the in-plane perpendicular spins.
f16043:m38
def phi_s(spin1x, spin1y, spin2x, spin2y):
phi1 = phi_from_spinx_spiny(spin1x, spin1y)<EOL>phi2 = phi_from_spinx_spiny(spin2x, spin2y)<EOL>return (phi1 + phi2) % (<NUM_LIT:2> * numpy.pi)<EOL>
Returns the sum of the in-plane perpendicular spins.
f16043:m39
def chi_eff_from_spherical(mass1, mass2, spin1_a, spin1_polar,<EOL>spin2_a, spin2_polar):
spin1z = spin1_a * numpy.cos(spin1_polar)<EOL>spin2z = spin2_a * numpy.cos(spin2_polar)<EOL>return chi_eff(mass1, mass2, spin1z, spin2z)<EOL>
Returns the effective spin using spins in spherical coordinates.
f16043:m40
def chi_p_from_spherical(mass1, mass2, spin1_a, spin1_azimuthal, spin1_polar,<EOL>spin2_a, spin2_azimuthal, spin2_polar):
spin1x, spin1y, _ = _spherical_to_cartesian(<EOL>spin1_a, spin1_azimuthal, spin1_polar)<EOL>spin2x, spin2y, _ = _spherical_to_cartesian(<EOL>spin2_a, spin2_azimuthal, spin2_polar)<EOL>return chi_p(mass1, mass2, spin1x, spin1y, spin2x, spin2y)<EOL>
Returns the effective precession spin using spins in spherical coordinates.
f16043:m41
def primary_spin(mass1, mass2, spin1, spin2):
mass1, mass2, spin1, spin2, input_is_array = ensurearray(<EOL>mass1, mass2, spin1, spin2)<EOL>sp = copy.copy(spin1)<EOL>mask = mass1 < mass2<EOL>sp[mask] = spin2[mask]<EOL>return formatreturn(sp, input_is_array)<EOL>
Returns the dimensionless spin of the primary mass.
f16043:m42
def secondary_spin(mass1, mass2, spin1, spin2):
mass1, mass2, spin1, spin2, input_is_array = ensurearray(<EOL>mass1, mass2, spin1, spin2)<EOL>ss = copy.copy(spin2)<EOL>mask = mass1 < mass2<EOL>ss[mask] = spin1[mask]<EOL>return formatreturn(ss, input_is_array)<EOL>
Returns the dimensionless spin of the secondary mass.
f16043:m43
def primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
spinx = primary_spin(mass1, mass2, spin1x, spin2x)<EOL>spiny = primary_spin(mass1, mass2, spin1y, spin2y)<EOL>return chi_perp_from_spinx_spiny(spinx, spiny)<EOL>
Returns the effective precession spin argument for the larger mass.
f16043:m44
def secondary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
spinx = secondary_spin(mass1, mass2, spin1x, spin2x)<EOL>spiny = secondary_spin(mass1, mass2, spin1y, spin2y)<EOL>return xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spinx, spiny)<EOL>
Returns the effective precession spin argument for the smaller mass.
f16043:m45
def xi1_from_spin1x_spin1y(spin1x, spin1y):
return chi_perp_from_spinx_spiny(spin1x, spin1y)<EOL>
Returns the effective precession spin argument for the larger mass. This function assumes it's given spins of the primary mass.
f16043:m46
def xi2_from_mass1_mass2_spin2x_spin2y(mass1, mass2, spin2x, spin2y):
q = q_from_mass1_mass2(mass1, mass2)<EOL>a1 = <NUM_LIT:2> + <NUM_LIT:3> * q / <NUM_LIT:2><EOL>a2 = <NUM_LIT:2> + <NUM_LIT:3> / (<NUM_LIT:2> * q)<EOL>return a1 / (q**<NUM_LIT:2> * a2) * chi_perp_from_spinx_spiny(spin2x, spin2y)<EOL>
Returns the effective precession spin argument for the smaller mass. This function assumes it's given spins of the secondary mass.
f16043:m47
def chi_perp_from_spinx_spiny(spinx, spiny):
return numpy.sqrt(spinx**<NUM_LIT:2> + spiny**<NUM_LIT:2>)<EOL>
Returns the in-plane spin from the x/y components of the spin.
f16043:m48
def chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2):
q = q_from_mass1_mass2(mass1, mass2)<EOL>a1 = <NUM_LIT:2> + <NUM_LIT:3> * q / <NUM_LIT:2><EOL>a2 = <NUM_LIT:2> + <NUM_LIT:3> / (<NUM_LIT:2> * q)<EOL>return q**<NUM_LIT:2> * a2 / a1 * xi2<EOL>
Returns the in-plane spin from mass1, mass2, and xi2 for the secondary mass.
f16043:m49
def chi_p_from_xi1_xi2(xi1, xi2):
xi1, xi2, input_is_array = ensurearray(xi1, xi2)<EOL>chi_p = copy.copy(xi1)<EOL>mask = xi1 < xi2<EOL>chi_p[mask] = xi2[mask]<EOL>return formatreturn(chi_p, input_is_array)<EOL>
Returns effective precession spin from xi1 and xi2.
f16043:m50
def phi1_from_phi_a_phi_s(phi_a, phi_s):
return (phi_s + phi_a) / <NUM_LIT><EOL>
Returns the angle between the x-component axis and the in-plane spin for the primary mass from phi_s and phi_a.
f16043:m51
def phi2_from_phi_a_phi_s(phi_a, phi_s):
return (phi_s - phi_a) / <NUM_LIT><EOL>
Returns the angle between the x-component axis and the in-plane spin for the secondary mass from phi_s and phi_a.
f16043:m52
def phi_from_spinx_spiny(spinx, spiny):
phi = numpy.arctan2(spiny, spinx)<EOL>return phi % (<NUM_LIT:2> * numpy.pi)<EOL>
Returns the angle between the x-component axis and the in-plane spin.
f16043:m53
def spin1z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a):
return (mass1 + mass2) / (<NUM_LIT> * mass1) * (chi_eff - chi_a)<EOL>
Returns spin1z.
f16043:m54
def spin2z_from_mass1_mass2_chi_eff_chi_a(mass1, mass2, chi_eff, chi_a):
return (mass1 + mass2) / (<NUM_LIT> * mass2) * (chi_eff + chi_a)<EOL>
Returns spin2z.
f16043:m55
def spin1x_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s):
phi1 = phi1_from_phi_a_phi_s(phi_a, phi_s)<EOL>return xi1 * numpy.cos(phi1)<EOL>
Returns x-component spin for primary mass.
f16043:m56
def spin1y_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s):
phi1 = phi1_from_phi_a_phi_s(phi_s, phi_a)<EOL>return xi1 * numpy.sin(phi1)<EOL>
Returns y-component spin for primary mass.
f16043:m57
def spin2x_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)<EOL>phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s)<EOL>return chi_perp * numpy.cos(phi2)<EOL>
Returns x-component spin for secondary mass.
f16043:m58
def spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)<EOL>phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s)<EOL>return chi_perp * numpy.sin(phi2)<EOL>
Returns y-component spin for secondary mass.
f16043:m59
def dquadmon_from_lambda(lambdav):
ll = numpy.log(lambdav)<EOL>ai = <NUM_LIT><EOL>bi = <NUM_LIT><EOL>ci = <NUM_LIT><EOL>di = -<NUM_LIT> * <NUM_LIT:10>**-<NUM_LIT><EOL>ei = <NUM_LIT> * <NUM_LIT:10>**-<NUM_LIT><EOL>ln_quad_moment = ai + bi*ll + ci*ll**<NUM_LIT> + di*ll**<NUM_LIT> + ei*ll**<NUM_LIT><EOL>return numpy.exp(ln_quad_moment) - <NUM_LIT:1><EOL>
r"""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: .. math:: \mathrm{dquadmon} = \bar{Q} - 1. Where :math:`\bar{Q}` (dimensionless) is the reduced quadrupole moment.
f16043:m60
def chirp_distance(dist, mchirp, ref_mass=<NUM_LIT>):
return dist * (<NUM_LIT>**(-<NUM_LIT:1.>/<NUM_LIT:5>) * ref_mass / mchirp)**(<NUM_LIT>/<NUM_LIT:6>)<EOL>
Returns the chirp distance given the luminosity distance and chirp mass.
f16043:m61
def distance_from_chirp_distance_mchirp(chirp_distance, mchirp, ref_mass=<NUM_LIT>):
return chirp_distance * (<NUM_LIT>**(-<NUM_LIT:1.>/<NUM_LIT:5>) * ref_mass / mchirp)**(-<NUM_LIT>/<NUM_LIT:6>)<EOL>
Returns the luminosity distance given a chirp distance and chirp mass.
f16043:m62
def _det_tc(detector_name, ra, dec, tc, ref_frame='<STR_LIT>'):
if ref_frame == detector_name:<EOL><INDENT>return tc<EOL><DEDENT>detector = Detector(detector_name)<EOL>if ref_frame == '<STR_LIT>':<EOL><INDENT>return tc + detector.time_delay_from_earth_center(ra, dec, tc)<EOL><DEDENT>else:<EOL><INDENT>other = Detector(ref_frame)<EOL>return tc + detector.time_delay_from_detector(other, ra, dec, tc)<EOL><DEDENT>
Returns the coalescence time of a signal in the given detector. Parameters ---------- detector_name : string The name of the detector, e.g., 'H1'. ra : float The right ascension of the signal, in radians. dec : float The declination of the signal, in radians. tc : float The GPS time of the coalescence of the signal in the `ref_frame`. ref_frame : {'geocentric', string} The reference frame that the given coalescence time is defined in. May specify 'geocentric', or a detector name; default is 'geocentric'. Returns ------- float : The GPS time of the coalescence in detector `detector_name`.
f16043:m63
def _optimal_orientation_from_detector(detector_name, tc):
d = Detector(detector_name)<EOL>ra, dec = d.optimal_orientation(tc)<EOL>return ra, dec<EOL>
Low-level function to be called from _optimal_dec_from_detector and _optimal_ra_from_detector
f16043:m64
def _optimal_dec_from_detector(detector_name, tc):
return _optimal_orientation_from_detector(detector_name, tc)[<NUM_LIT:1>]<EOL>
For a given detector and GPS time, return the optimal orientation (directly overhead of the detector) in declination. Parameters ---------- detector_name : string The name of the detector, e.g., 'H1'. tc : float The GPS time of the coalescence of the signal in the `ref_frame`. Returns ------- float : The declination of the signal, in radians.
f16043:m65
def _optimal_ra_from_detector(detector_name, tc):
return _optimal_orientation_from_detector(detector_name, tc)[<NUM_LIT:0>]<EOL>
For a given detector and GPS time, return the optimal orientation (directly overhead of the detector) in right ascension. Parameters ---------- detector_name : string The name of the detector, e.g., 'H1'. tc : float The GPS time of the coalescence of the signal in the `ref_frame`. Returns ------- float : The declination of the signal, in radians.
f16043:m66
def snr_from_loglr(loglr):
singleval = isinstance(loglr, float)<EOL>if singleval:<EOL><INDENT>loglr = numpy.array([loglr])<EOL><DEDENT>numpysettings = numpy.seterr(invalid='<STR_LIT:ignore>')<EOL>snrs = numpy.sqrt(<NUM_LIT:2>*loglr)<EOL>numpy.seterr(**numpysettings)<EOL>snrs[numpy.isnan(snrs)] = <NUM_LIT:0.><EOL>if singleval:<EOL><INDENT>snrs = snrs[<NUM_LIT:0>]<EOL><DEDENT>return snrs<EOL>
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 ------- array or float The SNRs computed from the log likelihood ratios.
f16043:m67
def _genqnmfreq(mass, spin, l, m, nmodes, qnmfreq=None):
if qnmfreq is None:<EOL><INDENT>qnmfreq = lal.CreateCOMPLEX16Vector(int(nmodes))<EOL><DEDENT>lalsim.SimIMREOBGenerateQNMFreqV2fromFinal(<EOL>qnmfreq, float(mass), float(spin), int(l), int(m), int(nmodes))<EOL>return qnmfreq<EOL>
Convenience function to generate QNM frequencies from lalsimulation. Parameters ---------- mass : float The mass of the black hole (in solar masses). spin : float The dimensionless spin of the black hole. l : int l-index of the harmonic. m : int m-index of the harmonic. nmodes : int The number of overtones to generate. qnmfreq : lal.COMPLEX16Vector, optional LAL vector to write the results into. Must be the same length as ``nmodes``. If None, will create one. Returns ------- lal.COMPLEX16Vector LAL vector containing the complex QNM frequencies.
f16043:m68
def get_lm_f0tau(mass, spin, l, m, nmodes):
<EOL>mass, spin, l, m, input_is_array = ensurearray(<EOL>mass, spin, l, m)<EOL>origshape = mass.shape<EOL>if nmodes < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if nmodes > <NUM_LIT:1>:<EOL><INDENT>newshape = tuple(list(origshape)+[nmodes])<EOL><DEDENT>else:<EOL><INDENT>newshape = origshape<EOL><DEDENT>f0s = numpy.zeros((mass.size, nmodes))<EOL>taus = numpy.zeros((mass.size, nmodes))<EOL>mass = mass.ravel()<EOL>spin = spin.ravel()<EOL>l = l.ravel()<EOL>m = m.ravel()<EOL>qnmfreq = None<EOL>modes = range(nmodes)<EOL>for ii in range(mass.size):<EOL><INDENT>qnmfreq = _genqnmfreq(mass[ii], spin[ii], l[ii], m[ii], nmodes,<EOL>qnmfreq=qnmfreq)<EOL>f0s[ii, :] = [qnmfreq.data[n].real/(<NUM_LIT:2> * numpy.pi) for n in modes]<EOL>taus[ii, :] = [<NUM_LIT:1.>/qnmfreq.data[n].imag for n in modes]<EOL><DEDENT>f0s = f0s.reshape(newshape)<EOL>taus = taus.reshape(newshape)<EOL>return (formatreturn(f0s, input_is_array),<EOL>formatreturn(taus, input_is_array))<EOL>
Return the f0 and the tau of each overtone for a given l, m mode. Parameters ---------- mass : float or array Mass of the black hole (in solar masses). spin : float or array Dimensionless spin of the final black hole. l : int or array l-index of the harmonic. m : int or array m-index of the harmonic. nmodes : int The number of overtones to generate. Returns ------- f0 : float or array 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. tau : float or array The damping time of the QNM(s), in seconds. Return type is same as f0.
f16043:m69
def get_lm_f0tau_allmodes(mass, spin, modes):
f0, tau = {}, {}<EOL>key = '<STR_LIT>'<EOL>for lmn in modes:<EOL><INDENT>l, m, nmodes = int(lmn[<NUM_LIT:0>]), int(lmn[<NUM_LIT:1>]), int(lmn[<NUM_LIT:2>])<EOL>tmp_f0, tmp_tau = get_lm_f0tau(mass, spin, l, m, nmodes)<EOL>if nmodes == <NUM_LIT:1>:<EOL><INDENT>f0[key.format(l, m, '<STR_LIT:0>')] = tmp_f0<EOL>tau[key.format(l, m, '<STR_LIT:0>')] = tmp_tau<EOL><DEDENT>else:<EOL><INDENT>for n in range(nmodes):<EOL><INDENT>f0[key.format(l, m, n)] = formatreturn(tmp_f0[..., n])<EOL>tau[key.format(l, m, n)] = formatreturn(tmp_tau[..., n])<EOL><DEDENT><DEDENT><DEDENT>return f0, tau<EOL>
Returns a dictionary of all of the frequencies and damping times for the requested modes. Parameters ---------- mass : float or array Mass of the black hole (in solar masses). spin : float or array Dimensionless spin of the final black hole. modes : list of str The modes to get. Each string in the list should be formatted 'lmN', where l (m) is the l (m) index of the harmonic and N is the number of overtones to generate (note, N is not the index of the overtone). For example, '221' will generate the 0th overtone of the l = m = 2 mode. Returns ------- f0 : dict Dictionary mapping the modes to the frequencies. The dictionary keys are 'lmn' string, where l (m) is the l (m) index of the harmonic and n is the index of the overtone. For example, '220' is the l = m = 2 mode and the 0th overtone. tau : dict Dictionary mapping the modes to the damping times. The keys are the same as ``f0``.
f16043:m70
def freq_from_final_mass_spin(final_mass, final_spin, l=<NUM_LIT:2>, m=<NUM_LIT:2>, nmodes=<NUM_LIT:1>):
return get_lm_f0tau(final_mass, final_spin, l, m, nmodes)[<NUM_LIT:0>]<EOL>
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 ------- float or array 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.
f16043:m71
def tau_from_final_mass_spin(final_mass, final_spin, l=<NUM_LIT:2>, m=<NUM_LIT:2>, nmodes=<NUM_LIT:1>):
return get_lm_f0tau(final_mass, final_spin, l, m, nmodes)[<NUM_LIT:1>]<EOL>
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 ------- float or array 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.
f16043:m72
def final_spin_from_f0_tau(f0, tau, l=<NUM_LIT:2>, m=<NUM_LIT:2>):
f0, tau, input_is_array = ensurearray(f0, tau)<EOL>a, b, c = _berti_spin_constants[l,m]<EOL>origshape = f0.shape<EOL>f0 = f0.ravel()<EOL>tau = tau.ravel()<EOL>spins = numpy.zeros(f0.size)<EOL>for ii in range(spins.size):<EOL><INDENT>Q = f0[ii] * tau[ii] * numpy.pi<EOL>try:<EOL><INDENT>s = <NUM_LIT:1.> - ((Q-a)/b)**(<NUM_LIT:1.>/c)<EOL><DEDENT>except ValueError:<EOL><INDENT>s = numpy.nan<EOL><DEDENT>spins[ii] = s<EOL><DEDENT>spins = spins.reshape(origshape)<EOL>return formatreturn(spins, input_is_array)<EOL>
Returns the final spin based on the given frequency and damping time. .. note:: Currently, only l = m = 2 is 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 ------- float or array The spin of the final black hole. If the combination of frequency and damping times give an unphysical result, ``numpy.nan`` will be returned.
f16043:m73
def final_mass_from_f0_tau(f0, tau, l=<NUM_LIT:2>, m=<NUM_LIT:2>):
<EOL>spin = final_spin_from_f0_tau(f0, tau, l=l, m=m)<EOL>a, b, c = _berti_mass_constants[l,m]<EOL>return (a + b*(<NUM_LIT:1>-spin)**c)/(<NUM_LIT:2>*numpy.pi*f0*lal.MTSUN_SI)<EOL>
Returns the final mass (in solar masses) based on the given frequency and damping time. .. note:: Currently, only l = m = 2 is 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 ------- float or array The mass of the final black hole. If the combination of frequency and damping times give an unphysical result, ``numpy.nan`` will be returned.
f16043:m74
def get_final_from_initial(mass1, mass2, spin1x=<NUM_LIT:0.>, spin1y=<NUM_LIT:0.>, spin1z=<NUM_LIT:0.>,<EOL>spin2x=<NUM_LIT:0.>, spin2y=<NUM_LIT:0.>, spin2z=<NUM_LIT:0.>,<EOL>approximant='<STR_LIT>'):
args = (mass1, mass2, spin1x, spin1y, spin1z, spin2x, spin2y, spin2z)<EOL>args = ensurearray(*args)<EOL>input_is_array = args[-<NUM_LIT:1>]<EOL>origshape = args[<NUM_LIT:0>].shape<EOL>args = [a.ravel() for a in args[:-<NUM_LIT:1>]]<EOL>mass1, mass2, spin1x, spin1y, spin1z, spin2x, spin2y, spin2z = args<EOL>final_mass = numpy.zeros(mass1.shape)<EOL>final_spin = numpy.zeros(mass1.shape)<EOL>for ii in range(final_mass.size):<EOL><INDENT>m1 = mass1[ii]<EOL>m2 = mass2[ii]<EOL>spin1 = [spin1x[ii], spin1y[ii], spin1z[ii]]<EOL>spin2 = [spin2x[ii], spin2y[ii], spin2z[ii]]<EOL>_, fm, fs = lalsim.SimIMREOBFinalMassSpin(m1, m2, spin1, spin2,<EOL>getattr(lalsim, approximant))<EOL>final_mass[ii] = fm * (m1 + m2)<EOL>final_spin[ii] = fs<EOL><DEDENT>final_mass = final_mass.reshape(origshape)<EOL>final_spin = final_spin.reshape(origshape)<EOL>return (formatreturn(final_mass, input_is_array),<EOL>formatreturn(final_spin, input_is_array))<EOL>
Estimates the final mass and 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 ------- final_mass : float The final mass, in solar masses. final_spin : float The dimensionless final spin.
f16043:m75
def final_mass_from_initial(mass1, mass2, spin1x=<NUM_LIT:0.>, spin1y=<NUM_LIT:0.>, spin1z=<NUM_LIT:0.>,<EOL>spin2x=<NUM_LIT:0.>, spin2y=<NUM_LIT:0.>, spin2z=<NUM_LIT:0.>,<EOL>approximant='<STR_LIT>'):
return get_final_from_initial(mass1, mass2, spin1x, spin1y, spin1z,<EOL>spin2x, spin2y, spin2z, approximant)[<NUM_LIT:0>]<EOL>
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 ------- float The final mass, in solar masses.
f16043:m76
def final_spin_from_initial(mass1, mass2, spin1x=<NUM_LIT:0.>, spin1y=<NUM_LIT:0.>, spin1z=<NUM_LIT:0.>,<EOL>spin2x=<NUM_LIT:0.>, spin2y=<NUM_LIT:0.>, spin2z=<NUM_LIT:0.>,<EOL>approximant='<STR_LIT>'):
return get_final_from_initial(mass1, mass2, spin1x, spin1y, spin1z,<EOL>spin2x, spin2y, spin2z, approximant)[<NUM_LIT:1>]<EOL>
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 ------- float The dimensionless final spin.
f16043:m77
def velocity_to_frequency(v, M):
return v**(<NUM_LIT>) / (M * lal.MTSUN_SI * lal.PI)<EOL>
Calculate the gravitational-wave frequency from the total mass and invariant velocity. Parameters ---------- v : float Invariant velocity M : float Binary total mass Returns ------- f : float Gravitational-wave frequency
f16043:m78
def frequency_to_velocity(f, M):
return (lal.PI * M * lal.MTSUN_SI * f)**(<NUM_LIT:1.0>/<NUM_LIT>)<EOL>
Calculate the invariant velocity from the total mass and gravitational-wave frequency. Parameters ---------- f: float Gravitational-wave frequency M: float Binary total mass Returns ------- v : float or numpy.array Invariant velocity
f16043:m79
def f_schwarzchild_isco(M):
return velocity_to_frequency((<NUM_LIT:1.0>/<NUM_LIT>)**(<NUM_LIT:0.5>), M)<EOL>
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 : float or numpy.array Frequency in Hz
f16043:m80
def nltides_coefs(amplitude, n, m1, m2):
<EOL>f_ref = <NUM_LIT><EOL>mc = mchirp_from_mass1_mass2(m1, m2)<EOL>mc *= lal.lal.MSUN_SI<EOL>a = (<NUM_LIT>/<NUM_LIT>) *(lal.lal.G_SI * lal.lal.PI * mc * f_ref / lal.lal.C_SI**<NUM_LIT>)**(<NUM_LIT>/<NUM_LIT>)<EOL>b = <NUM_LIT> * amplitude<EOL>t_of_f_factor = -<NUM_LIT:1.>/(lal.lal.PI*f_ref) * b/(a*a * (n-<NUM_LIT>))<EOL>phi_of_f_factor = -<NUM_LIT>*b / (a*a * (n-<NUM_LIT>))<EOL>return f_ref, t_of_f_factor, phi_of_f_factor<EOL>
Calculate the coefficents needed to compute the shift in t(f) and phi(f) due to non-linear tides. Parameters ---------- amplitude: float Amplitude of effect n: float Growth dependence of effect m1: float Mass of component 1 m2: float Mass of component 2 Returns ------- f_ref : float Reference frequency used to define A and n t_of_f_factor: float The constant factor needed to compute t(f) phi_of_f_factor: float The constant factor needed to compute phi(f)
f16043:m81
def nltides_gw_phase_difference(f, f0, amplitude, n, m1, m2):
f, f0, amplitude, n, m1, m2, input_is_array = ensurearray(<EOL>f, f0, amplitude, n, m1, m2)<EOL>delta_phi = numpy.zeros(m1.shape)<EOL>f_ref, _, phi_of_f_factor = nltides_coefs(amplitude, n, m1, m2)<EOL>mask = f <= f0<EOL>delta_phi[mask] = - phi_of_f_factor[mask] * (f0[mask]/f_ref)**(n[mask]-<NUM_LIT>)<EOL>mask = f > f0<EOL>delta_phi[mask] = - phi_of_f_factor[mask] * (f[mask]/f_ref)**(n[mask]-<NUM_LIT>)<EOL>return formatreturn(delta_phi, input_is_array)<EOL>
Calculate the gravitational-wave phase shift bwtween f and f_coalescence = infinity due to non-linear tides. To compute the phase shift between e.g. f_low and f_isco, call this function twice and compute the difference. Parameters ---------- f: float or numpy.array Frequency from which to compute phase 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: float or numpy.array Phase in radians
f16043:m82
def nltides_gw_phase_diff_isco(f_low, f0, amplitude, n, m1, m2):
f0, amplitude, n, m1, m2, input_is_array = ensurearray(<EOL>f0, amplitude, n, m1, m2)<EOL>f_low = numpy.zeros(m1.shape) + f_low<EOL>phi_l = nltides_gw_phase_difference(<EOL>f_low, f0, amplitude, n, m1, m2)<EOL>f_isco = f_schwarzchild_isco(m1+m2)<EOL>phi_i = nltides_gw_phase_difference(<EOL>f_isco, f0, amplitude, n, m1, m2)<EOL>return formatreturn(phi_i - phi_l, input_is_array)<EOL>
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: float or numpy.array Phase in radians
f16043:m83
def get_available_detectors():
ld = lal.__dict__<EOL>known_lal_names = [j for j in ld.keys() if "<STR_LIT>" in j]<EOL>known_prefixes = [ld[k] for k in known_lal_names]<EOL>known_names = [ld[k.replace('<STR_LIT>', '<STR_LIT>')] for k in known_lal_names]<EOL>return zip(known_prefixes, known_names)<EOL>
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.
f16044:m1
def overhead_antenna_pattern(right_ascension, declination, polarization):
<EOL>theta = np.pi / <NUM_LIT> - declination<EOL>f_plus = - (<NUM_LIT:1.0>/<NUM_LIT>) * (<NUM_LIT:1.0> + cos(theta)*cos(theta)) *cos (<NUM_LIT> * right_ascension) * cos (<NUM_LIT> * polarization) -cos(theta) * sin(<NUM_LIT>*right_ascension) * sin (<NUM_LIT> * polarization)<EOL>f_cross = (<NUM_LIT:1.0>/<NUM_LIT>) * (<NUM_LIT:1.0> + cos(theta)*cos(theta)) *cos (<NUM_LIT> * right_ascension) * sin (<NUM_LIT>* polarization) -cos(theta) * sin(<NUM_LIT>*right_ascension) * cos (<NUM_LIT> * polarization)<EOL>return f_plus, f_cross<EOL>
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
f16044:m2
def __init__(self, detector_name, reference_time=<NUM_LIT>):
self.name = str(detector_name)<EOL>self.frDetector = lalsimulation.DetectorPrefixToLALDetector(self.name)<EOL>self.response = self.frDetector.response<EOL>self.location = self.frDetector.location<EOL>self.latitude = self.frDetector.frDetector.vertexLatitudeRadians<EOL>self.longitude = self.frDetector.frDetector.vertexLongitudeRadians<EOL>self.reference_time = reference_time<EOL>if reference_time is not None:<EOL><INDENT>self.sday = float(sday.si.scale)<EOL>self.gmst_reference = gmst_accurate(reference_time)<EOL><DEDENT>
Create class representing a gravitational-wave detector Parameters ---------- detector_name: str The two character detector string, i.e. H1, L1, V1, K1, I1 reference_time: float Default is time of GW150914. In this case, the earth's rotation will be estimated from a reference time. If 'None', we will calculate the time for each gps time requested explicitly using a slower but higher precision method.
f16044:c0:m0
def light_travel_time_to_detector(self, det):
d = self.location - det.location<EOL>return float(d.dot(d)**<NUM_LIT:0.5> / constants.c.value)<EOL>
Return the light travel time from this detector Parameters ---------- det: Detector The other detector to determine the light travel time to. Returns ------- time: float The light travel time in seconds
f16044:c0:m2
def antenna_pattern(self, right_ascension, declination, polarization, t_gps):
gha = self.gmst_estimate(t_gps) - right_ascension<EOL>cosgha = cos(gha)<EOL>singha = sin(gha)<EOL>cosdec = cos(declination)<EOL>sindec = sin(declination)<EOL>cospsi = cos(polarization)<EOL>sinpsi = sin(polarization)<EOL>x0 = -cospsi * singha - sinpsi * cosgha * sindec<EOL>x1 = -cospsi * cosgha + sinpsi * singha * sindec<EOL>x2 = sinpsi * cosdec<EOL>x = np.array([x0, x1, x2])<EOL>dx = self.response.dot(x)<EOL>y0 = sinpsi * singha - cospsi * cosgha * sindec<EOL>y1 = sinpsi * cosgha + cospsi * singha * sindec<EOL>y2 = cospsi * cosdec<EOL>y = np.array([y0, y1, y2])<EOL>dy = self.response.dot(y)<EOL>if hasattr(dx, '<STR_LIT>'):<EOL><INDENT>fplus = (x * dx - y * dy).sum(axis=<NUM_LIT:0>)<EOL>fcross = (x * dy + y * dx).sum(axis=<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>fplus = (x * dx - y * dy).sum()<EOL>fcross = (x * dy + y * dx).sum()<EOL><DEDENT>return fplus, fcross<EOL>
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
f16044:c0:m3
def time_delay_from_earth_center(self, right_ascension, declination, t_gps):
return self.time_delay_from_location(np.array([<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>]),<EOL>right_ascension,<EOL>declination,<EOL>t_gps)<EOL>
Return the time delay from the earth center
f16044:c0:m4
def time_delay_from_location(self, other_location, right_ascension,<EOL>declination, t_gps):
ra_angle = self.gmst_estimate(t_gps) - right_ascension<EOL>cosd = cos(declination)<EOL>e0 = cosd * cos(ra_angle)<EOL>e1 = cosd * -sin(ra_angle)<EOL>e2 = sin(declination)<EOL>ehat = np.array([e0, e1, e2])<EOL>dx = other_location - self.location<EOL>return dx.dot(ehat) / constants.c.value<EOL>
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 ------- float The arrival time difference between the detectors.
f16044:c0:m5
def time_delay_from_detector(self, other_detector, right_ascension,<EOL>declination, t_gps):
return self.time_delay_from_location(other_detector.location,<EOL>right_ascension,<EOL>declination,<EOL>t_gps)<EOL>
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 ------- float The arrival time difference between the detectors.
f16044:c0:m6
def project_wave(self, hp, hc, longitude, latitude, polarization):
h_lal = lalsimulation.SimDetectorStrainREAL8TimeSeries(<EOL>hp.astype(np.float64).lal(), hc.astype(np.float64).lal(),<EOL>longitude, latitude, polarization, self.frDetector)<EOL>return TimeSeries(<EOL>h_lal.data.data, delta_t=h_lal.deltaT, epoch=h_lal.epoch,<EOL>dtype=np.float64, copy=False)<EOL>
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.
f16044:c0:m7
def optimal_orientation(self, t_gps):
ra = self.longitude + (self.gmst_estimate(t_gps) % (<NUM_LIT>*np.pi))<EOL>dec = self.latitude<EOL>return ra, dec<EOL>
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
f16044:c0:m8
def init_logging(verbose=False, format='<STR_LIT>'):
def sig_handler(signum, frame):<EOL><INDENT>logger = logging.getLogger()<EOL>log_level = logger.level<EOL>if log_level == logging.DEBUG:<EOL><INDENT>log_level = logging.WARN<EOL><DEDENT>else:<EOL><INDENT>log_level = logging.DEBUG<EOL><DEDENT>logging.warn('<STR_LIT>',<EOL>signum, log_level)<EOL>logger.setLevel(log_level)<EOL><DEDENT>signal.signal(signal.SIGUSR1, sig_handler)<EOL>if verbose:<EOL><INDENT>initial_level = logging.DEBUG<EOL><DEDENT>else:<EOL><INDENT>initial_level = logging.WARN<EOL><DEDENT>logging.getLogger().setLevel(initial_level)<EOL>logging.basicConfig(format=format, level=initial_level)<EOL>
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.
f16045:m0
def makedir(path):
if path is not None and not os.path.exists(path):<EOL><INDENT>os.makedirs(path)<EOL><DEDENT>
Make the analysis directory path and any parent directories that don't already exist. Will do nothing if path already exists.
f16045:m1
def is_main_process():
try:<EOL><INDENT>from mpi4py import MPI<EOL>comm = MPI.COMM_WORLD<EOL>rank = comm.Get_rank()<EOL>return rank == <NUM_LIT:0><EOL><DEDENT>except (ImportError, ValueError, RuntimeError):<EOL><INDENT>return True<EOL><DEDENT>
Check if this is the main control process and may handle one time tasks
f16046:m0
def _lockstep_fcn(values):
numrequired, fcn, args = values<EOL>with _process_lock:<EOL><INDENT>_numdone.value += <NUM_LIT:1><EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>if _numdone.value == numrequired:<EOL><INDENT>return fcn(args)<EOL><DEDENT><DEDENT>
Wrapper to ensure that all processes execute together
f16046:m2
def broadcast(self, fcn, args):
results = self.map(_lockstep_fcn, [(len(self), fcn, args)] * len(self))<EOL>_numdone.value = <NUM_LIT:0><EOL>return results<EOL>
Do a function call on every worker. Parameters ---------- fcn: funtion Function to call. args: tuple The arguments for Pool.map
f16046:c0:m2
def allmap(self, fcn, args):
results = self.map(_lockstep_fcn,<EOL>[(len(self), fcn, arg) for arg in args])<EOL>_numdone.value = <NUM_LIT:0><EOL>return results<EOL>
Do a function call on every worker with different arguments Parameters ---------- fcn: funtion Function to call. args: tuple The arguments for Pool.map
f16046:c0:m3
def map(self, func, items, chunksize=None):
results = self.map_async(func, items, chunksize)<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>return results.get(<NUM_LIT>)<EOL><DEDENT>except TimeoutError:<EOL><INDENT>pass<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>self.terminate()<EOL>self.join()<EOL>raise KeyboardInterrupt<EOL><DEDENT><DEDENT>
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
f16046:c0:m4
def parse_veto_definer(veto_def_filename):
from glue.ligolw import table, lsctables, utils as ligolw_utils<EOL>from glue.ligolw.ligolw import LIGOLWContentHandler as h<EOL>lsctables.use_in(h)<EOL>indoc = ligolw_utils.load_filename(veto_def_filename, False,<EOL>contenthandler=h)<EOL>veto_table = table.get_table(indoc, '<STR_LIT>')<EOL>ifo = veto_table.getColumnByName('<STR_LIT>')<EOL>name = veto_table.getColumnByName('<STR_LIT:name>')<EOL>version = numpy.array(veto_table.getColumnByName('<STR_LIT:version>'))<EOL>category = numpy.array(veto_table.getColumnByName('<STR_LIT>'))<EOL>start = numpy.array(veto_table.getColumnByName('<STR_LIT>'))<EOL>end = numpy.array(veto_table.getColumnByName('<STR_LIT>'))<EOL>start_pad = numpy.array(veto_table.getColumnByName('<STR_LIT>'))<EOL>end_pad = numpy.array(veto_table.getColumnByName('<STR_LIT>'))<EOL>data = {}<EOL>for i in range(len(veto_table)):<EOL><INDENT>if ifo[i] not in data:<EOL><INDENT>data[ifo[i]] = {}<EOL><DEDENT>if category[i] > <NUM_LIT:3>:<EOL><INDENT>curr_cat = "<STR_LIT>".format(category[i]-<NUM_LIT:1>)<EOL><DEDENT>elif category[i] == <NUM_LIT:3>:<EOL><INDENT>curr_cat = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>curr_cat = "<STR_LIT>".format(category[i])<EOL><DEDENT>if curr_cat not in data[ifo[i]]:<EOL><INDENT>data[ifo[i]][curr_cat] = []<EOL><DEDENT>veto_info = {'<STR_LIT:name>': name[i],<EOL>'<STR_LIT:version>': version[i],<EOL>'<STR_LIT:start>': start[i],<EOL>'<STR_LIT:end>': end[i],<EOL>'<STR_LIT>': start_pad[i],<EOL>'<STR_LIT>': end_pad[i],<EOL>}<EOL>data[ifo[i]][curr_cat].append(veto_info)<EOL><DEDENT>return data<EOL>
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 Returns: parsed_definition: dict Returns a dictionary first indexed by ifo, then category level, and finally a list of veto definitions.
f16047:m0
def query_flag(ifo, name, start_time, end_time,<EOL>source='<STR_LIT>', server="<STR_LIT>",<EOL>veto_definer=None, cache=False):
info = name.split('<STR_LIT::>')<EOL>if len(info) == <NUM_LIT:2>:<EOL><INDENT>segment_name, version = info<EOL><DEDENT>elif len(info) == <NUM_LIT:1>:<EOL><INDENT>segment_name = info[<NUM_LIT:0>]<EOL>version = <NUM_LIT:1><EOL><DEDENT>flag_segments = segmentlist([])<EOL>if source in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if (('<STR_LIT>' in segment_name and '<STR_LIT>' not in segment_name) or<EOL>'<STR_LIT>' in segment_name):<EOL><INDENT>data = query_flag(ifo, '<STR_LIT>', start_time, end_time)<EOL>if '<STR_LIT>' in segment_name:<EOL><INDENT>name = '<STR_LIT>' + segment_name<EOL><DEDENT>else:<EOL><INDENT>name = segment_name.replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>negate = query_flag(ifo, name, start_time, end_time, cache=cache)<EOL>return (data - negate).coalesce()<EOL><DEDENT>duration = end_time - start_time<EOL>url = GWOSC_URL.format(get_run(start_time + duration/<NUM_LIT:2>),<EOL>ifo, segment_name,<EOL>int(start_time), int(duration))<EOL>try:<EOL><INDENT>fname = download_file(url, cache=cache)<EOL>data = json.load(open(fname, '<STR_LIT:r>'))<EOL>if '<STR_LIT>' in data:<EOL><INDENT>flag_segments = data['<STR_LIT>']<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>msg = "<STR_LIT>"<EOL>print(e)<EOL>if source != '<STR_LIT>':<EOL><INDENT>raise ValueError(msg)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>", name)<EOL><DEDENT>return query_flag(ifo, segment_name, start_time, end_time,<EOL>source='<STR_LIT>', server=server,<EOL>veto_definer=veto_definer)<EOL><DEDENT><DEDENT>elif source == '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>from dqsegdb.apicalls import dqsegdbQueryTimes as query<EOL><DEDENT>except ImportError:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if veto_definer is not None:<EOL><INDENT>veto_def = parse_veto_definer(veto_definer)<EOL><DEDENT>if veto_definer is not None and segment_name in veto_def[ifo]:<EOL><INDENT>for flag in veto_def[ifo][segment_name]:<EOL><INDENT>segs = query("<STR_LIT>", server, ifo, flag['<STR_LIT:name>'],<EOL>flag['<STR_LIT:version>'], '<STR_LIT>',<EOL>int(start_time), int(end_time))[<NUM_LIT:0>]['<STR_LIT>']<EOL>for rseg in segs:<EOL><INDENT>seg_start = rseg[<NUM_LIT:0>] + flag['<STR_LIT>']<EOL>seg_end = rseg[<NUM_LIT:1>] + flag['<STR_LIT>']<EOL>flag_segments.append(segment(seg_start, seg_end))<EOL><DEDENT><DEDENT>send = segmentlist([segment([veto_def['<STR_LIT:start>'], veto_def['<STR_LIT:end>']])])<EOL>flag_segments = (flag_segments.coalesce() & send)<EOL><DEDENT>else: <EOL><INDENT>try:<EOL><INDENT>segs = query("<STR_LIT>", server, ifo, name, version,<EOL>'<STR_LIT>', int(start_time),<EOL>int(end_time))[<NUM_LIT:0>]['<STR_LIT>']<EOL>for rseg in segs:<EOL><INDENT>flag_segments.append(segment(rseg[<NUM_LIT:0>], rseg[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>" % segment_name)<EOL>raise e<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(source))<EOL><DEDENT>return segmentlist(flag_segments).coalesce()<EOL>
Return the times where the flag is active Parameters ---------- ifo: string The interferometer to query (H1, L1). 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: glue.segments.segmentlist List of segments
f16047:m1
def query_cumulative_flags(ifo, segment_names, start_time, end_time,<EOL>source='<STR_LIT>', server="<STR_LIT>",<EOL>veto_definer=None,<EOL>bounds=None,<EOL>padding=None,<EOL>override_ifos=None,<EOL>cache=False):
total_segs = segmentlist([])<EOL>for flag_name in segment_names:<EOL><INDENT>ifo_name = ifo<EOL>if override_ifos is not None and flag_name in override_ifos:<EOL><INDENT>ifo_name = override_ifos[flag_name]<EOL><DEDENT>segs = query_flag(ifo_name, flag_name, start_time, end_time,<EOL>source=source, server=server,<EOL>veto_definer=veto_definer,<EOL>cache=cache)<EOL>if padding and flag_name in padding:<EOL><INDENT>s, e = padding[flag_name]<EOL>segs2 = segmentlist([])<EOL>for seg in segs:<EOL><INDENT>segs2.append(segment(seg[<NUM_LIT:0>] + s, seg[<NUM_LIT:1>] + e))<EOL><DEDENT>segs = segs2<EOL><DEDENT>if bounds is not None and flag_name in bounds:<EOL><INDENT>s, e = bounds[flag_name]<EOL>valid = segmentlist([segment([s, e])])<EOL>segs = (segs & valid).coalesce()<EOL><DEDENT>total_segs = (total_segs + segs).coalesce()<EOL><DEDENT>return total_segs<EOL>
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 indicated places which should have a distinct time period to be active. padding: dict, Optional Dict keyed by the flag name. Each element is a tuple (start_pad, end_pad) which indicates how to change the segment boundaries. override_ifos: dict, Optional A dict keyed by flag_name to override the ifo option on a per flag basis. Returns --------- segments: glue.segments.segmentlist List of segments
f16047:m2
def parse_flag_str(flag_str):
flags = flag_str.replace('<STR_LIT:U+0020>', '<STR_LIT>').strip().split('<STR_LIT:U+002C>')<EOL>signs = {}<EOL>ifos = {}<EOL>bounds = {}<EOL>padding = {}<EOL>bflags = []<EOL>for flag in flags:<EOL><INDENT>sign = flag[<NUM_LIT:0>] == '<STR_LIT:+>'<EOL>flag = flag[<NUM_LIT:1>:]<EOL>ifo = pad = bound = None<EOL>if len(flag.split('<STR_LIT::>')[<NUM_LIT:0>]) == <NUM_LIT:2>:<EOL><INDENT>ifo = flag.split('<STR_LIT::>')[<NUM_LIT:0>]<EOL>flag = flag[<NUM_LIT:3>:]<EOL><DEDENT>if '<STR_LIT:<>' in flag:<EOL><INDENT>popt = flag.split('<STR_LIT:<>')[<NUM_LIT:1>].split('<STR_LIT:>>')[<NUM_LIT:0>]<EOL>spad, epad = popt.split('<STR_LIT::>')<EOL>pad = (float(spad), float(epad))<EOL>flag = flag.replace(popt, '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>if '<STR_LIT:[>' in flag:<EOL><INDENT>bopt = flag.split('<STR_LIT:[>')[<NUM_LIT:1>].split('<STR_LIT:]>')[<NUM_LIT:0>]<EOL>start, end = bopt.split('<STR_LIT::>')<EOL>bound = (int(start), int(end))<EOL>flag = flag.replace(bopt, '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>if ifo:<EOL><INDENT>ifos[flag] = ifo<EOL><DEDENT>if pad:<EOL><INDENT>padding[flag] = pad<EOL><DEDENT>if bound:<EOL><INDENT>bounds[flag] = bound<EOL><DEDENT>bflags.append(flag)<EOL>signs[flag] = sign<EOL><DEDENT>return bflags, signs, ifos, bounds, padding<EOL>
Parse a dq flag query string Parameters ---------- flag_str: str String needing 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 indicated if this 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 in for a given flag.
f16047:m3
def query_str(ifo, flag_str, start_time, end_time, server="<STR_LIT>",<EOL>veto_definer=None):
flags, sign, ifos, bounds, padding = parse_flag_str(flag_str)<EOL>up = [f for f in flags if sign[f]]<EOL>down = [f for f in flags if not sign[f]]<EOL>if len(up) + len(down) != len(flags):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>segs = query_cumulative_flags(ifo, up, start_time, end_time,<EOL>server=server,<EOL>veto_definer=veto_definer,<EOL>bounds=bounds,<EOL>padding=padding,<EOL>override_ifos=ifos)<EOL>mseg = query_cumulative_flags(ifo, down, start_time, end_time,<EOL>server=server,<EOL>veto_definer=veto_definer,<EOL>bounds=bounds,<EOL>padding=padding,<EOL>override_ifos=ifos)<EOL>segs = (segs - mseg).coalesce()<EOL>return segs<EOL>
Query for flags based on a special str syntax Parameters ---------- ifo: str The ifo to be mainly quering for. (may be overriden 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 overriden for individual flags with the flag str bounds syntax end_time: int The end gps time. May be overriden for individual flags with the flag str bounds syntax Returns ------- segs: segmentlist A list of segments corresponding to the flag query string
f16047:m4
def __init__(self, name, source='<STR_LIT>'):
self.data = catalog.get_source(source)[name]<EOL>for key in self.data:<EOL><INDENT>if '<STR_LIT>' in self.data[key]:<EOL><INDENT>setattr(self, key, self.data[key]['<STR_LIT>'])<EOL><DEDENT><DEDENT>self.time = self.data['<STR_LIT>']['<STR_LIT>']<EOL>
Return the information of a merger Parameters ---------- name: str The name (GW prefixed date) of the merger event.
f16048:c0:m0
def median1d(self, name, return_errors=False):
if return_errors:<EOL><INDENT>mid = self.data[name]['<STR_LIT>']<EOL>low, high = self.data[name]['<STR_LIT>']<EOL>return (mid, low, high)<EOL><DEDENT>else:<EOL><INDENT>return self.data[name]['<STR_LIT>']<EOL><DEDENT>
Return median 1d marginalized parameters Parameters ---------- name: str The name of the parameter requested return_errors: Optional, {bool, False} If true, return a second and third parameter that represents the lower and upper 90% error on the parameter. Returns ------- param: float or tuple The requested parameter
f16048:c0:m1
def strain(self, ifo, duration=<NUM_LIT:32>, sample_rate=<NUM_LIT>):
from astropy.utils.data import download_file<EOL>from pycbc.frame import read_frame<EOL>length = "<STR_LIT>".format(duration)<EOL>if sample_rate == <NUM_LIT>:<EOL><INDENT>sampling = "<STR_LIT>"<EOL><DEDENT>elif sample_rate == <NUM_LIT>:<EOL><INDENT>sampling = "<STR_LIT>"<EOL><DEDENT>channel = "<STR_LIT>".format(ifo, sampling.upper())<EOL>url = self.data['<STR_LIT>'][ifo][length][sampling]['<STR_LIT>']<EOL>filename = download_file(url, cache=True)<EOL>return read_frame(str(filename), str(channel))<EOL>
Return strain around the event Currently this will return the strain around the event in the smallest format available. Selection of other data is not yet available. Parameters ---------- ifo: str The name of the observatory you want strain for. Ex. H1, L1, V1 Returns ------- strain: pycbc.types.TimeSeries Strain around the event.
f16048:c0:m2
def __init__(self, source='<STR_LIT>'):
self.data = catalog.get_source(source=source)<EOL>self.mergers = {name: Merger(name,<EOL>source=source) for name in self.data}<EOL>self.names = self.mergers.keys()<EOL>
Return the set of detected mergers The set of detected mergers. At some point this may have some selection abilities.
f16048:c1:m0
def median1d(self, param, return_errors=False):
v = [self.mergers[m].median1d(param, return_errors=return_errors) for m in self.mergers]<EOL>if return_errors:<EOL><INDENT>value, merror, perror = zip(*v)<EOL>return numpy.array(value), numpy.array(merror), numpy.array(perror)<EOL><DEDENT>else:<EOL><INDENT>return numpy.array(v)<EOL><DEDENT>
Return median 1d marginalized parameters Parameters ---------- name: str The name of the parameter requested return_errors: Optional, {bool, False} If true, return a second and third parameter that represents the lower and upper 90% error on the parameter. Returns ------- param: nump.ndarray or tuple The requested parameter
f16048:c1:m6
def get_source(source):
if source == '<STR_LIT>':<EOL><INDENT>fname = download_file(gwtc1_url, cache=True)<EOL>data = json.load(open(fname, '<STR_LIT:r>'))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(source))<EOL><DEDENT>return data['<STR_LIT:data>']<EOL>
Get the source data for a particular GW catalog
f16049:m0
def get_psd_model_list():
return get_lalsim_psd_list() + get_pycbc_psd_list()<EOL>
Returns a list of available reference PSD functions. Returns ------- list Returns a list of names of reference PSD functions.
f16050:m0
def get_lalsim_psd_list():
return _psd_list<EOL>
Return a list of available reference PSD functions from LALSimulation.
f16050:m1
def get_pycbc_psd_list():
pycbc_analytical_psd_list = pycbc_analytical_psds.keys()<EOL>pycbc_analytical_psd_list = sorted(pycbc_analytical_psd_list)<EOL>return pycbc_analytical_psd_list<EOL>
Return a list of available reference PSD functions coded in PyCBC. Returns ------- list Returns a list of names of all reference PSD functions coded in PyCBC.
f16050:m2
def from_string(psd_name, length, delta_f, low_freq_cutoff):
<EOL>if psd_name not in get_psd_model_list():<EOL><INDENT>raise ValueError(psd_name + '<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if psd_name in get_lalsim_psd_list():<EOL><INDENT>lalseries = lal.CreateREAL8FrequencySeries(<EOL>'<STR_LIT>', lal.LIGOTimeGPS(<NUM_LIT:0>), <NUM_LIT:0>, delta_f, lal.DimensionlessUnit, length)<EOL>try:<EOL><INDENT>func = lalsimulation.__dict__[<EOL>_name_prefix + psd_name + _name_suffix]<EOL><DEDENT>except KeyError:<EOL><INDENT>func = lalsimulation.__dict__[_name_prefix + psd_name]<EOL>func(lalseries, low_freq_cutoff)<EOL><DEDENT>else:<EOL><INDENT>lalsimulation.SimNoisePSD(lalseries, <NUM_LIT:0>, func)<EOL><DEDENT>psd = FrequencySeries(lalseries.data.data, delta_f=delta_f)<EOL><DEDENT>else:<EOL><INDENT>func = pycbc_analytical_psds[psd_name]<EOL>psd = func(length, delta_f, low_freq_cutoff)<EOL><DEDENT>kmin = int(low_freq_cutoff / delta_f)<EOL>psd.data[:kmin] = <NUM_LIT:0><EOL>return psd<EOL>
Generate a frequency series containing a LALSimulation PSD specified by name. Parameters ---------- psd_name : string PSD name as found in LALSimulation, minus the SimNoisePSD prefix. length : int Length of the frequency series in samples. delta_f : float Frequency resolution of the frequency series. low_freq_cutoff : float Frequencies below this value are set to zero. Returns ------- psd : FrequencySeries The generated frequency series.
f16050:m3
def flat_unity(length, delta_f, low_freq_cutoff):
fseries = FrequencySeries(numpy.ones(length), delta_f=delta_f)<EOL>kmin = int(low_freq_cutoff / fseries.delta_f)<EOL>fseries.data[:kmin] = <NUM_LIT:0><EOL>return fseries<EOL>
Returns a FrequencySeries of ones above the low_frequency_cutoff. Parameters ---------- length : int Length of output Frequencyseries. delta_f : float Frequency step for output FrequencySeries. low_freq_cutoff : int Low-frequency cutoff for output FrequencySeries. Returns ------- FrequencySeries Returns a FrequencySeries containing the unity PSD model.
f16050:m4
def from_cli(opt, length, delta_f, low_frequency_cutoff,<EOL>strain=None, dyn_range_factor=<NUM_LIT:1>, precision=None):
f_low = low_frequency_cutoff<EOL>sample_rate = int((length -<NUM_LIT:1>) * <NUM_LIT:2> * delta_f)<EOL>try:<EOL><INDENT>psd_estimation = opt.psd_estimation is not None<EOL><DEDENT>except AttributeError:<EOL><INDENT>psd_estimation = False<EOL><DEDENT>exclusive_opts = [opt.psd_model, opt.psd_file, opt.asd_file,<EOL>psd_estimation]<EOL>if sum(map(bool, exclusive_opts)) != <NUM_LIT:1>:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>if (opt.psd_model or opt.psd_file or opt.asd_file):<EOL><INDENT>if opt.psd_model:<EOL><INDENT>psd = from_string(opt.psd_model, length, delta_f, f_low)<EOL><DEDENT>elif opt.psd_file or opt.asd_file:<EOL><INDENT>if opt.asd_file:<EOL><INDENT>psd_file_name = opt.asd_file<EOL><DEDENT>else:<EOL><INDENT>psd_file_name = opt.psd_file<EOL><DEDENT>if psd_file_name.endswith(('<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>is_asd_file = bool(opt.asd_file)<EOL>psd = from_txt(psd_file_name, length,<EOL>delta_f, f_low, is_asd_file=is_asd_file)<EOL><DEDENT>elif opt.asd_file:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>".format(psd_file_name)<EOL><DEDENT>elif psd_file_name.endswith(('<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>psd = from_xml(psd_file_name, length, delta_f, f_low,<EOL>ifo_string=opt.psd_file_xml_ifo_string,<EOL>root_name=opt.psd_file_xml_root_name)<EOL><DEDENT><DEDENT>kmin = int(low_frequency_cutoff / psd.delta_f)<EOL>psd[<NUM_LIT:0>:kmin] = psd[kmin]<EOL>psd *= dyn_range_factor ** <NUM_LIT:2><EOL><DEDENT>elif psd_estimation:<EOL><INDENT>psd = welch(strain, avg_method=opt.psd_estimation,<EOL>seg_len=int(opt.psd_segment_length * sample_rate),<EOL>seg_stride=int(opt.psd_segment_stride * sample_rate),<EOL>num_segments=opt.psd_num_segments,<EOL>require_exact_data_fit=False)<EOL>if delta_f != psd.delta_f:<EOL><INDENT>psd = interpolate(psd, delta_f)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if opt.psd_inverse_length:<EOL><INDENT>psd = inverse_spectrum_truncation(psd,<EOL>int(opt.psd_inverse_length * sample_rate),<EOL>low_frequency_cutoff=f_low)<EOL><DEDENT>if hasattr(opt, '<STR_LIT>') and opt.psd_output:<EOL><INDENT>(psd.astype(float64) / (dyn_range_factor ** <NUM_LIT:2>)).save(opt.psd_output)<EOL><DEDENT>if precision is None:<EOL><INDENT>return psd<EOL><DEDENT>elif precision == '<STR_LIT>':<EOL><INDENT>return psd.astype(float32)<EOL><DEDENT>elif precision == '<STR_LIT>':<EOL><INDENT>return psd.astype(float64)<EOL><DEDENT>else:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>" %(precision)<EOL>raise ValueError(err_msg)<EOL><DEDENT>
Parses the CLI options related to the noise PSD and returns a FrequencySeries with the corresponding PSD. If necessary, the PSD is linearly interpolated to achieve the resolution specified in the CLI. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes (psd_model, psd_file, asd_file, psd_estimation, psd_segment_length, psd_segment_stride, psd_inverse_length, psd_output). length : int The length in samples of the output PSD. delta_f : float The frequency step of the output PSD. low_frequency_cutoff: float The low frequncy cutoff to use when calculating the PSD. strain : {None, TimeSeries} Time series containing the data from which the PSD should be measured, when psd_estimation is in use. dyn_range_factor : {1, float} For PSDs taken from models or text files, if `dyn_range_factor` is not None, then the PSD is multiplied by `dyn_range_factor` ** 2. precision : str, choices (None,'single','double') If not specified, or specified as None, the precision of the returned PSD will match the precision of the data, if measuring a PSD, or will match the default precision of the model if using an analytical PSD. If 'single' the PSD will be converted to float32, if not already in that precision. If 'double' the PSD will be converted to float64, if not already in that precision. Returns ------- psd : FrequencySeries The frequency series containing the PSD.
f16051:m0
def from_cli_single_ifo(opt, length, delta_f, low_frequency_cutoff, ifo,<EOL>**kwargs):
single_det_opt = copy_opts_for_single_ifo(opt, ifo)<EOL>return from_cli(single_det_opt, length, delta_f, low_frequency_cutoff,<EOL>**kwargs)<EOL>
Get the PSD for a single ifo when using the multi-detector CLI
f16051:m1
def from_cli_multi_ifos(opt, length_dict, delta_f_dict,<EOL>low_frequency_cutoff_dict, ifos, strain_dict=None,<EOL>**kwargs):
psd = {}<EOL>for ifo in ifos:<EOL><INDENT>if strain_dict is not None:<EOL><INDENT>strain = strain_dict[ifo]<EOL><DEDENT>else:<EOL><INDENT>strain = None<EOL><DEDENT>psd[ifo] = from_cli_single_ifo(opt, length_dict[ifo], delta_f_dict[ifo],<EOL>low_frequency_cutoff_dict[ifo], ifo,<EOL>strain=strain, **kwargs)<EOL><DEDENT>return psd<EOL>
Get the PSD for all ifos when using the multi-detector CLI
f16051:m2
def insert_psd_option_group(parser, output=True, include_data_options=True):
psd_options = parser.add_argument_group(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>choices=get_psd_model_list())<EOL>psd_options.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", default='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>metavar="<STR_LIT>", help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>metavar="<STR_LIT>", help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>metavar="<STR_LIT>", help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>metavar="<STR_LIT>", help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float, metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float, metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>if include_data_options :<EOL><INDENT>psd_options.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>",<EOL>choices=["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=int, default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if output:<EOL><INDENT>psd_options.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>")<EOL><DEDENT>return psd_options<EOL>
Adds the options used to call the pycbc.psd.from_cli function to an optparser as an OptionGroup. This should be used if you want to use these options in your code. Parameters ----------- parser : object OptionParser instance.
f16051:m3
def insert_psd_option_group_multi_ifo(parser):
psd_options = parser.add_argument_group(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>" %('<STR_LIT:U+002CU+0020>'.join(get_psd_model_list()),))<EOL>psd_options.add_argument("<STR_LIT>", nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float, nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float, nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=int, nargs="<STR_LIT:+>",<EOL>default=None,<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float, nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>metavar="<STR_LIT>", help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>metavar="<STR_LIT>", help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>metavar="<STR_LIT>", help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float,<EOL>metavar="<STR_LIT>", help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float, metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>psd_options.add_argument("<STR_LIT>", type=float, metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return psd_options<EOL>
Adds the options used to call the pycbc.psd.from_cli function to an optparser as an OptionGroup. This should be used if you want to use these options in your code. Parameters ----------- parser : object OptionParser instance.
f16051:m4
def verify_psd_options(opt, parser):
try:<EOL><INDENT>psd_estimation = opt.psd_estimation is not None<EOL><DEDENT>except AttributeError:<EOL><INDENT>psd_estimation = False<EOL><DEDENT>for opt_group in ensure_one_opt_groups:<EOL><INDENT>ensure_one_opt(opt, parser, opt_group)<EOL><DEDENT>if psd_estimation:<EOL><INDENT>required_opts(opt, parser,<EOL>['<STR_LIT>', '<STR_LIT>'],<EOL>required_by = "<STR_LIT>")<EOL><DEDENT>
Parses the CLI options and verifies that they are consistent and reasonable. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes (psd_model, psd_file, asd_file, psd_estimation, psd_segment_length, psd_segment_stride, psd_inverse_length, psd_output). parser : object OptionParser instance.
f16051:m5
def verify_psd_options_multi_ifo(opt, parser, ifos):
for ifo in ifos:<EOL><INDENT>for opt_group in ensure_one_opt_groups:<EOL><INDENT>ensure_one_opt_multi_ifo(opt, parser, ifo, opt_group)<EOL><DEDENT>if opt.psd_estimation[ifo]:<EOL><INDENT>required_opts_multi_ifo(opt, parser, ifo,<EOL>['<STR_LIT>', '<STR_LIT>'],<EOL>required_by = "<STR_LIT>")<EOL><DEDENT><DEDENT>
Parses the CLI options and verifies that they are consistent and reasonable. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes (psd_model, psd_file, asd_file, psd_estimation, psd_segment_length, psd_segment_stride, psd_inverse_length, psd_output). parser : object OptionParser instance.
f16051:m6
def generate_overlapping_psds(opt, gwstrain, flen, delta_f, flow,<EOL>dyn_range_factor=<NUM_LIT:1.>, precision=None):
if not opt.psd_estimation:<EOL><INDENT>psd = from_cli(opt, flen, delta_f, flow, strain=gwstrain,<EOL>dyn_range_factor=dyn_range_factor, precision=precision)<EOL>psds_and_times = [ (<NUM_LIT:0>, len(gwstrain), psd) ]<EOL>return psds_and_times<EOL><DEDENT>seg_stride = int(opt.psd_segment_stride * gwstrain.sample_rate)<EOL>seg_len = int(opt.psd_segment_length * gwstrain.sample_rate)<EOL>input_data_len = len(gwstrain)<EOL>if opt.psd_num_segments is None:<EOL><INDENT>num_segments = int(input_data_len // seg_stride) - <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>num_segments = int(opt.psd_num_segments)<EOL><DEDENT>psd_data_len = (num_segments - <NUM_LIT:1>) * seg_stride + seg_len<EOL>psds_and_times = []<EOL>if input_data_len < psd_data_len:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>" %(psd_data_len)<EOL>err_msg += "<STR_LIT>" %(input_data_len)<EOL>raise ValueError(err_msg)<EOL><DEDENT>elif input_data_len == psd_data_len:<EOL><INDENT>num_psd_measurements = <NUM_LIT:1><EOL>psd_stride = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>num_psd_measurements = int(<NUM_LIT:2> * (input_data_len-<NUM_LIT:1>) / psd_data_len)<EOL>psd_stride = int((input_data_len - psd_data_len) / num_psd_measurements)<EOL><DEDENT>for idx in range(num_psd_measurements):<EOL><INDENT>if idx == (num_psd_measurements - <NUM_LIT:1>):<EOL><INDENT>start_idx = input_data_len - psd_data_len<EOL>end_idx = input_data_len<EOL><DEDENT>else:<EOL><INDENT>start_idx = psd_stride * idx<EOL>end_idx = psd_data_len + psd_stride * idx<EOL><DEDENT>strain_part = gwstrain[start_idx:end_idx]<EOL>psd = from_cli(opt, flen, delta_f, flow, strain=strain_part,<EOL>dyn_range_factor=dyn_range_factor, precision=precision)<EOL>psds_and_times.append( (start_idx, end_idx, psd) )<EOL><DEDENT>return psds_and_times<EOL>
Generate a set of overlapping PSDs to cover a stretch of data. This allows one to analyse a long stretch of data with PSD measurements that change with time. Parameters ----------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes (psd_model, psd_file, asd_file, psd_estimation, psd_segment_length, psd_segment_stride, psd_inverse_length, psd_output). gwstrain : Strain object The timeseries of raw data on which to estimate PSDs. flen : int The length in samples of the output PSDs. delta_f : float The frequency step of the output PSDs. flow: float The low frequncy cutoff to use when calculating the PSD. dyn_range_factor : {1, float} For PSDs taken from models or text files, if `dyn_range_factor` is not None, then the PSD is multiplied by `dyn_range_factor` ** 2. precision : str, choices (None,'single','double') If not specified, or specified as None, the precision of the returned PSD will match the precision of the data, if measuring a PSD, or will match the default precision of the model if using an analytical PSD. If 'single' the PSD will be converted to float32, if not already in that precision. If 'double' the PSD will be converted to float64, if not already in that precision. Returns -------- psd_and_times : list of (start, end, PSD) tuples This is a list of tuples containing one entry for each PSD. The first and second entries (start, end) in each tuple represent the index range of the gwstrain data that was used to estimate that PSD. The third entry (psd) contains the PSD estimate between that interval.
f16051:m7
def associate_psds_to_segments(opt, fd_segments, gwstrain, flen, delta_f, flow,<EOL>dyn_range_factor=<NUM_LIT:1.>, precision=None):
psds_and_times = generate_overlapping_psds(opt, gwstrain, flen, delta_f,<EOL>flow, dyn_range_factor=dyn_range_factor,<EOL>precision=precision)<EOL>for fd_segment in fd_segments:<EOL><INDENT>best_psd = None<EOL>psd_overlap = <NUM_LIT:0><EOL>inp_seg = segments.segment(fd_segment.seg_slice.start,<EOL>fd_segment.seg_slice.stop)<EOL>for start_idx, end_idx, psd in psds_and_times:<EOL><INDENT>psd_seg = segments.segment(start_idx, end_idx)<EOL>if psd_seg.intersects(inp_seg):<EOL><INDENT>curr_overlap = abs(inp_seg & psd_seg)<EOL>if curr_overlap > psd_overlap:<EOL><INDENT>psd_overlap = curr_overlap<EOL>best_psd = psd<EOL><DEDENT><DEDENT><DEDENT>if best_psd is None:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>fd_segment.psd = best_psd<EOL><DEDENT>
Generate a set of overlapping PSDs covering the data in GWstrain. Then associate these PSDs with the appropriate segment in strain_segments. Parameters ----------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes (psd_model, psd_file, asd_file, psd_estimation, psd_segment_length, psd_segment_stride, psd_inverse_length, psd_output). fd_segments : StrainSegments.fourier_segments() object The fourier transforms of the various analysis segments. The psd attribute of each segment is updated to point to the appropriate PSD. gwstrain : Strain object The timeseries of raw data on which to estimate PSDs. flen : int The length in samples of the output PSDs. delta_f : float The frequency step of the output PSDs. flow: float The low frequncy cutoff to use when calculating the PSD. dyn_range_factor : {1, float} For PSDs taken from models or text files, if `dyn_range_factor` is not None, then the PSD is multiplied by `dyn_range_factor` ** 2. precision : str, choices (None,'single','double') If not specified, or specified as None, the precision of the returned PSD will match the precision of the data, if measuring a PSD, or will match the default precision of the model if using an analytical PSD. If 'single' the PSD will be converted to float32, if not already in that precision. If 'double' the PSD will be converted to float64, if not already in that precision.
f16051:m8