signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def associate_psds_to_single_ifo_segments(opt, fd_segments, gwstrain, flen,<EOL>delta_f, flow, ifo,<EOL>dyn_range_factor=<NUM_LIT:1.>, precision=None):
single_det_opt = copy_opts_for_single_ifo(opt, ifo)<EOL>associate_psds_to_segments(single_det_opt, fd_segments, gwstrain, flen,<EOL>delta_f, flow, dyn_range_factor=dyn_range_factor,<EOL>precision=precision)<EOL>
Associate PSDs to segments for a single ifo when using the multi-detector CLI
f16051:m9
def associate_psds_to_multi_ifo_segments(opt, fd_segments, gwstrain, flen,<EOL>delta_f, flow, ifos,<EOL>dyn_range_factor=<NUM_LIT:1.>, precision=None):
for ifo in ifos:<EOL><INDENT>if gwstrain is not None:<EOL><INDENT>strain = gwstrain[ifo]<EOL><DEDENT>else:<EOL><INDENT>strain = None<EOL><DEDENT>if fd_segments is not None:<EOL><INDENT>segments = fd_segments[ifo]<EOL><DEDENT>else:<EOL><INDENT>segments = None<EOL><DEDENT>associate_psds_to_single_ifo_segments(opt, segmen...
Associate PSDs to segments for all ifos when using the multi-detector CLI
f16051:m10
def median_bias(n):
if type(n) is not int or n <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if n >= <NUM_LIT:1000>:<EOL><INDENT>return numpy.log(<NUM_LIT:2>)<EOL><DEDENT>ans = <NUM_LIT:1><EOL>for i in range(<NUM_LIT:1>, int((n - <NUM_LIT:1>) / <NUM_LIT:2> + <NUM_LIT:1>)):<EOL><INDENT>ans += <NUM_LIT:1.0> / (<NUM_L...
Calculate the bias of the median average PSD computed from `n` segments. Parameters ---------- n : int Number of segments used in PSD estimation. Returns ------- ans : float Calculated bias. Raises ------ ValueError For non-integer or non-positive `n`. ...
f16052:m0
def welch(timeseries, seg_len=<NUM_LIT>, seg_stride=<NUM_LIT>, window='<STR_LIT>',<EOL>avg_method='<STR_LIT>', num_segments=None, require_exact_data_fit=False):
window_map = {<EOL>'<STR_LIT>': numpy.hanning<EOL>}<EOL>if isinstance(window, numpy.ndarray) and window.size != seg_len:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not isinstance(window, numpy.ndarray) and window not in window_map:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(window))<EOL><DEDENT>if av...
PSD estimator based on Welch's method. Parameters ---------- timeseries : TimeSeries Time series for which the PSD is to be estimated. seg_len : int Segment length in samples. seg_stride : int Separation between consecutive segments, in samples. window : {'hann', numpy.n...
f16052:m1
def inverse_spectrum_truncation(psd, max_filter_len, low_frequency_cutoff=None, trunc_method=None):
<EOL>if type(max_filter_len) is not int or max_filter_len <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if low_frequency_cutoff is not None and low_frequency_cutoff < <NUM_LIT:0>or low_frequency_cutoff > psd.sample_frequencies[-<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>...
Modify a PSD such that the impulse response associated with its inverse square root is no longer than `max_filter_len` time samples. In practice this corresponds to a coarse graining or smoothing of the PSD. Parameters ---------- psd : FrequencySeries PSD whose inverse spectrum is to be tru...
f16052:m2
def interpolate(series, delta_f):
new_n = (len(series)-<NUM_LIT:1>) * series.delta_f / delta_f + <NUM_LIT:1><EOL>samples = numpy.arange(<NUM_LIT:0>, numpy.rint(new_n)) * delta_f<EOL>interpolated_series = numpy.interp(samples, series.sample_frequencies.numpy(), series.numpy())<EOL>return FrequencySeries(interpolated_series, epoch=series.epoch,<EOL>delta...
Return a new PSD that has been interpolated to the desired delta_f. Parameters ---------- series : FrequencySeries Frequency series to be interpolated. delta_f : float The desired delta_f of the output Returns ------- interpolated series : FrequencySeries A new Freq...
f16052:m3
def bandlimited_interpolate(series, delta_f):
series = FrequencySeries(series, dtype=complex_same_precision_as(series), delta_f=series.delta_f)<EOL>N = (len(series) - <NUM_LIT:1>) * <NUM_LIT:2><EOL>delta_t = <NUM_LIT:1.0> / series.delta_f / N<EOL>new_N = int(<NUM_LIT:1.0> / (delta_t * delta_f))<EOL>new_n = new_N // <NUM_LIT:2> + <NUM_LIT:1><EOL>series_in_time = Ti...
Return a new PSD that has been interpolated to the desired delta_f. Parameters ---------- series : FrequencySeries Frequency series to be interpolated. delta_f : float The desired delta_f of the output Returns ------- interpolated series : FrequencySeries A new Freq...
f16052:m4
def calc_psd_variation(strain, psd_short_segment, psd_long_segment,<EOL>short_psd_duration, short_psd_stride, psd_avg_method,<EOL>low_freq, high_freq):
<EOL>if strain.precision == '<STR_LIT>':<EOL><INDENT>fs_dtype = numpy.float32<EOL><DEDENT>elif strain.precision == '<STR_LIT>':<EOL><INDENT>fs_dtype = numpy.float64<EOL><DEDENT>start_time = numpy.float(strain.start_time)<EOL>end_time = numpy.float(strain.end_time)<EOL>times_long = numpy.arange(start_time, end_time, psd...
Calculates time series of PSD variability This function first splits the segment up into 512 second chunks. It then calculates the PSD over this 512 second period as well as in 4 second chunks throughout each 512 second period. Next the function estimates how different the 4 second PSD is to the 512 se...
f16053:m0
def find_trigger_value(psd_var, idx, start, sample_rate):
<EOL>time = start + idx / sample_rate<EOL>ind = numpy.digitize(time, psd_var.sample_times)<EOL>ind -= <NUM_LIT:1><EOL>vals = psd_var[ind]<EOL>return vals<EOL>
Find the PSD variation value at a particular time Parameters ---------- psd_var : TimeSeries Time series of the varaibility in the PSD estimation idx : numpy.ndarray Time indices of the triggers start : float GPS start time sample_rate : float Sample rate defined...
f16053:m1
def from_numpy_arrays(freq_data, noise_data, length, delta_f, low_freq_cutoff):
<EOL>if freq_data[<NUM_LIT:0>] > low_freq_cutoff:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' + str(low_freq_cutoff))<EOL><DEDENT>kmin = int(low_freq_cutoff / delta_f)<EOL>flow = kmin * delta_f<EOL>data_start = (<NUM_LIT:0> if freq_data[<NUM_LIT:0>]==low_freq_cutoff else numpy.searchsorted(freq_data, flow)...
Interpolate n PSD (as two 1-dimensional arrays of frequency and data) to the desired length, delta_f and low frequency cutoff. Parameters ---------- freq_data : array Array of frequencies. noise_data : array PSD values corresponding to frequencies in freq_arr. length : int ...
f16054:m0
def from_txt(filename, length, delta_f, low_freq_cutoff, is_asd_file=True):
file_data = numpy.loadtxt(filename)<EOL>if (file_data < <NUM_LIT:0>).any() ornumpy.logical_not(numpy.isfinite(file_data)).any():<EOL><INDENT>raise ValueError('<STR_LIT>' + filename)<EOL><DEDENT>freq_data = file_data[:, <NUM_LIT:0>]<EOL>noise_data = file_data[:, <NUM_LIT:1>]<EOL>if is_asd_file:<EOL><INDENT>noise_data = ...
Read an ASCII file containing one-sided ASD or PSD data and generate a frequency series with the corresponding PSD. The ASD or PSD data is interpolated in order to match the desired resolution of the generated frequency series. Parameters ---------- filename : string Path to a two-colu...
f16054:m1
def from_xml(filename, length, delta_f, low_freq_cutoff, ifo_string=None,<EOL>root_name='<STR_LIT>'):
import lal.series<EOL>from glue.ligolw import utils as ligolw_utils<EOL>fp = open(filename, '<STR_LIT:r>')<EOL>ct_handler = lal.series.PSDContentHandler<EOL>fileobj, _ = ligolw_utils.load_fileobj(fp, contenthandler=ct_handler)<EOL>psd_dict = lal.series.read_psd_xmldoc(fileobj, root_name=root_name)<EOL>if ifo_string is ...
Read an ASCII file containing one-sided ASD or PSD data and generate a frequency series with the corresponding PSD. The ASD or PSD data is interpolated in order to match the desired resolution of the generated frequency series. Parameters ---------- filename : string Path to a two-colu...
f16054:m2
def nearest_larger_binary_number(input_len):
return int(<NUM_LIT:2>**numpy.ceil(numpy.log2(input_len)))<EOL>
Return the nearest binary number larger than input_len.
f16055:m0
def mchirp_mass1_to_mass2(mchirp, mass1):
return conversions.mass2_from_mchirp_mass1(mchirp, mass1)<EOL>
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 re...
f16055:m6
def eta_mass1_to_mass2(eta, mass1, return_mass_heavier=False, force_real=True):
return conversions.mass_from_knownmass_eta(mass1, eta,<EOL>known_is_secondary=return_mass_heavier, force_real=force_real)<EOL>
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 i...
f16055:m7
def mchirp_q_to_mass1_mass2(mchirp, q):
eta = conversions.eta_from_q(q)<EOL>mass1 = conversions.mass1_from_mchirp_eta(mchirp, eta)<EOL>mass2 = conversions.mass2_from_mchirp_eta(mchirp, eta)<EOL>return mass1, mass2<EOL>
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).
f16055:m8
def A0(f_lower):
return conversions._a0(f_lower)<EOL>
used in calculating chirp times: see Cokelaer, arxiv.org:0706.4437 appendix 1, also lalinspiral/python/sbank/tau0tau3.py
f16055:m9
def A3(f_lower):
return conversions._a3(f_lower)<EOL>
another parameter used for chirp times
f16055:m10
def get_beta_sigma_from_aligned_spins(eta, spin1z, spin2z):
chiS = <NUM_LIT:0.5> * (spin1z + spin2z)<EOL>chiA = <NUM_LIT:0.5> * (spin1z - spin2z)<EOL>delta = (<NUM_LIT:1> - <NUM_LIT:4> * eta) ** <NUM_LIT:0.5><EOL>spinspin = spin1z * spin2z<EOL>beta = (<NUM_LIT> / <NUM_LIT> - <NUM_LIT> / <NUM_LIT> * eta) * chiS<EOL>beta += <NUM_LIT> / <NUM_LIT> * delta * chiA<EOL>sigma = eta / <...
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...
f16055:m15
def f_SchwarzISCO(M):
return conversions.f_schwarzchild_isco(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
f16055:m21
def f_BKLISCO(m1, m2):
<EOL>q = numpy.minimum(m1/m2, m2/m1)<EOL>return f_SchwarzISCO(m1+m2) * ( <NUM_LIT:1> + <NUM_LIT>*q - <NUM_LIT>*q*q + <NUM_LIT>*q*q*q )<EOL>
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 compon...
f16055:m22
def f_LightRing(M):
return <NUM_LIT:1.0> / (<NUM_LIT>**(<NUM_LIT>) * lal.PI * M * lal.MTSUN_SI)<EOL>
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 : float or numpy.array Frequency in Hz
f16055:m23
def f_ERD(M):
return <NUM_LIT> * <NUM_LIT> / (<NUM_LIT:2>*lal.PI * <NUM_LIT> * M * lal.MTSUN_SI)<EOL>
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 ------...
f16055:m24
def f_FRD(m1, m2):
m_total, eta = mass1_mass2_to_mtotal_eta(m1, m2)<EOL>tmp = ( (<NUM_LIT:1.> - <NUM_LIT>*(<NUM_LIT:1.> - <NUM_LIT>*eta + <NUM_LIT>*eta**<NUM_LIT:2>)**(<NUM_LIT>)) /<EOL>(<NUM_LIT:1.> - <NUM_LIT>*eta - <NUM_LIT>*eta**<NUM_LIT:2>) )<EOL>return tmp / (<NUM_LIT>*lal.PI * m_total*lal.MTSUN_SI)<EOL>
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 F...
f16055:m25
def f_LRD(m1, m2):
return <NUM_LIT> * f_FRD(m1, m2)<EOL>
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 : float or numpy.array ...
f16055:m26
def _get_freq(freqfunc, m1, m2, s1z, s2z):
<EOL>m1kg = float(m1) * lal.MSUN_SI<EOL>m2kg = float(m2) * lal.MSUN_SI<EOL>return lalsimulation.SimInspiralGetFrequency(<EOL>m1kg, m2kg, <NUM_LIT:0>, <NUM_LIT:0>, float(s1z), <NUM_LIT:0>, <NUM_LIT:0>, float(s2z), int(freqfunc))<EOL>
Wrapper of the LALSimulation function returning the frequency for a given frequency function and template parameters. Parameters ---------- freqfunc : lalsimulation FrequencyFunction wrapped object e.g. lalsimulation.fEOBNRv2RD m1 : float-ish, i.e. castable to float First component mass in solar masses m2 : fl...
f16055:m27
def get_freq(freqfunc, m1, m2, s1z, s2z):
lalsim_ffunc = getattr(lalsimulation, freqfunc)<EOL>return _vec_get_freq(lalsim_ffunc, m1, m2, s1z, s2z)<EOL>
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 ...
f16055:m28
def _get_final_freq(approx, m1, m2, s1z, s2z):
<EOL>m1kg = float(m1) * lal.MSUN_SI<EOL>m2kg = float(m2) * lal.MSUN_SI<EOL>return lalsimulation.SimInspiralGetFinalFreq(<EOL>m1kg, m2kg, <NUM_LIT:0>, <NUM_LIT:0>, float(s1z), <NUM_LIT:0>, <NUM_LIT:0>, float(s2z), int(approx))<EOL>
Wrapper of the LALSimulation function returning the final (highest) frequency for a given approximant an template parameters Parameters ---------- approx : lalsimulation approximant wrapped object e.g. lalsimulation.EOBNRv2 m1 : float-ish, i.e. castable to float First component mass in solar masses m2 : float-...
f16055:m29
def get_final_freq(approx, m1, m2, s1z, s2z):
lalsim_approx = lalsimulation.GetApproximantFromString(approx)<EOL>return _vec_get_final_freq(lalsim_approx, m1, m2, s1z, s2z)<EOL>
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 ...
f16055:m30
def frequency_cutoff_from_name(name, m1, m2, s1z, s2z):
params = {"<STR_LIT>":m1, "<STR_LIT>":m2, "<STR_LIT>":s1z, "<STR_LIT>":s2z}<EOL>return named_frequency_cutoffs[name](params)<EOL>
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 mas...
f16055:m31
def _get_imr_duration(m1, m2, s1z, s2z, f_low, approximant="<STR_LIT>"):
m1, m2, s1z, s2z, f_low = float(m1), float(m2), float(s1z), float(s2z),float(f_low)<EOL>if approximant == "<STR_LIT>":<EOL><INDENT>chi = lalsimulation.SimIMRPhenomBComputeChi(m1, m2, s1z, s2z)<EOL>time_length = lalsimulation.SimIMRSEOBNRv2ChirpTimeSingleSpin(<EOL>m1 * lal.MSUN_SI, m2 * lal.MSUN_SI, chi, f_low)<EOL><DED...
Wrapper of lalsimulation template duration approximate formula
f16055:m32
def get_inspiral_tf(tc, mass1, mass2, spin1, spin2, f_low, n_points=<NUM_LIT:100>,<EOL>pn_2order=<NUM_LIT:7>, approximant='<STR_LIT>'):
<EOL>class Params:<EOL><INDENT>pass<EOL><DEDENT>params = Params()<EOL>params.mass1 = mass1<EOL>params.mass2 = mass2<EOL>params.spin1z = spin1<EOL>params.spin2z = spin2<EOL>try:<EOL><INDENT>approximant = eval(approximant, {'<STR_LIT>': None},<EOL>dict(params=params))<EOL><DEDENT>except NameError:<EOL><INDENT>pass<EOL><D...
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.
f16055:m33
def _energy_coeffs(m1, m2, chi1, chi2):
mtot = m1 + m2<EOL>eta = m1*m2 / (mtot*mtot)<EOL>chi = (m1*chi1 + m2*chi2) / mtot<EOL>chisym = (chi1 + chi2) / <NUM_LIT><EOL>beta = (<NUM_LIT>*chi - <NUM_LIT>*eta*chisym)/<NUM_LIT><EOL>sigma12 = <NUM_LIT>*eta*chi1*chi2/<NUM_LIT><EOL>sigmaqm = <NUM_LIT>*m1*m1*chi1*chi1/(<NUM_LIT>*mtot*mtot)+ <NUM_LIT>*m2*m2*chi2*chi2/(<...
Return the center-of-mass energy coefficients up to 3.0pN (2.5pN spin)
f16055:m34
def meco_velocity(m1, m2, chi1, chi2):
_, energy2, energy3, energy4, energy5, energy6 =_energy_coeffs(m1, m2, chi1, chi2)<EOL>def eprime(v):<EOL><INDENT>return <NUM_LIT> + v * v * (<NUM_LIT>*energy2 + v * (<NUM_LIT>*energy3+ v * (<NUM_LIT>*energy4<EOL>+ v * (<NUM_LIT>*energy5 + <NUM_LIT>*energy6 * v))))<EOL><DEDENT>return bisect(eprime, <NUM_LIT>, <NUM_LIT:...
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 dimens...
f16055:m35
def _meco_frequency(m1, m2, chi1, chi2):
return velocity_to_frequency(meco_velocity(m1, m2, chi1, chi2), m1+m2)<EOL>
Returns the frequency of the minimum energy cutoff for 3.5pN (2.5pN spin)
f16055:m36
def _dtdv_coeffs(m1, m2, chi1, chi2):
mtot = m1 + m2<EOL>eta = m1*m2 / (mtot*mtot)<EOL>chi = (m1*chi1 + m2*chi2) / mtot<EOL>chisym = (chi1 + chi2) / <NUM_LIT><EOL>beta = (<NUM_LIT>*chi - <NUM_LIT>*eta*chisym)/<NUM_LIT><EOL>sigma12 = <NUM_LIT>*eta*chi1*chi2/<NUM_LIT><EOL>sigmaqm = <NUM_LIT>*m1*m1*chi1*chi1/(<NUM_LIT>*mtot*mtot)+ <NUM_LIT>*m2*m2*chi2*chi2/(<...
Returns the dt/dv coefficients up to 3.5pN (2.5pN spin)
f16055:m37
def energy_coefficients(m1, m2, s1z=<NUM_LIT:0>, s2z=<NUM_LIT:0>, phase_order=-<NUM_LIT:1>, spin_order=-<NUM_LIT:1>):
implemented_phase_order = <NUM_LIT:7><EOL>implemented_spin_order = <NUM_LIT:7><EOL>if phase_order > implemented_phase_order:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif phase_order == -<NUM_LIT:1>:<EOL><INDENT>phase_order = implemented_phase_order<EOL><DEDENT>if spin_order > implemented_spin_order:<EOL><...
Return the energy coefficients. This assumes that the system has aligned spins only.
f16055:m39
def kerr_lightring(v, chi):
return <NUM_LIT:1> + chi * v**<NUM_LIT:3> - <NUM_LIT:3> * v**<NUM_LIT:2> * (<NUM_LIT:1> - chi * v**<NUM_LIT:3>)**(<NUM_LIT:1.>/<NUM_LIT:3>)<EOL>
Return the function whose first root defines the Kerr light ring
f16055:m44
def kerr_lightring_velocity(chi):
<EOL>if chi >= <NUM_LIT>:<EOL><INDENT>return brentq(kerr_lightring, <NUM_LIT:0>, <NUM_LIT>, args=(<NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>return brentq(kerr_lightring, <NUM_LIT:0>, <NUM_LIT>, args=(chi))<EOL><DEDENT>
Return the velocity at the Kerr light ring
f16055:m45
def hybridEnergy(v, m1, m2, chi1, chi2, qm1, qm2):
pi_sq = numpy.pi**<NUM_LIT:2><EOL>v2, v3, v4, v5, v6, v7 = v**<NUM_LIT:2>, v**<NUM_LIT:3>, v**<NUM_LIT:4>, v**<NUM_LIT:5>, v**<NUM_LIT:6>, v**<NUM_LIT:7><EOL>chi1_sq, chi2_sq = chi1**<NUM_LIT:2>, chi2**<NUM_LIT:2><EOL>m1, m2 = float(m1), float(m2)<EOL>M = float(m1 + m2)<EOL>M_2, M_4 = M**<NUM_LIT:2>, M**<NUM_LIT:4><EOL...
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. ...
f16055:m46
def hybrid_meco_velocity(m1, m2, chi1, chi2, qm1=None, qm2=None):
if qm1 is None:<EOL><INDENT>qm1 = <NUM_LIT:1><EOL><DEDENT>if qm2 is None:<EOL><INDENT>qm2 = <NUM_LIT:1><EOL><DEDENT>chi = (chi1 * m1 + chi2 * m2) / (m1 + m2)<EOL>vmax = kerr_lightring_velocity(chi) - <NUM_LIT><EOL>return minimize(hybridEnergy, <NUM_LIT>, args=(m1, m2, chi1, chi2, qm1, qm2),<EOL>bounds=[(<NUM_LIT:0.1>, ...
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 th...
f16055:m47
def hybrid_meco_frequency(m1, m2, chi1, chi2, qm1=None, qm2=None):
if qm1 is None:<EOL><INDENT>qm1 = <NUM_LIT:1><EOL><DEDENT>if qm2 is None:<EOL><INDENT>qm2 = <NUM_LIT:1><EOL><DEDENT>return velocity_to_frequency(hybrid_meco_velocity(m1, m2, chi1, chi2, qm1, qm2), m1 + m2)<EOL>
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 t...
f16055:m48
def check(self, triggers, data_reader):
if len(triggers['<STR_LIT>']) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>i = triggers['<STR_LIT>'].argmax()<EOL>rchisq = triggers['<STR_LIT>'][i]<EOL>nsnr = ranking.newsnr(triggers['<STR_LIT>'][i], rchisq)<EOL>dur = triggers['<STR_LIT>'][i]<EOL>if nsnr > self.newsnr_threshold andrchisq < self.reduced_chisq_thr...
Look for a single detector trigger that passes the thresholds in the current data.
f16056:c0:m3
def start_end_from_segments(segment_file):
from glue.ligolw.ligolw import LIGOLWContentHandler as h; lsctables.use_in(h)<EOL>indoc = ligolw_utils.load_filename(segment_file, False, contenthandler=h)<EOL>segment_table = table.get_table(indoc, lsctables.SegmentTable.tableName)<EOL>start = numpy.array(segment_table.getColumnByName('<STR_LIT>'))<EOL>start_ns = num...
Return the start and end time arrays from a segment file. Parameters ---------- segment_file: xml segment file Returns ------- start: numpy.ndarray end: numpy.ndarray
f16057:m2
def indices_within_times(times, start, end):
<EOL>start, end = segments_to_start_end(start_end_to_segments(start, end).coalesce())<EOL>tsort = times.argsort()<EOL>times_sorted = times[tsort]<EOL>left = numpy.searchsorted(times_sorted, start)<EOL>right = numpy.searchsorted(times_sorted, end)<EOL>if len(left) == <NUM_LIT:0>:<EOL><INDENT>return numpy.array([], dtype...
Return an index array into times that lie within the durations defined by start end arrays Parameters ---------- times: numpy.ndarray Array of times start: numpy.ndarray Array of duration start times end: numpy.ndarray Array of duration end times Returns ------- indices: numpy.ndarray Array of indices...
f16057:m3
def indices_outside_times(times, start, end):
exclude = indices_within_times(times, start, end)<EOL>indices = numpy.arange(<NUM_LIT:0>, len(times))<EOL>return numpy.delete(indices, exclude)<EOL>
Return an index array into times that like outside the durations defined by start end arrays Parameters ---------- times: numpy.ndarray Array of times start: numpy.ndarray Array of duration start times end: numpy.ndarray Array of duration end times Returns ------- indices: numpy.ndarray Array of indic...
f16057:m4
def select_segments_by_definer(segment_file, segment_name=None, ifo=None):
from glue.ligolw.ligolw import LIGOLWContentHandler as h; lsctables.use_in(h)<EOL>indoc = ligolw_utils.load_filename(segment_file, False, contenthandler=h)<EOL>segment_table = table.get_table(indoc, '<STR_LIT>')<EOL>seg_def_table = table.get_table(indoc, '<STR_LIT>')<EOL>def_ifos = seg_def_table.getColumnByName('<STR_...
Return the list of segments that match the segment name Parameters ---------- segment_file: str path to segment xml file segment_name: str Name of segment ifo: str, optional Returns ------- seg: list of segments
f16057:m5
def indices_within_segments(times, segment_files, ifo=None, segment_name=None):
veto_segs = segmentlist([])<EOL>indices = numpy.array([], dtype=numpy.uint32)<EOL>for veto_file in segment_files:<EOL><INDENT>veto_segs += select_segments_by_definer(veto_file, segment_name, ifo)<EOL><DEDENT>veto_segs.coalesce()<EOL>start, end = segments_to_start_end(veto_segs)<EOL>if len(start) > <NUM_LIT:0>:<EOL><IND...
Return the list of indices that should be vetoed by the segments in the list of veto_files. Parameters ---------- times: numpy.ndarray of integer type Array of gps start times segment_files: string or list of strings A string or list of strings that contain the path to xml files tha...
f16057:m6
def indices_outside_segments(times, segment_files, ifo=None, segment_name=None):
exclude, segs = indices_within_segments(times, segment_files,<EOL>ifo=ifo, segment_name=segment_name)<EOL>indices = numpy.arange(<NUM_LIT:0>, len(times))<EOL>return numpy.delete(indices, exclude), segs<EOL>
Return the list of indices that are outside the segments in the list of segment files. Parameters ---------- times: numpy.ndarray of integer type Array of gps start times segment_files: string or list of strings A string or list of strings that contain the path to xml files that ...
f16057:m7
def get_segment_definer_comments(xml_file, include_version=True):
from glue.ligolw.ligolw import LIGOLWContentHandler as h<EOL>lsctables.use_in(h)<EOL>xmldoc, _ = ligolw_utils.load_fileobj(xml_file,<EOL>gz=xml_file.name.endswith("<STR_LIT>"),<EOL>contenthandler=h)<EOL>seg_def_table = table.get_table(xmldoc,<EOL>lsctables.SegmentDefTable.tableName)<EOL>comment_dict = {}<EOL>for seg_de...
Returns a dict with the comment column as the value for each segment
f16057:m8
def insert_bank_bins_option_group(parser):
bins_group = parser.add_argument_group(<EOL>"<STR_LIT>")<EOL>bins_group.add_argument("<STR_LIT>", nargs="<STR_LIT:+>", 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>bins_group.add_argument("<STR_LIT>", default=None...
Add options to the optparser object for selecting templates in bins. Parameters ----------- parser : object OptionParser instance.
f16060:m0
def bank_bins_from_cli(opts):
bank = {}<EOL>fp = h5py.File(opts.bank_file)<EOL>for key in fp.keys():<EOL><INDENT>bank[key] = fp[key][:]<EOL><DEDENT>bank["<STR_LIT>"] = float(opts.f_lower) if opts.f_lower else None<EOL>if opts.bank_bins:<EOL><INDENT>bins_idx = coinc.background_bin_from_string(opts.bank_bins, bank)<EOL><DEDENT>else:<EOL><INDENT>bins_...
Parses the CLI options related to binning templates in the bank. Parameters ---------- opts : object Result of parsing the CLI with OptionParser. Results ------- bins_idx : dict A dict with bin names as key and an array of their indices as value. bank : dict A dict ...
f16060:m1
def insert_loudest_triggers_option_group(parser, coinc_options=True):
opt_group = insert_bank_bins_option_group(parser)<EOL>opt_group.title = "<STR_LIT>"<EOL>if coinc_options:<EOL><INDENT>opt_group.add_argument("<STR_LIT>", default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>opt_group.add_argument("<STR_LIT>", default="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>opt...
Add options to the optparser object for selecting templates in bins. Parameters ----------- parser : object OptionParser instance.
f16060:m2
def loudest_triggers_from_cli(opts, coinc_parameters=None,<EOL>sngl_parameters=None, bank_parameters=None):
<EOL>bin_results = []<EOL>ifos = opts.sngl_trigger_files.keys()<EOL>bins_idx, bank_data = bank_bins_from_cli(opts)<EOL>bin_names = bins_idx.keys()<EOL>if opts.statmap_file and opts.bank_file and opts.sngl_trigger_files:<EOL><INDENT>for bin_name in bin_names:<EOL><INDENT>data = {}<EOL>statmap = hdf.ForegroundTriggers(<E...
Parses the CLI options related to find the loudest coincident or single detector triggers. Parameters ---------- opts : object Result of parsing the CLI with OptionParser. coinc_parameters : list List of datasets in statmap file to retrieve. sngl_parameters : list List o...
f16060:m3
def get_mass_spin(bank, tid):
m1 = bank['<STR_LIT>'][:][tid]<EOL>m2 = bank['<STR_LIT>'][:][tid]<EOL>s1z = bank['<STR_LIT>'][:][tid]<EOL>s2z = bank['<STR_LIT>'][:][tid]<EOL>return m1, m2, s1z, s2z<EOL>
Helper function Parameters ---------- bank : h5py File object Bank parameter file tid : integer or array of int Indices of the entries to be returned Returns ------- m1, m2, s1z, s2z : tuple of floats or arrays of floats Parameter values of the bank entries
f16060:m4
def get_param(par, args, m1, m2, s1z, s2z):
if par == '<STR_LIT>':<EOL><INDENT>parvals = conversions.mchirp_from_mass1_mass2(m1, m2)<EOL><DEDENT>elif par == '<STR_LIT>':<EOL><INDENT>parvals = m1 + m2<EOL><DEDENT>elif par == '<STR_LIT>':<EOL><INDENT>parvals = conversions.eta_from_mass1_mass2(m1, m2)<EOL><DEDENT>elif par in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>...
Helper function Parameters ---------- par : string Name of parameter to calculate args : Namespace object returned from ArgumentParser instance Calling code command line options, used for f_lower value m1 : float or array of floats First binary component mass (etc.) Returns ------- parvals : float or arra...
f16060:m5
def get_found_param(injfile, bankfile, trigfile, param, ifo, args=None):
foundtmp = injfile["<STR_LIT>"][:]<EOL>if trigfile is not None:<EOL><INDENT>ifolabel = [name for name, val in injfile.attrs.items() if"<STR_LIT>" in name and val == ifo][<NUM_LIT:0>]<EOL>foundtrg = injfile["<STR_LIT>" + ifolabel[-<NUM_LIT:1>]]<EOL><DEDENT>if bankfile is not None and param in bankfile.keys():<EOL><INDEN...
Translates some popular trigger parameters into functions that calculate them from an hdf found injection file Parameters ---------- injfile: hdf5 File object Injection file of format known to ANitz (DOCUMENTME) bankfile: hdf5 File object or None Template bank file trigfile: hdf5 File object or None Single...
f16060:m6
def get_inj_param(injfile, param, ifo, args=None):
det = pycbc.detector.Detector(ifo)<EOL>inj = injfile["<STR_LIT>"]<EOL>if param in inj.keys():<EOL><INDENT>return inj["<STR_LIT>"+param]<EOL><DEDENT>if param == "<STR_LIT>"+ifo[<NUM_LIT:0>].lower():<EOL><INDENT>return inj['<STR_LIT>'][:] + det.time_delay_from_earth_center(<EOL>inj['<STR_LIT>'][:],<EOL>inj['<STR_LIT>'][:...
Translates some popular injection parameters into functions that calculate them from an hdf found injection file Parameters ---------- injfile: hdf5 File object Injection file of format known to ANitz (DOCUMENTME) param: string Parameter to be calculated for the injected signals ifo: string Standard detect...
f16060:m7
def background_bin_from_string(background_bins, data):
used = numpy.array([], dtype=numpy.uint32)<EOL>bins = {}<EOL>for mbin in background_bins:<EOL><INDENT>name, bin_type, boundary = tuple(mbin.split('<STR_LIT::>'))<EOL>if boundary[<NUM_LIT:0>:<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>member_func = lambda vals, bd=boundary : vals < float(bd[<NUM_LIT:2>:])<EOL><DEDENT>elif ...
Return template ids for each bin as defined by the format string Parameters ---------- bins: list of strings List of strings which define how a background bin is taken from the list of templates. data: dict of numpy.ndarrays Dict with parameter key values and numpy.ndarray value...
f16061:m0
def calculate_n_louder(bstat, fstat, dec, skip_background=False):
sort = bstat.argsort()<EOL>bstat = bstat[sort]<EOL>dec = dec[sort]<EOL>n_louder = dec[::-<NUM_LIT:1>].cumsum()[::-<NUM_LIT:1>] - dec<EOL>idx = numpy.searchsorted(bstat, fstat, side='<STR_LIT:left>') - <NUM_LIT:1><EOL>if isinstance(idx, numpy.ndarray): <EOL><INDENT>idx[idx < <NUM_LIT:0>] = <NUM_LIT:0><EOL><DEDENT>else: ...
Calculate for each foreground event the number of background events that are louder than it. Parameters ---------- bstat: numpy.ndarray Array of the background statistic values fstat: numpy.ndarray Array of the foreground statitsic values dec: numpy.ndarray Array of the ...
f16061:m1
def timeslide_durations(start1, start2, end1, end2, timeslide_offsets):
from . import veto<EOL>durations = []<EOL>seg2 = veto.start_end_to_segments(start2, end2)<EOL>for offset in timeslide_offsets:<EOL><INDENT>seg1 = veto.start_end_to_segments(start1 + offset, end1 + offset)<EOL>durations.append(abs((seg1 & seg2).coalesce()))<EOL><DEDENT>return numpy.array(durations)<EOL>
Find the coincident time for each timeslide. Find the coincident time for each timeslide, where the first time vector is slid to the right by the offset in the given timeslide_offsets vector. Parameters ---------- start1: numpy.ndarray Array of the start of valid analyzed times for detecto...
f16061:m2
def time_coincidence(t1, t2, window, slide_step=<NUM_LIT:0>):
if slide_step:<EOL><INDENT>fold1 = t1 % slide_step<EOL>fold2 = t2 % slide_step<EOL><DEDENT>else:<EOL><INDENT>fold1 = t1<EOL>fold2 = t2<EOL><DEDENT>sort1 = fold1.argsort()<EOL>sort2 = fold2.argsort()<EOL>fold1 = fold1[sort1]<EOL>fold2 = fold2[sort2]<EOL>if slide_step:<EOL><INDENT>fold2 = numpy.concatenate([fold2 - slide...
Find coincidences by time window Parameters ---------- t1 : numpy.ndarray Array of trigger times from the first detector t2 : numpy.ndarray Array of trigger times from the second detector window : float The coincidence window in seconds slide_step : optional, {None, floa...
f16061:m3
def time_multi_coincidence(times, slide_step=<NUM_LIT:0>, slop=<NUM_LIT>,<EOL>pivot='<STR_LIT>', fixed='<STR_LIT>'):
<EOL>def win(ifo1, ifo2):<EOL><INDENT>d1 = Detector(ifo1)<EOL>d2 = Detector(ifo2)<EOL>return d1.light_travel_time_to_detector(d2) + slop<EOL><DEDENT>pivot_id, fix_id, slide = time_coincidence(times[pivot], times[fixed],<EOL>win(pivot, fixed),<EOL>slide_step=slide_step)<EOL>fixed_time = times[fixed][fix_id]<EOL>pivot_ti...
Find multi detector concidences. Parameters ---------- times: dict of numpy.ndarrays Dictionary keyed by ifo of the times of each single detector trigger. slide_step: float The interval between time slides slop: float The amount of time to add to the TOF between detectors fo...
f16061:m4
def cluster_coincs(stat, time1, time2, timeslide_id, slide, window, argmax=numpy.argmax):
logging.info('<STR_LIT>' % window)<EOL>if len(time1) == <NUM_LIT:0> or len(time2) == <NUM_LIT:0>:<EOL><INDENT>logging.info('<STR_LIT>')<EOL>return numpy.array([])<EOL><DEDENT>if numpy.isfinite(slide):<EOL><INDENT>time = (time1 + time2 + timeslide_id * slide) / <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>time = <NUM_LIT:0...
Cluster coincident events for each timeslide separately, across templates, based on the ranking statistic Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time1: numpy.ndarray first time vector time2: numpy.ndarray second time vector tim...
f16061:m5
def cluster_coincs_multiifo(stat, time_coincs, timeslide_id, slide, window, argmax=numpy.argmax):
time_coinc_zip = zip(*time_coincs)<EOL>if len(time_coinc_zip) == <NUM_LIT:0>:<EOL><INDENT>logging.info('<STR_LIT>')<EOL>return numpy.array([])<EOL><DEDENT>time_avg_num = []<EOL>for tc in time_coinc_zip:<EOL><INDENT>time_avg_num.append(mean_if_greater_than_zero(tc))<EOL><DEDENT>time_avg, num_ifos = zip(*time_avg_num)<EO...
Cluster coincident events for each timeslide separately, across templates, based on the ranking statistic Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time_coincs: tuple of numpy.ndarrays trigger times for each ifo, or -1 if an ifo does not particip...
f16061:m6
def mean_if_greater_than_zero(vals):
vals = numpy.array(vals)<EOL>above_zero = vals > <NUM_LIT:0><EOL>return vals[above_zero].mean(), above_zero.sum()<EOL>
Calculate mean over numerical values, ignoring values less than zero. E.g. used for mean time over coincident triggers when timestamps are set to -1 for ifos not included in the coincidence. Parameters ---------- vals: iterator of numerical values values to be mean averaged Returns ...
f16061:m7
def cluster_over_time(stat, time, window, argmax=numpy.argmax):
logging.info('<STR_LIT>', window)<EOL>indices = []<EOL>time_sorting = time.argsort()<EOL>stat = stat[time_sorting]<EOL>time = time[time_sorting]<EOL>left = numpy.searchsorted(time, time - window)<EOL>right = numpy.searchsorted(time, time + window)<EOL>indices = numpy.zeros(len(left), dtype=numpy.uint32)<EOL>i = <NUM_LI...
Cluster generalized transient events over time via maximum stat over a symmetric sliding window Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time: numpy.ndarray time to use for clustering window: float length to cluster over argmax: ...
f16061:m8
def __init__(self, num_rings, max_time, dtype):
self.max_time = max_time<EOL>self.buffer = []<EOL>self.buffer_expire = []<EOL>for _ in range(num_rings):<EOL><INDENT>self.buffer.append(numpy.zeros(<NUM_LIT:0>, dtype=dtype))<EOL>self.buffer_expire.append(numpy.zeros(<NUM_LIT:0>, dtype=int))<EOL><DEDENT>self.time = <NUM_LIT:0><EOL>
Parameters ---------- num_rings: int The number of ring buffers to create. They all will have the same intrinsic size and will expire at the same time. max_time: int The maximum "time" an element can exist in each ring. dtype: numpy.dtype The type of each element in the ring buffer.
f16061:c0:m0
def discard_last(self, indices):
for i in indices:<EOL><INDENT>self.buffer_expire[i] = self.buffer_expire[i][:-<NUM_LIT:1>]<EOL>self.buffer[i] = self.buffer[i][:-<NUM_LIT:1>]<EOL><DEDENT>
Discard the triggers added in the latest update
f16061:c0:m4
def advance_time(self):
self.time += <NUM_LIT:1><EOL>
Advance the internal time increment by 1, expiring any triggers that are now too old.
f16061:c0:m5
def add(self, indices, values):
for i, v in zip(indices, values):<EOL><INDENT>self.buffer[i] = numpy.append(self.buffer[i], v)<EOL>self.buffer_expire[i] = numpy.append(self.buffer_expire[i], self.time)<EOL><DEDENT>self.advance_time()<EOL>
Add triggers in 'values' to the buffers indicated by the indices
f16061:c0:m6
def expire_vector(self, buffer_index):
return self.buffer_expire[buffer_index]<EOL>
Return the expiration vector of a given ring buffer
f16061:c0:m7
def data(self, buffer_index):
<EOL>expired = self.time - self.max_time <EOL>exp = self.buffer_expire[buffer_index]<EOL>j = <NUM_LIT:0><EOL>while j < len(exp):<EOL><INDENT>if exp[j] >= expired:<EOL><INDENT>self.buffer_expire[buffer_index] = exp[j:].copy()<EOL>self.buffer[buffer_index] = self.buffer[buffer_index][j:].copy()<EOL>break<EOL><DEDENT>...
Return the data vector for a given ring buffer
f16061:c0:m8
def __init__(self, expiration, ifos,<EOL>initial_size=<NUM_LIT:2>**<NUM_LIT:20>, dtype=numpy.float32):
self.expiration = expiration<EOL>self.buffer = numpy.zeros(initial_size, dtype=dtype)<EOL>self.index = <NUM_LIT:0><EOL>self.ifos = ifos<EOL>self.time = {}<EOL>self.timer = {}<EOL>for ifo in self.ifos:<EOL><INDENT>self.time[ifo] = <NUM_LIT:0><EOL>self.timer[ifo] = numpy.zeros(initial_size, dtype=numpy.int32)<EOL><DEDENT...
Parameters ---------- expiration: int The 'time' in arbitrary integer units to allow to pass before removing an element. ifos: list of strs List of strings to identify the multiple data expiration times. initial_size: int, optional The initial size of the buffer. dtype: numpy.dtype The dtype of each...
f16061:c1:m0
def increment(self, ifos):
self.add([], [], ifos)<EOL>
Increment without adding triggers
f16061:c1:m3
def remove(self, num):
self.index -= num<EOL>
Remove the the last 'num' elements from the buffer
f16061:c1:m4
def add(self, values, times, ifos):
for ifo in ifos:<EOL><INDENT>self.time[ifo] += <NUM_LIT:1><EOL><DEDENT>if self.index + len(values) >= len(self.buffer):<EOL><INDENT>newlen = len(self.buffer) * <NUM_LIT:2><EOL>for ifo in self.ifos:<EOL><INDENT>self.timer[ifo].resize(newlen)<EOL><DEDENT>self.buffer.resize(newlen)<EOL><DEDENT>self.buffer[self.index:self....
Add values to the internal buffer Parameters ---------- values: numpy.ndarray Array of elements to add to the internal buffer. times: dict of arrays The current time to use for each element being added. ifos: list of strs The set of timers to ...
f16061:c1:m5
def num_greater(self, value):
return (self.buffer[:self.index] > value).sum()<EOL>
Return the number of elements larger than 'value
f16061:c1:m6
@property<EOL><INDENT>def data(self):<DEDENT>
return self.buffer[:self.index]<EOL>
Return the array of elements
f16061:c1:m7
def __init__(self, num_templates, analysis_block, background_statistic,<EOL>stat_files, ifos,<EOL>ifar_limit=<NUM_LIT:100>,<EOL>timeslide_interval=<NUM_LIT>,<EOL>coinc_threshold=<NUM_LIT>,<EOL>return_background=False):
from . import stat<EOL>self.num_templates = num_templates<EOL>self.analysis_block = analysis_block<EOL>for fname in stat_files:<EOL><INDENT>f = h5py.File(fname, '<STR_LIT:r>')<EOL>ifos_set = set([f.attrs['<STR_LIT>'], f.attrs['<STR_LIT>']])<EOL>f.close()<EOL>if ifos_set == set(ifos):<EOL><INDENT>stat_files = [fname]<EO...
Parameters ---------- num_templates: int The size of the template bank analysis_block: int The number of seconds in each analysis segment background_statistic: str The name of the statistic to rank coincident events. stat_files: list of strs List of filenames that contain information used to construct ...
f16061:c2:m0
@classmethod<EOL><INDENT>def pick_best_coinc(cls, coinc_results):<DEDENT>
mstat = <NUM_LIT:0><EOL>mifar = <NUM_LIT:0><EOL>mresult = None<EOL>trials = <NUM_LIT:0><EOL>for result in coinc_results:<EOL><INDENT>if '<STR_LIT>' in result:<EOL><INDENT>trials += <NUM_LIT:1><EOL>if '<STR_LIT>' in result:<EOL><INDENT>ifar = result['<STR_LIT>']<EOL>stat = result['<STR_LIT>']<EOL>if ifar > mifar or (ifa...
Choose the best two-ifo coinc by ifar first, then statistic if needed. This function picks which of the available double-ifo coincs to use. It chooses the best (highest) ifar. The ranking statistic is used as a tie-breaker. A trials factor is applied if multiple types of coincs are poss...
f16061:c2:m1
@property<EOL><INDENT>def background_time(self):<DEDENT>
time = <NUM_LIT:1.0> / self.timeslide_interval<EOL>for ifo in self.singles:<EOL><INDENT>time *= self.singles[ifo].filled_time * self.analysis_block<EOL><DEDENT>return time<EOL>
Return the amount of background time that the buffers contain
f16061:c2:m4
def save_state(self, filename):
import cPickle<EOL>cPickle.dump(self, filename)<EOL>
Save the current state of the background buffers
f16061:c2:m5
@staticmethod<EOL><INDENT>def restore_state(filename):<DEDENT>
import cPickle<EOL>return cPickle.load(filename)<EOL>
Restore state of the background buffers from a file
f16061:c2:m6
def ifar(self, coinc_stat):
n = self.coincs.num_greater(coinc_stat)<EOL>return self.background_time / lal.YRJUL_SI / (n + <NUM_LIT:1>)<EOL>
Return the far that would be associated with the coincident given.
f16061:c2:m7
def set_singles_buffer(self, results):
<EOL>self.singles_dtype = []<EOL>data = False<EOL>for ifo in self.ifos:<EOL><INDENT>if ifo in results and results[ifo] is not False:<EOL><INDENT>data = results[ifo]<EOL>break<EOL><DEDENT><DEDENT>if data is False:<EOL><INDENT>return<EOL><DEDENT>for key in data:<EOL><INDENT>self.singles_dtype.append((key, data[key].dtype...
Create the singles buffer This creates the singles buffer for each ifo. The dtype is determined by a representative sample of the single triggers in the results. Parameters ---------- restuls: dict of dict Dict indexed by ifo and then trigger column.
f16061:c2:m8
def _add_singles_to_buffer(self, results, ifos):
if len(self.singles.keys()) == <NUM_LIT:0>:<EOL><INDENT>self.set_singles_buffer(results)<EOL><DEDENT>logging.info("<STR_LIT>")<EOL>updated_indices = {}<EOL>for ifo in ifos:<EOL><INDENT>trigs = results[ifo]<EOL>if len(trigs['<STR_LIT>'] > <NUM_LIT:0>):<EOL><INDENT>trigsc = copy.copy(trigs)<EOL>trigsc['<STR_LIT>'] = trig...
Add single detector triggers to the internal buffer Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it determined by the LiveBatchMatchedFilter class. R...
f16061:c2:m9
def _find_coincs(self, results, ifos):
<EOL>cstat = [[]]<EOL>offsets = []<EOL>ctimes = {self.ifos[<NUM_LIT:0>]:[], self.ifos[<NUM_LIT:1>]:[]}<EOL>single_expire = {self.ifos[<NUM_LIT:0>]:[], self.ifos[<NUM_LIT:1>]:[]}<EOL>template_ids = [[]]<EOL>trigger_ids = {self.ifos[<NUM_LIT:0>]:[[]], self.ifos[<NUM_LIT:1>]:[[]]}<EOL>for ifo in ifos:<EOL><INDENT>trigs = ...
Look for coincs within the set of single triggers Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it determined by the LiveBatchMatchedFilter class. Ret...
f16061:c2:m10
def backout_last(self, updated_singles, num_coincs):
for ifo in updated_singles:<EOL><INDENT>self.singles[ifo].discard_last(updated_singles[ifo])<EOL><DEDENT>self.coincs.remove(num_coincs)<EOL>
Remove the recently added singles and coincs Parameters ---------- updated_singles: dict of numpy.ndarrays Array of indices that have been just updated in the internal buffers of single detector triggers. num_coincs: int The number of coincs that were...
f16061:c2:m11
def add_singles(self, results):
<EOL>logging.info('<STR_LIT>',<EOL>len(self.coincs), self.coincs.nbytes)<EOL>valid_ifos = [k for k in results.keys() if results[k] and k in self.ifos]<EOL>if len(valid_ifos) == <NUM_LIT:0>: return {}<EOL>self._add_singles_to_buffer(results, ifos=valid_ifos)<EOL>_, coinc_results = self._find_coincs(results, ifos=valid_i...
Add singles to the bacckground estimate and find candidates Parameters ---------- results: dict of arrays Dictionary of dictionaries indexed by ifo and keys such as 'snr', 'chisq', etc. The specific format it determined by the LiveBatchMatchedFilter class. ...
f16061:c2:m12
def multiifo_noise_coinc_rate(rates, slop):
ifos = numpy.array(sorted(rates.keys()))<EOL>rates_raw = list(rates[ifo] for ifo in ifos)<EOL>expected_coinc_rates = {}<EOL>allowed_area = multiifo_noise_coincident_area(ifos, slop)<EOL>rateprod = [numpy.prod(rs) for rs in zip(*rates_raw)]<EOL>ifostring = '<STR_LIT:U+0020>'.join(ifos)<EOL>expected_coinc_rates[ifostring...
Calculate the expected rate of noise coincidences for multiple detectors Parameters ---------- rates: dict Dictionary keyed on ifo string Value is a sequence of single-detector trigger rates, units assumed to be Hz slop: float time added to maximum time-of-flight between detectors to account for ti...
f16062:m0
def multiifo_noise_coincident_area(ifos, slop):
<EOL>dets = {}<EOL>for ifo in ifos:<EOL><INDENT>dets[ifo] = pycbc.detector.Detector(ifo)<EOL><DEDENT>n_ifos = len(ifos)<EOL>if n_ifos == <NUM_LIT:2>:<EOL><INDENT>allowed_area = <NUM_LIT> *(dets[ifos[<NUM_LIT:0>]].light_travel_time_to_detector(dets[ifos[<NUM_LIT:1>]]) + slop)<EOL><DEDENT>elif n_ifos == <NUM_LIT:3>:<EOL>...
calculate the total extent of time offset between 2 detectors, or area of the 2d space of time offsets for 3 detectors, for which a coincidence can be generated Parameters ---------- ifos: list of strings list of interferometers slop: float extra time to add to maximum time-of-flight for timing error Returns ...
f16062:m1
def multiifo_signal_coincident_area(ifos):
n_ifos = len(ifos)<EOL>if n_ifos == <NUM_LIT:2>:<EOL><INDENT>det0 = pycbc.detector.Detector(ifos[<NUM_LIT:0>])<EOL>det1 = pycbc.detector.Detector(ifos[<NUM_LIT:1>])<EOL>allowed_area = <NUM_LIT:2> * det0.light_travel_time_to_detector(det1)<EOL><DEDENT>elif n_ifos == <NUM_LIT:3>:<EOL><INDENT>dets = {}<EOL>tofs = numpy.ze...
Calculate the area in which signal time differences are physically allowed Parameters ---------- ifos: list of strings list of interferometers Returns ------- allowed_area: float area in units of seconds^(n_ifos-1) that coincident signals will occupy
f16062:m2
def effsnr(snr, reduced_x2, fac=<NUM_LIT>):
snr = numpy.array(snr, ndmin=<NUM_LIT:1>, dtype=numpy.float64)<EOL>rchisq = numpy.array(reduced_x2, ndmin=<NUM_LIT:1>, dtype=numpy.float64)<EOL>esnr = snr / (<NUM_LIT:1> + snr ** <NUM_LIT:2> / fac) ** <NUM_LIT> / rchisq ** <NUM_LIT><EOL>if hasattr(snr, '<STR_LIT>'):<EOL><INDENT>return esnr<EOL><DEDENT>else:<EOL><INDENT...
Calculate the effective SNR statistic. See (S5y1 paper) for definition.
f16065:m0
def newsnr(snr, reduced_x2, q=<NUM_LIT>, n=<NUM_LIT>):
nsnr = numpy.array(snr, ndmin=<NUM_LIT:1>, dtype=numpy.float64)<EOL>reduced_x2 = numpy.array(reduced_x2, ndmin=<NUM_LIT:1>, dtype=numpy.float64)<EOL>ind = numpy.where(reduced_x2 > <NUM_LIT:1.>)[<NUM_LIT:0>]<EOL>nsnr[ind] *= (<NUM_LIT:0.5> * (<NUM_LIT:1.> + reduced_x2[ind] ** (q/n))) ** (-<NUM_LIT:1.>/q)<EOL>if hasattr(...
Calculate the re-weighted SNR statistic ('newSNR') from given SNR and reduced chi-squared values. See http://arxiv.org/abs/1208.3491 for definition. Previous implementation in glue/ligolw/lsctables.py
f16065:m1
def newsnr_sgveto(snr, bchisq, sgchisq):
nsnr = numpy.array(newsnr(snr, bchisq), ndmin=<NUM_LIT:1>)<EOL>sgchisq = numpy.array(sgchisq, ndmin=<NUM_LIT:1>)<EOL>t = numpy.array(sgchisq > <NUM_LIT:4>, ndmin=<NUM_LIT:1>)<EOL>if len(t):<EOL><INDENT>nsnr[t] = nsnr[t] / (sgchisq[t] / <NUM_LIT>) ** <NUM_LIT:0.5><EOL><DEDENT>if hasattr(snr, '<STR_LIT>'):<EOL><INDENT>re...
Combined SNR derived from NewSNR and Sine-Gaussian Chisq
f16065:m2
def newsnr_sgveto_psdvar(snr, bchisq, sgchisq, psd_var_val):
nsnr = numpy.array(newsnr_sgveto(snr, bchisq, sgchisq), ndmin=<NUM_LIT:1>)<EOL>psd_var_val = numpy.array(psd_var_val, ndmin=<NUM_LIT:1>)<EOL>lgc = psd_var_val >= <NUM_LIT><EOL>nsnr[lgc] = nsnr[lgc] / numpy.sqrt(psd_var_val[lgc])<EOL>if hasattr(snr, '<STR_LIT>'):<EOL><INDENT>return nsnr<EOL><DEDENT>else:<EOL><INDENT>ret...
Combined SNR derived from NewSNR, Sine-Gaussian Chisq and PSD variation statistic
f16065:m3
def get_newsnr(trigs):
dof = <NUM_LIT> * trigs['<STR_LIT>'][:] - <NUM_LIT><EOL>nsnr = newsnr(trigs['<STR_LIT>'][:], trigs['<STR_LIT>'][:] / dof)<EOL>return numpy.array(nsnr, ndmin=<NUM_LIT:1>, dtype=numpy.float32)<EOL>
Calculate newsnr ('reweighted SNR') for a trigs object Parameters ---------- trigs: dict of numpy.ndarrays, h5py group (or similar dict-like object) Dictionary-like object holding single detector trigger information. 'chisq_dof', 'snr', and 'chisq' are required keys Returns ------- numpy.ndarray Array of ...
f16065:m4
def get_newsnr_sgveto(trigs):
dof = <NUM_LIT> * trigs['<STR_LIT>'][:] - <NUM_LIT><EOL>nsnr_sg = newsnr_sgveto(trigs['<STR_LIT>'][:],<EOL>trigs['<STR_LIT>'][:] / dof,<EOL>trigs['<STR_LIT>'][:])<EOL>return numpy.array(nsnr_sg, ndmin=<NUM_LIT:1>, dtype=numpy.float32)<EOL>
Calculate newsnr re-weigthed by the sine-gaussian veto Parameters ---------- trigs: dict of numpy.ndarrays, h5py group (or similar dict-like object) Dictionary-like object holding single detector trigger information. 'chisq_dof', 'snr', 'sg_chisq' and 'chisq' are required keys Returns ------- numpy.ndarray ...
f16065:m5
def get_newsnr_sgveto_psdvar(trigs):
dof = <NUM_LIT> * trigs['<STR_LIT>'][:] - <NUM_LIT><EOL>nsnr_sg_psd =newsnr_sgveto_psdvar(trigs['<STR_LIT>'][:], trigs['<STR_LIT>'][:] / dof,<EOL>trigs['<STR_LIT>'][:],<EOL>trigs['<STR_LIT>'][:])<EOL>return numpy.array(nsnr_sg_psd, ndmin=<NUM_LIT:1>, dtype=numpy.float32)<EOL>
Calculate newsnr re-weighted by the sine-gaussian veto and psd variation statistic Parameters ---------- trigs: dict of numpy.ndarrays Dictionary holding single detector trigger information. 'chisq_dof', 'snr', 'chisq' and 'psd_var_val' are required keys Returns ------- numpy.ndarray Array of newsnr values
f16065:m6