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:<EOL><INDENT>raise ValueError('<STR_LIT>' % type(item))<EOL><DEDENT><DEDENT> | 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 < size:<EOL><INDENT>r = i + chunksize if i + chunksize < size else size<EOL>partial = [refs[arg][i:r] for arg in args]<EOL>keep = fcn(*partial)<EOL>if return_indices:<EOL><INDENT>indices = np.concatenate([indices, np.flatnonzero(keep) + i])<EOL><DEDENT>for arg, part in zip(args, partial):<EOL><INDENT>data[arg].append(part[keep])<EOL><DEDENT>i += chunksize<EOL><DEDENT>if len(args) == <NUM_LIT:1>:<EOL><INDENT>res = np.concatenate(data[args[<NUM_LIT:0>]])<EOL>if return_indices:<EOL><INDENT>return indices, res<EOL><DEDENT>else:<EOL><INDENT>return res<EOL><DEDENT><DEDENT>else:<EOL><INDENT>res = tuple(np.concatenate(data[arg]) for arg in args)<EOL>if return_indices:<EOL><INDENT>return (indices,) + res<EOL><DEDENT>else:<EOL><INDENT>return res<EOL><DEDENT><DEDENT> | 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 of strings that are keys into the hdf5. These must
refer to arrays of equal length.
chunksize : {1e6, int}, optional
Number of elements to read and process at a time.
return_indices : bool, optional
If True, also return the indices of elements passing the function.
Returns
-------
values : np.ndarrays
A variable number of arrays depending on the number of keys into
the hdf5 file that are given. If return_indices is True, the first
element is an array of indices of elements passing the function.
>>> f = HFile(filename)
>>> snr = f.select(lambda snr: snr > 6, 'H1/snr') | 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>if not len(self.data[k]) == <NUM_LIT:0>:<EOL><INDENT>self.data[k] = np.concatenate(self.data[k])<EOL><DEDENT><DEDENT><DEDENT>for k in self.data:<EOL><INDENT>setattr(self, k, self.data[k])<EOL><DEDENT> | 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 into each file. Required by the files options. | 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)<EOL> | 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>cid = cluster_coincs(self.stat,<EOL>self.data['<STR_LIT>' % pivot_ifo],<EOL>self.data['<STR_LIT>' % fixed_ifo],<EOL>self.timeslide_id,<EOL>interval,<EOL>window)<EOL>return self.select(cid)<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><DEDENT>self.group_key = group<EOL>self.group = self.h5file[group]<EOL>self.columns = columnlist if columnlist is not Noneelse self.group.keys()<EOL>self.filter_func = filter_func<EOL>self._mask = None<EOL> | 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. 'self.snr < 6.5' | 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)<EOL><DEDENT>return self._mask<EOL><DEDENT> | 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(vals)<EOL> | 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_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>else:<EOL><INDENT>self.stat_name = ranking_statistic<EOL><DEDENT>times = self.end_time<EOL>index = stat.argsort()[::-<NUM_LIT:1>]<EOL>new_times = []<EOL>new_index = []<EOL>for curr_idx in index:<EOL><INDENT>curr_time = times[curr_idx]<EOL>for time in new_times:<EOL><INDENT>if abs(curr_time - time) < cluster_window:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>new_index.append(curr_idx)<EOL>new_times.append(curr_time)<EOL><DEDENT>if len(new_index) >= n_loudest:<EOL><INDENT>break<EOL><DEDENT><DEDENT>index = np.array(new_index)<EOL>self.stat = stat[index]<EOL>if self.mask.dtype == '<STR_LIT:bool>':<EOL><INDENT>orig_indices = np.flatnonzero(self.mask)[index]<EOL>self.mask[:] = False<EOL>self.mask[orig_indices] = True<EOL><DEDENT>else:<EOL><INDENT>self.mask = self.mask[index]<EOL><DEDENT> | 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_LIT:1>-eff.array)/bins.denominator.array)<EOL>err = bin_utils.BinnedArray(bin_utils.NDBins(ndbins), array=err_arr)<EOL>return eff, err<EOL> | 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.NDBins(ndbins[<NUM_LIT:1>:]))<EOL>vol.array = numpy.trapz(eff.array.T * <NUM_LIT> * numpy.pi * r**<NUM_LIT:2>, r, dx)<EOL>errors.array = numpy.sqrt(<EOL>((<NUM_LIT:4> * numpy.pi * r**<NUM_LIT:2> * err.array.T * dx)**<NUM_LIT:2>).sum(axis=-<NUM_LIT:1>)<EOL>)<EOL>return vol, errors<EOL> | 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_LIT>)<EOL>return dist, ehigh, elow<EOL> | 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_LIT> / <NUM_LIT>,<EOL>'<STR_LIT>' : <NUM_LIT> / <NUM_LIT><EOL>}[distribution]<EOL>if limits_param == '<STR_LIT>':<EOL><INDENT>mchirp_standard_bns = <NUM_LIT> * <NUM_LIT>**(-<NUM_LIT:1.> / <NUM_LIT>)<EOL>all_mchirp = numpy.concatenate((found_mchirp, missed_mchirp))<EOL>max_mchirp = all_mchirp.max()<EOL>if max_param is not None:<EOL><INDENT>max_distance = max_param *(max_mchirp / mchirp_standard_bns)**(<NUM_LIT> / <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>max_distance = max(found_d.max(), missed_d.max())<EOL><DEDENT><DEDENT>elif limits_param == '<STR_LIT>':<EOL><INDENT>if max_param is not None:<EOL><INDENT>max_distance = max_param<EOL><DEDENT>else:<EOL><INDENT>max_distance = max(found_d.max(), missed_d.max())<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>"<EOL>% limits_param)<EOL><DEDENT>montecarlo_vtot = (<NUM_LIT> / <NUM_LIT>) * numpy.pi * max_distance**<NUM_LIT><EOL>if distribution_param == '<STR_LIT>':<EOL><INDENT>found_weights = found_d ** d_power<EOL>missed_weights = missed_d ** d_power<EOL><DEDENT>elif distribution_param == '<STR_LIT>':<EOL><INDENT>found_weights = found_d ** d_power *found_mchirp ** mchirp_power<EOL>missed_weights = missed_d ** d_power *missed_mchirp ** mchirp_power<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>"<EOL>% distribution_param)<EOL><DEDENT>all_weights = numpy.concatenate((found_weights, missed_weights))<EOL>mc_weight_samples = numpy.concatenate((found_weights, <NUM_LIT:0> * missed_weights))<EOL>mc_sum = sum(mc_weight_samples)<EOL>if limits_param == '<STR_LIT>':<EOL><INDENT>mc_norm = sum(all_weights)<EOL><DEDENT>elif limits_param == '<STR_LIT>':<EOL><INDENT>mc_norm = sum(all_weights * (max_mchirp / all_mchirp) ** (<NUM_LIT> / <NUM_LIT>))<EOL><DEDENT>mc_prefactor = montecarlo_vtot / mc_norm<EOL>if limits_param == '<STR_LIT>':<EOL><INDENT>Ninj = len(mc_weight_samples)<EOL><DEDENT>elif limits_param == '<STR_LIT>':<EOL><INDENT>if distribution == '<STR_LIT>':<EOL><INDENT>if min_param is not None:<EOL><INDENT>min_distance = min_param *(numpy.min(all_mchirp) / mchirp_standard_bns) ** (<NUM_LIT> / <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>min_distance = min(numpy.min(found_d), numpy.min(missed_d))<EOL><DEDENT>logrange = numpy.log(max_distance / min_distance)<EOL>Ninj = len(mc_weight_samples) + (<NUM_LIT> / <NUM_LIT>) *sum(numpy.log(max_mchirp / all_mchirp) / logrange)<EOL><DEDENT>else:<EOL><INDENT>Ninj = sum((max_mchirp / all_mchirp) ** mchirp_power)<EOL><DEDENT><DEDENT>mc_sample_variance = sum(mc_weight_samples ** <NUM_LIT>) / Ninj -(mc_sum / Ninj) ** <NUM_LIT><EOL>vol = mc_prefactor * mc_sum<EOL>vol_err = mc_prefactor * (Ninj * mc_sample_variance) ** <NUM_LIT:0.5><EOL>return vol, vol_err<EOL> | Compute sensitive volume and standard error via direct Monte Carlo integral
Injections should be made over a range of distances such that sensitive
volume due to signals closer than D_min is negligible, and efficiency at
distances above D_max is negligible
TODO : Replace this function by Collin's formula given in Usman et al .. ?
OR get that coded as a new function?
Parameters
-----------
found_d: numpy.ndarray
The distances of found injections
missed_d: numpy.ndarray
The distances of missed injections
found_mchirp: numpy.ndarray
Chirp mass of found injections
missed_mchirp: numpy.ndarray
Chirp mass of missed injections
distribution_param: string
Parameter D of the injections used to generate a distribution over
distance, may be 'distance', 'chirp_distance'.
distribution: string
form of the distribution over the parameter, may be
'log' (uniform in log D)
'uniform' (uniform in D)
'distancesquared' (uniform in D**2)
'volume' (uniform in D***3)
limits_param: string
Parameter Dlim specifying limits inside which injections were made
may be 'distance', 'chirp distance'
min_param: float
minimum value of Dlim at which injections were made; only used for
log distribution, then if None the minimum actually injected value
will be used
max_param: float
maximum value of Dlim out to which injections were made; if None
the maximum actually injected value will be used
Returns
--------
volume: float
Volume estimate
volume_error: float
The standard error in the volume | 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, total, ndbins, sims_to_bin)<EOL>return vol.array[<NUM_LIT:0>], verr.array[<NUM_LIT:0>]<EOL> | Compute the sensitive volume using a distance binned efficiency estimate
Parameters
-----------
f_dist: numpy.ndarray
The distances of found injections
m_dist: numpy.ndarray
The distances of missed injections
Returns
--------
volume: float
Volume estimate
volume_error: float
The standard error in the volume | 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>:<EOL><INDENT>break<EOL><DEDENT>high = (distances[i+<NUM_LIT:1>] + distances[i]) / <NUM_LIT:2><EOL>bin_width = high - low<EOL>if dist_sorting[i] < len(f_dist):<EOL><INDENT>vol += <NUM_LIT:4> * numpy.pi * distances[i]**<NUM_LIT> * bin_width<EOL>vol_err += (<NUM_LIT:4> * numpy.pi * distances[i]**<NUM_LIT> * bin_width)**<NUM_LIT><EOL><DEDENT>low = high<EOL><DEDENT>vol_err = vol_err ** <NUM_LIT:0.5><EOL>return vol, vol_err<EOL> | Compute the sensitive volume using sum over spherical shells.
Parameters
-----------
f_dist: numpy.ndarray
The distances of found injections
m_dist: numpy.ndarray
The distances of missed injections
Returns
--------
volume: float
Volume estimate
volume_error: float
The standard error in the volume | 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> or menergy > max_energy:<EOL><INDENT>max_energy = menergy<EOL>max_key = q<EOL><DEDENT><DEDENT>qplanes[q] = energies<EOL><DEDENT>plane = qplanes[max_key]<EOL>frequencies = qplane_tile_dict[max_key]<EOL>times = plane[<NUM_LIT:0>].sample_times.numpy()<EOL>plane = numpy.array([v.numpy() for v in plane])<EOL>return max_key, times, frequencies, numpy.array(plane)<EOL> | 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
fseries: 'pycbc FrequencySeries'
frequency-series data set
return_complex: {False, bool}
Return the raw complex series instead of the normalized power.
Returns
-------
q : float
The q of the maximum q plane
times : numpy.ndarray
The time that the qtransform is sampled.
freqs : numpy.ndarray
The frequencies that the qtransform is samled.
qplane : numpy.ndarray (2d)
The two dimensional interpolated qtransform of this time series. | 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
Returns
-------
qplane_tile_dict: 'dict'
dictionary containing Q-tile tuples for a set of Q-planes | 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>))<EOL><DEDENT>raise StopIteration()<EOL> | 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><INDENT>yield (float(minf) *<EOL>exp(<NUM_LIT:2> / (<NUM_LIT:2> + q**<NUM_LIT:2>)**(<NUM_LIT:1>/<NUM_LIT>) * (i + <NUM_LIT>) * fstep) //<EOL>fstepmin * fstepmin)<EOL><DEDENT>raise StopIteration()<EOL> | 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
-------
frequencies:
Q-Tile frequency | 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)) * fseries.duration)<EOL>end = int(start + window_size)<EOL>center = (start + end) / <NUM_LIT:2><EOL>windowed = fseries[start:end] * (<NUM_LIT:1> - xfrequencies ** <NUM_LIT:2>) ** <NUM_LIT:2> * norm<EOL>tlen = (len(fseries)-<NUM_LIT:1>) * <NUM_LIT:2><EOL>windowed.resize(tlen)<EOL>windowed.roll(-center)<EOL>windowed = FrequencySeries(windowed, delta_f=fseries.delta_f,<EOL>epoch=fseries.start_time)<EOL>ctseries = TimeSeries(zeros(tlen, dtype=numpy.complex128),<EOL>delta_t=fseries.delta_t)<EOL>ifft(windowed, ctseries)<EOL>if return_complex:<EOL><INDENT>return ctseries<EOL><DEDENT>else:<EOL><INDENT>energy = ctseries.squared_norm()<EOL>medianenergy = numpy.median(energy.numpy())<EOL>return energy / float(medianenergy)<EOL><DEDENT> | 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.
Returns
-------
energy: '~pycbc.types.TimeSeries'
A 'TimeSeries' of the normalized energy from the Q-transform of
this tile against the data. | 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_zero_locs] = <NUM_LIT:0><EOL><DEDENT><DEDENT>if thresh:<EOL><INDENT>idx_p, _ = events.threshold_only(hplus[analyse_slice],<EOL>thresh / (<NUM_LIT:2>**<NUM_LIT:0.5> * hpnorm))<EOL>idx_c, _ = events.threshold_only(hcross[analyse_slice],<EOL>thresh / (<NUM_LIT:2>**<NUM_LIT:0.5> * hcnorm))<EOL>idx_p = idx_p + analyse_slice.start<EOL>idx_c = idx_c + analyse_slice.start<EOL>hp_red = hplus[idx_p] * hpnorm<EOL>hc_red = hcross[idx_p] * hcnorm<EOL>stat_p = hp_red.real**<NUM_LIT:2> + hp_red.imag**<NUM_LIT:2> +hc_red.real**<NUM_LIT:2> + hc_red.imag**<NUM_LIT:2><EOL>locs_p = idx_p[stat_p > (thresh*thresh)]<EOL>hp_red = hplus[idx_c] * hpnorm<EOL>hc_red = hcross[idx_c] * hcnorm<EOL>stat_c = hp_red.real**<NUM_LIT:2> + hp_red.imag**<NUM_LIT:2> +hc_red.real**<NUM_LIT:2> + hc_red.imag**<NUM_LIT:2><EOL>locs_c = idx_c[stat_c > (thresh*thresh)]<EOL>locs = numpy.unique(numpy.concatenate((locs_p, locs_c)))<EOL>hplus = hplus[locs]<EOL>hcross = hcross[locs]<EOL><DEDENT>hplus = hplus * hpnorm<EOL>hcross = hcross * hcnorm<EOL>denom = <NUM_LIT:1> - hphccorr*hphccorr<EOL>if denom < <NUM_LIT:0>:<EOL><INDENT>if hphccorr > <NUM_LIT:1>:<EOL><INDENT>err_msg = "<STR_LIT>" %(hphccorr)<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>else:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT><DEDENT>if denom == <NUM_LIT:0>:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>assert(len(hplus) == len(hcross))<EOL>hplus_magsq = numpy.real(hplus) * numpy.real(hplus) +numpy.imag(hplus) * numpy.imag(hplus)<EOL>hcross_magsq = numpy.real(hcross) * numpy.real(hcross) +numpy.imag(hcross) * numpy.imag(hcross)<EOL>rho_pluscross = numpy.real(hplus) * numpy.real(hcross) + numpy.imag(hplus)*numpy.imag(hcross)<EOL>sqroot = (hplus_magsq - hcross_magsq)**<NUM_LIT:2><EOL>sqroot += <NUM_LIT:4> * (hphccorr * hplus_magsq - rho_pluscross) *(hphccorr * hcross_magsq - rho_pluscross)<EOL>if (sqroot < <NUM_LIT:0>).any():<EOL><INDENT>indices = numpy.arange(len(sqroot))[sqroot < <NUM_LIT:0>]<EOL>if (sqroot[indices] < -<NUM_LIT>).any():<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>sqroot[indices] = <NUM_LIT:0><EOL><DEDENT>sqroot = numpy.sqrt(sqroot)<EOL>det_stat_sq = <NUM_LIT:0.5> * (hplus_magsq + hcross_magsq -<NUM_LIT:2> * rho_pluscross*hphccorr + sqroot) / denom<EOL>det_stat = numpy.sqrt(det_stat_sq)<EOL>if thresh:<EOL><INDENT>out.data[locs] = det_stat<EOL>out.non_zero_locs = locs<EOL>return out<EOL><DEDENT>else:<EOL><INDENT>return Array(det_stat, copy=False)<EOL><DEDENT> | 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 : TimeSeries
This is the IFFTed complex SNR time series of (hx, data). If not
normalized, supply the normalization factor so this can be done!
hphccorr : float
The real component of the overlap between the two polarizations
Re[(h+, hx)]. Note that the imaginary component does not enter the
detection statistic. This must be normalized and is sign-sensitive.
thresh : float
Used for optimization. If we do not care about the value of SNR
values below thresh we can calculate a quick statistic that will
always overestimate SNR and then only calculate the proper, more
expensive, statistic at points where the quick SNR is above thresh.
hpsigmasq : float
The normalization factor (h+, h+). Default = None (=1, already
normalized)
hcsigmasq : float
The normalization factor (hx, hx). Default = None (=1, already
normalized)
out : TimeSeries (optional, default=None)
If given, use this array to store the output.
Returns
--------
det_stat : TimeSeries
The SNR maximized over sky location | 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.imag(hplus)<EOL>hcross_magsq = numpy.real(hcross) * numpy.real(hcross) +numpy.imag(hcross) * numpy.imag(hcross)<EOL>rho_pluscross = numpy.real(hplus) * numpy.real(hcross) +numpy.imag(hplus)*numpy.imag(hcross)<EOL>a = hphccorr * hplus_magsq - rho_pluscross<EOL>b = hplus_magsq - hcross_magsq<EOL>c = rho_pluscross - hphccorr * hcross_magsq<EOL>sq_root = b*b - <NUM_LIT:4>*a*c<EOL>sq_root = sq_root**<NUM_LIT:0.5><EOL>sq_root = -sq_root<EOL>bad_lgc = (a == <NUM_LIT:0>)<EOL>dbl_bad_lgc = numpy.logical_and(c == <NUM_LIT:0>, b == <NUM_LIT:0>)<EOL>dbl_bad_lgc = numpy.logical_and(bad_lgc, dbl_bad_lgc)<EOL>u = sq_root * <NUM_LIT:0.><EOL>u[dbl_bad_lgc] = <NUM_LIT:1.><EOL>u[bad_lgc & ~dbl_bad_lgc] = <NUM_LIT><EOL>u[~bad_lgc] = (-b[~bad_lgc] + sq_root[~bad_lgc]) / (<NUM_LIT:2>*a[~bad_lgc])<EOL>snr_cplx = hplus * u + hcross<EOL>coa_phase = numpy.angle(snr_cplx)<EOL>return u, coa_phase<EOL> | 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_zero_locs] = <NUM_LIT:0><EOL><DEDENT><DEDENT>if thresh:<EOL><INDENT>idx_p, _ = events.threshold_only(hplus[analyse_slice],<EOL>thresh / (<NUM_LIT:2>**<NUM_LIT:0.5> * hpnorm))<EOL>idx_c, _ = events.threshold_only(hcross[analyse_slice],<EOL>thresh / (<NUM_LIT:2>**<NUM_LIT:0.5> * hcnorm))<EOL>idx_p = idx_p + analyse_slice.start<EOL>idx_c = idx_c + analyse_slice.start<EOL>hp_red = hplus[idx_p] * hpnorm<EOL>hc_red = hcross[idx_p] * hcnorm<EOL>stat_p = hp_red.real**<NUM_LIT:2> + hp_red.imag**<NUM_LIT:2> +hc_red.real**<NUM_LIT:2> + hc_red.imag**<NUM_LIT:2><EOL>locs_p = idx_p[stat_p > (thresh*thresh)]<EOL>hp_red = hplus[idx_c] * hpnorm<EOL>hc_red = hcross[idx_c] * hcnorm<EOL>stat_c = hp_red.real**<NUM_LIT:2> + hp_red.imag**<NUM_LIT:2> +hc_red.real**<NUM_LIT:2> + hc_red.imag**<NUM_LIT:2><EOL>locs_c = idx_c[stat_c > (thresh*thresh)]<EOL>locs = numpy.unique(numpy.concatenate((locs_p, locs_c)))<EOL>hplus = hplus[locs]<EOL>hcross = hcross[locs]<EOL><DEDENT>hplus = hplus * hpnorm<EOL>hcross = hcross * hcnorm<EOL>denom = <NUM_LIT:1> - hphccorr*hphccorr<EOL>if denom < <NUM_LIT:0>:<EOL><INDENT>if hphccorr > <NUM_LIT:1>:<EOL><INDENT>err_msg = "<STR_LIT>" %(hphccorr)<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>else:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT><DEDENT>if denom == <NUM_LIT:0>:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>assert(len(hplus) == len(hcross))<EOL>hplus_magsq = numpy.real(hplus) * numpy.real(hplus)<EOL>hcross_magsq = numpy.real(hcross) * numpy.real(hcross)<EOL>rho_pluscross = numpy.real(hplus) * numpy.real(hcross)<EOL>det_stat_sq = (hplus_magsq + hcross_magsq - <NUM_LIT:2> * rho_pluscross*hphccorr)<EOL>det_stat = numpy.sqrt(det_stat_sq / denom)<EOL>if thresh:<EOL><INDENT>out.data[locs] = det_stat<EOL>out.non_zero_locs = locs<EOL>return out<EOL><DEDENT>else:<EOL><INDENT>return Array(det_stat, copy=False)<EOL><DEDENT> | 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 computational cost!)
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 : TimeSeries
This is the IFFTed complex SNR time series of (hx, data). If not
normalized, supply the normalization factor so this can be done!
hphccorr : float
The real component of the overlap between the two polarizations
Re[(h+, hx)]. Note that the imaginary component does not enter the
detection statistic. This must be normalized and is sign-sensitive.
thresh : float
Used for optimization. If we do not care about the value of SNR
values below thresh we can calculate a quick statistic that will
always overestimate SNR and then only calculate the proper, more
expensive, statistic at points where the quick SNR is above thresh.
hpsigmasq : float
The normalization factor (h+, h+). Default = None (=1, already
normalized)
hcsigmasq : float
The normalization factor (hx, hx). Default = None (=1, already
normalized)
out : TimeSeries (optional, default=None)
If given, use this array to store the output.
Returns
--------
det_stat : TimeSeries
The SNR maximized over sky location | 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=numpy.real(hphccorr)<EOL>denom = (-rhocrossre+overlap*rhoplusre)<EOL>u_val = denom * <NUM_LIT:0.><EOL>bad_lgc = (denom == <NUM_LIT:0>)<EOL>u_val[bad_lgc] = <NUM_LIT><EOL>u_val[~bad_lgc] = (-rhoplusre+overlap*rhocrossre) /(-rhocrossre+overlap*rhoplusre)<EOL>coa_phase = numpy.zeros(len(indices), dtype=numpy.float32)<EOL>return u_val, coa_phase<EOL> | 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)<EOL>fft(vec, vectilde)<EOL>return vectilde<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT> | 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
-------
Frequency Series: FrequencySeries
A frequency domain version of the input vector. | 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)),<EOL>delta_f = htilde.delta_f, copy=False)<EOL>mag = htilde.squared_norm()<EOL>if psd is not None:<EOL><INDENT>mag /= psd<EOL><DEDENT>sigma_vec[kmin:kmax] = mag[kmin:kmax].cumsum()<EOL>return sigma_vec*norm<EOL> | 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 weight the accumulated power.
low_frequency_cutoff : {None, float}, optional
The frequency to begin accumulating power. If None, start at the beginning
of the vector.
high_frequency_cutoff : {None, float}, optional
The frequency to stop considering accumulated power. If None, continue
until the end of the input vector.
Returns
-------
Frequency Series: FrequencySeries
A frequency series containing the cumulative sigmasq. | 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_almost_equal(ht.delta_f, psd.delta_f)<EOL><DEDENT>except:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>if psd is None:<EOL><INDENT>sq = ht.inner(ht)<EOL><DEDENT>else:<EOL><INDENT>sq = ht.weighted_inner(ht, psd[kmin:kmax])<EOL><DEDENT>return sq.real * norm<EOL> | 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
----------
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, float}, optional
The frequency to begin considering waveform power.
high_frequency_cutoff : {None, float}, optional
The frequency to stop considering waveform power.
Returns
-------
sigmasq: float | 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, float}, optional
The frequency to begin considering waveform power.
high_frequency_cutoff : {None, float}, optional
The frequency to stop considering waveform power.
Returns
-------
sigmasq: float | 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 + <NUM_LIT:1>)/<NUM_LIT>):<EOL><INDENT>kmax = int((N + <NUM_LIT:1>)/<NUM_LIT>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>kmax = int((N + <NUM_LIT:1>)/<NUM_LIT>)<EOL><DEDENT>if kmax <= kmin:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>".format(flow, fhigh)<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>".format(kmin, kmax)<EOL>raise ValueError(err_msg)<EOL><DEDENT>return kmin,kmax<EOL> | 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 the **time** series. Can be odd
or even.
Returns
-------
kmin: int
kmax: int | 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)<EOL>if corr_out is not None:<EOL><INDENT>qtilde = corr_out<EOL><DEDENT>else:<EOL><INDENT>qtilde = zeros(N, dtype=complex_same_precision_as(data))<EOL><DEDENT>if out is None:<EOL><INDENT>_q = zeros(N, dtype=complex_same_precision_as(data))<EOL><DEDENT>elif (len(out) == N) and type(out) is Array and out.kind =='<STR_LIT>':<EOL><INDENT>_q = out<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>correlate(htilde[kmin:kmax], stilde[kmin:kmax], qtilde[kmin:kmax])<EOL>if psd is not None:<EOL><INDENT>if isinstance(psd, FrequencySeries):<EOL><INDENT>if psd.delta_f == stilde.delta_f :<EOL><INDENT>qtilde[kmin:kmax] /= psd[kmin:kmax]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>ifft(qtilde, _q)<EOL>if h_norm is None:<EOL><INDENT>h_norm = sigmasq(htilde, psd, low_frequency_cutoff, high_frequency_cutoff)<EOL><DEDENT>norm = (<NUM_LIT> * stilde.delta_f) / sqrt( h_norm)<EOL>return (TimeSeries(_q, epoch=stilde._epoch, delta_t=stilde.delta_t, copy=False),<EOL>FrequencySeries(qtilde, epoch=stilde._epoch, delta_f=stilde.delta_f, copy=False),<EOL>norm)<EOL> | 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
The strain data to be filtered.
psd : {FrequencySeries}, optional
The noise weighting of the filter.
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 to the
the nyquist frequency.
h_norm : {None, float}, optional
The template normalization. If none, this value is calculated internally.
out : {None, Array}, optional
An array to use as memory for snr storage. If None, memory is allocated
internally.
corr_out : {None, Array}, optional
An array to use as memory for correlation storage. If None, memory is allocated
internally. If provided, management of the vector is handled externally by the
caller. No zero'ing is done internally.
Returns
-------
snr : TimeSeries
A time series containing the complex snr.
corrrelation: FrequencySeries
A frequency series containing the correlation vector.
norm : float
The normalization of the complex snr. | 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 the input array.
Returns
--------
new_idx : numpy.array of ints
The smeared array of indexes. | 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 to be filtered.
psd : FrequencySeries
The noise weighting of the filter.
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 to the
the nyquist frequency.
sigmasq : {None, float}, optional
The template normalization. If none, this value is calculated
internally.
Returns
-------
snr : TimeSeries
A time series containing the complex snr. | 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_filter_core(htilde,stilde,psd,low_frequency_cutoff,<EOL>high_frequency_cutoff, v1_norm, out=_snr)<EOL>maxsnr, max_id = snr.abs_max_loc()<EOL>if v2_norm is None:<EOL><INDENT>v2_norm = sigmasq(stilde, psd, low_frequency_cutoff, high_frequency_cutoff)<EOL><DEDENT>return maxsnr * snr_norm / sqrt(v2_norm), max_id<EOL> | 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 or FrequencySeries
The input vector containing a waveform.
psd : Frequency Series
A power spectral density to weight the overlap.
low_frequency_cutoff : {None, float}, optional
The frequency to begin the match.
high_frequency_cutoff : {None, float}, optional
The frequency to stop the match.
v1_norm : {None, float}, optional
The normalization of the first waveform. This is equivalent to its
sigmasq value. If None, it is internally calculated.
v2_norm : {None, float}, optional
The normalization of the second waveform. This is equivalent to its
sigmasq value. If None, it is internally calculated.
Returns
-------
match: float
index: int
The number of samples to shift to get the match. | 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 spectral density to weight the overlap.
low_frequency_cutoff : {None, float}, optional
The frequency to begin the overlap.
high_frequency_cutoff : {None, float}, optional
The frequency to stop the overlap.
normalized : {True, boolean}, optional
Set if the overlap is normalized. If true, it will range from 0 to 1.
Returns
-------
overlap: float | 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])<EOL><DEDENT>else:<EOL><INDENT>inner = (htilde[kmin:kmax]).inner(stilde[kmin:kmax])<EOL><DEDENT>if normalized:<EOL><INDENT>sig1 = sigma(vec1, psd=psd, low_frequency_cutoff=low_frequency_cutoff,<EOL>high_frequency_cutoff=high_frequency_cutoff)<EOL>sig2 = sigma(vec2, psd=psd, low_frequency_cutoff=low_frequency_cutoff,<EOL>high_frequency_cutoff=high_frequency_cutoff)<EOL>norm = <NUM_LIT:1> / sig1 / sig2<EOL><DEDENT>else:<EOL><INDENT>norm = <NUM_LIT:1><EOL><DEDENT>return <NUM_LIT:4> * htilde.delta_f * inner * norm<EOL> | 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 power spectral density to weight the overlap.
low_frequency_cutoff : {None, float}, optional
The frequency to begin the overlap.
high_frequency_cutoff : {None, float}, optional
The frequency to stop the overlap.
normalized : {True, boolean}, optional
Set if the overlap is normalized. If true, it will range from 0 to 1.
Returns
-------
overlap: complex | 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
-------
bin_offset : numpy array
Array of bins offsets, each in the range [-1/2, 1/2]
peak_values : numpy array
Array of the estimated peak values at the interpolated offset | 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 cifo in coinc_times:<EOL><INDENT>time = coinc_times[cifo]<EOL>dtravel = Detector(cifo).light_travel_time_to_detector(fdet)<EOL>if time - dtravel > onsource_start:<EOL><INDENT>onsource_start = time - dtravel<EOL><DEDENT>if time + dtravel < onsource_end:<EOL><INDENT>onsource_end = time + dtravel<EOL><DEDENT><DEDENT>onsource_start -= coinc_threshold<EOL>onsource_end += coinc_threshold<EOL>trim_pad = (data_reader.trim_padding * data_reader.strain.delta_t)<EOL>bdur = int(lookback + <NUM_LIT> * trim_pad + length_in_time)<EOL>if bdur > data_reader.strain.duration * <NUM_LIT>:<EOL><INDENT>bdur = data_reader.strain.duration * <NUM_LIT><EOL><DEDENT>if data_reader.state is not None:<EOL><INDENT>state_start_time = data_reader.strain.end_time- data_reader.reduced_pad * data_reader.strain.delta_t - bdur<EOL>if not data_reader.state.is_extent_valid(state_start_time, bdur):<EOL><INDENT>return None, None, None, None<EOL><DEDENT><DEDENT>if data_reader.dq is not None:<EOL><INDENT>dq_start_time = onsource_start - duration / <NUM_LIT><EOL>dq_duration = onsource_end - onsource_start + duration<EOL>if not data_reader.dq.is_extent_valid(dq_start_time, dq_duration):<EOL><INDENT>return None, None, None, None<EOL><DEDENT><DEDENT>htilde = bank.get_template(template_id, min_buffer=bdur)<EOL>stilde = data_reader.overwhitened_data(htilde.delta_f)<EOL>sigma2 = htilde.sigmasq(stilde.psd)<EOL>snr, _, norm = matched_filter_core(htilde, stilde, h_norm=sigma2)<EOL>onsrc = snr.time_slice(onsource_start, onsource_end)<EOL>peak = onsrc.abs_arg_max()<EOL>peak_time = peak * snr.delta_t + onsrc.start_time<EOL>peak_value = abs(onsrc[peak])<EOL>bstart = float(snr.start_time) + length_in_time + trim_pad<EOL>bkg = abs(snr.time_slice(bstart, onsource_start)).numpy()<EOL>window = int((onsource_end - onsource_start) * snr.sample_rate)<EOL>nsamples = int(len(bkg) / window)<EOL>peaks = bkg[:nsamples*window].reshape(nsamples, window).max(axis=<NUM_LIT:1>)<EOL>pvalue = (<NUM_LIT:1> + (peaks >= peak_value).sum()) / float(<NUM_LIT:1> + nsamples)<EOL>baysnr = snr.time_slice(peak_time - duration / <NUM_LIT>,<EOL>peak_time + duration / <NUM_LIT>)<EOL>logging.info('<STR_LIT>', ifo,<EOL>pvalue, nsamples)<EOL>return baysnr * norm, peak_time, pvalue, sigma2<EOL> | 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_time,<EOL>state_duration):<EOL><INDENT>return None<EOL><DEDENT><DEDENT>dq_start_time = state_start_time - data_reader.dq_padding<EOL>dq_duration = state_duration + <NUM_LIT:2> * data_reader.dq_padding<EOL>if data_reader.dq is not None:<EOL><INDENT>if not data_reader.dq.is_extent_valid(dq_start_time, dq_duration):<EOL><INDENT>return None<EOL><DEDENT><DEDENT><DEDENT>stilde = data_reader.overwhitened_data(htilde.delta_f)<EOL>snr, _, norm = matched_filter_core(htilde, stilde,<EOL>h_norm=htilde.sigmasq(stilde.psd))<EOL>valid_end = int(len(snr) - data_reader.trim_padding)<EOL>valid_start = int(valid_end - data_reader.blocksize * snr.sample_rate)<EOL>half_dur_samples = int(snr.sample_rate * duration / <NUM_LIT:2>)<EOL>coinc_samples = int(snr.sample_rate * coinc_window)<EOL>valid_start -= half_dur_samples + coinc_samples<EOL>valid_end += half_dur_samples<EOL>if valid_start < <NUM_LIT:0> or valid_end > len(snr)-<NUM_LIT:1>:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>').format(duration))<EOL><DEDENT>onsource_idx = float(trig_time - snr.start_time) * snr.sample_rate<EOL>onsource_idx = int(round(onsource_idx))<EOL>onsource_slice = slice(onsource_idx - half_dur_samples,<EOL>onsource_idx + half_dur_samples + <NUM_LIT:1>)<EOL>return snr[onsource_slice] * norm<EOL> | 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 slightly contaminated by
filter and wrap-around effects. For reasonable durations this will only
affect a small fraction of the triggers and probably in a negligible way.
Parameters
----------
data_reader : StrainBuffer
The StrainBuffer object to read strain data from.
htilde : FrequencySeries
The frequency series containing the template waveform.
trig_time : {float, lal.LIGOTimeGPS}
The trigger time.
duration : float (optional)
Duration of the computed SNR series in seconds. If omitted, it defaults
to twice the Earth light travel time plus 10 ms of timing uncertainty.
check_state : boolean
If True, and the detector was offline or flagged for bad data quality
at any point during the inspiral, then return (None, None) instead.
coinc_window : float (optional)
Maximum possible time between coincident triggers at different
detectors. This is needed to properly determine data padding.
Returns
-------
snr : TimeSeries
The portion of SNR around the trigger. None if the detector is offline
or has bad data quality, and check_state is True. | 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_callback_method = gpu_callback_method<EOL>if cluster_function not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.cluster_function = cluster_function<EOL>self.segments = segment_list<EOL>self.htilde = template_output<EOL>if downsample_factor == <NUM_LIT:1>:<EOL><INDENT>self.snr_mem = zeros(self.tlen, dtype=self.dtype)<EOL>self.corr_mem = zeros(self.tlen, dtype=self.dtype)<EOL>if use_cluster and (cluster_function == '<STR_LIT>'):<EOL><INDENT>self.matched_filter_and_cluster = self.full_matched_filter_and_cluster_symm<EOL>self.threshold_and_clusterers = []<EOL>for seg in self.segments:<EOL><INDENT>thresh = events.ThresholdCluster(self.snr_mem[seg.analyze])<EOL>self.threshold_and_clusterers.append(thresh)<EOL><DEDENT><DEDENT>elif use_cluster and (cluster_function == '<STR_LIT>'):<EOL><INDENT>self.matched_filter_and_cluster = self.full_matched_filter_and_cluster_fc<EOL><DEDENT>else:<EOL><INDENT>self.matched_filter_and_cluster = self.full_matched_filter_thresh_only<EOL><DEDENT>self.kmin, self.kmax = get_cutoff_indices(self.flow, self.fhigh,<EOL>self.delta_f, self.tlen)<EOL>corr_slice = slice(self.kmin, self.kmax)<EOL>self.correlators = []<EOL>for seg in self.segments:<EOL><INDENT>corr = Correlator(self.htilde[corr_slice],<EOL>seg[corr_slice],<EOL>self.corr_mem[corr_slice])<EOL>self.correlators.append(corr)<EOL><DEDENT>self.ifft = IFFT(self.corr_mem, self.snr_mem)<EOL><DEDENT>elif downsample_factor >= <NUM_LIT:1>:<EOL><INDENT>self.matched_filter_and_cluster = self.heirarchical_matched_filter_and_cluster<EOL>self.downsample_factor = downsample_factor<EOL>self.upsample_method = upsample_method<EOL>self.upsample_threshold = upsample_threshold<EOL>N_full = self.tlen<EOL>N_red = N_full / downsample_factor<EOL>self.kmin_full, self.kmax_full = get_cutoff_indices(self.flow,<EOL>self.fhigh, self.delta_f, N_full)<EOL>self.kmin_red, _ = get_cutoff_indices(self.flow,<EOL>self.fhigh, self.delta_f, N_red)<EOL>if self.kmax_full < N_red:<EOL><INDENT>self.kmax_red = self.kmax_full<EOL><DEDENT>else:<EOL><INDENT>self.kmax_red = N_red - <NUM_LIT:1><EOL><DEDENT>self.snr_mem = zeros(N_red, dtype=self.dtype)<EOL>self.corr_mem_full = FrequencySeries(zeros(N_full, dtype=self.dtype), delta_f=self.delta_f)<EOL>self.corr_mem = Array(self.corr_mem_full[<NUM_LIT:0>:N_red], copy=False)<EOL>self.inter_vec = zeros(N_full, dtype=self.dtype)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT> | 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 to the
the nyquist frequency.
snr_threshold : float
The minimum snr to return when filtering
segment_list : list
List of FrequencySeries that are the Fourier-transformed data segments
template_output : complex64
Array of memory given as the 'out' parameter to waveform.FilterBank
use_cluster : boolean
If true, cluster triggers above threshold using a window; otherwise,
only apply a threshold.
downsample_factor : {1, int}, optional
The factor by which to reduce the sample rate when doing a heirarchical
matched filter
upsample_threshold : {1, float}, optional
The fraction of the snr_threshold to trigger on the subsampled filter.
upsample_method : {pruned_fft, str}
The method to upsample or interpolate the reduced rate filter.
cluster_function : {symmetric, str}, optional
Which method is used to cluster triggers over time. If 'findchirp', a
sliding forward window; if 'symmetric', each window's peak is compared
to the windows before and after it, and only kept as a trigger if larger
than both. | 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>logging.info("<STR_LIT>" % str(len(idx)))<EOL>snr = TimeSeries(self.snr_mem, epoch=epoch, delta_t=self.delta_t, copy=False)<EOL>corr = FrequencySeries(self.corr_mem, delta_f=self.delta_f, copy=False)<EOL>return snr, norm, corr, idx, snrv<EOL> | 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 matched filter, threshold, and cluster.
Parameters
----------
segnum : int
Index into the list of segments at MatchedFilterControl construction
against which to filter.
template_norm : float
The htilde, template normalization factor.
window : int
Size of the window over which to cluster triggers, in samples
Returns
-------
snr : TimeSeries
A time series containing the complex snr.
norm : float
The normalization of the complex snr.
corrrelation: FrequencySeries
A frequency series containing the correlation vector.
idx : Array
List of indices of the triggers.
snrv : Array
The snr values at the trigger locations. | 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>:<EOL><INDENT>return [], [], [], [], []<EOL><DEDENT>logging.info("<STR_LIT>" % str(len(idx)))<EOL>snr = TimeSeries(self.snr_mem, epoch=epoch, delta_t=self.delta_t, copy=False)<EOL>corr = FrequencySeries(self.corr_mem, delta_f=self.delta_f, copy=False)<EOL>return snr, norm, corr, idx, snrv<EOL> | 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 matched filter, threshold, and cluster.
Parameters
----------
segnum : int
Index into the list of segments at MatchedFilterControl construction
against which to filter.
template_norm : float
The htilde, template normalization factor.
window : int
Size of the window over which to cluster triggers, in samples
Returns
-------
snr : TimeSeries
A time series containing the complex snr.
norm : float
The normalization of the complex snr.
corrrelation: FrequencySeries
A frequency series containing the correlation vector.
idx : Array
List of indices of the triggers.
snrv : Array
The snr values at the trigger locations. | 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, epoch=epoch, delta_t=self.delta_t, copy=False)<EOL>corr = FrequencySeries(self.corr_mem, delta_f=self.delta_f, copy=False)<EOL>return snr, norm, corr, idx, snrv<EOL> | 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 matched filter, threshold, and cluster.
Parameters
----------
segnum : int
Index into the list of segments at MatchedFilterControl construction
against which to filter.
template_norm : float
The htilde, template normalization factor.
window : int
Size of the window over which to cluster triggers, in samples.
This is IGNORED by this function, and provided only for API compatibility.
Returns
-------
snr : TimeSeries
A time series containing the complex snr.
norm : float
The normalization of the complex snr.
corrrelation: FrequencySeries
A frequency series containing the correlation vector.
idx : Array
List of indices of the triggers.
snrv : Array
The snr values at the trigger locations. | 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_red])<EOL>ifft(self.corr_mem, self.snr_mem)<EOL>if not hasattr(stilde, '<STR_LIT>'):<EOL><INDENT>stilde.red_analyze =slice(stilde.analyze.start/self.downsample_factor,<EOL>stilde.analyze.stop/self.downsample_factor)<EOL><DEDENT>idx_red, snrv_red = events.threshold(self.snr_mem[stilde.red_analyze],<EOL>self.snr_threshold / norm * self.upsample_threshold)<EOL>if len(idx_red) == <NUM_LIT:0>:<EOL><INDENT>return [], None, [], [], []<EOL><DEDENT>idx_red, _ = events.cluster_reduce(idx_red, snrv_red, window / self.downsample_factor)<EOL>logging.info("<STR_LIT>"%(str(len(idx_red)),))<EOL>if self.upsample_method=='<STR_LIT>':<EOL><INDENT>idx = (idx_red + stilde.analyze.start/self.downsample_factor)* self.downsample_factor<EOL>idx = smear(idx, self.downsample_factor)<EOL>if not hasattr(self.corr_mem_full, '<STR_LIT>'):<EOL><INDENT>self.corr_mem_full.transposed = zeros(len(self.corr_mem_full), dtype=self.dtype)<EOL><DEDENT>if not hasattr(htilde, '<STR_LIT>'):<EOL><INDENT>htilde.transposed = zeros(len(self.corr_mem_full), dtype=self.dtype)<EOL>htilde.transposed[self.kmin_full:self.kmax_full] = htilde[self.kmin_full:self.kmax_full]<EOL>htilde.transposed = fft_transpose(htilde.transposed)<EOL><DEDENT>if not hasattr(stilde, '<STR_LIT>'):<EOL><INDENT>stilde.transposed = zeros(len(self.corr_mem_full), dtype=self.dtype)<EOL>stilde.transposed[self.kmin_full:self.kmax_full] = stilde[self.kmin_full:self.kmax_full]<EOL>stilde.transposed = fft_transpose(stilde.transposed)<EOL><DEDENT>correlate(htilde.transposed, stilde.transposed, self.corr_mem_full.transposed)<EOL>snrv = pruned_c2cifft(self.corr_mem_full.transposed, self.inter_vec, idx, pretransposed=True)<EOL>idx = idx - stilde.analyze.start<EOL>idx2, snrv = events.threshold(Array(snrv, copy=False), self.snr_threshold / norm)<EOL>if len(idx2) > <NUM_LIT:0>:<EOL><INDENT>correlate(htilde[self.kmax_red:self.kmax_full],<EOL>stilde[self.kmax_red:self.kmax_full],<EOL>self.corr_mem_full[self.kmax_red:self.kmax_full])<EOL>idx, snrv = events.cluster_reduce(idx[idx2], snrv, window)<EOL><DEDENT>else:<EOL><INDENT>idx, snrv = [], []<EOL><DEDENT>logging.info("<STR_LIT>" % len(idx))<EOL>return self.snr_mem, norm, self.corr_mem_full, idx, snrv<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT> | 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 matched filter, threshold, and cluster.
Parameters
----------
segnum : int
Index into the list of segments at MatchedFilterControl construction
template_norm : float
The htilde, template normalization factor.
window : int
Size of the window over which to cluster triggers, in samples
Returns
-------
snr : TimeSeries
A time series containing the complex snr at the reduced sample rate.
norm : float
The normalization of the complex snr.
corrrelation: FrequencySeries
A frequency series containing the correlation vector.
idx : Array
List of indices of the triggers.
snrv : Array
The snr values at the trigger locations. | 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>self.corr_plus_mem = zeros(self.tlen, dtype=self.dtype)<EOL>self.snr_cross_mem = zeros(self.tlen, dtype=self.dtype)<EOL>self.corr_cross_mem = zeros(self.tlen, dtype=self.dtype)<EOL>self.snr_mem = zeros(self.tlen, dtype=self.dtype)<EOL>self.cached_hplus_hcross_correlation = None<EOL>self.cached_hplus_hcross_hplus = None<EOL>self.cached_hplus_hcross_hcross = None<EOL>self.cached_hplus_hcross_psd = None<EOL> | 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
to the nyquist frequency.
snr_threshold : float
The minimum snr to return when filtering | 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_norm,<EOL>low_frequency_cutoff=self.flow,<EOL>high_frequency_cutoff=self.fhigh,<EOL>out=self.snr_cross_mem,<EOL>corr_out=self.corr_cross_mem)<EOL>if not id(hplus) == self.cached_hplus_hcross_hplus:<EOL><INDENT>self.cached_hplus_hcross_correlation = None<EOL><DEDENT>if not id(hcross) == self.cached_hplus_hcross_hcross:<EOL><INDENT>self.cached_hplus_hcross_correlation = None<EOL><DEDENT>if not id(psd) == self.cached_hplus_hcross_psd:<EOL><INDENT>self.cached_hplus_hcross_correlation = None<EOL><DEDENT>if self.cached_hplus_hcross_correlation is None:<EOL><INDENT>hplus_cross_corr = overlap_cplx(hplus, hcross, psd=psd,<EOL>low_frequency_cutoff=self.flow,<EOL>high_frequency_cutoff=self.fhigh,<EOL>normalized=False)<EOL>hplus_cross_corr = numpy.real(hplus_cross_corr)<EOL>hplus_cross_corr = hplus_cross_corr / (hcross_norm*hplus_norm)**<NUM_LIT:0.5><EOL>self.cached_hplus_hcross_correlation = hplus_cross_corr<EOL>self.cached_hplus_hcross_hplus = id(hplus)<EOL>self.cached_hplus_hcross_hcross = id(hcross)<EOL>self.cached_hplus_hcross_psd = id(psd)<EOL><DEDENT>else:<EOL><INDENT>hplus_cross_corr = self.cached_hplus_hcross_correlation<EOL><DEDENT>snr = self._maximized_snr(I_plus,I_cross,<EOL>hplus_cross_corr,<EOL>hpnorm=Iplus_norm,<EOL>hcnorm=Icross_norm,<EOL>out=self.snr_mem,<EOL>thresh=self.snr_threshold,<EOL>analyse_slice=stilde.analyze)<EOL>delta_t = <NUM_LIT:1.0> / (self.tlen * stilde.delta_f)<EOL>snr = TimeSeries(snr, epoch=stilde.start_time, delta_t=delta_t,<EOL>copy=False)<EOL>idx, snrv = events.threshold_real_numpy(snr[stilde.analyze],<EOL>self.snr_threshold)<EOL>if len(idx) == <NUM_LIT:0>:<EOL><INDENT>return [], <NUM_LIT:0>, <NUM_LIT:0>, [], [], [], [], <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0><EOL><DEDENT>logging.info("<STR_LIT>", str(len(idx)))<EOL>idx, snrv = events.cluster_reduce(idx, snrv, window)<EOL>logging.info("<STR_LIT>", str(len(idx)))<EOL>u_vals, coa_phase = self._maximized_extrinsic_params(I_plus.data, I_cross.data, hplus_cross_corr,<EOL>indices=idx+stilde.analyze.start, hpnorm=Iplus_norm,<EOL>hcnorm=Icross_norm)<EOL>return snr, Iplus_corr, Icross_corr, idx, snrv, u_vals, coa_phase,hplus_cross_corr, Iplus_norm, Icross_norm<EOL> | 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 time series containing the complex snr.
norm : float
The normalization of the complex snr.
correlation: FrequencySeries
A frequency series containing the correlation vector.
idx : Array
List of indices of the triggers.
snrv : Array
The snr values at the trigger locations. | 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>durations = numpy.array([<NUM_LIT:1.0> / t.delta_f for t in templates])<EOL>lsort = durations.argsort()<EOL>durations = durations[lsort]<EOL>templates = [templates[li] for li in lsort]<EOL>_, counts = numpy.unique(durations, return_counts=True)<EOL>tsamples = [(len(t) - <NUM_LIT:1>) * <NUM_LIT:2> for t in templates]<EOL>grabs = maxelements / numpy.unique(tsamples)<EOL>chunks = numpy.array([])<EOL>num = <NUM_LIT:0><EOL>for count, grab in zip(counts, grabs):<EOL><INDENT>chunks = numpy.append(chunks, numpy.arange(num, count + num, grab))<EOL>chunks = numpy.append(chunks, [count + num])<EOL>num += count<EOL><DEDENT>chunks = numpy.unique(chunks).astype(numpy.uint32)<EOL>self.chunks = chunks[<NUM_LIT:1>:] - chunks[<NUM_LIT:0>:-<NUM_LIT:1>]<EOL>self.out_mem = {}<EOL>self.cout_mem = {}<EOL>self.ifts = {}<EOL>chunk_durations = [durations[i] for i in chunks[:-<NUM_LIT:1>]]<EOL>self.chunk_tsamples = [tsamples[int(i)] for i in chunks[:-<NUM_LIT:1>]]<EOL>samples = self.chunk_tsamples * self.chunks<EOL>mem_ids = [(a, b) for a, b in zip(chunk_durations, self.chunks)]<EOL>mem_types = set(zip(mem_ids, samples))<EOL>self.tgroups, self.mids = [], []<EOL>for i, size in mem_types:<EOL><INDENT>dur, count = i<EOL>self.out_mem[i] = zeros(size, dtype=numpy.complex64)<EOL>self.cout_mem[i] = zeros(size, dtype=numpy.complex64)<EOL>self.ifts[i] = IFFT(self.cout_mem[i], self.out_mem[i],<EOL>nbatch=count,<EOL>size=len(self.cout_mem[i]) / count)<EOL><DEDENT>for dur, count in mem_ids:<EOL><INDENT>tgroup = templates[<NUM_LIT:0>:count]<EOL>self.tgroups.append(tgroup)<EOL>self.mids.append((dur, count))<EOL>templates = templates[count:]<EOL><DEDENT>self.corr = []<EOL>for i, tgroup in enumerate(self.tgroups):<EOL><INDENT>psize = self.chunk_tsamples[i]<EOL>s = <NUM_LIT:0><EOL>e = psize<EOL>mid = self.mids[i]<EOL>for htilde in tgroup:<EOL><INDENT>htilde.out = self.out_mem[mid][s:e]<EOL>htilde.cout = self.cout_mem[mid][s:e]<EOL>s += psize<EOL>e += psize<EOL><DEDENT>self.corr.append(BatchCorrelator(tgroup, [t.cout for t in tgroup], len(tgroup[<NUM_LIT:0>])))<EOL><DEDENT> | 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 determines how the number of chisq bins varies as a
function of the template bank parameters.
sg_chisq: pycbc.vetoes.SingleDetSGChisq
Instance of the sg_chisq class to calculate sg_chisq with.
maxelements: {int, 2**27}
Maximum size of a batched fourier transform.
snr_abort_threshold: {float, None}
If the SNR is above this threshold, do not record any triggers.
newsnr_threshold: {float, None}
Only record triggers that have a re-weighted NewSNR above this
threshold.
max_triggers_in_batch: {int, None}
Record X number of the loudest triggers by newsnr in each mpi
process group. Signal consistency values will also only be calculated
for these triggers. | 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>sort = result['<STR_LIT>'].argsort()[::-<NUM_LIT:1>][:self.max_triggers_in_batch]<EOL>for key in result:<EOL><INDENT>result[key] = result[key][sort]<EOL><DEDENT>tmp = veto_info<EOL>veto_info = [tmp[i] for i in sort]<EOL><DEDENT>result = self._process_vetoes(result, veto_info)<EOL>return result<EOL> | 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>'] = dof<EOL>results['<STR_LIT>'] = sg_chisq<EOL>keep = []<EOL>for i, (snrv, norm, l, htilde, stilde) in enumerate(veto_info):<EOL><INDENT>correlate(htilde, stilde, htilde.cout)<EOL>c, d = self.power_chisq.values(htilde.cout, snrv,<EOL>norm, stilde.psd, [l], htilde)<EOL>chisq[i] = c[<NUM_LIT:0>] / d[<NUM_LIT:0>]<EOL>dof[i] = d[<NUM_LIT:0>]<EOL>sgv = self.sg_chisq.values(stilde, htilde, stilde.psd,<EOL>snrv, norm, c, d, [l])<EOL>if sgv is not None:<EOL><INDENT>sg_chisq[i] = sgv[<NUM_LIT:0>]<EOL><DEDENT>if self.newsnr_threshold:<EOL><INDENT>newsnr = ranking.newsnr(results['<STR_LIT>'][i], chisq[i])<EOL>if newsnr >= self.newsnr_threshold:<EOL><INDENT>keep.append(i)<EOL><DEDENT><DEDENT><DEDENT>if self.newsnr_threshold:<EOL><INDENT>keep = numpy.array(keep, dtype=numpy.uint32)<EOL>for key in results:<EOL><INDENT>results[key] = results[key][keep]<EOL><DEDENT><DEDENT>return results<EOL> | 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 - self.data.trim_padding)<EOL>valid_start = int(valid_end - self.data.blocksize * self.data.sample_rate)<EOL>seg = slice(valid_start, valid_end)<EOL>self.corr[self.block_id].execute(stilde)<EOL>self.ifts[mid].execute()<EOL>self.block_id += <NUM_LIT:1><EOL>snr = numpy.zeros(len(tgroup), dtype=numpy.complex64)<EOL>time = numpy.zeros(len(tgroup), dtype=numpy.float64)<EOL>templates = numpy.zeros(len(tgroup), dtype=numpy.uint64)<EOL>sigmasq = numpy.zeros(len(tgroup), dtype=numpy.float32)<EOL>time[:] = self.data.start_time<EOL>result = {}<EOL>tkeys = tgroup[<NUM_LIT:0>].params.dtype.names<EOL>for key in tkeys:<EOL><INDENT>result[key] = []<EOL><DEDENT>veto_info = []<EOL>i = <NUM_LIT:0><EOL>for htilde in tgroup:<EOL><INDENT>l = htilde.out[seg].abs_arg_max()<EOL>sgm = htilde.sigmasq(psd)<EOL>norm = <NUM_LIT> * htilde.delta_f / (sgm ** <NUM_LIT:0.5>)<EOL>l += valid_start<EOL>snrv = numpy.array([htilde.out[l]])<EOL>s = abs(snrv[<NUM_LIT:0>]) * norm<EOL>if s < self.snr_threshold:<EOL><INDENT>continue<EOL><DEDENT>time[i] += float(l - valid_start) / self.data.sample_rate<EOL>if self.snr_abort_threshold is not None and s > self.snr_abort_threshold:<EOL><INDENT>logging.info("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return False, []<EOL><DEDENT>veto_info.append((snrv, norm, l, htilde, stilde))<EOL>snr[i] = snrv[<NUM_LIT:0>] * norm<EOL>sigmasq[i] = sgm<EOL>templates[i] = htilde.id<EOL>if not hasattr(htilde, '<STR_LIT>'):<EOL><INDENT>htilde.dict_params = {}<EOL>for key in tkeys:<EOL><INDENT>htilde.dict_params[key] = htilde.params[key]<EOL><DEDENT><DEDENT>for key in tkeys:<EOL><INDENT>result[key].append(htilde.dict_params[key])<EOL><DEDENT>i += <NUM_LIT:1><EOL><DEDENT>result['<STR_LIT>'] = abs(snr[<NUM_LIT:0>:i])<EOL>result['<STR_LIT>'] = numpy.angle(snr[<NUM_LIT:0>:i])<EOL>result['<STR_LIT>'] = time[<NUM_LIT:0>:i]<EOL>result['<STR_LIT>'] = templates[<NUM_LIT:0>:i]<EOL>result['<STR_LIT>'] = sigmasq[<NUM_LIT:0>:i]<EOL>for key in tkeys:<EOL><INDENT>result[key] = numpy.array(result[key])<EOL><DEDENT>return result, veto_info<EOL> | 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_off = True<EOL><DEDENT>return bits[-<NUM_LIT:10>:], filterbank_off<EOL> | 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 = Filter on/off switches for the 10 filters in an SFM.
Bit 10 = Filter module input switch on/off
Bit 11 = Filter module offset switch on/off
Bit 12 = Filter module output switch on/off
Bit 13 = Filter module limit switch on/off
Bit 14 = Filter module history reset momentary switch | 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(data)<EOL><DEDENT>else:<EOL><INDENT>coeffs = iir2z(filter_file[filter_name][i])<EOL>if len(coeffs) > <NUM_LIT:1>:<EOL><INDENT>logging.info('<STR_LIT>')<EOL>sys.exit()<EOL><DEDENT>gain = coeffs[<NUM_LIT:0>]<EOL>data = gain * data<EOL><DEDENT><DEDENT><DEDENT>return data<EOL> | 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 = (Array(coefficients[::-<NUM_LIT:1>] * <NUM_LIT:1>)).astype(timeseries.dtype)<EOL>cseries.resize(len(timeseries))<EOL>cseries.roll(len(timeseries) - len(coefficients) + <NUM_LIT:1>)<EOL>timeseries = Array(timeseries, copy=False)<EOL>flen = len(cseries) / <NUM_LIT:2> + <NUM_LIT:1><EOL>ftype = complex_same_precision_as(timeseries)<EOL>cfreq = zeros(flen, dtype=ftype)<EOL>tfreq = zeros(flen, dtype=ftype)<EOL>fft(Array(cseries), cfreq)<EOL>fft(Array(timeseries), tfreq)<EOL>cout = zeros(flen, ftype)<EOL>out = zeros(len(timeseries), dtype=timeseries)<EOL>correlate(cfreq, tfreq, cout)<EOL>ifft(cout, out)<EOL>return out.numpy() / len(out)<EOL><DEDENT> | 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
Return the filtered timeseries, which has been properly shifted to account
for the FIR filter delay and the corrupted regions zeroed out. | 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_data = timeseries.lal()<EOL>_resample_func[timeseries.dtype](lal_data, delta_t)<EOL>data = lal_data.data.data<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>factor = int(delta_t / timeseries.delta_t)<EOL>numtaps = factor * <NUM_LIT:20> + <NUM_LIT:1><EOL>filter_coefficients = scipy.signal.firwin(numtaps, <NUM_LIT:1.0> / factor,<EOL>window=('<STR_LIT>', <NUM_LIT:5>))<EOL>data = fir_zero_filter(filter_coefficients, timeseries)[::factor]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % method)<EOL><DEDENT>ts = TimeSeries(data, delta_t = delta_t,<EOL>dtype=timeseries.dtype,<EOL>epoch=timeseries._epoch)<EOL>ts.corrupted_samples = <NUM_LIT:10><EOL>return ts<EOL> | 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: TimeSeries
The time series to be resampled
delta_t: float
The desired time step
Returns
-------
Time Series: TimeSeries
A TimeSeries that has been resampled to delta_t.
Raises
------
TypeError:
time_series is not an instance of TimeSeries.
TypeError:
time_series is not real valued
Examples
--------
>>> h_plus_sampled = resample_to_delta_t(h_plus, 1.0/2048) | 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 TimeSeries(data, epoch=timeseries.start_time, delta_t=timeseries.delta_t)<EOL> | 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 a few seconds is typically
required to create significant suppression in the notched band.
To achieve frequency resolution df at sampling frequency fs,
order should be at least fs/df.
Parameters
----------
Time Series: TimeSeries
The time series to be notched.
f1: float
The start of the frequency suppression.
f2: float
The end of the frequency suppression.
order: int
Number of corrupted samples on each side of the time series
(Extent of the filter on either side of zero)
beta: float
Beta parameter of the kaiser window that sets the side lobe attenuation. | 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
Number of corrupted samples on each side of the time series
beta: float
Beta parameter of the kaiser window that sets the side lobe attenuation. | 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.delta_t)<EOL> | 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: int
Number of corrupted samples on each side of the time series
beta: float
Beta parameter of the kaiser window that sets the side lobe attenuation. | 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 TimeSeries(lal_data.data.data, delta_t = lal_data.deltaT,<EOL>dtype=timeseries.dtype, epoch=timeseries._epoch)<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}, optional
The order of the filter to use when high-passing the time series.
attenuation: {0.1, float}, optional
The attenuation of the filter.
Returns
-------
Time Series: TimeSeries
A new TimeSeries that has been high-passed.
Raises
------
TypeError:
time_series is not an instance of TimeSeries.
TypeError:
time_series is not real valued | 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(series))<EOL>ifft(series, time_series)<EOL>time_series.roll(-zeros_offset)<EOL>time_series.resize(new_N)<EOL>if side == '<STR_LIT:left>':<EOL><INDENT>time_series.roll(zeros_offset + new_N - old_N)<EOL><DEDENT>elif side == '<STR_LIT:right>':<EOL><INDENT>time_series.roll(zeros_offset)<EOL><DEDENT>out_series = FrequencySeries(zeros(new_n), epoch=series.epoch,<EOL>delta_f=delta_f, dtype=series.dtype)<EOL>fft(time_series, out_series)<EOL>return out_series<EOL> | 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 output
zeros_offset : optional, {0, int}
Number of sample to delay the start of the zero padding
side : optional, {'right', str}
The side of the vector to zero pad
Returns
-------
interpolated series : FrequencySeries
A new FrequencySeries that has been interpolated. | 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)<EOL>ypad[:ny_orig] = y<EOL>fdata = TimeSeries(ypad, delta_t=delta_t).to_frequencyseries()<EOL>cdata = FrequencySeries(zeros(len(fdata), dtype=fdata.dtype),<EOL>delta_f=fdata.delta_f, copy=False)<EOL>correlate(fdata, fdata, cdata)<EOL>acf = cdata.to_timeseries()<EOL>acf = acf[:ny_orig]<EOL>if unbiased:<EOL><INDENT>acf /= ( y.var() * numpy.arange(len(acf), <NUM_LIT:0>, -<NUM_LIT:1>) )<EOL><DEDENT>else:<EOL><INDENT>acf /= acf[<NUM_LIT:0>]<EOL><DEDENT>if isinstance(data, TimeSeries):<EOL><INDENT>return TimeSeries(acf, delta_t=delta_t)<EOL><DEDENT>else:<EOL><INDENT>return acf<EOL><DEDENT> | 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} \left( X_{t} - \mu \right) \left( X_{t+k} - \mu \right)
Where :math:`\hat{R}(k)` is the ACF, :math:`X_{t}` is the data series at
time t, :math:`\mu` is the mean of :math:`X_{t}`, and :math:`\sigma^{2}` is
the variance of :math:`X_{t}`.
Parameters
-----------
data : TimeSeries or numpy.array
A TimeSeries or numpy.array of data.
delta_t : float
The time step of the data series if it is not a TimeSeries instance.
unbiased : bool
If True the normalization of the autocovariance function is n-k
instead of n. This is called the unbiased estimation of the
autocovariance. Note that this does not mean the ACF is unbiased.
Returns
-------
acf : numpy.array
If data is a TimeSeries then acf will be a TimeSeries of the
one-sided ACF. Else acf is a numpy.array. | 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><INDENT>acl = cacf[numpy.where(win)[<NUM_LIT:0>][<NUM_LIT:0>]]<EOL>if dtype == int:<EOL><INDENT>acl = int(numpy.ceil(acl))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>acl = numpy.inf<EOL><DEDENT>return acl<EOL> | 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 first point
such that:
.. math::
m \tau[K] \leq K,
where :math:`m` is a tuneable parameter (default = 5). If no such point
exists, then the given data set it too short to estimate the ACL; in this
case ``inf`` is returned.
This algorithm for computing the ACL is taken from:
N. Madras and A.D. Sokal, J. Stat. Phys. 50, 109 (1988).
Parameters
-----------
data : TimeSeries or array
A TimeSeries of data.
m : int
The number of autocorrelation lengths to use for determining the window
size :math:`K` (see above).
dtype : int or float
The datatype of the output. If the dtype was set to int, then the
ceiling is returned.
Returns
-------
acl : int or float
The autocorrelation length. If the ACL cannot be estimated, returns
``numpy.inf``. | 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<EOL>fs = <NUM_LIT> * timeseries.sample_rate<EOL>z_zd = (<NUM_LIT:1> + z/fs) / (<NUM_LIT:1> - z/fs)<EOL>z_zd = z_zd[np.isfinite(z_zd)]<EOL>z_zd = np.append(z_zd, -np.ones(degree))<EOL>p_zd = (<NUM_LIT:1> + p/fs) / (<NUM_LIT:1> - p/fs)<EOL>k_zd = k * np.prod(fs - z) / np.prod(fs - p)<EOL>sos = zpk2sos(z_zd, p_zd, k_zd)<EOL>filtered_data = sosfilt(sos, timeseries.numpy())<EOL>return TimeSeries(filtered_data, delta_t = timeseries.delta_t,<EOL>dtype=timeseries.dtype,<EOL>epoch=timeseries._epoch)<EOL> | 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 frequency,
along the imaginary axis in the s-domain s=i*omega. Then the zeroes, and
poles are bilinearly transformed via:
.. math::
z(s) = \\frac{(1 + s*T/2)}{(1 - s*T/2)}
Where z is the z-domain value, s is the s-domain value, and T is the
sampling period. After the poles and zeroes have been bilinearly
transformed, then the second-order sections are found and filter the data
using scipy.
Parameters
----------
timeseries: TimeSeries
The TimeSeries instance to be filtered.
z: array
Array of zeros to include in zero-pole-gain filter design.
In units of Hz.
p: array
Array of poles to include in zero-pole-gain filter design.
In units of Hz.
k: float
Gain to include in zero-pole-gain filter design. This gain is a
constant multiplied to the transfer function.
Returns
-------
Time Series: TimeSeries
A new TimeSeries that has been filtered.
Examples
--------
To apply a 5 zeroes at 100Hz, 5 poles at 1Hz, and a gain of 1e-10 filter
to a TimeSeries instance, do:
>>> filtered_data = zpk_filter(timeseries, [100]*5, [1]*5, 1e-10) | 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(lockfile_name, '<STR_LIT:w>')<EOL>fcntl.lockf(lockfile, fcntl.LOCK_EX)<EOL>logging.info("<STR_LIT>")<EOL>func = _compile_function(code,arg_names, local_dict, global_dict,<EOL>module_dir, compiler, verbose,<EOL>support_code, headers, customize,<EOL>type_converters,<EOL>auto_downcast, **kw)<EOL>fcntl.lockf(lockfile, fcntl.LOCK_UN)<EOL>logging.info("<STR_LIT>")<EOL>return func<EOL> | 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="<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>"<STR_LIT>")<EOL>optimization_group.add_argument("<STR_LIT>",<EOL>action="<STR_LIT:store_true>",<EOL>default=False,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL> | 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.getcwd(),"<STR_LIT>")<EOL><DEDENT>os.environ['<STR_LIT>'] = cache_dir<EOL>logging.debug("<STR_LIT>", cache_dir)<EOL>sys.path = [cache_dir] + sys.path<EOL>try: os.makedirs(cache_dir)<EOL>except OSError: pass<EOL>if not os.environ.get("<STR_LIT>", None):<EOL><INDENT>os.environ['<STR_LIT>'] = cache_dir<EOL><DEDENT><DEDENT>if opt.per_process_weave_cache:<EOL><INDENT>cache_dir = os.path.join(cache_dir, str(os.getpid()))<EOL>os.environ['<STR_LIT>'] = cache_dir<EOL>logging.info("<STR_LIT>", cache_dir)<EOL><DEDENT>if not os.path.exists(cache_dir):<EOL><INDENT>try:<EOL><INDENT>os.makedirs(cache_dir)<EOL><DEDENT>except:<EOL><INDENT>logging.error("<STR_LIT>", cache_dir)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if opt.clear_weave_cache_at_start:<EOL><INDENT>_clear_weave_cache()<EOL>os.makedirs(cache_dir)<EOL><DEDENT>if opt.clear_weave_cache_at_end:<EOL><INDENT>atexit.register(_clear_weave_cache)<EOL>signal.signal(signal.SIGTERM, _clear_weave_cache)<EOL><DEDENT> | 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<EOL> | 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<EOL><DEDENT>parser.add_argument(<EOL>'<STR_LIT>', '<STR_LIT>', type=match_type, required=True,<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>'<STR_LIT>', '<STR_LIT>', required=True,<EOL>help="<STR_LIT>")<EOL>parser.add_argument('<STR_LIT>', type=str, metavar='<STR_LIT>',<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL> | 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:store>", type=positive_float,<EOL>default=<NUM_LIT>,help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>metricOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>", type=positive_float,<EOL>required=True,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>metricOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>", type=positive_float,<EOL>required=True,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>metricOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>", type=positive_float,<EOL>required=True,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>metricOpts.add_argument("<STR_LIT>", action="<STR_LIT:store_true>",<EOL>default=False, help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return metricOpts<EOL> | 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>help="<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>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>", type=positive_float,<EOL>required=True,<EOL>help="<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=positive_float, default=None, <EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=positive_float, default=None, <EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=positive_float, default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=positive_float, default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>", type=positive_float,<EOL>default=<NUM_LIT>,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>", type=nonnegative_float,<EOL>default=<NUM_LIT:0.>,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=nonnegative_float, default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", default=False,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=positive_float, default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=positive_float, default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>if nonSpin:<EOL><INDENT>parser.add_argument_group(massOpts)<EOL>return massOpts<EOL><DEDENT>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=nonnegative_float, default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>massOpts.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=nonnegative_float, default=None,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>action = massOpts.add_mutually_exclusive_group(required=False)<EOL>action.add_argument("<STR_LIT>", action='<STR_LIT:store>',<EOL>type=positive_float,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"% massRangeParameters.default_nsbh_boundary_mass)<EOL>action.add_argument("<STR_LIT>", action="<STR_LIT:store_true>", default=False,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return massOpts<EOL> | 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-related options will not be added. | 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,)<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>" %(opts.max_mass1,opts.max_mass2)<EOL>parser.error(err_msg)<EOL><DEDENT>if opts.max_total_massand (opts.max_total_mass < opts.min_mass1 + opts.min_mass2):<EOL><INDENT>err_msg = "<STR_LIT>" %(opts.max_total_mass,)<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>" %(opts.min_mass1,opts.min_mass2)<EOL>parser.error(err_msg)<EOL><DEDENT>if opts.max_total_mass and opts.min_total_massand (opts.max_total_mass < opts.min_total_mass):<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>if hasattr(opts, '<STR_LIT>')and opts.remnant_mass_threshold is not None:<EOL><INDENT>logging.info("""<STR_LIT>""")<EOL>if opts.use_eos_max_ns_mass:<EOL><INDENT>logging.info("""<STR_LIT>""")<EOL><DEDENT>if os.path.isfile('<STR_LIT>'):<EOL><INDENT>logging.info("""<STR_LIT>""")<EOL><DEDENT><DEDENT>if (not opts.min_total_mass) or((opts.min_mass1 + opts.min_mass2) > opts.min_total_mass):<EOL><INDENT>opts.min_total_mass = opts.min_mass1 + opts.min_mass2<EOL><DEDENT>if (not opts.max_total_mass) or((opts.max_mass1 + opts.max_mass2) < opts.max_total_mass):<EOL><INDENT>opts.max_total_mass = opts.max_mass1 + opts.max_mass2<EOL><DEDENT>if opts.min_chirp_mass is not None:<EOL><INDENT>m1_at_max_m2 = pnutils.mchirp_mass1_to_mass2(opts.min_chirp_mass,<EOL>opts.max_mass2)<EOL>if m1_at_max_m2 < opts.max_mass2:<EOL><INDENT>m1_at_max_m2 = -<NUM_LIT:1><EOL><DEDENT>m2_at_min_m1 = pnutils.mchirp_mass1_to_mass2(opts.min_chirp_mass,<EOL>opts.min_mass1)<EOL>if m2_at_min_m1 > opts.min_mass1:<EOL><INDENT>m2_at_min_m1 = -<NUM_LIT:1><EOL><DEDENT>m1_at_equal_mass, m2_at_equal_mass = pnutils.mchirp_eta_to_mass1_mass2(<EOL>opts.min_chirp_mass, <NUM_LIT>)<EOL>if m1_at_max_m2 <= opts.max_mass1 and m1_at_max_m2 >= opts.min_mass1:<EOL><INDENT>min_tot_mass = opts.max_mass2 + m1_at_max_m2<EOL><DEDENT>elif m2_at_min_m1 <= opts.max_mass2 and m2_at_min_m1 >= opts.min_mass2:<EOL><INDENT>min_tot_mass = opts.min_mass1 + m2_at_min_m1<EOL><DEDENT>elif m1_at_equal_mass <= opts.max_mass1 andm1_at_equal_mass >= opts.min_mass1 andm2_at_equal_mass <= opts.max_mass2 andm2_at_equal_mass >= opts.min_mass2:<EOL><INDENT>min_tot_mass = m1_at_equal_mass + m2_at_equal_mass<EOL><DEDENT>elif m2_at_min_m1 < opts.min_mass2:<EOL><INDENT>min_tot_mass = opts.min_total_mass<EOL><DEDENT>else:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>if opts.max_eta:<EOL><INDENT>max_eta_m1, max_eta_m2 = pnutils.mchirp_eta_to_mass1_mass2(<EOL>opts.min_chirp_mass, opts.max_eta)<EOL>max_eta_min_tot_mass = max_eta_m1 + max_eta_m2<EOL>if max_eta_min_tot_mass > min_tot_mass:<EOL><INDENT>min_tot_mass = max_eta_min_tot_mass<EOL>if max_eta_m1 > opts.max_mass1:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT><DEDENT><DEDENT>if min_tot_mass > opts.min_total_mass:<EOL><INDENT>opts.min_total_mass = float(min_tot_mass)<EOL><DEDENT><DEDENT>if opts.max_chirp_mass is not None:<EOL><INDENT>m1_at_min_m2 = pnutils.mchirp_mass1_to_mass2(opts.max_chirp_mass,<EOL>opts.min_mass2)<EOL>m2_at_max_m1 = pnutils.mchirp_mass1_to_mass2(opts.max_chirp_mass,<EOL>opts.max_mass1)<EOL>if m1_at_min_m2 <= opts.max_mass1 and m1_at_min_m2 >= opts.min_mass1:<EOL><INDENT>max_tot_mass = opts.min_mass2 + m1_at_min_m2<EOL><DEDENT>elif m2_at_max_m1 <= opts.max_mass2 and m2_at_max_m1 >= opts.min_mass2:<EOL><INDENT>max_tot_mass = opts.max_mass1 + m2_at_max_m1<EOL><DEDENT>elif m2_at_max_m1 > opts.max_mass2:<EOL><INDENT>max_tot_mass = opts.max_total_mass<EOL><DEDENT>else:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>if opts.min_eta:<EOL><INDENT>min_eta_m1, min_eta_m2 = pnutils.mchirp_eta_to_mass1_mass2(<EOL>opts.max_chirp_mass, opts.min_eta)<EOL>min_eta_max_tot_mass = min_eta_m1 + min_eta_m2<EOL>if min_eta_max_tot_mass < max_tot_mass:<EOL><INDENT>max_tot_mass = min_eta_max_tot_mass<EOL>if min_eta_m1 < opts.min_mass1:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT><DEDENT><DEDENT>if max_tot_mass < opts.max_total_mass:<EOL><INDENT>opts.max_total_mass = float(max_tot_mass)<EOL><DEDENT><DEDENT>if opts.max_eta:<EOL><INDENT>m1_at_min_m2 = pnutils.eta_mass1_to_mass2(opts.max_eta, opts.min_mass2,<EOL>return_mass_heavier=True)<EOL>m2_at_min_m1 = pnutils.eta_mass1_to_mass2(opts.max_eta, opts.min_mass1,<EOL>return_mass_heavier=False)<EOL>m1_at_max_m2 = pnutils.eta_mass1_to_mass2(opts.max_eta, opts.max_mass2,<EOL>return_mass_heavier=True)<EOL>m2_at_max_m1 = pnutils.eta_mass1_to_mass2(opts.max_eta, opts.max_mass1,<EOL>return_mass_heavier=False)<EOL>if m1_at_min_m2 <= opts.max_mass1 and m1_at_min_m2 >= opts.min_mass1:<EOL><INDENT>min_tot_mass = opts.min_mass2 + m1_at_min_m2<EOL><DEDENT>elif m2_at_min_m1 <= opts.max_mass2 and m2_at_min_m1 >= opts.min_mass2:<EOL><INDENT>min_tot_mass = opts.min_total_mass<EOL><DEDENT>elif m2_at_min_m1 > opts.max_mass2:<EOL><INDENT>min_tot_mass = opts.min_total_mass<EOL><DEDENT>elif opts.max_eta == <NUM_LIT> and (m1_at_min_m2 < opts.min_mass2 orm2_at_min_m1 > opts.min_mass1): <EOL><INDENT>min_tot_mass = opts.min_total_mass<EOL><DEDENT>else:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>print(m1_at_min_m2, m2_at_min_m1, m1_at_max_m2, m2_at_max_m1)<EOL>print(opts.min_mass1, opts.max_mass1, opts.min_mass2, opts.max_mass2)<EOL>raise ValueError(err_msg)<EOL><DEDENT>if min_tot_mass > opts.min_total_mass:<EOL><INDENT>opts.min_total_mass = float(min_tot_mass)<EOL><DEDENT>if m2_at_max_m1 <= opts.max_mass2 and m2_at_max_m1 >= opts.min_mass2:<EOL><INDENT>max_tot_mass = opts.max_mass1 + m2_at_max_m1<EOL><DEDENT>elif m1_at_max_m2 <= opts.max_mass1 and m1_at_max_m2 >= opts.min_mass1:<EOL><INDENT>max_tot_mass = opts.max_total_mass<EOL><DEDENT>else:<EOL><INDENT>max_tot_mass = opts.max_total_mass<EOL><DEDENT>if max_tot_mass < opts.max_total_mass:<EOL><INDENT>opts.max_total_mass = float(max_tot_mass)<EOL><DEDENT><DEDENT>if opts.min_eta:<EOL><INDENT>m1_at_min_m2 = pnutils.eta_mass1_to_mass2(opts.min_eta, opts.min_mass2,<EOL>return_mass_heavier=True)<EOL>m2_at_min_m1 = pnutils.eta_mass1_to_mass2(opts.min_eta, opts.min_mass1,<EOL>return_mass_heavier=False)<EOL>m1_at_max_m2 = pnutils.eta_mass1_to_mass2(opts.min_eta, opts.max_mass2,<EOL>return_mass_heavier=True)<EOL>m2_at_max_m1 = pnutils.eta_mass1_to_mass2(opts.min_eta, opts.max_mass1,<EOL>return_mass_heavier=False)<EOL>if m1_at_max_m2 <= opts.max_mass1 and m1_at_max_m2 >= opts.min_mass1:<EOL><INDENT>max_tot_mass = opts.max_mass2 + m1_at_max_m2<EOL><DEDENT>elif m2_at_max_m1 <= opts.max_mass2 and m2_at_max_m1 >= opts.min_mass2:<EOL><INDENT>max_tot_mass = opts.max_total_mass<EOL><DEDENT>elif m2_at_max_m1 < opts.min_mass2:<EOL><INDENT>max_tot_mass = opts.max_total_mass<EOL><DEDENT>else:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>if max_tot_mass < opts.max_total_mass:<EOL><INDENT>opts.max_total_mass = float(max_tot_mass)<EOL><DEDENT>if m2_at_min_m1 <= opts.max_mass2 and m2_at_min_m1 >= opts.min_mass2:<EOL><INDENT>min_tot_mass = opts.min_mass1 + m2_at_min_m1<EOL><DEDENT>elif m1_at_min_m2 <= opts.max_mass1 and m1_at_min_m2 >= opts.min_mass1:<EOL><INDENT>min_tot_mass = opts.min_total_mass<EOL><DEDENT>else:<EOL><INDENT>min_tot_mass = opts.min_total_mass<EOL><DEDENT>if min_tot_mass > opts.min_total_mass:<EOL><INDENT>opts.min_total_mass = float(min_tot_mass)<EOL><DEDENT><DEDENT>if opts.max_total_mass < opts.min_total_mass:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>"<EOL>raise ValueError(err_msg)<EOL><DEDENT>if opts.max_eta and opts.min_eta and (opts.max_eta < opts.min_eta):<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>if nonSpin:<EOL><INDENT>return<EOL><DEDENT>if opts.max_ns_spin_mag is None:<EOL><INDENT>if opts.nsbh_flag:<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>elif opts.min_mass2 < (opts.ns_bh_boundary_mass or<EOL>massRangeParameters.default_nsbh_boundary_mass):<EOL><INDENT>parser.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>opts.max_ns_spin_mag = opts.max_bh_spin_mag<EOL><DEDENT><DEDENT>if opts.max_bh_spin_mag is None:<EOL><INDENT>if opts.nsbh_flag:<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT>if opts.max_mass1 >= (opts.ns_bh_boundary_mass or<EOL>massRangeParameters.default_nsbh_boundary_mass):<EOL><INDENT>parser.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>opts.max_bh_spin_mag = opts.max_ns_spin_mag<EOL><DEDENT><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.
nonSpin : boolean, optional (default=False)
If this is provided the spin-related options will not be checked. | 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>")<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>")<EOL>ethincaGroup.add_argument("<STR_LIT>",<EOL>default=None, choices=get_ethinca_orders(), <EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>ethincaGroup.add_argument("<STR_LIT>",<EOL>default=None, <EOL>choices=pnutils.named_frequency_cutoffs.keys(),<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>ethincaGroup.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>type=float, default=<NUM_LIT>,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return ethincaGroup<EOL> | 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_frequency_step:<EOL><INDENT>parser.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if not (opts.calculate_ethinca_metric oropts.calculate_time_metric_components) and opts.ethinca_pn_order:<EOL><INDENT>parser.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT> | 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><DEDENT>if ethincaParams.pnOrder is None:<EOL><INDENT>ethincaParams.pnOrder = metricParams.pnOrder<EOL><DEDENT><DEDENT>else: pass<EOL> | 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 bits]<EOL>result = "<STR_LIT:\n>".join(formatted_bits) + "<STR_LIT:\n>"<EOL>return result<EOL> | 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>" % (self.current_indent, "<STR_LIT>", opt_width, opts)<EOL>indent_first = <NUM_LIT:0><EOL><DEDENT>result.append(opts)<EOL>if option.help:<EOL><INDENT>help_text = self.expand_default(option)<EOL>help_lines = []<EOL>for para in help_text.split("<STR_LIT:\n>"):<EOL><INDENT>help_lines.extend(textwrap.wrap(para, self.help_width))<EOL><DEDENT>result.append("<STR_LIT>" % (<EOL>indent_first, "<STR_LIT>", help_lines[<NUM_LIT:0>]))<EOL>result.extend(["<STR_LIT>" % (self.help_position, "<STR_LIT>", line)<EOL>for line in help_lines[<NUM_LIT:1>:]])<EOL><DEDENT>elif opts[-<NUM_LIT:1>] != "<STR_LIT:\n>":<EOL><INDENT>result.append("<STR_LIT:\n>")<EOL><DEDENT>return "<STR_LIT>".join(result)<EOL> | No documentation | f15981:c0:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.