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, segments, strain, flen,<EOL>delta_f, flow, ifo, dyn_range_factor=dyn_range_factor,<EOL>precision=precision)<EOL><DEDENT>
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_LIT:2>*i + <NUM_LIT:1>) - <NUM_LIT:1.0> / (<NUM_LIT:2>*i)<EOL><DEDENT>return ans<EOL>
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`. Notes ----- See arXiv:gr-qc/0509116 appendix B for details.
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 avg_method not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if type(seg_len) is not int or type(seg_stride) is not intor seg_len <= <NUM_LIT:0> or seg_stride <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if timeseries.precision == '<STR_LIT>':<EOL><INDENT>fs_dtype = numpy.complex64<EOL><DEDENT>elif timeseries.precision == '<STR_LIT>':<EOL><INDENT>fs_dtype = numpy.complex128<EOL><DEDENT>num_samples = len(timeseries)<EOL>if num_segments is None:<EOL><INDENT>num_segments = int(num_samples // seg_stride)<EOL>if (num_segments - <NUM_LIT:1>) * seg_stride + seg_len > num_samples:<EOL><INDENT>num_segments -= <NUM_LIT:1><EOL><DEDENT><DEDENT>if not require_exact_data_fit:<EOL><INDENT>data_len = (num_segments - <NUM_LIT:1>) * seg_stride + seg_len<EOL>if data_len < num_samples:<EOL><INDENT>diff = num_samples - data_len<EOL>start = diff // <NUM_LIT:2><EOL>end = num_samples - diff // <NUM_LIT:2><EOL>if diff % <NUM_LIT:2>:<EOL><INDENT>start = start + <NUM_LIT:1><EOL><DEDENT>timeseries = timeseries[start:end]<EOL>num_samples = len(timeseries)<EOL><DEDENT>if data_len > num_samples:<EOL><INDENT>err_msg = "<STR_LIT>" %(data_len)<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>" %(num_samples)<EOL><DEDENT><DEDENT>if num_samples != (num_segments - <NUM_LIT:1>) * seg_stride + seg_len:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not isinstance(window, numpy.ndarray):<EOL><INDENT>window = window_map[window](seg_len)<EOL><DEDENT>w = Array(window.astype(timeseries.dtype))<EOL>delta_f = <NUM_LIT:1.> / timeseries.delta_t / seg_len<EOL>segment_tilde = FrequencySeries(<EOL>numpy.zeros(int(seg_len / <NUM_LIT:2> + <NUM_LIT:1>)),<EOL>delta_f=delta_f,<EOL>dtype=fs_dtype,<EOL>)<EOL>segment_psds = []<EOL>for i in range(num_segments):<EOL><INDENT>segment_start = i * seg_stride<EOL>segment_end = segment_start + seg_len<EOL>segment = timeseries[segment_start:segment_end]<EOL>assert len(segment) == seg_len<EOL>fft(segment * w, segment_tilde)<EOL>seg_psd = abs(segment_tilde * segment_tilde.conj()).numpy()<EOL>seg_psd[<NUM_LIT:0>] /= <NUM_LIT:2><EOL>seg_psd[-<NUM_LIT:1>] /= <NUM_LIT:2><EOL>segment_psds.append(seg_psd)<EOL><DEDENT>segment_psds = numpy.array(segment_psds)<EOL>if avg_method == '<STR_LIT>':<EOL><INDENT>psd = numpy.mean(segment_psds, axis=<NUM_LIT:0>)<EOL><DEDENT>elif avg_method == '<STR_LIT>':<EOL><INDENT>psd = numpy.median(segment_psds, axis=<NUM_LIT:0>) / median_bias(num_segments)<EOL><DEDENT>elif avg_method == '<STR_LIT>':<EOL><INDENT>odd_psds = segment_psds[::<NUM_LIT:2>]<EOL>even_psds = segment_psds[<NUM_LIT:1>::<NUM_LIT:2>]<EOL>odd_median = numpy.median(odd_psds, axis=<NUM_LIT:0>) /median_bias(len(odd_psds))<EOL>even_median = numpy.median(even_psds, axis=<NUM_LIT:0>) /median_bias(len(even_psds))<EOL>psd = (odd_median + even_median) / <NUM_LIT:2><EOL><DEDENT>psd *= <NUM_LIT:2> * delta_f * seg_len / (w*w).sum()<EOL>return FrequencySeries(psd, delta_f=delta_f, dtype=timeseries.dtype,<EOL>epoch=timeseries.start_time)<EOL>
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.ndarray} Function used to window segments before Fourier transforming, or a `numpy.ndarray` that specifies the window. avg_method : {'median', 'mean', 'median-mean'} Method used for averaging individual segment PSDs. Returns ------- psd : FrequencySeries Frequency series containing the estimated PSD. Raises ------ ValueError For invalid choices of `seg_len`, `seg_stride` `window` and `avg_method` and for inconsistent combinations of len(`timeseries`), `seg_len` and `seg_stride`. Notes ----- See arXiv:gr-qc/0509116 for details.
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>N = (len(psd)-<NUM_LIT:1>)*<NUM_LIT:2><EOL>inv_asd = FrequencySeries((<NUM_LIT:1.> / psd)**<NUM_LIT:0.5>, delta_f=psd.delta_f,dtype=complex_same_precision_as(psd))<EOL>inv_asd[<NUM_LIT:0>] = <NUM_LIT:0><EOL>inv_asd[N//<NUM_LIT:2>] = <NUM_LIT:0><EOL>q = TimeSeries(numpy.zeros(N), delta_t=(N / psd.delta_f),dtype=real_same_precision_as(psd))<EOL>if low_frequency_cutoff:<EOL><INDENT>kmin = int(low_frequency_cutoff / psd.delta_f)<EOL>inv_asd[<NUM_LIT:0>:kmin] = <NUM_LIT:0><EOL><DEDENT>ifft(inv_asd, q)<EOL>trunc_start = max_filter_len // <NUM_LIT:2><EOL>trunc_end = N - max_filter_len // <NUM_LIT:2><EOL>if trunc_end < trunc_start:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if trunc_method == '<STR_LIT>':<EOL><INDENT>trunc_window = Array(numpy.hanning(max_filter_len), dtype=q.dtype)<EOL>q[<NUM_LIT:0>:trunc_start] *= trunc_window[max_filter_len//<NUM_LIT:2>:max_filter_len]<EOL>q[trunc_end:N] *= trunc_window[<NUM_LIT:0>:max_filter_len//<NUM_LIT:2>]<EOL><DEDENT>if trunc_start < trunc_end:<EOL><INDENT>q[trunc_start:trunc_end] = <NUM_LIT:0><EOL><DEDENT>psd_trunc = FrequencySeries(numpy.zeros(len(psd)), delta_f=psd.delta_f,dtype=complex_same_precision_as(psd))<EOL>fft(q, psd_trunc)<EOL>psd_trunc *= psd_trunc.conj()<EOL>psd_out = <NUM_LIT:1.> / abs(psd_trunc)<EOL>return psd_out<EOL>
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 truncated. max_filter_len : int Maximum length of the time-domain filter in samples. low_frequency_cutoff : {None, int} Frequencies below `low_frequency_cutoff` are zeroed in the output. trunc_method : {None, 'hann'} Function used for truncating the time-domain filter. None produces a hard truncation at `max_filter_len`. Returns ------- psd : FrequencySeries PSD whose inverse spectrum has been truncated. Raises ------ ValueError For invalid types or values of `max_filter_len` and `low_frequency_cutoff`. Notes ----- See arXiv:gr-qc/0509116 for details.
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_f=delta_f, dtype=series.dtype)<EOL>
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 FrequencySeries that has been interpolated.
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 = TimeSeries(zeros(N), dtype=real_same_precision_as(series), delta_t=delta_t)<EOL>ifft(series, series_in_time)<EOL>padded_series_in_time = TimeSeries(zeros(new_N), dtype=series_in_time.dtype, delta_t=delta_t)<EOL>padded_series_in_time[<NUM_LIT:0>:N//<NUM_LIT:2>] = series_in_time[<NUM_LIT:0>:N//<NUM_LIT:2>]<EOL>padded_series_in_time[new_N-N//<NUM_LIT:2>:new_N] = series_in_time[N//<NUM_LIT:2>:N]<EOL>interpolated_series = FrequencySeries(zeros(new_n), dtype=series.dtype, delta_f=delta_f)<EOL>fft(padded_series_in_time, interpolated_series)<EOL>return interpolated_series<EOL>
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 FrequencySeries that has been interpolated.
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_long_segment)<EOL>psd_var = TimeSeries(zeros(int(numpy.ceil((end_time -<EOL>start_time) / psd_short_segment))),<EOL>delta_t=psd_short_segment, copy=False,<EOL>epoch=start_time)<EOL>ind = <NUM_LIT:0><EOL>for tlong in times_long:<EOL><INDENT>if tlong + psd_long_segment <= end_time:<EOL><INDENT>psd_long = pycbc.psd.welch(<EOL>strain.time_slice(tlong, tlong + psd_long_segment),<EOL>seg_len=int(short_psd_duration * strain.sample_rate),<EOL>seg_stride=int(short_psd_stride *<EOL>strain.sample_rate),<EOL>avg_method=psd_avg_method)<EOL>times_short = numpy.arange(tlong, tlong + psd_long_segment,<EOL>psd_short_segment)<EOL><DEDENT>else:<EOL><INDENT>psd_long = pycbc.psd.welch(<EOL>strain.time_slice(end_time - psd_long_segment,<EOL>end_time),<EOL>seg_len=int(short_psd_duration * strain.sample_rate),<EOL>seg_stride=int(short_psd_stride *<EOL>strain.sample_rate),<EOL>avg_method=psd_avg_method)<EOL>times_short = numpy.arange(tlong, end_time, psd_short_segment)<EOL><DEDENT>psd_short = []<EOL>for tshort in times_short:<EOL><INDENT>if tshort + psd_short_segment <= end_time:<EOL><INDENT>pshort = pycbc.psd.welch(<EOL>strain.time_slice(tshort, tshort +<EOL>psd_short_segment),<EOL>seg_len=int(short_psd_duration *<EOL>strain.sample_rate),<EOL>seg_stride=int(short_psd_stride *<EOL>strain.sample_rate),<EOL>avg_method=psd_avg_method)<EOL><DEDENT>else:<EOL><INDENT>pshort = pycbc.psd.welch(<EOL>strain.time_slice(tshort - psd_short_segment,<EOL>end_time),<EOL>seg_len=int(short_psd_duration *<EOL>strain.sample_rate),<EOL>seg_stride=int(short_psd_stride *<EOL>strain.sample_rate),<EOL>avg_method=psd_avg_method)<EOL><DEDENT>psd_short.append(pshort)<EOL><DEDENT>kmin = int(low_freq / psd_long.delta_f)<EOL>kmax = int(high_freq / psd_long.delta_f)<EOL>freqs = FrequencySeries(psd_long.sample_frequencies,<EOL>delta_f=psd_long.delta_f,<EOL>epoch=psd_long.epoch, dtype=fs_dtype)<EOL>weight = numpy.array(<EOL>freqs[kmin:kmax]**(-<NUM_LIT>/<NUM_LIT>) / psd_long[kmin:kmax])<EOL>weight /= weight.sum()<EOL>diff = numpy.array([(weight * numpy.array(p_short[kmin:kmax] /<EOL>psd_long[kmin:kmax])).sum()<EOL>for p_short in psd_short])<EOL>for i, val in enumerate(diff):<EOL><INDENT>psd_var[ind+i] = val<EOL><DEDENT>ind = ind+len(diff)<EOL><DEDENT>return psd_var<EOL>
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 second PSD and produces a timeseries of this variability. Parameters ---------- strain : TimeSeries Input strain time series to estimate PSDs psd_short_segment : {float, 8} Duration of the short segments for PSD estimation in seconds. psd_long_segment : {float, 512} Duration of the long segments for PSD estimation in seconds. short_psd_duration : {float, 4} Duration of the segments for PSD estimation in seconds. short_psd_stride : {float, 2} Separation between PSD estimation segments in seconds. psd_avg_method : {string, 'median'} Method for averaging PSD estimation segments. low_freq : {float, 20} Minimum frequency to consider the comparison between PSDs. high_freq : {float, 480} Maximum frequency to consider the comparison between PSDs. Returns ------- psd_var : TimeSeries Time series of the variability in the PSD estimation
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 in ini file Returns ------- vals : Array PSD variation value at a particular time
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) - <NUM_LIT:1>)<EOL>if freq_data[data_start+<NUM_LIT:1>] == low_freq_cutoff:<EOL><INDENT>data_start += <NUM_LIT:1><EOL><DEDENT>freq_data = freq_data[data_start:]<EOL>noise_data = noise_data[data_start:]<EOL>flog = numpy.log(freq_data)<EOL>slog = numpy.log(noise_data)<EOL>psd_interp = scipy.interpolate.interp1d(flog, slog)<EOL>kmin = int(low_freq_cutoff / delta_f)<EOL>psd = numpy.zeros(length, dtype=numpy.float64)<EOL>vals = numpy.log(numpy.arange(kmin, length) * delta_f)<EOL>psd[kmin:] = numpy.exp(psd_interp(vals))<EOL>return FrequencySeries(psd, delta_f=delta_f)<EOL>
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 Length of the frequency series in samples. delta_f : float Frequency resolution of the frequency series in Herz. low_freq_cutoff : float Frequencies below this value are set to zero. Returns ------- psd : FrequencySeries The generated frequency series.
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 = noise_data ** <NUM_LIT:2><EOL><DEDENT>return from_numpy_arrays(freq_data, noise_data, length, delta_f,<EOL>low_freq_cutoff)<EOL>
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-column ASCII file. The first column must contain the frequency (positive frequencies only) and the second column must contain the amplitude density OR power spectral density. length : int Length of the frequency series in samples. delta_f : float Frequency resolution of the frequency series in Herz. low_freq_cutoff : float Frequencies below this value are set to zero. is_asd_file : Boolean If false assume that the second column holds power spectral density. If true assume that the second column holds amplitude spectral density. Default: True Returns ------- psd : FrequencySeries The generated frequency series. Raises ------ ValueError If the ASCII file contains negative, infinite or NaN frequencies or amplitude densities.
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 not None:<EOL><INDENT>psd_freq_series = psd_dict[ifo_string]<EOL><DEDENT>else:<EOL><INDENT>if len(psd_dict.keys()) == <NUM_LIT:1>:<EOL><INDENT>psd_freq_series = psd_dict[psd_dict.keys()[<NUM_LIT:0>]]<EOL><DEDENT>else:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT><DEDENT>noise_data = psd_freq_series.data.data[:]<EOL>freq_data = numpy.arange(len(noise_data)) * psd_freq_series.deltaF<EOL>return from_numpy_arrays(freq_data, noise_data, length, delta_f,<EOL>low_freq_cutoff)<EOL>
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-column ASCII file. The first column must contain the frequency (positive frequencies only) and the second column must contain the amplitude density OR power spectral density. length : int Length of the frequency series in samples. delta_f : float Frequency resolution of the frequency series in Herz. low_freq_cutoff : float Frequencies below this value are set to zero. ifo_string : string Use the PSD in the file's PSD dictionary with this ifo string. If not given and only one PSD present in the file return that, if not given and multiple (or zero) PSDs present an exception will be raised. root_name : string (default='psd') If given use this as the root name for the PSD XML file. If this means nothing to you, then it is probably safe to ignore this option. Returns ------- psd : FrequencySeries The generated frequency series.
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 real.
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 it being the lighter mass. By default the value corresponding to mass1 > mass2 is returned. Use the return_mass_heavier kwarg to invert this behaviour.
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 / <NUM_LIT> * (<NUM_LIT> * spinspin)<EOL>sigma += (<NUM_LIT:1> - <NUM_LIT:2> * eta) * (<NUM_LIT> / <NUM_LIT> * (chiS * chiS + chiA * chiA))<EOL>sigma += delta * (<NUM_LIT> / <NUM_LIT> * (chiS * chiA))<EOL>gamma = (<NUM_LIT> / <NUM_LIT> - <NUM_LIT> / <NUM_LIT> * eta -<NUM_LIT> / <NUM_LIT> * eta * eta) * chiS<EOL>gamma += (<NUM_LIT> / <NUM_LIT> + <NUM_LIT> / <NUM_LIT> * eta) * delta * chiA<EOL>return beta, sigma, gamma<EOL>
Calculate the various PN spin combinations from the masses and spins. See <http://arxiv.org/pdf/0810.5336v3.pdf>. Parameters ----------- eta : float or numpy.array Symmetric mass ratio of the input system(s) spin1z : float or numpy.array Spin(s) parallel to the orbit of the heaviest body(ies) spin2z : float or numpy.array Spin(s) parallel to the orbit of the smallest body(ies) Returns -------- beta : float or numpy.array The 1.5PN spin combination sigma : float or numpy.array The 2PN spin combination gamma : float or numpy.array The 2.5PN spin combination chis : float or numpy.array (spin1z + spin2z) / 2.
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 component mass in solar mass units Returns ------- f : float or numpy.array Frequency in Hz
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 ------- f : float or numpy.array Frequency in Hz
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 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 Frequency in Hz
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 Frequency in Hz
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 : float-ish Second component mass in solar masses s1z : float-ish First component dimensionless spin S_1/m_1^2 projected onto L s2z : float-ish Second component dimensionless spin S_2/m_2^2 projected onto L Returns ------- f : float Frequency in Hz
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 Second component mass in solar masses s1z : float or numpy.array First component dimensionless spin S_1/m_1^2 projected onto L s2z : float or numpy.array Second component dimensionless spin S_2/m_2^2 projected onto L Returns ------- f : float or numpy.array Frequency in Hz
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-ish Second component mass in solar masses s1z : float-ish First component dimensionless spin S_1/m_1^2 projected onto L s2z : float-ish Second component dimensionless spin S_2/m_2^2 projected onto L Returns ------- f : float Frequency in Hz
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 First component mass in solar masses m2 : float or numpy.array Second component mass in solar masses s1z : float or numpy.array First component dimensionless spin S_1/m_1^2 projected onto L s2z : float or numpy.array Second component dimensionless spin S_2/m_2^2 projected onto L Returns ------- f : float or numpy.array Frequency in Hz
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 masses s1z : float or numpy.array First component dimensionless spin S_1/m_1^2 projected onto L s2z : float or numpy.array Second component dimensionless spin S_2/m_2^2 projected onto L Returns ------- f : float or numpy.array Frequency in Hz
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><DEDENT>elif approximant == "<STR_LIT>":<EOL><INDENT>time_length = lalsimulation.SimIMRPhenomDChirpTime(<EOL>m1 * lal.MSUN_SI, m2 * lal.MSUN_SI, s1z, s2z, f_low)<EOL><DEDENT>elif approximant == "<STR_LIT>":<EOL><INDENT>time_length = lalsimulation.SimIMRSEOBNRv4ROMTimeOfFrequency(<EOL>f_low, m1 * lal.MSUN_SI, m2 * lal.MSUN_SI, s1z, s2z)<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>" % approximant)<EOL><DEDENT>return time_length * <NUM_LIT><EOL>
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><DEDENT>if approximant in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>from pycbc.waveform.spa_tmplt import findchirp_chirptime<EOL>f_high = f_SchwarzISCO(mass1 + mass2)<EOL>track_f = numpy.logspace(numpy.log10(f_low), numpy.log10(f_high),<EOL>n_points)<EOL>track_t = numpy.array([findchirp_chirptime(float(mass1), float(mass2),<EOL>float(f), pn_2order) for f in track_f])<EOL><DEDENT>elif approximant in ['<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>f_high = get_final_freq('<STR_LIT>', mass1, mass2, spin1, spin2)<EOL>track_f = numpy.logspace(numpy.log10(f_low), numpy.log10(f_high),<EOL>n_points)<EOL>track_t = numpy.array([<EOL>lalsimulation.SimIMRSEOBNRv2ROMDoubleSpinHITimeOfFrequency(f,<EOL>solar_mass_to_kg(mass1), solar_mass_to_kg(mass2),<EOL>float(spin1), float(spin2)) for f in track_f])<EOL><DEDENT>elif approximant in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>f_high = get_final_freq('<STR_LIT>', mass1, mass2, spin1, spin2)<EOL>track_f = numpy.logspace(numpy.log10(f_low), numpy.log10(<NUM_LIT>*f_high),<EOL>n_points)<EOL>track_t = numpy.array([<EOL>lalsimulation.SimIMRSEOBNRv4ROMTimeOfFrequency(<EOL>f, solar_mass_to_kg(mass1), solar_mass_to_kg(mass2),<EOL>float(spin1), float(spin2)) for f in track_f])<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' + approximant + '<STR_LIT>')<EOL><DEDENT>return (tc - track_t, track_f)<EOL>
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/(<NUM_LIT>*mtot*mtot)<EOL>energy0 = -<NUM_LIT:0.5>*eta<EOL>energy2 = -<NUM_LIT> - eta/<NUM_LIT><EOL>energy3 = <NUM_LIT:0.><EOL>energy4 = -<NUM_LIT> + (<NUM_LIT>*eta)/<NUM_LIT> - pow(eta,<NUM_LIT:2>)/<NUM_LIT><EOL>energy5 = <NUM_LIT:0.><EOL>energy6 = -<NUM_LIT> - (<NUM_LIT>*pow(eta,<NUM_LIT:2>))/<NUM_LIT> - (<NUM_LIT>*pow(eta,<NUM_LIT:3>))/<NUM_LIT>+ eta*(<NUM_LIT> - (<NUM_LIT>*pow(lal.PI,<NUM_LIT:2>))/<NUM_LIT>)<EOL>energy3 += (<NUM_LIT:32>*beta)/<NUM_LIT> + (<NUM_LIT>*chisym*eta)/<NUM_LIT><EOL>energy4 += (-<NUM_LIT:16>*sigma12)/<NUM_LIT> - (<NUM_LIT:16>*sigmaqm)/<NUM_LIT><EOL>energy5 += (<NUM_LIT>*beta)/<NUM_LIT> + ((-<NUM_LIT>*beta)/<NUM_LIT> - (<NUM_LIT>*chisym)/<NUM_LIT>)*eta- (<NUM_LIT>*chisym*pow(eta,<NUM_LIT:2>))/<NUM_LIT><EOL>return (energy0, energy2, energy3, energy4, energy5, energy6)<EOL>
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:1.0>)<EOL>
Returns the velocity of the minimum energy cutoff for 3.5pN (2.5pN spin) Parameters ---------- m1 : float First component mass in solar masses m2 : float Second component mass in solar masses chi1 : float First component dimensionless spin S_1/m_1^2 projected onto L chi2 : float Second component dimensionless spin S_2/m_2^2 projected onto L Returns ------- v : float Velocity (dimensionless)
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/(<NUM_LIT>*mtot*mtot)<EOL>dtdv0 = <NUM_LIT:1.> <EOL>dtdv2 = (<NUM_LIT:1.>/<NUM_LIT>) * (<NUM_LIT> + <NUM_LIT>*eta)<EOL>dtdv3 = -<NUM_LIT> * lal.PI + beta<EOL>dtdv4 = (<NUM_LIT> + <NUM_LIT>*eta + <NUM_LIT>*eta*eta)/<NUM_LIT> - sigma12 - sigmaqm<EOL>dtdv5 = (<NUM_LIT:1.>/<NUM_LIT>) * lal.PI * (-<NUM_LIT> + <NUM_LIT>*eta) + (<NUM_LIT>*beta/<NUM_LIT> + <NUM_LIT>*beta*eta/<NUM_LIT> - <NUM_LIT>*chisym*eta/<NUM_LIT> - <NUM_LIT>*chisym*eta*eta/<NUM_LIT>)<EOL>dtdv6 = <NUM_LIT> + <NUM_LIT>*eta - <NUM_LIT>*eta*eta + <NUM_LIT>*eta*eta*eta<EOL>dtdv6log = <NUM_LIT>/<NUM_LIT><EOL>dtdv7 = (lal.PI/<NUM_LIT>) * (-<NUM_LIT> - <NUM_LIT>*eta + <NUM_LIT>*eta*eta)<EOL>return (dtdv0, dtdv2, dtdv3, dtdv4, dtdv5, dtdv6, dtdv6log, dtdv7)<EOL>
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><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif spin_order == -<NUM_LIT:1>:<EOL><INDENT>spin_order = implemented_spin_order<EOL><DEDENT>qmdef1 = <NUM_LIT:1.0><EOL>qmdef2 = <NUM_LIT:1.0><EOL>M = m1 + m2<EOL>dm = (m1-m2)/M<EOL>m1M = m1 / M<EOL>m2M = m2 / M<EOL>s1z = s1z * m1M * m1M<EOL>s2z = s2z * m2M * m2M<EOL>_, eta = mass1_mass2_to_mchirp_eta(m1, m2)<EOL>ecof = numpy.zeros(phase_order+<NUM_LIT:1>)<EOL>if phase_order >= <NUM_LIT:0>:<EOL><INDENT>ecof[<NUM_LIT:0>] = <NUM_LIT:1.0><EOL><DEDENT>if phase_order >= <NUM_LIT:1>:<EOL><INDENT>ecof[<NUM_LIT:1>] = <NUM_LIT:0><EOL><DEDENT>if phase_order >= <NUM_LIT:2>:<EOL><INDENT>ecof[<NUM_LIT:2>] = -(<NUM_LIT:1.0>/<NUM_LIT>) * (<NUM_LIT> + eta)<EOL><DEDENT>if phase_order >= <NUM_LIT:3>:<EOL><INDENT>ecof[<NUM_LIT:3>] = <NUM_LIT:0><EOL><DEDENT>if phase_order >= <NUM_LIT:4>:<EOL><INDENT>ecof[<NUM_LIT:4>] = (-<NUM_LIT> + <NUM_LIT>*eta - eta*eta) / <NUM_LIT><EOL><DEDENT>if phase_order >= <NUM_LIT:5>:<EOL><INDENT>ecof[<NUM_LIT:5>] = <NUM_LIT:0><EOL><DEDENT>if phase_order >= <NUM_LIT:6>:<EOL><INDENT>ecof[<NUM_LIT:6>] = - <NUM_LIT>/<NUM_LIT> + ( <NUM_LIT>/<NUM_LIT>- <NUM_LIT>/<NUM_LIT> * lal.PI * lal.PI ) * eta- (<NUM_LIT>/<NUM_LIT>) *eta * eta - <NUM_LIT>/<NUM_LIT> * eta * eta<EOL><DEDENT>ESO15s1 = <NUM_LIT>/<NUM_LIT> + <NUM_LIT>*m2/m1<EOL>ESO15s2 = <NUM_LIT>/<NUM_LIT> + <NUM_LIT>*m1/m2<EOL>ESS2 = <NUM_LIT:1.0> / eta<EOL>EQM2s1 = qmdef1/<NUM_LIT>/m1M/m1M<EOL>EQM2s1L = -qmdef1*<NUM_LIT>/<NUM_LIT>/m1M/m1M<EOL>EQM2s2L = -qmdef2*<NUM_LIT>/<NUM_LIT>/m2M/m2M<EOL>ESO25s1 = <NUM_LIT> - <NUM_LIT>*eta/<NUM_LIT> + (dm/m1M) * (-<NUM_LIT> + <NUM_LIT>*eta/<NUM_LIT>)<EOL>ESO25s2 = <NUM_LIT> - <NUM_LIT>*eta/<NUM_LIT> + (dm/m2M) * (<NUM_LIT> - <NUM_LIT>*eta/<NUM_LIT>)<EOL>ESO35s1 = <NUM_LIT>/<NUM_LIT> - <NUM_LIT>*eta/<NUM_LIT> + <NUM_LIT>*eta*eta/<NUM_LIT> + (dm/m1M) * (-<NUM_LIT>/<NUM_LIT> + <NUM_LIT>*eta - <NUM_LIT>*eta*eta/<NUM_LIT>)<EOL>ESO35s2 = <NUM_LIT>/<NUM_LIT> - <NUM_LIT>*eta/<NUM_LIT> + <NUM_LIT>*eta*eta/<NUM_LIT> - (dm/m2M) * (-<NUM_LIT>/<NUM_LIT> + <NUM_LIT>*eta - <NUM_LIT>*eta*eta/<NUM_LIT>)<EOL>if spin_order >=<NUM_LIT:3>:<EOL><INDENT>ecof[<NUM_LIT:3>] += ESO15s1 * s1z + ESO15s2 * s2z<EOL><DEDENT>if spin_order >=<NUM_LIT:4>:<EOL><INDENT>ecof[<NUM_LIT:4>] += ESS2 * (s1z*s2z - <NUM_LIT>*s1z*s2z)<EOL>ecof[<NUM_LIT:4>] += EQM2s1*s1z*s1z + EQM2s1*s2z*s2z + EQM2s1L*s1z*s1z + EQM2s2L*s2z*s2z<EOL><DEDENT>if spin_order >=<NUM_LIT:5>:<EOL><INDENT>ecof[<NUM_LIT:5>] = ESO25s1*s1z + ESO25s2*s2z<EOL><DEDENT>if spin_order >=<NUM_LIT:7>:<EOL><INDENT>ecof[<NUM_LIT:7>] += ESO35s1*s1z + ESO35s2*s2z<EOL><DEDENT>return ecof<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>eta = m1 * m2 / M_2<EOL>eta2, eta3 = eta**<NUM_LIT:2>, eta**<NUM_LIT:3><EOL>m1_2, m1_4 = m1**<NUM_LIT:2>, m1**<NUM_LIT:4><EOL>m2_2, m2_4 = m2**<NUM_LIT:2>, m2**<NUM_LIT:4><EOL>chi = (chi1 * m1 + chi2 * m2) / M<EOL>Kerr = -<NUM_LIT:1.> + (<NUM_LIT:1.> - <NUM_LIT> * v2 * (<NUM_LIT:1.> - chi * v3)**(<NUM_LIT:1.>/<NUM_LIT>)) /numpy.sqrt((<NUM_LIT:1.> - chi * v3) * (<NUM_LIT:1.> + chi * v3 - <NUM_LIT> * v2 * (<NUM_LIT:1> - chi * v3)**(<NUM_LIT:1.>/<NUM_LIT>)))<EOL>h_E = Kerr -(v2 / <NUM_LIT>) *(<EOL>- eta * v2 / <NUM_LIT> - <NUM_LIT:2> * (chi1 + chi2) * eta * v3 / <NUM_LIT> +<EOL>(<NUM_LIT> * eta / <NUM_LIT> - eta2 / <NUM_LIT> + chi1_sq * m1_2 * (<NUM_LIT:1> - qm1) / M_2 +<EOL>chi2_sq * m2_2 * (<NUM_LIT:1> - qm2) / M_2) * v4<EOL>- <NUM_LIT:1.> / <NUM_LIT> * (<NUM_LIT> * (chi1 + chi2) * eta2 +<EOL>(<NUM_LIT> * chi1 + <NUM_LIT> * chi2) * m1_2 * eta / M_2 +<EOL>(<NUM_LIT> * chi1 + <NUM_LIT> * chi2) * m2_2 * eta / M_2) * v5<EOL>+ (<NUM_LIT> * eta / <NUM_LIT> - <NUM_LIT> * pi_sq * eta / <NUM_LIT> - <NUM_LIT> * eta2 / <NUM_LIT> -<EOL><NUM_LIT> * eta3 / <NUM_LIT> +<EOL><NUM_LIT> / <NUM_LIT> * (<NUM_LIT> * chi1_sq * (<NUM_LIT:1.> - qm1) * m1_4 / M_4 +<EOL><NUM_LIT> * chi2_sq * (<NUM_LIT:1.> - qm2) * m2_4 / M_4 +<EOL>(chi1_sq * (<NUM_LIT> - <NUM_LIT> * qm1) + <NUM_LIT> * chi1 * chi2) * eta * m1_2 / M_2 +<EOL>(chi2_sq * (<NUM_LIT> - <NUM_LIT> * qm2) + <NUM_LIT> * chi1 * chi2) * eta * m2_2 / M_2 +<EOL>(chi1_sq * (<NUM_LIT> - <NUM_LIT> * qm1) + <NUM_LIT> * chi1 * chi2 +<EOL>chi2_sq * (<NUM_LIT> - <NUM_LIT> * qm2)) * eta2)) * v6<EOL>- eta / <NUM_LIT> * (<NUM_LIT> * (<NUM_LIT> * chi1 + <NUM_LIT> * chi2) * m1_4 / M_4 +<EOL><NUM_LIT> * (<NUM_LIT> * chi1 + <NUM_LIT> * chi2) * m2_4 / M_4 +<EOL><NUM_LIT> * (<NUM_LIT> * chi1 + <NUM_LIT> * chi2) * eta * m1_2 / M_2 +<EOL><NUM_LIT> * (<NUM_LIT> * chi1 + <NUM_LIT> * chi2) * eta * m2_2 / M_2 +<EOL><NUM_LIT> * eta2 * (chi1 + chi2)) * v7<EOL>)<EOL>return h_E<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. chi1: float Dimensionless spin of the primary object. chi2: float Dimensionless spin of the secondary object. qm1: float Quadrupole-monopole term of the primary object (1 for black holes). qm2: float Quadrupole-monopole term of the secondary object (1 for black holes). Returns ------- h_E: float The hybrid energy as a function of v
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>, vmax)]).x.item()<EOL>
Return the velocity of the hybrid MECO Parameters ---------- m1 : float Mass of the primary object in solar masses. m2 : float Mass of the secondary object in solar masses. chi1: float Dimensionless spin of the primary object. chi2: float Dimensionless spin of the secondary object. qm1: {None, float}, optional Quadrupole-monopole term of the primary object (1 for black holes). If None, will be set to qm1 = 1. qm2: {None, float}, optional Quadrupole-monopole term of the secondary object (1 for black holes). If None, will be set to qm2 = 1. Returns ------- v: float The velocity (dimensionless) of the hybrid MECO
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 the secondary object. qm1: {None, float}, optional Quadrupole-monopole term of the primary object (1 for black holes). If None, will be set to qm1 = 1. qm2: {None, float}, optional Quadrupole-monopole term of the secondary object (1 for black holes). If None, will be set to qm2 = 1. Returns ------- f: float The frequency (in Hz) of the hybrid MECO
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_threshold anddur > self.duration_threshold:<EOL><INDENT>fake_coinc = {'<STR_LIT>' % (self.ifo, k): triggers[k][i]<EOL>for k in triggers}<EOL>fake_coinc['<STR_LIT>'] = nsnr<EOL>fake_coinc['<STR_LIT>'] = self.fixed_ifar<EOL>fake_coinc['<STR_LIT>'] = data_reader.near_hwinj()<EOL>return fake_coinc<EOL><DEDENT>return None<EOL>
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 = numpy.array(segment_table.getColumnByName('<STR_LIT>'))<EOL>end = numpy.array(segment_table.getColumnByName('<STR_LIT>'))<EOL>end_ns = numpy.array(segment_table.getColumnByName('<STR_LIT>'))<EOL>return start + start_ns * <NUM_LIT>, end + end_ns * <NUM_LIT><EOL>
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=numpy.uint32)<EOL><DEDENT>return tsort[numpy.hstack(numpy.r_[s:e] for s, e in zip(left, right))]<EOL>
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 into times
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 indices into times
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_LIT>')<EOL>def_names = seg_def_table.getColumnByName('<STR_LIT:name>')<EOL>def_ids = seg_def_table.getColumnByName('<STR_LIT>')<EOL>valid_id = []<EOL>for def_ifo, def_name, def_id in zip(def_ifos, def_names, def_ids):<EOL><INDENT>if ifo and ifo != def_ifo:<EOL><INDENT>continue<EOL><DEDENT>if segment_name and segment_name != def_name:<EOL><INDENT>continue<EOL><DEDENT>valid_id += [def_id]<EOL><DEDENT>start = numpy.array(segment_table.getColumnByName('<STR_LIT>'))<EOL>start_ns = numpy.array(segment_table.getColumnByName('<STR_LIT>'))<EOL>end = numpy.array(segment_table.getColumnByName('<STR_LIT>'))<EOL>end_ns = numpy.array(segment_table.getColumnByName('<STR_LIT>'))<EOL>start, end = start + <NUM_LIT> * start_ns, end + <NUM_LIT> * end_ns<EOL>did = segment_table.getColumnByName('<STR_LIT>')<EOL>keep = numpy.array([d in valid_id for d in did])<EOL>if sum(keep) > <NUM_LIT:0>:<EOL><INDENT>return start_end_to_segments(start[keep], end[keep])<EOL><DEDENT>else:<EOL><INDENT>return segmentlist([])<EOL><DEDENT>
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><INDENT>idx = indices_within_times(times, start, end)<EOL>indices = numpy.union1d(indices, idx)<EOL><DEDENT>return indices, veto_segs.coalesce()<EOL>
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 that contain a segment table ifo: string, optional The ifo to retrieve segments for from the segment files segment_name: str, optional name of segment Returns ------- indices: numpy.ndarray The array of index values within the segments segmentlist: The segment list corresponding to the selected time.
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 contain a segment table ifo: string, optional The ifo to retrieve segments for from the segment files segment_name: str, optional name of segment Returns -------- indices: numpy.ndarray The array of index values outside the segments segmentlist: The segment list corresponding to the selected time.
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_def in seg_def_table:<EOL><INDENT>if include_version:<EOL><INDENT>full_channel_name = '<STR_LIT::>'.join([str(seg_def.ifos),<EOL>str(seg_def.name),<EOL>str(seg_def.version)])<EOL><DEDENT>else:<EOL><INDENT>full_channel_name = '<STR_LIT::>'.join([str(seg_def.ifos),<EOL>str(seg_def.name)])<EOL><DEDENT>comment_dict[full_channel_name] = seg_def.comment<EOL><DEDENT>return comment_dict<EOL>
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,<EOL>help="<STR_LIT>")<EOL>bins_group.add_argument("<STR_LIT>", default=None,<EOL>help="<STR_LIT>")<EOL>return bins_group<EOL>
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_idx = {"<STR_LIT:all>" : numpy.arange(<NUM_LIT:0>, len(bank[fp.keys()[<NUM_LIT:0>]]))}<EOL><DEDENT>fp.close()<EOL>return bins_idx, bank<EOL>
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 of the datasets from the bank file.
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_group.add_argument("<STR_LIT>", nargs="<STR_LIT:+>", default=None,<EOL>action=types.MultiDetOptionAction,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>opt_group.add_argument("<STR_LIT>", default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>opt_group.add_argument("<STR_LIT>", default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>opt_group.add_argument("<STR_LIT>", type=int, default=None,<EOL>help="<STR_LIT>")<EOL>opt_group.add_argument("<STR_LIT>", type=int, default=None,<EOL>help="<STR_LIT>")<EOL>return opt_group<EOL>
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(<EOL>opts.statmap_file, opts.bank_file,<EOL>sngl_files=opts.sngl_trigger_files.values(),<EOL>n_loudest=opts.search_n_loudest,<EOL>group=opts.statmap_group)<EOL>template_hash = statmap.get_bankfile_array("<STR_LIT>")<EOL>stat = statmap.get_coincfile_array("<STR_LIT>")<EOL>bin_idx = numpy.in1d(template_hash,<EOL>bank_data["<STR_LIT>"][bins_idx[bin_name]])<EOL>sorting = stat[bin_idx].argsort()[::-<NUM_LIT:1>]<EOL>for p in coinc_parameters:<EOL><INDENT>arr = statmap.get_coincfile_array(p)<EOL>data[p] = arr[bin_idx][sorting][:opts.n_loudest]<EOL><DEDENT>for p in sngl_parameters:<EOL><INDENT>for ifo in ifos:<EOL><INDENT>key = "<STR_LIT:/>".join([ifo, p])<EOL>arr = statmap.get_snglfile_array_dict(p)[ifo]<EOL>data[key] = arr[bin_idx][sorting][:opts.n_loudest]<EOL><DEDENT><DEDENT>for p in bank_parameters:<EOL><INDENT>arr = statmap.get_bankfile_array(p)<EOL>data[p] = arr[bin_idx][sorting][:opts.n_loudest]<EOL><DEDENT>bin_results.append(data)<EOL><DEDENT><DEDENT>elif opts.bank_file and opts.sngl_trigger_files:<EOL><INDENT>for bin_name in bin_names:<EOL><INDENT>data = {}<EOL>if len(opts.sngl_trigger_files.keys()) == <NUM_LIT:1>:<EOL><INDENT>ifo = opts.sngl_trigger_files.keys()[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>sngls = hdf.SingleDetTriggers(opts.sngl_trigger_files[ifo],<EOL>opts.bank_file, opts.veto_file,<EOL>opts.veto_segment_name, None, ifo)<EOL>n_loudest = opts.search_n_loudestif opts.search_n_loudest else len(sngls.template_id)<EOL>sngls.mask_to_n_loudest_clustered_events(n_loudest=n_loudest)<EOL>template_hash =sngls.bank["<STR_LIT>"][:][sngls.template_id]<EOL>bin_idx = numpy.in1d(template_hash,<EOL>bank_data["<STR_LIT>"][bins_idx[bin_name]])<EOL>stats = sngls.stat<EOL>sorting = stats[bin_idx].argsort()[::-<NUM_LIT:1>]<EOL>for p in sngl_parameters:<EOL><INDENT>key = "<STR_LIT:/>".join([ifo, p])<EOL>arr = sngls.get_column(p)<EOL>data[key] = arr[bin_idx][sorting][:opts.n_loudest]<EOL><DEDENT>for p in bank_parameters:<EOL><INDENT>arr = sngls.bank[p][:]<EOL>data[p] =arr[sngls.template_id][bin_idx][sorting][:opts.n_loudest]<EOL><DEDENT>bin_results.append(data)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return bin_names, bin_results<EOL>
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 of datasets in single-detector trigger files to retrieve. bank_parameters : list List of datasets in template bank file to retrieve. Results ------- bin_names : dict A list of bin names. bin_results : dict A list of dict holding trigger data data.
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>parvals = conversions.chi_eff(m1, m2, s1z, s2z)<EOL><DEDENT>elif par == '<STR_LIT>':<EOL><INDENT>parvals = pnutils.get_imr_duration(m1, m2, s1z, s2z, args.f_lower,<EOL>args.approximant or "<STR_LIT>")<EOL>if args.min_duration:<EOL><INDENT>parvals += args.min_duration<EOL><DEDENT><DEDENT>elif par == '<STR_LIT>':<EOL><INDENT>parvals = conversions.tau0_from_mass1_mass2(m1, m2, args.f_lower)<EOL><DEDENT>elif par == '<STR_LIT>':<EOL><INDENT>parvals = conversions.tau3_from_mass1_mass2(m1, m2, args.f_lower)<EOL><DEDENT>elif par in pnutils.named_frequency_cutoffs.keys():<EOL><INDENT>parvals = pnutils.frequency_cutoff_from_name(par, m1, m2, s1z, s2z)<EOL><DEDENT>else:<EOL><INDENT>parvals = pnutils.get_freq(par, m1, m2, s1z, s2z)<EOL><DEDENT>return parvals<EOL>
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 array of floats Calculated parameter values
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><INDENT>return bankfile[param][:][foundtmp]<EOL><DEDENT>elif trigfile is not None and param in trigfile[ifo].keys():<EOL><INDENT>return trigfile[ifo][param][:][foundtrg]<EOL><DEDENT>else:<EOL><INDENT>b = bankfile<EOL>return get_param(param, args, b['<STR_LIT>'][:], b['<STR_LIT>'][:],<EOL>b['<STR_LIT>'][:], b['<STR_LIT>'][:])[foundtmp]<EOL><DEDENT>
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-detector trigger file param: string Parameter to be calculated for the recovered triggers ifo: string or None Standard ifo name, ex. 'L1' args : Namespace object returned from ArgumentParser instance Calling code command line options, used for f_lower value Returns ------- [return value]: NumPy array of floats The calculated parameter values
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>'][:],<EOL>inj['<STR_LIT>'][:])<EOL><DEDENT>else:<EOL><INDENT>return get_param(param, args, inj['<STR_LIT>'][:], inj['<STR_LIT>'][:],<EOL>inj['<STR_LIT>'][:], inj['<STR_LIT>'][:])<EOL><DEDENT>
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 detector name, ex. 'L1' args: Namespace object returned from ArgumentParser instance Calling code command line options, used for f_lower value Returns ------- [return value]: NumPy array of floats The calculated parameter values
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 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>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if bin_type == '<STR_LIT>' and boundary[<NUM_LIT:0>:<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>vals = numpy.maximum(data['<STR_LIT>'], data['<STR_LIT>'])<EOL><DEDENT>if bin_type == '<STR_LIT>' and boundary[<NUM_LIT:0>:<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>vals = numpy.minimum(data['<STR_LIT>'], data['<STR_LIT>'])<EOL><DEDENT>elif bin_type == '<STR_LIT>':<EOL><INDENT>vals = data['<STR_LIT>'] + data['<STR_LIT>']<EOL><DEDENT>elif bin_type == '<STR_LIT>':<EOL><INDENT>vals = pycbc.pnutils.mass1_mass2_to_mchirp_eta(<EOL>data['<STR_LIT>'], data['<STR_LIT>'])[<NUM_LIT:0>]<EOL><DEDENT>elif bin_type == '<STR_LIT>':<EOL><INDENT>vals = pycbc.pnutils.get_freq('<STR_LIT>',<EOL>data['<STR_LIT>'], data['<STR_LIT>'], data['<STR_LIT>'], data['<STR_LIT>'])<EOL><DEDENT>elif bin_type == '<STR_LIT>':<EOL><INDENT>vals = pycbc.pnutils.get_freq('<STR_LIT>', data['<STR_LIT>'],<EOL>data['<STR_LIT>'], data['<STR_LIT>'],<EOL>data['<STR_LIT>'])<EOL><DEDENT>elif bin_type == '<STR_LIT>':<EOL><INDENT>vals = pycbc.pnutils.get_imr_duration(data['<STR_LIT>'], data['<STR_LIT>'],<EOL>data['<STR_LIT>'], data['<STR_LIT>'], data['<STR_LIT>'],<EOL>approximant='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % bin_type)<EOL><DEDENT>locs = member_func(vals)<EOL>del vals<EOL>locs = numpy.where(locs)[<NUM_LIT:0>]<EOL>locs = numpy.delete(locs, numpy.where(numpy.in1d(locs, used))[<NUM_LIT:0>])<EOL>used = numpy.concatenate([used, locs])<EOL>bins[name] = locs<EOL><DEDENT>return bins<EOL>
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 values which define the parameters of the template bank to bin up. Returns ------- bins: dict Dictionary of location indices indexed by a bin name
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: <EOL><INDENT>if idx < <NUM_LIT:0>:<EOL><INDENT>idx = <NUM_LIT:0><EOL><DEDENT><DEDENT>fore_n_louder = n_louder[idx]<EOL>if not skip_background:<EOL><INDENT>unsort = sort.argsort()<EOL>back_cum_num = n_louder[unsort]<EOL>return back_cum_num, fore_n_louder<EOL><DEDENT>else:<EOL><INDENT>return fore_n_louder<EOL><DEDENT>
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 decimation factors for the background statistics skip_background: optional, {boolean, False} Skip calculating cumulative numbers for background triggers Returns ------- cum_back_num: numpy.ndarray The cumulative array of background triggers. Does not return this argument if skip_background == True fore_n_louder: numpy.ndarray The number of background triggers above each foreground trigger
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 detector 1 start2: numpy.ndarray Array of the start of valid analyzed times for detector 2 end1: numpy.ndarray Array of the end of valid analyzed times for detector 1 end2: numpy.ndarray Array of the end of valid analyzed times for detector 2 timseslide_offset: numpy.ndarray Array of offsets (in seconds) for each timeslide Returns -------- durations: numpy.ndarray Array of coincident time for each timeslide in the offset array
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_step, fold2, fold2 + slide_step])<EOL>sort2 = numpy.concatenate([sort2, sort2, sort2])<EOL><DEDENT>left = numpy.searchsorted(fold2, fold1 - window)<EOL>right = numpy.searchsorted(fold2, fold1 + window)<EOL>idx1 = numpy.repeat(sort1, right-left)<EOL>idx2 = [sort2[l:r] for l,r in zip(left, right)]<EOL>if len(idx2) > <NUM_LIT:0>:<EOL><INDENT>idx2 = numpy.concatenate(idx2)<EOL><DEDENT>else:<EOL><INDENT>idx2 = numpy.array([], dtype=numpy.int64)<EOL><DEDENT>if slide_step:<EOL><INDENT>diff = ((t1 / slide_step)[idx1] - (t2 / slide_step)[idx2])<EOL>slide = numpy.rint(diff)<EOL><DEDENT>else:<EOL><INDENT>slide = numpy.zeros(len(idx1))<EOL><DEDENT>return idx1.astype(numpy.uint32), idx2.astype(numpy.uint32), slide.astype(numpy.int32)<EOL>
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, float} If calculating background coincidences, the interval between background slides in seconds. Returns ------- idx1 : numpy.ndarray Array of indices into the t1 array. idx2 : numpy.ndarray Array of indices into the t2 array. slide : numpy.ndarray Array of slide ids
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_time = times[pivot][pivot_id] - slide_step * slide<EOL>ctimes = {fixed: fixed_time, pivot:pivot_time}<EOL>ids = {fixed:fix_id, pivot:pivot_id}<EOL>dep_ifos = [ifo for ifo in times.keys() if ifo != fixed and ifo != pivot]<EOL>for ifo1 in dep_ifos:<EOL><INDENT>otime = times[ifo1]<EOL>sort = times[ifo1].argsort()<EOL>time = otime[sort]<EOL>for ifo2 in ids.keys():<EOL><INDENT>w = win(ifo1, ifo2)<EOL>left = numpy.searchsorted(time, ctimes[ifo2] - w)<EOL>right = numpy.searchsorted(time, ctimes[ifo2] + w)<EOL>nz = (right - left).nonzero()<EOL>dep_ids = left[nz]<EOL>if len(left) > <NUM_LIT:0> and (right - left).max() > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>slide = slide[nz]<EOL>for ifo in ctimes:<EOL><INDENT>ctimes[ifo] = ctimes[ifo][nz]<EOL>ids[ifo] = ids[ifo][nz]<EOL><DEDENT><DEDENT>ids[ifo1] = sort[dep_ids]<EOL>ctimes[ifo1] = otime[ids[ifo1]]<EOL><DEDENT>return ids, slide<EOL>
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 for coincidence pivot: str ifo used to test coincidence against in first stage fixed: str the other ifo used in the first stage coincidence which we'll use as a fixed time reference for coincident triggers. All other detectors are time slid by being fixed to this detector.
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.5> * (time2 + time1)<EOL><DEDENT>tslide = timeslide_id.astype(numpy.float128)<EOL>time = time.astype(numpy.float128)<EOL>span = (time.max() - time.min()) + window * <NUM_LIT:10><EOL>time = time + span * tslide<EOL>cidx = cluster_over_time(stat, time, window, argmax)<EOL>return cidx<EOL>
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 timeslide_id: numpy.ndarray vector that determines the timeslide offset slide: float length of the timeslides offset interval window: float length to cluster over Returns ------- cindex: numpy.ndarray The set of indices corresponding to the surviving coincidences.
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)<EOL>time_avg = numpy.array(time_avg)<EOL>num_ifos = numpy.array(num_ifos)<EOL>if numpy.isfinite(slide):<EOL><INDENT>nifos_minusone = (num_ifos - numpy.ones_like(num_ifos))<EOL>time_avg = time_avg + (nifos_minusone * timeslide_id * slide)/num_ifos<EOL><DEDENT>tslide = timeslide_id.astype(numpy.float128)<EOL>time_avg = time_avg.astype(numpy.float128)<EOL>span = (time_avg.max() - time_avg.min()) + window * <NUM_LIT:10><EOL>time_avg = time_avg + span * tslide<EOL>cidx = cluster_over_time(stat, time_avg, window, argmax)<EOL>return cidx<EOL>
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 participate in a coinc timeslide_id: numpy.ndarray vector that determines the timeslide offset slide: float length of the timeslides offset interval window: float duration of clustering window in seconds Returns ------- cindex: numpy.ndarray The set of indices corresponding to the surviving coincidences
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 ------- mean: float The mean of the values in the original vector which are greater than zero num_above_zero: int The number of entries in the vector which are above zero
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_LIT:0><EOL>j = <NUM_LIT:0><EOL>while i < len(left):<EOL><INDENT>l = left[i]<EOL>r = right[i]<EOL>if (r - l) == <NUM_LIT:1>:<EOL><INDENT>indices[j] = i<EOL>j += <NUM_LIT:1><EOL>i += <NUM_LIT:1><EOL>continue<EOL><DEDENT>max_loc = argmax(stat[l:r]) + l<EOL>if max_loc == i:<EOL><INDENT>indices[j] = i<EOL>i = r<EOL>j += <NUM_LIT:1><EOL><DEDENT>elif max_loc > i:<EOL><INDENT>i = max_loc<EOL><DEDENT>elif max_loc < i:<EOL><INDENT>i += <NUM_LIT:1><EOL><DEDENT><DEDENT>indices = indices[:j]<EOL>logging.info('<STR_LIT>', len(indices))<EOL>return time_sorting[indices]<EOL>
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: function the function used to calculate the maximum value Returns ------- cindex: numpy.ndarray The set of indices corresponding to the surviving coincidences.
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>j += <NUM_LIT:1><EOL><DEDENT>return self.buffer[buffer_index]<EOL>
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 element of the buffer.
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.index+len(values)] = values<EOL>if len(values) > <NUM_LIT:0>:<EOL><INDENT>for ifo in self.ifos:<EOL><INDENT>self.timer[ifo][self.index:self.index+len(values)] = times[ifo]<EOL><DEDENT>self.index += len(values)<EOL><DEDENT>keep = None<EOL>for ifo in ifos:<EOL><INDENT>kt = self.timer[ifo][:self.index] >= self.time[ifo] - self.expiration<EOL>keep = numpy.logical_and(keep, kt) if keep is not None else kt<EOL><DEDENT>self.buffer[:keep.sum()] = self.buffer[:self.index][keep]<EOL>for ifo in self.ifos:<EOL><INDENT>self.timer[ifo][:keep.sum()] = self.timer[ifo][:self.index][keep]<EOL><DEDENT>self.index = keep.sum()<EOL>
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 be incremented.
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]<EOL>logging.info('<STR_LIT>',<EOL>ifos[<NUM_LIT:0>], ifos[<NUM_LIT:1>], fname, background_statistic)<EOL><DEDENT><DEDENT>self.stat_calculator = stat.get_statistic(background_statistic)(stat_files)<EOL>self.timeslide_interval = timeslide_interval<EOL>self.return_background = return_background<EOL>self.ifos = ifos<EOL>if len(self.ifos) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.lookback_time = (ifar_limit * lal.YRJUL_SI * timeslide_interval) ** <NUM_LIT:0.5><EOL>self.buffer_size = int(numpy.ceil(self.lookback_time / analysis_block))<EOL>det0, det1 = Detector(ifos[<NUM_LIT:0>]), Detector(ifos[<NUM_LIT:1>])<EOL>self.time_window = det0.light_travel_time_to_detector(det1) + coinc_threshold<EOL>self.coincs = CoincExpireBuffer(self.buffer_size, self.ifos)<EOL>self.singles = {}<EOL>
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 various coincident statistics. ifos: list of strs List of ifo names that are being analyzed. At the moment this must be two items such as ['H1', 'L1']. ifar_limit: float The largest inverse false alarm rate in years that we would like to calculate. timeslide_interval: float The time in seconds between consecutive timeslide offsets. coinc_threshold: float Amount of time allowed to form a coincidence in addition to the time of flight in seconds. return_background: boolean If true, background triggers will also be included in the file output.
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 (ifar == mifar and stat > mstat):<EOL><INDENT>mifar = ifar<EOL>mstat = stat<EOL>mresult = result<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if mresult:<EOL><INDENT>mresult['<STR_LIT>'] = mifar / float(trials)<EOL>logging.info('<STR_LIT>',<EOL>mresult['<STR_LIT>'],<EOL>mresult['<STR_LIT>'])<EOL>return mresult<EOL><DEDENT>else:<EOL><INDENT>return coinc_results[<NUM_LIT:0>]<EOL><DEDENT>
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 possible at this time given the active ifos. Parameters ---------- coinc_results: list of coinc result dicts Dictionary by detector pair of coinc result dicts. Returns ------- best: coinc results dict If there is a coinc, this will contain the 'best' one. Otherwise it will return the provided dict.
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))<EOL><DEDENT>if '<STR_LIT>' not in data:<EOL><INDENT>self.singles_dtype.append(('<STR_LIT>', self.stat_calculator.single_dtype))<EOL><DEDENT>for ifo in self.ifos:<EOL><INDENT>self.singles[ifo] = MultiRingBuffer(self.num_templates,<EOL>self.buffer_size,<EOL>self.singles_dtype)<EOL><DEDENT>
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>'] = trigs['<STR_LIT>'] * trigs['<STR_LIT>']<EOL>trigsc['<STR_LIT>'] = (trigs['<STR_LIT>'] + <NUM_LIT:2>) / <NUM_LIT:2><EOL>single_stat = self.stat_calculator.single(trigsc)<EOL><DEDENT>else:<EOL><INDENT>single_stat = numpy.array([], ndmin=<NUM_LIT:1>,<EOL>dtype=self.stat_calculator.single_dtype)<EOL><DEDENT>trigs['<STR_LIT>'] = single_stat<EOL>data = numpy.zeros(len(single_stat), dtype=self.singles_dtype)<EOL>for key, value in trigs.items():<EOL><INDENT>data[key] = value<EOL><DEDENT>self.singles[ifo].add(trigs['<STR_LIT>'], data)<EOL>updated_indices[ifo] = trigs['<STR_LIT>']<EOL><DEDENT>return updated_indices<EOL>
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. Returns ------- updated_singles: dict of numpy.ndarrays Array of indices that have been just updated in the internal buffers of single detector triggers.
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 = results[ifo]<EOL>oifo = self.ifos[<NUM_LIT:1>] if self.ifos[<NUM_LIT:0>] == ifo else self.ifos[<NUM_LIT:0>]<EOL>for i in range(len(trigs['<STR_LIT>'])):<EOL><INDENT>trig_stat = trigs['<STR_LIT>'][i]<EOL>trig_time = trigs['<STR_LIT>'][i]<EOL>template = trigs['<STR_LIT>'][i]<EOL>times = self.singles[oifo].data(template)['<STR_LIT>']<EOL>stats = self.singles[oifo].data(template)['<STR_LIT>']<EOL>i1, _, slide = time_coincidence(times,<EOL>numpy.array(trig_time, ndmin=<NUM_LIT:1>,<EOL>dtype=numpy.float64),<EOL>self.time_window,<EOL>self.timeslide_interval)<EOL>trig_stat = numpy.resize(trig_stat, len(i1))<EOL>c = self.stat_calculator.coinc(stats[i1], trig_stat,<EOL>slide, self.timeslide_interval)<EOL>offsets.append(slide)<EOL>cstat.append(c)<EOL>ctimes[oifo].append(times[i1])<EOL>ctimes[ifo].append(numpy.zeros(len(c), dtype=numpy.float64))<EOL>ctimes[ifo][-<NUM_LIT:1>].fill(trig_time)<EOL>single_expire[oifo].append(self.singles[oifo].expire_vector(template)[i1])<EOL>single_expire[ifo].append(numpy.zeros(len(c),<EOL>dtype=numpy.int32))<EOL>single_expire[ifo][-<NUM_LIT:1>].fill(self.singles[ifo].time - <NUM_LIT:1>)<EOL>template_ids.append(numpy.zeros(len(c)) + template)<EOL>trigger_ids[oifo].append(i1)<EOL>trigger_ids[ifo].append(numpy.zeros(len(c)) - <NUM_LIT:1>)<EOL><DEDENT><DEDENT>cstat = numpy.concatenate(cstat)<EOL>template_ids = numpy.concatenate(template_ids).astype(numpy.int32)<EOL>for ifo in ifos:<EOL><INDENT>trigger_ids[ifo] = numpy.concatenate(trigger_ids[ifo]).astype(numpy.int32)<EOL><DEDENT>num_zerolag = <NUM_LIT:0><EOL>num_background = <NUM_LIT:0><EOL>logging.info('<STR_LIT>', len(cstat))<EOL>if len(cstat) > <NUM_LIT:0>:<EOL><INDENT>offsets = numpy.concatenate(offsets)<EOL>ctime0 = numpy.concatenate(ctimes[self.ifos[<NUM_LIT:0>]]).astype(numpy.float64)<EOL>ctime1 = numpy.concatenate(ctimes[self.ifos[<NUM_LIT:1>]]).astype(numpy.float64)<EOL>cidx = cluster_coincs(cstat, ctime0, ctime1, offsets,<EOL>self.timeslide_interval,<EOL>self.analysis_block)<EOL>offsets = offsets[cidx]<EOL>zerolag_idx = (offsets == <NUM_LIT:0>)<EOL>bkg_idx = (offsets != <NUM_LIT:0>)<EOL>for ifo in self.ifos:<EOL><INDENT>single_expire[ifo] = numpy.concatenate(single_expire[ifo])<EOL>single_expire[ifo] = single_expire[ifo][cidx][bkg_idx]<EOL><DEDENT>self.coincs.add(cstat[cidx][bkg_idx], single_expire, ifos)<EOL>num_zerolag = zerolag_idx.sum()<EOL>num_background = bkg_idx.sum()<EOL><DEDENT>elif len(ifos) > <NUM_LIT:0>:<EOL><INDENT>self.coincs.increment(ifos)<EOL><DEDENT>coinc_results = {}<EOL>if num_zerolag > <NUM_LIT:0>:<EOL><INDENT>zerolag_results = {}<EOL>idx = cidx[zerolag_idx][<NUM_LIT:0>]<EOL>zerolag_cstat = cstat[cidx][zerolag_idx]<EOL>zerolag_results['<STR_LIT>'] = self.ifar(zerolag_cstat)<EOL>zerolag_results['<STR_LIT>'] = zerolag_cstat<EOL>template = template_ids[idx]<EOL>for ifo in self.ifos:<EOL><INDENT>trig_id = trigger_ids[ifo][idx]<EOL>single_data = self.singles[ifo].data(template)[trig_id]<EOL>for key in single_data.dtype.names:<EOL><INDENT>path = '<STR_LIT>' % (ifo, key)<EOL>zerolag_results[path] = single_data[key]<EOL><DEDENT><DEDENT>zerolag_results['<STR_LIT>'] = '<STR_LIT:->'.join(self.ifos)<EOL>coinc_results.update(zerolag_results)<EOL><DEDENT>coinc_results['<STR_LIT>'] = numpy.array([self.background_time])<EOL>coinc_results['<STR_LIT>'] = len(self.coincs.data)<EOL>if self.return_background:<EOL><INDENT>coinc_results['<STR_LIT>'] = self.coincs.data<EOL><DEDENT>return num_background, coinc_results<EOL>
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. Returns ------- coinc_results: dict of arrays A dictionary of arrays containing the coincident results.
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 just added to the internal buffer of coincident triggers
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_ifos)<EOL>if len(valid_ifos) == <NUM_LIT:2>:<EOL><INDENT>coinc_results['<STR_LIT>'] = True<EOL><DEDENT>return coinc_results<EOL>
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. Returns ------- coinc_results: dict of arrays A dictionary of arrays containing the coincident results.
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] = allowed_area * numpy.array(rateprod)<EOL>if len(ifos) > <NUM_LIT:2>:<EOL><INDENT>subsets = itertools.combinations(ifos, len(ifos) - <NUM_LIT:1>)<EOL>for subset in subsets:<EOL><INDENT>rates_subset = {}<EOL>for ifo in subset:<EOL><INDENT>rates_subset[ifo] = rates[ifo]<EOL><DEDENT>sub_coinc_rates = multiifo_noise_coinc_rate(rates_subset, slop)<EOL>for sub_coinc in sub_coinc_rates:<EOL><INDENT>expected_coinc_rates[sub_coinc] = sub_coinc_rates[sub_coinc]<EOL><DEDENT><DEDENT><DEDENT>return expected_coinc_rates<EOL>
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 timing error Returns ------- expected_coinc_rates: dict Dictionary keyed on the ifo combination string Value is expected coincidence rate in the combination, units Hz
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><INDENT>tofs = numpy.zeros(n_ifos)<EOL>ifo2_num = []<EOL>for i, ifo in enumerate(ifos):<EOL><INDENT>ifo2_num.append(int(numpy.mod(i + <NUM_LIT:1>, n_ifos)))<EOL>det0 = dets[ifo]<EOL>det1 = dets[ifos[ifo2_num[i]]]<EOL>tofs[i] = det0.light_travel_time_to_detector(det1) + slop<EOL><DEDENT>allowed_area = <NUM_LIT:0><EOL>for i, _ in enumerate(ifos):<EOL><INDENT>allowed_area += <NUM_LIT:2> * tofs[i] * tofs[ifo2_num[i]] - tofs[i]**<NUM_LIT:2><EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>return allowed_area<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 ------- allowed_area: float area in units of seconds^(n_ifos-1) that coincident values can fall in
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.zeros(n_ifos)<EOL>ifo2_num = []<EOL>for ifo in ifos:<EOL><INDENT>dets[ifo] = pycbc.detector.Detector(ifo)<EOL><DEDENT>for i, ifo in enumerate(ifos):<EOL><INDENT>ifo2_num.append(int(numpy.mod(i + <NUM_LIT:1>, n_ifos)))<EOL>det0 = dets[ifo]<EOL>det1 = dets[ifos[ifo2_num[i]]]<EOL>tofs[i] = det0.light_travel_time_to_detector(det1)<EOL><DEDENT>phi_12 = numpy.arccos((tofs[<NUM_LIT:0>]**<NUM_LIT:2> + tofs[<NUM_LIT:1>]**<NUM_LIT:2> - tofs[<NUM_LIT:2>]**<NUM_LIT:2>)<EOL>/ (<NUM_LIT:2> * tofs[<NUM_LIT:0>] * tofs[<NUM_LIT:1>]))<EOL>allowed_area = numpy.pi * tofs[<NUM_LIT:0>] * tofs[<NUM_LIT:1>] * numpy.sin(phi_12)<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>return allowed_area<EOL>
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>return esnr[<NUM_LIT:0>]<EOL><DEDENT>
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(snr, '<STR_LIT>'):<EOL><INDENT>return nsnr<EOL><DEDENT>else:<EOL><INDENT>return nsnr[<NUM_LIT:0>]<EOL><DEDENT>
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>return nsnr<EOL><DEDENT>else:<EOL><INDENT>return nsnr[<NUM_LIT:0>]<EOL><DEDENT>
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>return nsnr[<NUM_LIT:0>]<EOL><DEDENT>
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 newsnr values
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 Array of newsnr values
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