signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@property<EOL><INDENT>def spin_pz(self):<DEDENT>
return conversions.primary_spin(self.mass1, self.mass2, self.spin1z,<EOL>self.spin2z)<EOL>
Returns the z-component of the spin of the primary mass.
f15966:c2:m9
@property<EOL><INDENT>def spin_sx(self):<DEDENT>
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1x,<EOL>self.spin2x)<EOL>
Returns the x-component of the spin of the secondary mass.
f15966:c2:m10
@property<EOL><INDENT>def spin_sy(self):<DEDENT>
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1y,<EOL>self.spin2y)<EOL>
Returns the y-component of the spin of the secondary mass.
f15966:c2:m11
@property<EOL><INDENT>def spin_sz(self):<DEDENT>
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1z,<EOL>self.spin2z)<EOL>
Returns the z-component of the spin of the secondary mass.
f15966:c2:m12
@property<EOL><INDENT>def spin1_a(self):<DEDENT>
return coordinates.cartesian_to_spherical_rho(<EOL>self.spin1x, self.spin1y, self.spin1z)<EOL>
Returns the dimensionless spin magnitude of mass 1.
f15966:c2:m13
@property<EOL><INDENT>def spin1_azimuthal(self):<DEDENT>
return coordinates.cartesian_to_spherical_azimuthal(<EOL>self.spin1x, self.spin1y)<EOL>
Returns the azimuthal spin angle of mass 1.
f15966:c2:m14
@property<EOL><INDENT>def spin1_polar(self):<DEDENT>
return coordinates.cartesian_to_spherical_polar(<EOL>self.spin1x, self.spin1y, self.spin1z)<EOL>
Returns the polar spin angle of mass 1.
f15966:c2:m15
@property<EOL><INDENT>def spin2_a(self):<DEDENT>
return coordinates.cartesian_to_spherical_rho(<EOL>self.spin1x, self.spin1y, self.spin1z)<EOL>
Returns the dimensionless spin magnitude of mass 2.
f15966:c2:m16
@property<EOL><INDENT>def spin2_azimuthal(self):<DEDENT>
return coordinates.cartesian_to_spherical_azimuthal(<EOL>self.spin2x, self.spin2y)<EOL>
Returns the azimuthal spin angle of mass 2.
f15966:c2:m17
@property<EOL><INDENT>def spin2_polar(self):<DEDENT>
return coordinates.cartesian_to_spherical_polar(<EOL>self.spin2x, self.spin2y, self.spin2z)<EOL>
Returns the polar spin angle of mass 2.
f15966:c2:m18
def save_dict_to_hdf5(dic, filename):
with h5py.File(filename, '<STR_LIT:w>') as h5file:<EOL><INDENT>recursively_save_dict_contents_to_group(h5file, '<STR_LIT:/>', dic)<EOL><DEDENT>
Parameters ---------- dic: python dictionary to be converted to hdf5 format filename: desired name of hdf5 file
f15967:m1
def recursively_save_dict_contents_to_group(h5file, path, dic):
for key, item in dic.items():<EOL><INDENT>if isinstance(item, (np.ndarray, np.int64, np.float64, str, bytes, tuple, list)):<EOL><INDENT>h5file[path + str(key)] = item<EOL><DEDENT>elif isinstance(item, dict):<EOL><INDENT>recursively_save_dict_contents_to_group(h5file, path + key + '<STR_LIT:/>', item)<EOL><DEDENT>else:<...
Parameters ---------- h5file: h5py file to be written to path: path within h5py file to saved dictionary dic: python dictionary to be converted to hdf5 format
f15967:m2
def combine_and_copy(f, files, group):
f[group] = np.concatenate([fi[group][:] if group in fi elsenp.array([], dtype=np.uint32) for fi in files])<EOL>
Combine the same column from multiple files and save to a third
f15967:m3
def select(self, fcn, *args, **kwds):
<EOL>refs = {}<EOL>data = {}<EOL>for arg in args:<EOL><INDENT>refs[arg] = self[arg]<EOL>data[arg] = []<EOL><DEDENT>return_indices = kwds.get('<STR_LIT>', False)<EOL>indices = np.array([], dtype=np.uint64)<EOL>chunksize = kwds.get('<STR_LIT>', int(<NUM_LIT>))<EOL>size = len(refs[arg])<EOL>i = <NUM_LIT:0><EOL>while i < s...
Return arrays from an hdf5 file that satisfy the given function Parameters ---------- fcn : a function A function that accepts the same number of argument as keys given and returns a boolean array of the same length. args : strings A variable number ...
f15967:c0:m0
def __init__(self, data=None, files=None, groups=None):
self.data = data<EOL>if files:<EOL><INDENT>self.data = {}<EOL>for g in groups:<EOL><INDENT>self.data[g] = []<EOL><DEDENT>for f in files:<EOL><INDENT>d = HFile(f)<EOL>for g in groups:<EOL><INDENT>if g in d:<EOL><INDENT>self.data[g].append(d[g][:])<EOL><DEDENT><DEDENT>d.close()<EOL><DEDENT>for k in self.data:<EOL><INDENT...
Create a DictArray Parameters ---------- data: dict, optional Dictionary of equal length numpy arrays files: list of filenames, optional List of hdf5 file filenames. Incompatibile with the `data` option. groups: list of strings List of keys in...
f15967:c1:m0
def select(self, idx):
data = {}<EOL>for k in self.data:<EOL><INDENT>data[k] = self.data[k][idx]<EOL><DEDENT>return self._return(data=data)<EOL>
Return a new DictArray containing only the indexed values
f15967:c1:m4
def remove(self, idx):
data = {}<EOL>for k in self.data:<EOL><INDENT>data[k] = np.delete(self.data[k], idx)<EOL><DEDENT>return self._return(data=data)<EOL>
Return a new DictArray that does not contain the indexed values
f15967:c1:m5
def cluster(self, window):
<EOL>if len(self.time1) == <NUM_LIT:0> or len(self.time2) == <NUM_LIT:0>:<EOL><INDENT>return self<EOL><DEDENT>from pycbc.events import cluster_coincs<EOL>interval = self.attrs['<STR_LIT>']<EOL>cid = cluster_coincs(self.stat, self.time1, self.time2,<EOL>self.timeslide_id, interval, window)<EOL>return self.select(cid)<EO...
Cluster the dict array, assuming it has the relevant Coinc colums, time1, time2, stat, and timeslide_id
f15967:c2:m2
def cluster(self, window):
<EOL>pivot_ifo = self.attrs['<STR_LIT>']<EOL>fixed_ifo = self.attrs['<STR_LIT>']<EOL>if len(self.data['<STR_LIT>' % pivot_ifo]) == <NUM_LIT:0> or len(self.data['<STR_LIT>' % fixed_ifo]) == <NUM_LIT:0>:<EOL><INDENT>return self<EOL><DEDENT>from pycbc.events import cluster_coincs<EOL>interval = self.attrs['<STR_LIT>']<EOL...
Cluster the dict array, assuming it has the relevant Coinc colums, time1, time2, stat, and timeslide_id
f15967:c3:m2
def __init__(self, fname, group=None, columnlist=None, filter_func=None):
if not fname: raise RuntimeError("<STR_LIT>")<EOL>self.fname = fname<EOL>self.h5file = HFile(fname, "<STR_LIT:r>")<EOL>if group is None:<EOL><INDENT>if len(self.h5file.keys()) == <NUM_LIT:1>:<EOL><INDENT>group = self.h5file.keys()[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT><D...
Parameters ---------- group : string Name of group to be read from the file columnlist : list of strings Names of columns to be read; if None, use all existing columns filter_func : string String should evaluate to a Boolean expression using attributes of the class instance derived from columns: ex. 'se...
f15967:c4:m0
@property<EOL><INDENT>def mask(self):<DEDENT>
if self.filter_func is None:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>if self._mask is None:<EOL><INDENT>for column in self.columns:<EOL><INDENT>if column in self.filter_func:<EOL><INDENT>setattr(self, column, self.group[column][:])<EOL><DEDENT><DEDENT>self._mask = eval(self.filter_func...
Create a mask implementing the requested filter on the datasets Returns ------- array of Boolean True for dataset indices to be returned by the get_column method
f15967:c4:m2
def get_column(self, col):
<EOL>if not len(self.group.keys()):<EOL><INDENT>return np.array([])<EOL><DEDENT>vals = self.group[col]<EOL>if self.filter_func:<EOL><INDENT>return vals[self.mask]<EOL><DEDENT>else:<EOL><INDENT>return vals[:]<EOL><DEDENT>
Parameters ---------- col : string Name of the dataset to be returned Returns ------- numpy array Values from the dataset, filtered if requested
f15967:c4:m3
def get_column(self, col):
logging.info('<STR_LIT>' % col)<EOL>vals = []<EOL>for f in self.files:<EOL><INDENT>d = FileData(f, group=self.group, columnlist=self.columns,<EOL>filter_func=self.filter_func)<EOL>vals.append(d.get_column(col))<EOL>d.close()<EOL><DEDENT>logging.info('<STR_LIT>' % sum(len(v) for v in vals))<EOL>return np.concatenate(val...
Loop over files getting the requested dataset values from each Parameters ---------- col : string Name of the dataset to be returned Returns ------- numpy array Values from the dataset, filtered if requested and concatenated in order of file list
f15967:c5:m1
@classmethod<EOL><INDENT>def get_param_names(cls):<DEDENT>
return [m[<NUM_LIT:0>] for m in inspect.getmembers(cls)if type(m[<NUM_LIT:1>]) == property]<EOL>
Returns a list of plottable CBC parameter variables
f15967:c6:m2
def mask_to_n_loudest_clustered_events(self, n_loudest=<NUM_LIT:10>,<EOL>ranking_statistic="<STR_LIT>",<EOL>cluster_window=<NUM_LIT:10>):
<EOL>stat_instance = sngl_statistic_dict[ranking_statistic]([])<EOL>stat = stat_instance.single(self.trigs)[self.mask]<EOL>if ranking_statistic == "<STR_LIT>":<EOL><INDENT>self.stat_name = "<STR_LIT>"<EOL><DEDENT>elif ranking_statistic == "<STR_LIT>":<EOL><INDENT>self.stat_name = "<STR_LIT>"<EOL><DEDENT>elif ranking_st...
Edits the mask property of the class to point to the N loudest single detector events as ranked by ranking statistic. Events are clustered so that no more than 1 event within +/- cluster-window will be considered.
f15967:c6:m3
def compute_search_efficiency_in_bins(<EOL>found, total, ndbins,<EOL>sim_to_bins_function=lambda sim: (sim.distance,)):
bins = bin_utils.BinnedRatios(ndbins)<EOL>[bins.incnumerator(sim_to_bins_function(sim)) for sim in found]<EOL>[bins.incdenominator(sim_to_bins_function(sim)) for sim in total]<EOL>bins.regularize()<EOL>eff = bin_utils.BinnedArray(bin_utils.NDBins(ndbins), array=bins.ratio())<EOL>err_arr = numpy.sqrt(eff.array * (<NUM_L...
Calculate search efficiency in the given ndbins. The first dimension of ndbins must be bins over injected distance. sim_to_bins_function must map an object to a tuple indexing the ndbins.
f15969:m0
def compute_search_volume_in_bins(found, total, ndbins, sim_to_bins_function):
eff, err = compute_search_efficiency_in_bins(<EOL>found, total, ndbins, sim_to_bins_function)<EOL>dx = ndbins[<NUM_LIT:0>].upper() - ndbins[<NUM_LIT:0>].lower()<EOL>r = ndbins[<NUM_LIT:0>].centres()<EOL>vol = bin_utils.BinnedArray(bin_utils.NDBins(ndbins[<NUM_LIT:1>:]))<EOL>errors = bin_utils.BinnedArray(bin_utils.NDBi...
Calculate search sensitive volume by integrating efficiency in distance bins No cosmological corrections are applied: flat space is assumed. The first dimension of ndbins must be bins over injected distance. sim_to_bins_function must maps an object to a tuple indexing the ndbins.
f15969:m1
def volume_to_distance_with_errors(vol, vol_err):
dist = (vol * <NUM_LIT>/<NUM_LIT>/numpy.pi) ** (<NUM_LIT:1.0>/<NUM_LIT>)<EOL>ehigh = ((vol + vol_err) * <NUM_LIT>/<NUM_LIT>/numpy.pi) ** (<NUM_LIT:1.0>/<NUM_LIT>) - dist<EOL>delta = numpy.where(vol >= vol_err, vol - vol_err, <NUM_LIT:0>)<EOL>elow = dist - (delta * <NUM_LIT>/<NUM_LIT>/numpy.pi) ** (<NUM_LIT:1.0>/<NUM_LI...
Return the distance and standard deviation upper and lower bounds Parameters ---------- vol: float vol_err: float Returns ------- dist: float ehigh: float elow: float
f15969:m2
def volume_montecarlo(found_d, missed_d, found_mchirp, missed_mchirp,<EOL>distribution_param, distribution, limits_param,<EOL>min_param=None, max_param=None):
d_power = {<EOL>'<STR_LIT>' : <NUM_LIT>,<EOL>'<STR_LIT>' : <NUM_LIT>,<EOL>'<STR_LIT>' : <NUM_LIT:1.>,<EOL>'<STR_LIT>' : <NUM_LIT:0.><EOL>}[distribution]<EOL>mchirp_power = {<EOL>'<STR_LIT>' : <NUM_LIT:0.>,<EOL>'<STR_LIT>' : <NUM_LIT> / <NUM_LIT>,<EOL>'<STR_LIT>' : <NUM_L...
Compute sensitive volume and standard error via direct Monte Carlo integral Injections should be made over a range of distances such that sensitive volume due to signals closer than D_min is negligible, and efficiency at distances above D_max is negligible TODO : Replace this function by Collin's formula given in Usma...
f15969:m3
def volume_binned_pylal(f_dist, m_dist, bins=<NUM_LIT:15>):
def sims_to_bin(sim):<EOL><INDENT>return (sim, <NUM_LIT:0>)<EOL><DEDENT>total = numpy.concatenate([f_dist, m_dist])<EOL>ndbins = bin_utils.NDBins([bin_utils.LinearBins(min(total), max(total), bins),<EOL>bin_utils.LinearBins(<NUM_LIT:0.>, <NUM_LIT:1>, <NUM_LIT:1>)])<EOL>vol, verr = compute_search_volume_in_bins(f_dist, ...
Compute the sensitive volume using a distance binned efficiency estimate Parameters ----------- f_dist: numpy.ndarray The distances of found injections m_dist: numpy.ndarray The distances of missed injections Returns -------- volume: float Volume estimate volume...
f15969:m4
def volume_shell(f_dist, m_dist):
f_dist.sort()<EOL>m_dist.sort()<EOL>distances = numpy.concatenate([f_dist, m_dist])<EOL>dist_sorting = distances.argsort()<EOL>distances = distances[dist_sorting]<EOL>low = <NUM_LIT:0><EOL>vol = <NUM_LIT:0><EOL>vol_err = <NUM_LIT:0><EOL>for i in range(len(distances)):<EOL><INDENT>if i == len(distances) - <NUM_LIT:1>:<E...
Compute the sensitive volume using sum over spherical shells. Parameters ----------- f_dist: numpy.ndarray The distances of found injections m_dist: numpy.ndarray The distances of missed injections Returns -------- volume: float Volume estimate volume_error: flo...
f15969:m5
def qplane(qplane_tile_dict, fseries, return_complex=False):
<EOL>qplanes = {}<EOL>max_energy, max_key = None, None<EOL>for i, q in enumerate(qplane_tile_dict):<EOL><INDENT>energies = []<EOL>for f0 in qplane_tile_dict[q]:<EOL><INDENT>energy = qseries(fseries, q, f0, return_complex=return_complex)<EOL>menergy = abs(energy).max()<EOL>energies.append(energy)<EOL>if i == <NUM_LIT:0>...
Performs q-transform on each tile for each q-plane and selects tile with the maximum energy. Q-transform can then be interpolated to a desired frequency and time resolution. Parameters ---------- qplane_tile_dict: Dictionary containing a list of q-tile tupples for each q-plane fse...
f15970:m0
def qtiling(fseries, qrange, frange, mismatch=<NUM_LIT>):
qplane_tile_dict = {}<EOL>qs = list(_iter_qs(qrange, deltam_f(mismatch)))<EOL>for q in qs:<EOL><INDENT>qtilefreq = _iter_frequencies(q, frange, mismatch, fseries.duration)<EOL>qplane_tile_dict[q] = numpy.array(list(qtilefreq))<EOL><DEDENT>return qplane_tile_dict<EOL>
Iterable constructor of QTile tuples Parameters ---------- fseries: 'pycbc FrequencySeries' frequency-series data set qrange: upper and lower bounds of q range frange: upper and lower bounds of frequency range mismatch: percentage of desired fractional mismatch ...
f15970:m1
def deltam_f(mismatch):
return <NUM_LIT:2> * (mismatch / <NUM_LIT>) ** (<NUM_LIT:1>/<NUM_LIT>)<EOL>
Fractional mismatch between neighbouring tiles Parameters ---------- mismatch: 'float' percentage of desired fractional mismatch Returns ------- :type: 'float'
f15970:m2
def _iter_qs(qrange, deltam):
<EOL>cumum = log(float(qrange[<NUM_LIT:1>]) / qrange[<NUM_LIT:0>]) / <NUM_LIT:2>**(<NUM_LIT:1>/<NUM_LIT>)<EOL>nplanes = int(max(ceil(cumum / deltam), <NUM_LIT:1>))<EOL>dq = cumum / nplanes<EOL>for i in xrange(nplanes):<EOL><INDENT>yield qrange[<NUM_LIT:0>] * exp(<NUM_LIT:2>**(<NUM_LIT:1>/<NUM_LIT>) * dq * (i + <NUM_LIT...
Iterate over the Q values Parameters ---------- qrange: upper and lower bounds of q range deltam: Fractional mismatch between neighbouring tiles Returns ------- Q-value: Q value for Q-tile
f15970:m3
def _iter_frequencies(q, frange, mismatch, dur):
<EOL>minf, maxf = frange<EOL>fcum_mismatch = log(float(maxf) / minf) * (<NUM_LIT:2> + q**<NUM_LIT:2>)**(<NUM_LIT:1>/<NUM_LIT>) / <NUM_LIT><EOL>nfreq = int(max(<NUM_LIT:1>, ceil(fcum_mismatch / deltam_f(mismatch))))<EOL>fstep = fcum_mismatch / nfreq<EOL>fstepmin = <NUM_LIT:1.> / dur<EOL>for i in xrange(nfreq):<EOL><INDE...
Iterate over the frequencies of this 'QPlane' Parameters ---------- q: q value frange: 'list' upper and lower bounds of frequency range mismatch: percentage of desired fractional mismatch dur: duration of timeseries in seconds Returns ------- frequen...
f15970:m4
def qseries(fseries, Q, f0, return_complex=False):
<EOL>qprime = Q / <NUM_LIT:11>**(<NUM_LIT:1>/<NUM_LIT>)<EOL>norm = numpy.sqrt(<NUM_LIT> * qprime / (<NUM_LIT> * f0))<EOL>window_size = <NUM_LIT:2> * int(f0 / qprime * fseries.duration) + <NUM_LIT:1><EOL>xfrequencies = numpy.linspace(-<NUM_LIT:1.>, <NUM_LIT:1.>, window_size)<EOL>start = int((f0 - (f0 / qprime)) * fserie...
Calculate the energy 'TimeSeries' for the given fseries Parameters ---------- fseries: 'pycbc FrequencySeries' frequency-series data set Q: q value f0: central frequency return_complex: {False, bool} Return the raw complex series instead of the normalized power. ...
f15970:m5
def compute_max_snr_over_sky_loc_stat(hplus, hcross, hphccorr,<EOL>hpnorm=None, hcnorm=None,<EOL>out=None, thresh=<NUM_LIT:0>,<EOL>analyse_slice=None):
<EOL>if out is None:<EOL><INDENT>out = zeros(len(hplus))<EOL>out.non_zero_locs = numpy.array([], dtype=out.dtype)<EOL><DEDENT>else:<EOL><INDENT>if not hasattr(out, '<STR_LIT>'):<EOL><INDENT>out.data[:] = <NUM_LIT:0><EOL>out.non_zero_locs = numpy.array([], dtype=out.dtype)<EOL><DEDENT>else:<EOL><INDENT>out.data[out.non_...
Compute the maximized over sky location statistic. Parameters ----------- hplus : TimeSeries This is the IFFTed complex SNR time series of (h+, data). If not normalized, supply the normalization factor so this can be done! It is recommended to normalize this before sending through this function hcross ...
f15971:m2
def compute_u_val_for_sky_loc_stat(hplus, hcross, hphccorr,<EOL>hpnorm=None, hcnorm=None, indices=None):
if indices is not None:<EOL><INDENT>hplus = hplus[indices]<EOL>hcross = hcross[indices]<EOL><DEDENT>if hpnorm is not None:<EOL><INDENT>hplus = hplus * hpnorm<EOL><DEDENT>if hcnorm is not None:<EOL><INDENT>hcross = hcross * hcnorm<EOL><DEDENT>hplus_magsq = numpy.real(hplus) * numpy.real(hplus) +numpy.imag(hplus) * numpy...
The max-over-sky location detection statistic maximizes over a phase, an amplitude and the ratio of F+ and Fx, encoded in a variable called u. Here we return the value of u for the given indices.
f15971:m3
def compute_max_snr_over_sky_loc_stat_no_phase(hplus, hcross, hphccorr,<EOL>hpnorm=None, hcnorm=None,<EOL>out=None, thresh=<NUM_LIT:0>,<EOL>analyse_slice=None):
<EOL>if out is None:<EOL><INDENT>out = zeros(len(hplus))<EOL>out.non_zero_locs = numpy.array([], dtype=out.dtype)<EOL><DEDENT>else:<EOL><INDENT>if not hasattr(out, '<STR_LIT>'):<EOL><INDENT>out.data[:] = <NUM_LIT:0><EOL>out.non_zero_locs = numpy.array([], dtype=out.dtype)<EOL><DEDENT>else:<EOL><INDENT>out.data[out.non_...
Compute the match maximized over polarization phase. In contrast to compute_max_snr_over_sky_loc_stat_no_phase this function performs no maximization over orbital phase, treating that as an intrinsic parameter. In the case of aligned-spin 2,2-mode only waveforms, this collapses to the normal statistic (at twice the co...
f15971:m4
def compute_u_val_for_sky_loc_stat_no_phase(hplus, hcross, hphccorr,<EOL>hpnorm=None , hcnorm=None, indices=None):
if indices is not None:<EOL><INDENT>hplus = hplus[indices]<EOL>hcross = hcross[indices]<EOL><DEDENT>if hpnorm is not None:<EOL><INDENT>hplus = hplus * hpnorm<EOL><DEDENT>if hcnorm is not None:<EOL><INDENT>hcross = hcross * hcnorm<EOL><DEDENT>rhoplusre=numpy.real(hplus)<EOL>rhocrossre=numpy.real(hcross)<EOL>overlap=nump...
The max-over-sky location (no phase) detection statistic maximizes over an amplitude and the ratio of F+ and Fx, encoded in a variable called u. Here we return the value of u for the given indices.
f15971:m5
def make_frequency_series(vec):
if isinstance(vec, FrequencySeries):<EOL><INDENT>return vec<EOL><DEDENT>if isinstance(vec, TimeSeries):<EOL><INDENT>N = len(vec)<EOL>n = N/<NUM_LIT:2>+<NUM_LIT:1><EOL>delta_f = <NUM_LIT:1.0> / N / vec.delta_t<EOL>vectilde = FrequencySeries(zeros(n, dtype=complex_same_precision_as(vec)),<EOL>delta_f=delta_f, copy=False...
Return a frequency series of the input vector. If the input is a frequency series it is returned, else if the input vector is a real time series it is fourier transformed and returned as a frequency series. Parameters ---------- vector : TimeSeries or FrequencySeries Returns ------- ...
f15971:m6
def sigmasq_series(htilde, psd=None, low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None):
htilde = make_frequency_series(htilde)<EOL>N = (len(htilde)-<NUM_LIT:1>) * <NUM_LIT:2><EOL>norm = <NUM_LIT> * htilde.delta_f<EOL>kmin, kmax = get_cutoff_indices(low_frequency_cutoff,<EOL>high_frequency_cutoff, htilde.delta_f, N)<EOL>sigma_vec = FrequencySeries(zeros(len(htilde), dtype=real_same_precision_as(htilde)),<E...
Return a cumulative sigmasq frequency series. Return a frequency series containing the accumulated power in the input up to that frequency. Parameters ---------- htilde : TimeSeries or FrequencySeries The input vector psd : {None, FrequencySeries}, optional The psd used to weig...
f15971:m7
def sigmasq(htilde, psd = None, low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None):
htilde = make_frequency_series(htilde)<EOL>N = (len(htilde)-<NUM_LIT:1>) * <NUM_LIT:2><EOL>norm = <NUM_LIT> * htilde.delta_f<EOL>kmin, kmax = get_cutoff_indices(low_frequency_cutoff,<EOL>high_frequency_cutoff, htilde.delta_f, N)<EOL>ht = htilde[kmin:kmax]<EOL>if psd:<EOL><INDENT>try:<EOL><INDENT>numpy.testing.assert_al...
Return the loudness of the waveform. This is defined (see Duncan Brown's thesis) as the unnormalized matched-filter of the input waveform, htilde, with itself. This quantity is usually referred to as (sigma)^2 and is then used to normalize matched-filters with the data. Parameters ---------- ht...
f15971:m8
def sigma(htilde, psd = None, low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None):
return sqrt(sigmasq(htilde, psd, low_frequency_cutoff, high_frequency_cutoff))<EOL>
Return the sigma of the waveform. See sigmasq for more details. Parameters ---------- htilde : TimeSeries or FrequencySeries The input vector containing a waveform. psd : {None, FrequencySeries}, optional The psd used to weight the accumulated power. low_frequency_cutoff : {None, fl...
f15971:m9
def get_cutoff_indices(flow, fhigh, df, N):
if flow:<EOL><INDENT>kmin = int(flow / df)<EOL>if kmin < <NUM_LIT:0>:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>".format(flow, kmin)<EOL>raise ValueError(err_msg)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>kmin = <NUM_LIT:1><EOL><DEDENT>if fhigh:<EOL><INDENT>kmax = int(fhigh / df )<EOL>if kmax > int((N + <N...
Gets the indices of a frequency series at which to stop an overlap calculation. Parameters ---------- flow: float The frequency (in Hz) of the lower index. fhigh: float The frequency (in Hz) of the upper index. df: float The frequency step (in Hz) of the frequency series. N: int The number of points in...
f15971:m10
def matched_filter_core(template, data, psd=None, low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None, h_norm=None, out=None, corr_out=None):
htilde = make_frequency_series(template)<EOL>stilde = make_frequency_series(data)<EOL>if len(htilde) != len(stilde):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>N = (len(stilde)-<NUM_LIT:1>) * <NUM_LIT:2><EOL>kmin, kmax = get_cutoff_indices(low_frequency_cutoff,<EOL>high_frequency_cutoff, stilde.delta_f, N)<E...
Return the complex snr and normalization. Return the complex snr, along with its associated normalization of the template, matched filtered against the data. Parameters ---------- template : TimeSeries or FrequencySeries The template waveform data : TimeSeries or FrequencySeries ...
f15971:m11
def smear(idx, factor):
s = [idx]<EOL>for i in range(factor+<NUM_LIT:1>):<EOL><INDENT>a = i - factor/<NUM_LIT:2><EOL>s += [idx + a]<EOL><DEDENT>return numpy.unique(numpy.concatenate(s))<EOL>
This function will take as input an array of indexes and return every unique index within the specified factor of the inputs. E.g.: smear([5,7,100],2) = [3,4,5,6,7,8,9,98,99,100,101,102] Parameters ----------- idx : numpy.array of ints The indexes to be smeared. factor : idx The factor by which to smear out t...
f15971:m12
def matched_filter(template, data, psd=None, low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None, sigmasq=None):
snr, _, norm = matched_filter_core(template, data, psd=psd,<EOL>low_frequency_cutoff=low_frequency_cutoff,<EOL>high_frequency_cutoff=high_frequency_cutoff, h_norm=sigmasq)<EOL>return snr * norm<EOL>
Return the complex snr. Return the complex snr, along with its associated normalization of the template, matched filtered against the data. Parameters ---------- template : TimeSeries or FrequencySeries The template waveform data : TimeSeries or FrequencySeries The strain data ...
f15971:m13
def match(vec1, vec2, psd=None, low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None, v1_norm=None, v2_norm=None):
htilde = make_frequency_series(vec1)<EOL>stilde = make_frequency_series(vec2)<EOL>N = (len(htilde)-<NUM_LIT:1>) * <NUM_LIT:2><EOL>global _snr<EOL>if _snr is None or _snr.dtype != htilde.dtype or len(_snr) != N:<EOL><INDENT>_snr = zeros(N,dtype=complex_same_precision_as(vec1))<EOL><DEDENT>snr, _, snr_norm = matched_filt...
Return the match between the two TimeSeries or FrequencySeries. Return the match between two waveforms. This is equivelant to the overlap maximized over time and phase. Parameters ---------- vec1 : TimeSeries or FrequencySeries The input vector containing a waveform. vec2 : TimeSeries ...
f15971:m14
def overlap(vec1, vec2, psd=None, low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None, normalized=True):
return overlap_cplx(vec1, vec2, psd=psd,low_frequency_cutoff=low_frequency_cutoff,high_frequency_cutoff=high_frequency_cutoff,normalized=normalized).real<EOL>
Return the overlap between the two TimeSeries or FrequencySeries. Parameters ---------- vec1 : TimeSeries or FrequencySeries The input vector containing a waveform. vec2 : TimeSeries or FrequencySeries The input vector containing a waveform. psd : Frequency Series A power sp...
f15971:m15
def overlap_cplx(vec1, vec2, psd=None, low_frequency_cutoff=None,<EOL>high_frequency_cutoff=None, normalized=True):
htilde = make_frequency_series(vec1)<EOL>stilde = make_frequency_series(vec2)<EOL>kmin, kmax = get_cutoff_indices(low_frequency_cutoff,<EOL>high_frequency_cutoff, stilde.delta_f, (len(stilde)-<NUM_LIT:1>) * <NUM_LIT:2>)<EOL>if psd:<EOL><INDENT>inner = (htilde[kmin:kmax]).weighted_inner(stilde[kmin:kmax], psd[kmin:kmax]...
Return the complex overlap between the two TimeSeries or FrequencySeries. Parameters ---------- vec1 : TimeSeries or FrequencySeries The input vector containing a waveform. vec2 : TimeSeries or FrequencySeries The input vector containing a waveform. psd : Frequency Series A ...
f15971:m16
def quadratic_interpolate_peak(left, middle, right):
bin_offset = <NUM_LIT:1.0>/<NUM_LIT> * (left - right) / (left - <NUM_LIT:2> * middle + right)<EOL>peak_value = middle + <NUM_LIT> * (left - right) * bin_offset<EOL>return bin_offset, peak_value<EOL>
Interpolate the peak and offset using a quadratic approximation Parameters ---------- left : numpy array Values at a relative bin value of [-1] middle : numpy array Values at a relative bin value of [0] right : numpy array Values at a relative bin value of [1] Returns ...
f15971:m17
def followup_event_significance(ifo, data_reader, bank,<EOL>template_id, coinc_times,<EOL>coinc_threshold=<NUM_LIT>,<EOL>lookback=<NUM_LIT>, duration=<NUM_LIT>):
from pycbc.waveform import get_waveform_filter_length_in_time<EOL>tmplt = bank.table[template_id]<EOL>length_in_time = get_waveform_filter_length_in_time(tmplt['<STR_LIT>'],<EOL>tmplt)<EOL>from pycbc.detector import Detector<EOL>onsource_start = -numpy.inf<EOL>onsource_end = numpy.inf<EOL>fdet = Detector(ifo)<EOL>for c...
Followup an event in another detector and determine its significance
f15971:m18
def compute_followup_snr_series(data_reader, htilde, trig_time,<EOL>duration=<NUM_LIT>, check_state=True,<EOL>coinc_window=<NUM_LIT>):
if check_state:<EOL><INDENT>state_start_time = trig_time - duration / <NUM_LIT:2> - htilde.length_in_time<EOL>state_end_time = trig_time + duration / <NUM_LIT:2><EOL>state_duration = state_end_time - state_start_time<EOL>if data_reader.state is not None:<EOL><INDENT>if not data_reader.state.is_extent_valid(state_start_...
Given a StrainBuffer, a template frequency series and a trigger time, compute a portion of the SNR time series centered on the trigger for its rapid sky localization and followup. If the trigger time is too close to the boundary of the valid data segment the SNR series is calculated anyway and might be...
f15971:m19
def __init__(self, xs, zs, size):
self.size = int(size)<EOL>self.dtype = xs[<NUM_LIT:0>].dtype<EOL>self.num_vectors = len(xs)<EOL>self.xs = xs<EOL>self.zs = zs<EOL>self.x = Array([v.ptr for v in xs], dtype=numpy.int)<EOL>self.z = Array([v.ptr for v in zs], dtype=numpy.int)<EOL>
Correlate x and y, store in z. Arrays need not be equal length, but must be at least size long and of the same dtype. No error checking will be performed, so be careful. All dtypes must be complex64. Note, must be created within the processing context that it will be used in.
f15971:c0:m0
def correlate(self):
pass<EOL>
Compute the correlation of the vectors specified at object instantiation, writing into the output vector given when the object was instantiated. The intention is that this method should be called many times, with the contents of those vectors changing between invocations, but not their locations in memory or length.
f15971:c2:m0
def __init__(self, low_frequency_cutoff, high_frequency_cutoff, snr_threshold, tlen,<EOL>delta_f, dtype, segment_list, template_output, use_cluster,<EOL>downsample_factor=<NUM_LIT:1>, upsample_threshold=<NUM_LIT:1>, upsample_method='<STR_LIT>',<EOL>gpu_callback_method='<STR_LIT:none>', cluster_function='<STR_LIT>'):
<EOL>self.tlen = tlen<EOL>self.flen = self.tlen / <NUM_LIT:2> + <NUM_LIT:1><EOL>self.delta_f = delta_f<EOL>self.delta_t = <NUM_LIT:1.0>/(self.delta_f * self.tlen)<EOL>self.dtype = dtype<EOL>self.snr_threshold = snr_threshold<EOL>self.flow = low_frequency_cutoff<EOL>self.fhigh = high_frequency_cutoff<EOL>self.gpu_callba...
Create a matched filter engine. Parameters ---------- low_frequency_cutoff : {None, float}, optional The frequency to begin the filter calculation. If None, begin at the first frequency after DC. high_frequency_cutoff : {None, float}, optional The fre...
f15971:c3:m0
def full_matched_filter_and_cluster_symm(self, segnum, template_norm, window, epoch=None):
norm = (<NUM_LIT> * self.delta_f) / sqrt(template_norm)<EOL>self.correlators[segnum].correlate()<EOL>self.ifft.execute()<EOL>snrv, idx = self.threshold_and_clusterers[segnum].threshold_and_cluster(self.snr_threshold / norm, window)<EOL>if len(idx) == <NUM_LIT:0>:<EOL><INDENT>return [], [], [], [], []<EOL><DEDENT>loggin...
Returns the complex snr timeseries, normalization of the complex snr, the correlation vector frequency series, the list of indices of the triggers, and the snr values at the trigger locations. Returns empty lists for these for points that are not above the threshold. Calculated the matc...
f15971:c3:m1
def full_matched_filter_and_cluster_fc(self, segnum, template_norm, window, epoch=None):
norm = (<NUM_LIT> * self.delta_f) / sqrt(template_norm)<EOL>self.correlators[segnum].correlate()<EOL>self.ifft.execute()<EOL>idx, snrv = events.threshold(self.snr_mem[self.segments[segnum].analyze],<EOL>self.snr_threshold / norm)<EOL>idx, snrv = events.cluster_reduce(idx, snrv, window)<EOL>if len(idx) == <NUM_LIT:0>:<E...
Returns the complex snr timeseries, normalization of the complex snr, the correlation vector frequency series, the list of indices of the triggers, and the snr values at the trigger locations. Returns empty lists for these for points that are not above the threshold. Calculated the matc...
f15971:c3:m2
def full_matched_filter_thresh_only(self, segnum, template_norm, window=None, epoch=None):
norm = (<NUM_LIT> * self.delta_f) / sqrt(template_norm)<EOL>self.correlators[segnum].correlate()<EOL>self.ifft.execute()<EOL>idx, snrv = events.threshold_only(self.snr_mem[self.segments[segnum].analyze],<EOL>self.snr_threshold / norm)<EOL>logging.info("<STR_LIT>" % str(len(idx)))<EOL>snr = TimeSeries(self.snr_mem, epoc...
Returns the complex snr timeseries, normalization of the complex snr, the correlation vector frequency series, the list of indices of the triggers, and the snr values at the trigger locations. Returns empty lists for these for points that are not above the threshold. Calculated the matc...
f15971:c3:m3
def heirarchical_matched_filter_and_cluster(self, segnum, template_norm, window):
from pycbc.fft.fftw_pruned import pruned_c2cifft, fft_transpose<EOL>htilde = self.htilde<EOL>stilde = self.segments[segnum]<EOL>norm = (<NUM_LIT> * stilde.delta_f) / sqrt(template_norm)<EOL>correlate(htilde[self.kmin_red:self.kmax_red],<EOL>stilde[self.kmin_red:self.kmax_red],<EOL>self.corr_mem[self.kmin_red:self.kmax_...
Returns the complex snr timeseries, normalization of the complex snr, the correlation vector frequency series, the list of indices of the triggers, and the snr values at the trigger locations. Returns empty lists for these for points that are not above the threshold. Calculated the matc...
f15971:c3:m4
def __init__(self, low_frequency_cutoff, high_frequency_cutoff,<EOL>snr_threshold, tlen, delta_f, dtype):
self.tlen = tlen<EOL>self.delta_f = delta_f<EOL>self.dtype = dtype<EOL>self.snr_threshold = snr_threshold<EOL>self.flow = low_frequency_cutoff<EOL>self.fhigh = high_frequency_cutoff<EOL>self.matched_filter_and_cluster =self.full_matched_filter_and_cluster<EOL>self.snr_plus_mem = zeros(self.tlen, dtype=self.dtype)<EOL>s...
Create a matched filter engine. Parameters ---------- low_frequency_cutoff : {None, float}, optional The frequency to begin the filter calculation. If None, begin at the first frequency after DC. high_frequency_cutoff : {None, float}, optional The frequency to stop the filter calculation. If None, continue...
f15971:c4:m0
def full_matched_filter_and_cluster(self, hplus, hcross, hplus_norm,<EOL>hcross_norm, psd, stilde, window):
I_plus, Iplus_corr, Iplus_norm = matched_filter_core(hplus, stilde,<EOL>h_norm=hplus_norm,<EOL>low_frequency_cutoff=self.flow,<EOL>high_frequency_cutoff=self.fhigh,<EOL>out=self.snr_plus_mem,<EOL>corr_out=self.corr_plus_mem)<EOL>I_cross, Icross_corr, Icross_norm = matched_filter_core(hcross,<EOL>stilde, h_norm=hcross_n...
Return the complex snr and normalization. Calculated the matched filter, threshold, and cluster. Parameters ---------- h_quantities : Various FILL ME IN stilde : FrequencySeries The strain data to be filtered. window : int The size of the cluster window in samples. Returns ------- snr : TimeSeries A ...
f15971:c4:m1
def __init__(self, templates, snr_threshold, chisq_bins, sg_chisq,<EOL>maxelements=<NUM_LIT:2>**<NUM_LIT>,<EOL>snr_abort_threshold=None,<EOL>newsnr_threshold=None,<EOL>max_triggers_in_batch=None):
self.snr_threshold = snr_threshold<EOL>self.snr_abort_threshold = snr_abort_threshold<EOL>self.newsnr_threshold = newsnr_threshold<EOL>self.max_triggers_in_batch = max_triggers_in_batch<EOL>from pycbc import vetoes<EOL>self.power_chisq = vetoes.SingleDetPowerChisq(chisq_bins, None)<EOL>self.sg_chisq = sg_chisq<EOL>dura...
Create a batched matchedfilter instance Parameters ---------- templates: list of `FrequencySeries` List of templates from the FilterBank class. snr_threshold: float Minimum value to record peaks in the SNR time series. chisq_bins: str Str that...
f15971:c6:m0
def set_data(self, data):
self.data = data<EOL>self.block_id = <NUM_LIT:0><EOL>
Set the data reader object to use
f15971:c6:m1
def combine_results(self, results):
result = {}<EOL>for key in results[<NUM_LIT:0>]:<EOL><INDENT>result[key] = numpy.concatenate([r[key] for r in results])<EOL><DEDENT>return result<EOL>
Combine results from different batches of filtering
f15971:c6:m2
def process_data(self, data_reader):
self.set_data(data_reader)<EOL>return self.process_all()<EOL>
Process the data for all of the templates
f15971:c6:m3
def process_all(self):
results = []<EOL>veto_info = []<EOL>while <NUM_LIT:1>:<EOL><INDENT>result, veto = self._process_batch()<EOL>if result is False: return False<EOL>if result is None: break<EOL>results.append(result)<EOL>veto_info += veto<EOL><DEDENT>result = self.combine_results(results)<EOL>if self.max_triggers_in_batch:<EOL><INDENT>sor...
Process every batch group and return as single result
f15971:c6:m4
def _process_vetoes(self, results, veto_info):
chisq = numpy.array(numpy.zeros(len(veto_info)), numpy.float32, ndmin=<NUM_LIT:1>)<EOL>dof = numpy.array(numpy.zeros(len(veto_info)), numpy.uint32, ndmin=<NUM_LIT:1>)<EOL>sg_chisq = numpy.array(numpy.zeros(len(veto_info)), numpy.float32,<EOL>ndmin=<NUM_LIT:1>)<EOL>results['<STR_LIT>'] = chisq<EOL>results['<STR_LIT>'] =...
Calculate signal based vetoes
f15971:c6:m5
def _process_batch(self):
if self.block_id == len(self.tgroups):<EOL><INDENT>return None, None<EOL><DEDENT>tgroup = self.tgroups[self.block_id]<EOL>psize = self.chunk_tsamples[self.block_id]<EOL>mid = self.mids[self.block_id]<EOL>stilde = self.data.overwhitened_data(tgroup[<NUM_LIT:0>].delta_f)<EOL>psd = stilde.psd<EOL>valid_end = int(psize - s...
Process only a single batch group of data
f15971:c6:m6
def get_swstat_bits(frame_filenames, swstat_channel_name, start_time, end_time):
<EOL>swstat = frame.read_frame(frame_filenames, swstat_channel_name,<EOL>start_time=start_time, end_time=end_time)<EOL>bits = bin(int(swstat[<NUM_LIT:0>]))<EOL>filterbank_off = False<EOL>if len(bits) < <NUM_LIT> or int(bits[-<NUM_LIT>]) == <NUM_LIT:0> or int(bits[-<NUM_LIT:11>]) == <NUM_LIT:0>:<EOL><INDENT>filterbank_o...
This function just checks the first time in the SWSTAT channel to see if the filter was on, it doesn't check times beyond that. This is just for a first test on a small chunck of data. To read the SWSTAT bits, reference: https://dcc.ligo.org/DocDB/0107/T1300711/001/LIGO-T1300711-v1.pdf Bit 0-9 = Filt...
f15973:m0
def filter_data(data, filter_name, filter_file, bits, filterbank_off=False,<EOL>swstat_channel_name=None):
<EOL>if filterbank_off:<EOL><INDENT>return numpy.zeros(len(data))<EOL><DEDENT>for i in range(<NUM_LIT:10>):<EOL><INDENT>filter = Filter(filter_file[filter_name][i])<EOL>bit = int(bits[-(i+<NUM_LIT:1>)])<EOL>if bit:<EOL><INDENT>logging.info('<STR_LIT>', i)<EOL>if len(filter.sections):<EOL><INDENT>data = filter.apply(dat...
A naive function to determine if the filter was on at the time and then filter the data.
f15973:m1
def read_gain_from_frames(frame_filenames, gain_channel_name, start_time, end_time):
<EOL>gain = frame.read_frame(frame_filenames, gain_channel_name,<EOL>start_time=start_time, end_time=end_time)<EOL>return gain[<NUM_LIT:0>]<EOL>
Returns the gain from the file.
f15973:m2
def lfilter(coefficients, timeseries):
from pycbc.filter import correlate<EOL>if len(timeseries) < <NUM_LIT:2>**<NUM_LIT:7>:<EOL><INDENT>if hasattr(timeseries, '<STR_LIT>'):<EOL><INDENT>timeseries = timeseries.numpy()<EOL><DEDENT>series = scipy.signal.lfilter(coefficients, <NUM_LIT:1.0>, timeseries)<EOL>return series<EOL><DEDENT>else:<EOL><INDENT>cseries = ...
Apply filter coefficients to a time series Parameters ---------- coefficients: numpy.ndarray Filter coefficients to apply timeseries: numpy.ndarray Time series to be filtered. Returns ------- tseries: numpy.ndarray filtered array
f15974:m0
def fir_zero_filter(coeff, timeseries):
<EOL>series = lfilter(coeff, timeseries.numpy())<EOL>data = numpy.zeros(len(timeseries))<EOL>data[len(coeff)//<NUM_LIT:2>:len(data)-len(coeff)//<NUM_LIT:2>] = series[(len(coeff) // <NUM_LIT:2>) * <NUM_LIT:2>:]<EOL>return data<EOL>
Filter the timeseries with a set of FIR coefficients Parameters ---------- coeff: numpy.ndarray FIR coefficients. Should be and odd length and symmetric. timeseries: pycbc.types.TimeSeries Time series to be filtered. Returns ------- filtered_series: pycbc.types.TimeSeries ...
f15974:m1
def resample_to_delta_t(timeseries, delta_t, method='<STR_LIT>'):
if not isinstance(timeseries,TimeSeries):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if timeseries.kind is not '<STR_LIT>':<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if timeseries.delta_t == delta_t:<EOL><INDENT>return timeseries * <NUM_LIT:1><EOL><DEDENT>if method == '<STR_LIT>':<EOL><INDENT>lal_d...
Resmple the time_series to delta_t Resamples the TimeSeries instance time_series to the given time step, delta_t. Only powers of two and real valued time series are supported at this time. Additional restrictions may apply to particular filter methods. Parameters ---------- time_series: Ti...
f15974:m2
def notch_fir(timeseries, f1, f2, order, beta=<NUM_LIT>):
k1 = f1 / float((int(<NUM_LIT:1.0> / timeseries.delta_t) / <NUM_LIT:2>))<EOL>k2 = f2 / float((int(<NUM_LIT:1.0> / timeseries.delta_t) / <NUM_LIT:2>))<EOL>coeff = scipy.signal.firwin(order * <NUM_LIT:2> + <NUM_LIT:1>, [k1, k2], window=('<STR_LIT>', beta))<EOL>data = fir_zero_filter(coeff, timeseries)<EOL>return TimeSeri...
notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and the number of samples in the filter length. For a few Hz bandwidth, a length corresponding to ...
f15974:m3
def lowpass_fir(timeseries, frequency, order, beta=<NUM_LIT>):
k = frequency / float((int(<NUM_LIT:1.0> / timeseries.delta_t) / <NUM_LIT:2>))<EOL>coeff = scipy.signal.firwin(order * <NUM_LIT:2> + <NUM_LIT:1>, k, window=('<STR_LIT>', beta))<EOL>data = fir_zero_filter(coeff, timeseries)<EOL>return TimeSeries(data, epoch=timeseries.start_time, delta_t=timeseries.delta_t)<EOL>
Lowpass filter the time series using an FIR filtered generated from the ideal response passed through a kaiser window (beta = 5.0) Parameters ---------- Time Series: TimeSeries The time series to be low-passed. frequency: float The frequency below which is suppressed. order: int...
f15974:m4
def highpass_fir(timeseries, frequency, order, beta=<NUM_LIT>):
k = frequency / float((int(<NUM_LIT:1.0> / timeseries.delta_t) / <NUM_LIT:2>))<EOL>coeff = scipy.signal.firwin(order * <NUM_LIT:2> + <NUM_LIT:1>, k, window=('<STR_LIT>', beta), pass_zero=False)<EOL>data = fir_zero_filter(coeff, timeseries)<EOL>return TimeSeries(data, epoch=timeseries.start_time, delta_t=timeseries.delt...
Highpass filter the time series using an FIR filtered generated from the ideal response passed through a kaiser window (beta = 5.0) Parameters ---------- Time Series: TimeSeries The time series to be high-passed. frequency: float The frequency below which is suppressed. order: i...
f15974:m5
def highpass(timeseries, frequency, filter_order=<NUM_LIT:8>, attenuation=<NUM_LIT:0.1>):
if not isinstance(timeseries, TimeSeries):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if timeseries.kind is not '<STR_LIT>':<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>lal_data = timeseries.lal()<EOL>_highpass_func[timeseries.dtype](lal_data, frequency,<EOL><NUM_LIT:1>-attenuation, filter_order)<EOL...
Return a new timeseries that is highpassed. Return a new time series that is highpassed above the `frequency`. Parameters ---------- Time Series: TimeSeries The time series to be high-passed. frequency: float The frequency below which is suppressed. filter_order: {8, int}, opti...
f15974:m6
def interpolate_complex_frequency(series, delta_f, zeros_offset=<NUM_LIT:0>, side='<STR_LIT:right>'):
new_n = int( (len(series)-<NUM_LIT:1>) * series.delta_f / delta_f + <NUM_LIT:1>)<EOL>old_N = int( (len(series)-<NUM_LIT:1>) * <NUM_LIT:2> )<EOL>new_N = int( (new_n - <NUM_LIT:1>) * <NUM_LIT:2> )<EOL>time_series = TimeSeries(zeros(old_N), delta_t =<NUM_LIT:1.0>/(series.delta_f*old_N),<EOL>dtype=real_same_precision_as(se...
Interpolate complex frequency series to desired delta_f. Return a new complex frequency series 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 outpu...
f15974:m7
def calculate_acf(data, delta_t=<NUM_LIT:1.0>, unbiased=False):
<EOL>if isinstance(data, TimeSeries):<EOL><INDENT>y = data.numpy()<EOL>delta_t = data.delta_t<EOL><DEDENT>else:<EOL><INDENT>y = data<EOL><DEDENT>y = y - y.mean()<EOL>ny_orig = len(y)<EOL>npad = <NUM_LIT:1><EOL>while npad < <NUM_LIT:2>*ny_orig:<EOL><INDENT>npad = npad << <NUM_LIT:1><EOL><DEDENT>ypad = numpy.zeros(npad)<...
r"""Calculates the one-sided autocorrelation function. Calculates the autocorrelation function (ACF) and returns the one-sided ACF. The ACF is defined as the autocovariance divided by the variance. The ACF can be estimated using .. math:: \hat{R}(k) = \frac{1}{n \sigma^{2}} \sum_{t=1}^{n-k} \...
f15977:m0
def calculate_acl(data, m=<NUM_LIT:5>, dtype=int):
<EOL>if dtype not in [int, float]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(data) < <NUM_LIT:2>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>acf = calculate_acf(data)<EOL>cacf = <NUM_LIT:2> * acf.numpy().cumsum() - <NUM_LIT:1><EOL>win = m * cacf <= numpy.arange(len(cacf))<EOL>if win.any():<EOL><INDEN...
r"""Calculates the autocorrelation length (ACL). Given a normalized autocorrelation function :math:`\rho[i]` (by normalized, we mean that :math:`\rho[0] = 1`), the ACL :math:`\tau` is: .. math:: \tau = 1 + 2 \sum_{i=1}^{K} \rho[i]. The number of samples used :math:`K` is found by using the f...
f15977:m1
def filter_zpk(timeseries, z, p, k):
<EOL>if not isinstance(timeseries, TimeSeries):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>degree = len(p) - len(z)<EOL>if degree < <NUM_LIT:0>:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>z = np.array(z)<EOL>p = np.array(p)<EOL>k = float(k)<EOL>z *= -<NUM_LIT:2> * np.pi<EOL>p *= -<NUM_LIT:2> * np.pi...
Return a new timeseries that was filtered with a zero-pole-gain filter. The transfer function in the s-domain looks like: .. math:: \\frac{H(s) = (s - s_1) * (s - s_3) * ... * (s - s_n)}{(s - s_2) * (s - s_4) * ... * (s - s_m)}, m >= n The zeroes, and poles entered in Hz are converted to angular freque...
f15978:m0
def pycbc_compile_function(code,arg_names,local_dict,global_dict,<EOL>module_dir,<EOL>compiler='<STR_LIT>',<EOL>verbose=<NUM_LIT:1>,<EOL>support_code=None,<EOL>headers=None,<EOL>customize=None,<EOL>type_converters=None,<EOL>auto_downcast=<NUM_LIT:1>,<EOL>**kw):
headers = [] if headers is None else headers<EOL>lockfile_dir = os.environ['<STR_LIT>']<EOL>lockfile_name = os.path.join(lockfile_dir, '<STR_LIT>')<EOL>logging.info("<STR_LIT>"<EOL>"<STR_LIT>" % lockfile_name)<EOL>if not os.path.exists(lockfile_dir):<EOL><INDENT>os.makedirs(lockfile_dir)<EOL><DEDENT>lockfile = open(loc...
Dummy wrapper around scipy weave compile to implement file locking
f15980:m0
def insert_weave_option_group(parser):
optimization_group = parser.add_argument_group("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>optimization_group.add_argument("<STR_LIT>",<EOL>action="<STR_LIT:store_true>",<EOL>default=False,<EOL>help="""<STR_LIT>""")<EOL>optimization_group.add_argument("<STR_LIT>",<EOL>action="<STR_LIT:store_true>",<EOL>default=False,<EOL>help="<S...
Adds the options used to specify weave options. Parameters ---------- parser : object OptionParser instance
f15980:m1
def _clear_weave_cache():
cache_dir = os.environ['<STR_LIT>']<EOL>if os.path.exists(cache_dir):<EOL><INDENT>shutil.rmtree(cache_dir)<EOL><DEDENT>logging.info("<STR_LIT>", cache_dir)<EOL>
Deletes the weave cache specified in os.environ['PYTHONCOMPILED']
f15980:m2
def verify_weave_options(opt, parser):
<EOL>cache_dir = os.environ['<STR_LIT>']<EOL>if opt.fixed_weave_cache:<EOL><INDENT>if os.environ.get("<STR_LIT>", None):<EOL><INDENT>cache_dir = os.environ["<STR_LIT>"]<EOL><DEDENT>elif getattr(sys, '<STR_LIT>', False):<EOL><INDENT>cache_dir = sys._MEIPASS<EOL><DEDENT>else:<EOL><INDENT>cache_dir = os.path.join(os.getcw...
Parses the CLI options, verifies that they are consistent and reasonable, and acts on them if they are Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes parser : object OptionParser instance.
f15980:m3
def get_options_from_group(option_group):
option_list = option_group._group_actions<EOL>command_lines = []<EOL>for option in option_list:<EOL><INDENT>option_strings = option.option_strings<EOL>for string in option_strings:<EOL><INDENT>if string.startswith('<STR_LIT>'):<EOL><INDENT>command_lines.append(string)<EOL><DEDENT><DEDENT><DEDENT>return command_lines<EO...
Take an option group and return all the options that are defined in that group.
f15981:m0
def insert_base_bank_options(parser):
def match_type(s):<EOL><INDENT>err_msg = "<STR_LIT>" % s<EOL>try:<EOL><INDENT>value = float(s)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise argparse.ArgumentTypeError(err_msg)<EOL><DEDENT>if value <= <NUM_LIT:0> or value >= <NUM_LIT:1>:<EOL><INDENT>raise argparse.ArgumentTypeError(err_msg)<EOL><DEDENT>return value<...
Adds essential common options for template bank generation to an ArgumentParser instance.
f15981:m1
def insert_metric_calculation_options(parser):
metricOpts = parser.add_argument_group(<EOL>"<STR_LIT>")<EOL>metricOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>", type=str,<EOL>required=True,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %(pycbcValidOrdersHelpDescriptions))<EOL>metricOpts.add_argument("<STR_LIT>", action="<STR_LIT:sto...
Adds the options used to obtain a metric in the bank generation codes to an argparser as an OptionGroup. This should be used if you want to use these options in your code.
f15981:m2
def verify_metric_calculation_options(opts, parser):
if not opts.pn_order:<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>
Parses the metric calculation options given and verifies that they are correct. Parameters ---------- opts : argparse.Values instance Result of parsing the input options with OptionParser parser : object The OptionParser instance.
f15981:m3
def insert_mass_range_option_group(parser,nonSpin=False):
massOpts = parser.add_argument_group("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>", type=positive_float,<EOL>required=True, <EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>", type=positive_float,<EOL>required=True,<EOL>h...
Adds the options used to specify mass ranges in the bank generation codes to an argparser as an OptionGroup. This should be used if you want to use these options in your code. Parameters ----------- parser : object OptionParser instance. nonSpin : boolean, optional (default=False) If this is provided the spin-...
f15981:m4
def verify_mass_range_options(opts, parser, nonSpin=False):
<EOL>if opts.min_mass1 < opts.min_mass2:<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>if opts.max_mass1 < opts.max_mass2:<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>if opts.min_total_massand (opts.min_total_mass > opts.max_mass1 + opts.max_mass2):<EOL><INDENT>err_msg = "<STR_LIT>" %(opts.min_total_mass,)<EO...
Parses the metric calculation options given and verifies that they are correct. Parameters ---------- opts : argparse.Values instance Result of parsing the input options with OptionParser parser : object The OptionParser instance. nonSpin : boolean, optional (default=False) If this is provided the spin-rel...
f15981:m5
def insert_ethinca_metric_options(parser):
ethincaGroup = parser.add_argument_group("<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>ethinca_methods = ethincaGroup.add_mutually_exclusive_group()<EOL>ethinca_methods.add_argument("<STR_LIT>",<EOL>action="<STR_LIT:store_true>", default=False,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<E...
Adds the options used to calculate the ethinca metric, if required. Parameters ----------- parser : object OptionParser instance.
f15981:m6
def verify_ethinca_metric_options(opts, parser):
if opts.filter_cutoff is not None and not (opts.filter_cutoff in<EOL>pnutils.named_frequency_cutoffs.keys()):<EOL><INDENT>parser.error("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>+str(pnutils.named_frequency_cutoffs.keys()))<EOL><DEDENT>if (opts.calculate_ethinca_metric or opts.calculate_time_metric_components)and not opts.ethinca...
Checks that the necessary options are given for the ethinca metric calculation. Parameters ---------- opts : argparse.Values instance Result of parsing the input options with OptionParser parser : object The OptionParser instance.
f15981:m7
def check_ethinca_against_bank_params(ethincaParams, metricParams):
if ethincaParams.doEthinca:<EOL><INDENT>if metricParams.f0 != metricParams.fLow:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if ethincaParams.fLow is not None and (<EOL>ethincaParams.fLow != metricParams.fLow):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDE...
Cross-check the ethinca and bank layout metric calculation parameters and set the ethinca metric PN order equal to the bank PN order if not previously set. Parameters ---------- ethincaParams: instance of ethincaParameters metricParams: instance of metricParameters
f15981:m8
def format_description(self, description):
if not description: return "<STR_LIT>"<EOL>desc_width = self.width - self.current_indent<EOL>indent = "<STR_LIT:U+0020>"*self.current_indent<EOL>bits = description.split('<STR_LIT:\n>')<EOL>formatted_bits = [<EOL>textwrap.fill(bit,<EOL>desc_width,<EOL>initial_indent=indent,<EOL>subsequent_indent=indent)<EOL>for bit in ...
No documentation
f15981:c0:m0
def format_option(self, option):
<EOL>result = []<EOL>opts = self.option_strings[option]<EOL>opt_width = self.help_position - self.current_indent - <NUM_LIT:2><EOL>if len(opts) > opt_width:<EOL><INDENT>opts = "<STR_LIT>" % (self.current_indent, "<STR_LIT>", opts)<EOL>indent_first = self.help_position<EOL><DEDENT>else: <EOL><INDENT>opts = "<STR_LIT>" %...
No documentation
f15981:c0:m1