signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def calibration_lines(freqs, data, tref=None): | if tref is None:<EOL><INDENT>tref = float(data.start_time)<EOL><DEDENT>for freq in freqs:<EOL><INDENT>measured_line = matching_line(freq, data, tref,<EOL>bin_size=data.duration)<EOL>data -= measured_line.data.real<EOL><DEDENT>return data<EOL> | Extract the calibration lines from strain data.
Parameters
----------
freqs: list
List containing the frequencies of the calibration lines.
data: pycbc.types.TimeSeries
Strain data to extract the calibration lines from.
tref: {None, float}, optional
Reference time for the line. If None, will use data.start_time.
Returns
-------
data: pycbc.types.TimeSeries
The strain data with the calibration lines removed. | f16021:m4 |
def clean_data(freqs, data, chunk, avg_bin): | if avg_bin >= chunk:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if chunk >= data.duration:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>steps = numpy.arange(<NUM_LIT:0>, int(data.duration/chunk)-<NUM_LIT:0.5>, <NUM_LIT:0.5>)<EOL>seglen = chunk * data.sample_rate<EOL>tref = float(data.start_time)<EOL>for freq in freqs:<EOL><INDENT>for step in steps:<EOL><INDENT>start, end = int(step*seglen), int((step+<NUM_LIT:1>)*seglen)<EOL>chunk_line = matching_line(freq, data[start:end],<EOL>tref, bin_size=avg_bin)<EOL>hann_window = numpy.hanning(len(chunk_line))<EOL>apply_hann = TimeSeries(numpy.ones(len(chunk_line)),<EOL>delta_t=chunk_line.delta_t,<EOL>epoch=chunk_line.start_time)<EOL>if step == <NUM_LIT:0>:<EOL><INDENT>apply_hann.data[len(hann_window)/<NUM_LIT:2>:] *=hann_window[len(hann_window)/<NUM_LIT:2>:]<EOL><DEDENT>elif step == steps[-<NUM_LIT:1>]:<EOL><INDENT>apply_hann.data[:len(hann_window)/<NUM_LIT:2>] *=hann_window[:len(hann_window)/<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>apply_hann.data *= hann_window<EOL><DEDENT>chunk_line.data *= apply_hann.data<EOL>data.data[start:end] -= chunk_line.data.real<EOL><DEDENT><DEDENT>return data<EOL> | Extract time-varying (wandering) lines from strain data.
Parameters
----------
freqs: list
List containing the frequencies of the wandering lines.
data: pycbc.types.TimeSeries
Strain data to extract the wandering lines from.
chunk: float
Duration of the chunks the data will be divided into to account
for the time variation of the wandering lines. Should be smaller
than data.duration, and allow for at least a few chunks.
avg_bin: float
Duration of the bins each chunk will be divided into for averaging
the inner product when measuring the parameters of the line. Should
be smaller than chunk.
Returns
-------
data: pycbc.types.TimeSeries
The strain data with the wandering lines removed. | f16021:m5 |
@abstractmethod<EOL><INDENT>def apply_calibration(self, strain):<DEDENT> | return<EOL> | Apply calibration model
This method should be overwritten by subclasses
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain. | f16022:c0:m1 |
def map_to_adjust(self, strain, prefix='<STR_LIT>', **params): | self.params.update({<EOL>key[len(prefix):]: params[key]<EOL>for key in params if prefix in key and self.ifo_name in key})<EOL>strain_adjusted = self.apply_calibration(strain)<EOL>return strain_adjusted<EOL> | Map an input dictionary of sampling parameters to the
adjust_strain function by filtering the dictionary for the
calibration parameters, then calling adjust_strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
prefix: str
Prefix for calibration parameter names
params : dict
Dictionary of sampling parameters which includes
calibration parameters.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain. | f16022:c0:m2 |
@classmethod<EOL><INDENT>def from_config(cls, cp, ifo, section):<DEDENT> | all_params = dict(cp.items(section))<EOL>params = {key[len(ifo)+<NUM_LIT:1>:]: all_params[key]<EOL>for key in all_params if ifo.lower() in key}<EOL>model = params.pop('<STR_LIT>')<EOL>params['<STR_LIT>'] = ifo.lower()<EOL>return all_models[model](**params)<EOL> | Read a config file to get calibration options and transfer
functions which will be used to intialize the model.
Parameters
----------
cp : WorkflowConfigParser
An open config file.
ifo : string
The detector (H1, L1) for which the calibration model will
be loaded.
section : string
The section name in the config file from which to retrieve
the calibration options.
Return
------
instance
An instance of the class. | f16022:c0:m3 |
def __init__(self, minimum_frequency, maximum_frequency, n_points,<EOL>ifo_name): | Recalibrate.__init__(self, ifo_name=ifo_name)<EOL>minimum_frequency = float(minimum_frequency)<EOL>maximum_frequency = float(maximum_frequency)<EOL>n_points = int(n_points)<EOL>if n_points < <NUM_LIT:4>:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>self.n_points = n_points<EOL>self.spline_points = np.logspace(np.log10(minimum_frequency),<EOL>np.log10(maximum_frequency), n_points)<EOL> | Cubic spline recalibration
see https://dcc.ligo.org/LIGO-T1400682/public
This assumes the spline points follow
np.logspace(np.log(minimum_frequency), np.log(maximum_frequency),
n_points)
Parameters
----------
minimum_frequency: float
minimum frequency of spline points
maximum_frequency: float
maximum frequency of spline points
n_points: int
number of spline points | f16022:c1:m0 |
def apply_calibration(self, strain): | amplitude_parameters =[self.params['<STR_LIT>'.format(self.ifo_name, ii)]<EOL>for ii in range(self.n_points)]<EOL>amplitude_spline = UnivariateSpline(self.spline_points,<EOL>amplitude_parameters)<EOL>delta_amplitude = amplitude_spline(strain.sample_frequencies.numpy())<EOL>phase_parameters =[self.params['<STR_LIT>'.format(self.ifo_name, ii)]<EOL>for ii in range(self.n_points)]<EOL>phase_spline = UnivariateSpline(self.spline_points, phase_parameters)<EOL>delta_phase = phase_spline(strain.sample_frequencies.numpy())<EOL>strain_adjusted = strain * (<NUM_LIT:1.0> + delta_amplitude)* (<NUM_LIT> + <NUM_LIT> * delta_phase) / (<NUM_LIT> - <NUM_LIT> * delta_phase)<EOL>return strain_adjusted<EOL> | Apply calibration model
This applies cubic spline calibration to the strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain. | f16022:c1:m1 |
def read_model_from_config(cp, ifo, section="<STR_LIT>"): | model = cp.get_opt_tag(section, "<STR_LIT>".format(ifo.lower()), None)<EOL>recalibrator = models[model].from_config(cp, ifo.lower(), section)<EOL>return recalibrator<EOL> | Returns an instance of the calibration model specified in the
given configuration file.
Parameters
----------
cp : WorflowConfigParser
An open config file to read.
ifo : string
The detector (H1, L1) whose model will be loaded.
section : {"calibration", string}
Section name from which to retrieve the model.
Returns
-------
instance
An instance of the calibration model class. | f16023:m0 |
def next_power_of_2(n): | <EOL>return <NUM_LIT:1> << (len(bin(n)) - <NUM_LIT:2>)<EOL> | Return the smallest integer power of 2 larger than the argument.
Parameters
----------
n : int
A positive integer.
Returns
-------
m : int
Smallest integer power of 2 larger than n. | f16024:m0 |
def detect_loud_glitches(strain, psd_duration=<NUM_LIT>, psd_stride=<NUM_LIT>,<EOL>psd_avg_method='<STR_LIT>', low_freq_cutoff=<NUM_LIT>,<EOL>threshold=<NUM_LIT>, cluster_window=<NUM_LIT>, corrupt_time=<NUM_LIT>,<EOL>high_freq_cutoff=None, output_intermediates=False): | logging.info('<STR_LIT>')<EOL>taper_length = int(corrupt_time * strain.sample_rate)<EOL>w = numpy.arange(taper_length) / float(taper_length)<EOL>strain[<NUM_LIT:0>:taper_length] *= pycbc.types.Array(w, dtype=strain.dtype)<EOL>strain[(len(strain)-taper_length):] *= pycbc.types.Array(w[::-<NUM_LIT:1>],<EOL>dtype=strain.dtype)<EOL>pycbc.fft.fftw.set_measure_level(<NUM_LIT:0>)<EOL>if high_freq_cutoff:<EOL><INDENT>logging.info('<STR_LIT>')<EOL>strain = resample_to_delta_t(strain, <NUM_LIT:0.5> / high_freq_cutoff,<EOL>method='<STR_LIT>')<EOL><DEDENT>if output_intermediates:<EOL><INDENT>strain.save_to_wav('<STR_LIT>')<EOL><DEDENT>corrupt_length = int(corrupt_time * strain.sample_rate)<EOL>strain_pad_length = next_power_of_2(len(strain))<EOL>pad_start = strain_pad_length/<NUM_LIT:2> - len(strain)/<NUM_LIT:2><EOL>pad_end = pad_start + len(strain)<EOL>strain_pad = pycbc.types.TimeSeries(<EOL>pycbc.types.zeros(strain_pad_length, dtype=strain.dtype),<EOL>delta_t=strain.delta_t, copy=False,<EOL>epoch=strain.start_time-pad_start/strain.sample_rate)<EOL>strain_pad[pad_start:pad_end] = strain[:]<EOL>logging.info('<STR_LIT>')<EOL>psd = pycbc.psd.welch(strain[corrupt_length:(len(strain)-corrupt_length)],<EOL>seg_len=int(psd_duration * strain.sample_rate),<EOL>seg_stride=int(psd_stride * strain.sample_rate),<EOL>avg_method=psd_avg_method,<EOL>require_exact_data_fit=False)<EOL>psd = pycbc.psd.interpolate(psd, <NUM_LIT:1.>/strain_pad.duration)<EOL>psd = pycbc.psd.inverse_spectrum_truncation(<EOL>psd, int(psd_duration * strain.sample_rate),<EOL>low_frequency_cutoff=low_freq_cutoff,<EOL>trunc_method='<STR_LIT>')<EOL>kmin = int(low_freq_cutoff / psd.delta_f)<EOL>psd[<NUM_LIT:0>:kmin] = numpy.inf<EOL>if high_freq_cutoff:<EOL><INDENT>kmax = int(high_freq_cutoff / psd.delta_f)<EOL>psd[kmax:] = numpy.inf<EOL><DEDENT>logging.info('<STR_LIT>')<EOL>strain_tilde = pycbc.types.FrequencySeries(<EOL>pycbc.types.zeros(len(strain_pad) / <NUM_LIT:2> + <NUM_LIT:1>,<EOL>dtype=pycbc.types.complex_same_precision_as(strain)),<EOL>delta_f=psd.delta_f, copy=False)<EOL>pycbc.fft.fft(strain_pad, strain_tilde)<EOL>logging.info('<STR_LIT>')<EOL>if high_freq_cutoff:<EOL><INDENT>norm = high_freq_cutoff - low_freq_cutoff<EOL><DEDENT>else:<EOL><INDENT>norm = strain.sample_rate/<NUM_LIT> - low_freq_cutoff<EOL><DEDENT>strain_tilde *= (psd * norm) ** (-<NUM_LIT:0.5>)<EOL>logging.info('<STR_LIT>')<EOL>pycbc.fft.ifft(strain_tilde, strain_pad)<EOL>pycbc.fft.fftw.set_measure_level(pycbc.fft.fftw._default_measurelvl)<EOL>if output_intermediates:<EOL><INDENT>strain_pad[pad_start:pad_end].save_to_wav('<STR_LIT>')<EOL><DEDENT>logging.info('<STR_LIT>')<EOL>mag = abs(strain_pad[pad_start:pad_end])<EOL>if output_intermediates:<EOL><INDENT>mag.save('<STR_LIT>')<EOL><DEDENT>mag = mag.numpy()<EOL>mag[<NUM_LIT:0>:corrupt_length] = <NUM_LIT:0><EOL>mag[-<NUM_LIT:1>:-corrupt_length-<NUM_LIT:1>:-<NUM_LIT:1>] = <NUM_LIT:0><EOL>logging.info('<STR_LIT>')<EOL>indices = numpy.where(mag > threshold)[<NUM_LIT:0>]<EOL>cluster_idx = pycbc.events.findchirp_cluster_over_window(<EOL>indices, numpy.array(mag[indices]),<EOL>int(cluster_window*strain.sample_rate))<EOL>times = [idx * strain.delta_t + strain.start_timefor idx in indices[cluster_idx]]<EOL>return times<EOL> | Automatic identification of loud transients for gating purposes.
This function first estimates the PSD of the input time series using the
FindChirp Welch method. Then it whitens the time series using that
estimate. Finally, it computes the magnitude of the whitened series,
thresholds it and applies the FindChirp clustering over time to the
surviving samples.
Parameters
----------
strain : TimeSeries
Input strain time series to detect glitches over.
psd_duration : {float, 4}
Duration of the segments for PSD estimation in seconds.
psd_stride : {float, 2}
Separation between PSD estimation segments in seconds.
psd_avg_method : {string, 'median'}
Method for averaging PSD estimation segments.
low_freq_cutoff : {float, 30}
Minimum frequency to include in the whitened strain.
threshold : {float, 50}
Minimum magnitude of whitened strain for considering a transient to
be present.
cluster_window : {float, 5}
Length of time window to cluster surviving samples over, in seconds.
corrupt_time : {float, 4}
Amount of time to be discarded at the beginning and end of the input
time series.
high_frequency_cutoff : {float, None}
Maximum frequency to include in the whitened strain. If given, the
input series is downsampled accordingly. If omitted, the Nyquist
frequency is used.
output_intermediates : {bool, False}
Save intermediate time series for debugging. | f16024:m1 |
def from_cli(opt, dyn_range_fac=<NUM_LIT:1>, precision='<STR_LIT>',<EOL>inj_filter_rejector=None): | gating_info = {}<EOL>if opt.frame_cache or opt.frame_files or opt.frame_type:<EOL><INDENT>if opt.frame_cache:<EOL><INDENT>frame_source = opt.frame_cache<EOL><DEDENT>if opt.frame_files:<EOL><INDENT>frame_source = opt.frame_files<EOL><DEDENT>logging.info("<STR_LIT>")<EOL>if hasattr(opt, '<STR_LIT>') and opt.frame_sieve:<EOL><INDENT>sieve = opt.frame_sieve<EOL><DEDENT>else:<EOL><INDENT>sieve = None<EOL><DEDENT>if opt.frame_type:<EOL><INDENT>strain = pycbc.frame.query_and_read_frame(<EOL>opt.frame_type, opt.channel_name,<EOL>start_time=opt.gps_start_time-opt.pad_data,<EOL>end_time=opt.gps_end_time+opt.pad_data,<EOL>sieve=sieve)<EOL><DEDENT>else:<EOL><INDENT>strain = pycbc.frame.read_frame(<EOL>frame_source, opt.channel_name,<EOL>start_time=opt.gps_start_time-opt.pad_data,<EOL>end_time=opt.gps_end_time+opt.pad_data,<EOL>sieve=sieve)<EOL><DEDENT>if opt.zpk_z and opt.zpk_p and opt.zpk_k:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>strain = highpass(strain, frequency=opt.strain_high_pass)<EOL>logging.info("<STR_LIT>")<EOL>z = numpy.array(opt.zpk_z)<EOL>p = numpy.array(opt.zpk_p)<EOL>k = float(opt.zpk_k)<EOL>strain = filter_zpk(strain.astype(numpy.float64), z, p, k)<EOL><DEDENT>if opt.normalize_strain:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>l = opt.normalize_strain<EOL>strain = strain / l<EOL><DEDENT>if opt.injection_file:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>injector = InjectionSet(opt.injection_file)<EOL>injections =injector.apply(strain, opt.channel_name[<NUM_LIT:0>:<NUM_LIT:2>],<EOL>distance_scale=opt.injection_scale_factor,<EOL>inj_filter_rejector=inj_filter_rejector)<EOL><DEDENT>if opt.sgburst_injection_file:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>injector = SGBurstInjectionSet(opt.sgburst_injection_file)<EOL>injector.apply(strain, opt.channel_name[<NUM_LIT:0>:<NUM_LIT:2>],<EOL>distance_scale=opt.injection_scale_factor)<EOL><DEDENT>logging.info("<STR_LIT>")<EOL>strain = highpass(strain, frequency=opt.strain_high_pass)<EOL>if precision == '<STR_LIT>':<EOL><INDENT>logging.info("<STR_LIT>")<EOL>strain = (strain * dyn_range_fac).astype(pycbc.types.float32)<EOL><DEDENT>elif precision == "<STR_LIT>":<EOL><INDENT>logging.info("<STR_LIT>")<EOL>strain = (strain * dyn_range_fac).astype(pycbc.types.float64)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(precision))<EOL><DEDENT>if opt.gating_file is not None:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>gate_params = numpy.loadtxt(opt.gating_file)<EOL>if len(gate_params.shape) == <NUM_LIT:1>:<EOL><INDENT>gate_params = [gate_params]<EOL><DEDENT>strain = gate_data(strain, gate_params)<EOL>gating_info['<STR_LIT:file>'] =[gp for gp in gate_paramsif (gp[<NUM_LIT:0>] + gp[<NUM_LIT:1>] + gp[<NUM_LIT:2>] >= strain.start_time)and (gp[<NUM_LIT:0>] - gp[<NUM_LIT:1>] - gp[<NUM_LIT:2>] <= strain.end_time)]<EOL><DEDENT>if opt.autogating_threshold is not None:<EOL><INDENT>glitch_times = detect_loud_glitches(<EOL>strain + <NUM_LIT:0.>, threshold=opt.autogating_threshold,<EOL>cluster_window=opt.autogating_cluster,<EOL>low_freq_cutoff=opt.strain_high_pass,<EOL>high_freq_cutoff=opt.sample_rate/<NUM_LIT:2>,<EOL>corrupt_time=opt.pad_data+opt.autogating_pad)<EOL>gate_params = [[gt, opt.autogating_width, opt.autogating_taper]for gt in glitch_times]<EOL>if len(glitch_times) > <NUM_LIT:0>:<EOL><INDENT>logging.info('<STR_LIT>',<EOL>'<STR_LIT:U+002CU+0020>'.join(['<STR_LIT>' % gt for gt in glitch_times]))<EOL><DEDENT>strain = gate_data(strain, gate_params)<EOL>gating_info['<STR_LIT>'] = gate_params<EOL><DEDENT>logging.info("<STR_LIT>")<EOL>strain = resample_to_delta_t(strain, <NUM_LIT:1.0>/opt.sample_rate, method='<STR_LIT>')<EOL>logging.info("<STR_LIT>")<EOL>strain = highpass(strain, frequency=opt.strain_high_pass)<EOL>if hasattr(opt, '<STR_LIT>') and opt.witness_frame_type:<EOL><INDENT>stilde = strain.to_frequencyseries()<EOL>import h5py<EOL>tf_file = h5py.File(opt.witness_tf_file)<EOL>for key in tf_file:<EOL><INDENT>witness = pycbc.frame.query_and_read_frame(opt.witness_frame_type, str(key),<EOL>start_time=strain.start_time, end_time=strain.end_time)<EOL>witness = (witness * dyn_range_fac).astype(strain.dtype)<EOL>tf = pycbc.types.load_frequencyseries(opt.witness_tf_file, group=key)<EOL>tf = tf.astype(stilde.dtype)<EOL>flen = int(opt.witness_filter_length * strain.sample_rate)<EOL>tf = pycbc.psd.interpolate(tf, stilde.delta_f)<EOL>tf_time = tf.to_timeseries()<EOL>window = Array(numpy.hanning(flen*<NUM_LIT:2>), dtype=strain.dtype)<EOL>tf_time[<NUM_LIT:0>:flen] *= window[flen:]<EOL>tf_time[len(tf_time)-flen:] *= window[<NUM_LIT:0>:flen]<EOL>tf = tf_time.to_frequencyseries()<EOL>kmax = min(len(tf), len(stilde)-<NUM_LIT:1>)<EOL>stilde[:kmax] -= tf[:kmax] * witness.to_frequencyseries()[:kmax]<EOL><DEDENT>strain = stilde.to_timeseries()<EOL><DEDENT>logging.info("<STR_LIT>")<EOL>start = opt.pad_data*opt.sample_rate<EOL>end = len(strain)-opt.sample_rate*opt.pad_data<EOL>strain = strain[start:end]<EOL><DEDENT>if opt.fake_strain or opt.fake_strain_from_file:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>if not opt.low_frequency_cutoff:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>duration = opt.gps_end_time - opt.gps_start_time<EOL>tlen = duration * opt.sample_rate<EOL>pdf = <NUM_LIT:1.0>/<NUM_LIT><EOL>plen = int(opt.sample_rate / pdf) / <NUM_LIT:2> + <NUM_LIT:1><EOL>if opt.fake_strain_from_file:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>strain_psd = pycbc.psd.from_txt(opt.fake_strain_from_file, plen, pdf,<EOL>opt.low_frequency_cutoff, is_asd_file=True)<EOL><DEDENT>elif opt.fake_strain != '<STR_LIT>':<EOL><INDENT>logging.info("<STR_LIT>")<EOL>strain_psd = pycbc.psd.from_string(opt.fake_strain, plen, pdf,<EOL>opt.low_frequency_cutoff)<EOL><DEDENT>if opt.fake_strain == '<STR_LIT>':<EOL><INDENT>logging.info("<STR_LIT>")<EOL>strain = TimeSeries(pycbc.types.zeros(tlen),<EOL>delta_t=<NUM_LIT:1.0>/opt.sample_rate,<EOL>epoch=opt.gps_start_time)<EOL><DEDENT>else:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>from pycbc.noise.reproduceable import colored_noise<EOL>lowfreq = opt.low_frequency_cutoff / <NUM_LIT><EOL>strain = colored_noise(strain_psd, opt.gps_start_time,<EOL>opt.gps_end_time,<EOL>seed=opt.fake_strain_seed,<EOL>low_frequency_cutoff=lowfreq)<EOL>strain = resample_to_delta_t(strain, <NUM_LIT:1.0>/opt.sample_rate)<EOL><DEDENT>if not opt.channel_name and (opt.injection_fileor opt.sgburst_injection_file):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if opt.injection_file:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>injector = InjectionSet(opt.injection_file)<EOL>injections =injector.apply(strain, opt.channel_name[<NUM_LIT:0>:<NUM_LIT:2>],<EOL>distance_scale=opt.injection_scale_factor,<EOL>inj_filter_rejector=inj_filter_rejector)<EOL><DEDENT>if opt.sgburst_injection_file:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>injector = SGBurstInjectionSet(opt.sgburst_injection_file)<EOL>injector.apply(strain, opt.channel_name[<NUM_LIT:0>:<NUM_LIT:2>],<EOL>distance_scale=opt.injection_scale_factor)<EOL><DEDENT>if precision == '<STR_LIT>':<EOL><INDENT>logging.info("<STR_LIT>")<EOL>strain = (dyn_range_fac * strain).astype(pycbc.types.float32)<EOL><DEDENT>elif precision == '<STR_LIT>':<EOL><INDENT>logging.info("<STR_LIT>")<EOL>strain = (dyn_range_fac * strain).astype(pycbc.types.float64)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(precision))<EOL><DEDENT><DEDENT>if opt.taper_data:<EOL><INDENT>logging.info("<STR_LIT>")<EOL>pd_taper_window = opt.taper_data<EOL>gate_params = [(strain.start_time, <NUM_LIT:0.>, pd_taper_window)]<EOL>gate_params.append( (strain.end_time, <NUM_LIT:0.>,<EOL>pd_taper_window) )<EOL>gate_data(strain, gate_params)<EOL><DEDENT>if opt.injection_file:<EOL><INDENT>strain.injections = injections<EOL><DEDENT>strain.gating_info = gating_info<EOL>return strain<EOL> | Parses the CLI options related to strain data reading and conditioning.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (gps-start-time, gps-end-time, strain-high-pass,
pad-data, sample-rate, (frame-cache or frame-files), channel-name,
fake-strain, fake-strain-seed, fake-strain-from-file, gating_file).
dyn_range_fac : {float, 1}, optional
A large constant to reduce the dynamic range of the strain.
precision : string
Precision of the returned strain ('single' or 'double').
inj_filter_rejector : InjFilterRejector instance; optional, default=None
If given send the InjFilterRejector instance to the inject module so
that it can store a reduced representation of injections if
necessary.
Returns
-------
strain : TimeSeries
The time series containing the conditioned strain data. | f16024:m2 |
def from_cli_single_ifo(opt, ifo, **kwargs): | single_det_opt = copy_opts_for_single_ifo(opt, ifo)<EOL>return from_cli(single_det_opt, **kwargs)<EOL> | Get the strain for a single ifo when using the multi-detector CLI | f16024:m3 |
def from_cli_multi_ifos(opt, ifos, **kwargs): | strain = {}<EOL>for ifo in ifos:<EOL><INDENT>strain[ifo] = from_cli_single_ifo(opt, ifo, **kwargs)<EOL><DEDENT>return strain<EOL> | Get the strain for all ifos when using the multi-detector CLI | f16024:m4 |
def insert_strain_option_group(parser, gps_times=True): | data_reading_group = parser.add_argument_group("<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>if gps_times:<EOL><INDENT>data_reading_group.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>", type=int)<EOL>data_reading_group.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>", type=int)<EOL><DEDENT>data_reading_group.add_argument("<STR_LIT>", type=float,<EOL>help="<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>", type=int)<EOL>data_reading_group.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>", type=int, default=<NUM_LIT:0>)<EOL>data_reading_group.add_argument("<STR_LIT>", type=int,<EOL>help="<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=str,<EOL>help="<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=str, nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>",<EOL>type=str, nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>",<EOL>type=str,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>",<EOL>type=str,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>choices=pycbc.psd.get_lalsim_psd_list() + ['<STR_LIT>'])<EOL>data_reading_group.add_argument("<STR_LIT>", type=int, default=<NUM_LIT:0>,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=str,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=str,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=float,<EOL>default=<NUM_LIT:1>, help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=str,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument('<STR_LIT>', type=float,<EOL>metavar='<STR_LIT>',<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>data_reading_group.add_argument('<STR_LIT>', type=float,<EOL>metavar='<STR_LIT>', default=<NUM_LIT>,<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>data_reading_group.add_argument('<STR_LIT>', type=float,<EOL>metavar='<STR_LIT>', default=<NUM_LIT>,<EOL>help='<STR_LIT>')<EOL>data_reading_group.add_argument('<STR_LIT>', type=float,<EOL>metavar='<STR_LIT>', default=<NUM_LIT>,<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>data_reading_group.add_argument('<STR_LIT>', type=float,<EOL>metavar='<STR_LIT>', default=<NUM_LIT:16>,<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>data_reading_group.add_argument("<STR_LIT>", type=float,<EOL>help="<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=float, nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=float, nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=float,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=str,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=str,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group.add_argument("<STR_LIT>", type=float,<EOL>help="<STR_LIT>")<EOL>return data_reading_group<EOL> | Add strain-related options to the optparser object.
Adds the options used to call the pycbc.strain.from_cli function to an
optparser as an OptionGroup. This should be used if you
want to use these options in your code.
Parameters
-----------
parser : object
OptionParser instance. | f16024:m5 |
def insert_strain_option_group_multi_ifo(parser): | data_reading_group_multi = parser.add_argument_group("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", nargs='<STR_LIT:+>',<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>", type=int)<EOL>data_reading_group_multi.add_argument("<STR_LIT>", nargs='<STR_LIT:+>', type=int,<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", nargs='<STR_LIT:+>',<EOL>action=MultiDetOptionAction,<EOL>type=float, metavar='<STR_LIT>',<EOL>help="<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", nargs='<STR_LIT:+>',<EOL>action=MultiDetOptionAction,<EOL>type=int, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", nargs='<STR_LIT:+>',<EOL>action=MultiDetOptionAction,<EOL>type=int, default=<NUM_LIT:0>, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=int, nargs='<STR_LIT:+>',<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=str, nargs='<STR_LIT:+>',<EOL>action=MultiDetOptionActionSpecial,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=str, nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAppendAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=str, nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAppendAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=str, nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=str, nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=str, nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"%(('<STR_LIT:U+002CU+0020>').join(pycbc.psd.get_lalsim_psd_list()),) )<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=int,<EOL>default=<NUM_LIT:0>, nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", nargs="<STR_LIT:+>",<EOL>action=MultiDetOptionAction, metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=str,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=str,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>",<EOL>type=float, nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar="<STR_LIT>", default=<NUM_LIT:1.>,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=str,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument('<STR_LIT>', type=float,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>',<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>data_reading_group_multi.add_argument('<STR_LIT>', type=float,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>', default=<NUM_LIT>,<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>data_reading_group_multi.add_argument('<STR_LIT>', type=float,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>', default=<NUM_LIT>,<EOL>help='<STR_LIT>')<EOL>data_reading_group_multi.add_argument('<STR_LIT>', type=float,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>', default=<NUM_LIT>,<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>data_reading_group_multi.add_argument('<STR_LIT>', type=float,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>', default=<NUM_LIT:16>,<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=float,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=float,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAppendAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=float,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAppendAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>data_reading_group_multi.add_argument("<STR_LIT>", type=float,<EOL>nargs="<STR_LIT:+>", action=MultiDetOptionAppendAction,<EOL>metavar='<STR_LIT>',<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return data_reading_group_multi<EOL> | Adds the options used to call the pycbc.strain.from_cli function to an
optparser as an OptionGroup. This should be used if you
want to use these options in your code.
Parameters
-----------
parser : object
OptionParser instance. | f16024:m6 |
def verify_strain_options(opts, parser): | for opt_group in ensure_one_opt_groups:<EOL><INDENT>ensure_one_opt(opts, parser, opt_group)<EOL><DEDENT>required_opts(opts, parser, required_opts_list)<EOL> | Sanity check provided strain arguments.
Parses the strain data CLI options and verifies that they are consistent
and reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (gps-start-time, gps-end-time, strain-high-pass,
pad-data, sample-rate, frame-cache, channel-name, fake-strain,
fake-strain-seed).
parser : object
OptionParser instance. | f16024:m7 |
def verify_strain_options_multi_ifo(opts, parser, ifos): | for ifo in ifos:<EOL><INDENT>for opt_group in ensure_one_opt_groups:<EOL><INDENT>ensure_one_opt_multi_ifo(opts, parser, ifo, opt_group)<EOL><DEDENT>required_opts_multi_ifo(opts, parser, ifo, required_opts_list)<EOL><DEDENT> | Sanity check provided strain arguments.
Parses the strain data CLI options and verifies that they are consistent
and reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (gps-start-time, gps-end-time, strain-high-pass,
pad-data, sample-rate, frame-cache, channel-name, fake-strain,
fake-strain-seed).
parser : object
OptionParser instance.
ifos : list of strings
List of ifos for which to verify options for | f16024:m8 |
def gate_data(data, gate_params): | def inverted_tukey(M, n_pad):<EOL><INDENT>midlen = M - <NUM_LIT:2>*n_pad<EOL>if midlen < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>padarr = <NUM_LIT:0.5>*(<NUM_LIT:1.>+numpy.cos(numpy.pi*numpy.arange(n_pad)/n_pad))<EOL>return numpy.concatenate((padarr,numpy.zeros(midlen),padarr[::-<NUM_LIT:1>]))<EOL><DEDENT>sample_rate = <NUM_LIT:1.>/data.delta_t<EOL>temp = data.data<EOL>for glitch_time, glitch_width, pad_width in gate_params:<EOL><INDENT>t_start = glitch_time - glitch_width - pad_width - data.start_time<EOL>t_end = glitch_time + glitch_width + pad_width - data.start_time<EOL>if t_start > data.duration or t_end < <NUM_LIT:0.>:<EOL><INDENT>continue <EOL><DEDENT>win_samples = int(<NUM_LIT:2>*sample_rate*(glitch_width+pad_width))<EOL>pad_samples = int(sample_rate*pad_width)<EOL>window = inverted_tukey(win_samples, pad_samples)<EOL>offset = int(t_start * sample_rate)<EOL>idx1 = max(<NUM_LIT:0>, -offset)<EOL>idx2 = min(len(window), len(data)-offset)<EOL>temp[idx1+offset:idx2+offset] *= window[idx1:idx2]<EOL><DEDENT>return data<EOL> | Apply a set of gating windows to a time series.
Each gating window is
defined by a central time, a given duration (centered on the given
time) to zero out, and a given duration of smooth tapering on each side of
the window. The window function used for tapering is a Tukey window.
Parameters
----------
data : TimeSeries
The time series to be gated.
gate_params : list
List of parameters for the gating windows. Each element should be a
list or tuple with 3 elements: the central time of the gating window,
the half-duration of the portion to zero out, and the duration of the
Tukey tapering on each side. All times in seconds. The total duration
of the data affected by one gating window is thus twice the second
parameter plus twice the third parameter.
Returns
-------
data: TimeSeries
The gated time series. | f16024:m9 |
def __init__(self, strain, segment_length=None, segment_start_pad=<NUM_LIT:0>,<EOL>segment_end_pad=<NUM_LIT:0>, trigger_start=None, trigger_end=None,<EOL>filter_inj_only=False, injection_window=None,<EOL>allow_zero_padding=False): | self._fourier_segments = None<EOL>self.strain = strain<EOL>self.delta_t = strain.delta_t<EOL>self.sample_rate = strain.sample_rate<EOL>if segment_length:<EOL><INDENT>seg_len = segment_length<EOL><DEDENT>else:<EOL><INDENT>seg_len = strain.duration<EOL><DEDENT>self.delta_f = <NUM_LIT:1.0> / seg_len<EOL>self.time_len = seg_len * self.sample_rate<EOL>self.freq_len = self.time_len / <NUM_LIT:2> + <NUM_LIT:1><EOL>seg_end_pad = segment_end_pad<EOL>seg_start_pad = segment_start_pad<EOL>if not trigger_start:<EOL><INDENT>trigger_start = int(strain.start_time) + segment_start_pad<EOL><DEDENT>else:<EOL><INDENT>if not allow_zero_padding:<EOL><INDENT>min_start_time = int(strain.start_time) + segment_start_pad<EOL><DEDENT>else:<EOL><INDENT>min_start_time = int(strain.start_time)<EOL><DEDENT>if trigger_start < min_start_time:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>" %(trigger_start)<EOL>err_msg += "<STR_LIT>" %(min_start_time)<EOL>raise ValueError(err_msg)<EOL><DEDENT><DEDENT>if not trigger_end:<EOL><INDENT>trigger_end = int(strain.end_time) - segment_end_pad<EOL><DEDENT>else:<EOL><INDENT>if not allow_zero_padding:<EOL><INDENT>max_end_time = int(strain.end_time) - segment_end_pad<EOL><DEDENT>else:<EOL><INDENT>max_end_time = int(strain.end_time)<EOL><DEDENT>if trigger_end > max_end_time:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>err_msg += "<STR_LIT>" %(trigger_end)<EOL>err_msg += "<STR_LIT>" %(max_end_time)<EOL>raise ValueError(err_msg)<EOL><DEDENT><DEDENT>throwaway_size = seg_start_pad + seg_end_pad<EOL>seg_width = seg_len - throwaway_size<EOL>analyzable = trigger_end - trigger_start<EOL>data_start = (trigger_start - segment_start_pad) -int(strain.start_time)<EOL>data_end = trigger_end + segment_end_pad - int(strain.start_time)<EOL>data_dur = data_end - data_start<EOL>data_start = data_start * strain.sample_rate<EOL>data_end = data_end * strain.sample_rate<EOL>num_segs = int(numpy.ceil(float(analyzable) / float(seg_width)))<EOL>seg_offset = int(numpy.ceil(analyzable / float(num_segs)))<EOL>self.segment_slices = []<EOL>self.analyze_slices = []<EOL>for nseg in range(num_segs-<NUM_LIT:1>):<EOL><INDENT>seg_start = int(data_start + (nseg*seg_offset) * strain.sample_rate)<EOL>seg_end = int(seg_start + seg_len * strain.sample_rate)<EOL>seg_slice = slice(seg_start, seg_end)<EOL>self.segment_slices.append(seg_slice)<EOL>ana_start = int(seg_start_pad * strain.sample_rate)<EOL>ana_end = int(ana_start + seg_offset * strain.sample_rate)<EOL>ana_slice = slice(ana_start, ana_end)<EOL>self.analyze_slices.append(ana_slice)<EOL><DEDENT>seg_end = int(data_end)<EOL>seg_start = int(seg_end - seg_len * strain.sample_rate)<EOL>seg_slice = slice(seg_start, seg_end)<EOL>self.segment_slices.append(seg_slice)<EOL>remaining = (data_dur - ((num_segs - <NUM_LIT:1>) * seg_offset + seg_start_pad))<EOL>ana_start = int((seg_len - remaining) * strain.sample_rate)<EOL>ana_end = int((seg_len - seg_end_pad) * strain.sample_rate)<EOL>ana_slice = slice(ana_start, ana_end)<EOL>self.analyze_slices.append(ana_slice)<EOL>self.full_segment_slices = copy.deepcopy(self.segment_slices)<EOL>segment_slices_red = []<EOL>analyze_slices_red = []<EOL>trig_start_idx = (trigger_start - int(strain.start_time)) * strain.sample_rate<EOL>trig_end_idx = (trigger_end - int(strain.start_time)) * strain.sample_rate<EOL>if filter_inj_only and hasattr(strain, '<STR_LIT>'):<EOL><INDENT>end_times = strain.injections.end_times()<EOL>end_times = [time for time in end_times if float(time) < trigger_end and float(time) > trigger_start]<EOL>inj_idx = [(float(time) - float(strain.start_time)) * strain.sample_rate for time in end_times]<EOL><DEDENT>for seg, ana in zip(self.segment_slices, self.analyze_slices):<EOL><INDENT>start = ana.start<EOL>stop = ana.stop<EOL>cum_start = start + seg.start<EOL>cum_end = stop + seg.start<EOL>if trig_start_idx > cum_start:<EOL><INDENT>start += (trig_start_idx - cum_start)<EOL><DEDENT>if trig_end_idx < cum_end:<EOL><INDENT>stop -= (cum_end - trig_end_idx)<EOL><DEDENT>if filter_inj_only and hasattr(strain, '<STR_LIT>'):<EOL><INDENT>analyze_this = False<EOL>inj_window = strain.sample_rate * <NUM_LIT:8><EOL>for inj_id in inj_idx:<EOL><INDENT>if inj_id < (cum_end + inj_window) andinj_id > (cum_start - inj_window):<EOL><INDENT>analyze_this = True<EOL><DEDENT><DEDENT>if not analyze_this:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if start < stop:<EOL><INDENT>segment_slices_red.append(seg)<EOL>analyze_slices_red.append(slice(start, stop))<EOL><DEDENT><DEDENT>self.segment_slices = segment_slices_red<EOL>self.analyze_slices = analyze_slices_red<EOL> | Determine how to chop up the strain data into smaller segments
for analysis. | f16024:c0:m0 |
def fourier_segments(self): | if not self._fourier_segments:<EOL><INDENT>self._fourier_segments = []<EOL>for seg_slice, ana in zip(self.segment_slices, self.analyze_slices):<EOL><INDENT>if seg_slice.start >= <NUM_LIT:0> and seg_slice.stop <= len(self.strain):<EOL><INDENT>freq_seg = make_frequency_series(self.strain[seg_slice])<EOL><DEDENT>elif seg_slice.start < <NUM_LIT:0>:<EOL><INDENT>strain_chunk = self.strain[:seg_slice.stop]<EOL>strain_chunk.prepend_zeros(-seg_slice.start)<EOL>freq_seg = make_frequency_series(strain_chunk)<EOL><DEDENT>elif seg_slice.stop > len(self.strain):<EOL><INDENT>strain_chunk = self.strain[seg_slice.start:]<EOL>strain_chunk.append_zeros(seg_slice.stop - len(self.strain))<EOL>freq_seg = make_frequency_series(strain_chunk)<EOL><DEDENT>freq_seg.analyze = ana<EOL>freq_seg.cumulative_index = seg_slice.start + ana.start<EOL>freq_seg.seg_slice = seg_slice<EOL>self._fourier_segments.append(freq_seg)<EOL><DEDENT><DEDENT>return self._fourier_segments<EOL> | Return a list of the FFT'd segments.
Return the list of FrequencySeries. Additional properties are
added that describe the strain segment. The property 'analyze'
is a slice corresponding to the portion of the time domain equivelant
of the segment to analyze for triggers. The value 'cumulative_index'
indexes from the beginning of the original strain series. | f16024:c0:m1 |
@classmethod<EOL><INDENT>def from_cli(cls, opt, strain):<DEDENT> | return cls(strain, segment_length=opt.segment_length,<EOL>segment_start_pad=opt.segment_start_pad,<EOL>segment_end_pad=opt.segment_end_pad,<EOL>trigger_start=opt.trig_start_time,<EOL>trigger_end=opt.trig_end_time,<EOL>filter_inj_only=opt.filter_inj_only,<EOL>injection_window=opt.injection_window,<EOL>allow_zero_padding=opt.allow_zero_padding)<EOL> | Calculate the segmentation of the strain data for analysis from
the command line options. | f16024:c0:m2 |
@classmethod<EOL><INDENT>def from_cli_single_ifo(cls, opt, strain, ifo):<DEDENT> | return cls(strain, segment_length=opt.segment_length[ifo],<EOL>segment_start_pad=opt.segment_start_pad[ifo],<EOL>segment_end_pad=opt.segment_end_pad[ifo],<EOL>trigger_start=opt.trig_start_time[ifo],<EOL>trigger_end=opt.trig_end_time[ifo],<EOL>filter_inj_only=opt.filter_inj_only,<EOL>allow_zero_padding=opt.allow_zero_padding)<EOL> | Calculate the segmentation of the strain data for analysis from
the command line options. | f16024:c0:m4 |
@classmethod<EOL><INDENT>def from_cli_multi_ifos(cls, opt, strain_dict, ifos):<DEDENT> | strain_segments = {}<EOL>for ifo in ifos:<EOL><INDENT>strain_segments[ifo] = cls.from_cli_single_ifo(opt,<EOL>strain_dict[ifo], ifo)<EOL><DEDENT>return strain_segments<EOL> | Calculate the segmentation of the strain data for analysis from
the command line options. | f16024:c0:m5 |
def __init__(self, frame_src, channel_name, start_time,<EOL>max_buffer=<NUM_LIT>,<EOL>sample_rate=<NUM_LIT>,<EOL>low_frequency_cutoff=<NUM_LIT:20>,<EOL>highpass_frequency=<NUM_LIT>,<EOL>highpass_reduction=<NUM_LIT>,<EOL>highpass_bandwidth=<NUM_LIT>,<EOL>psd_samples=<NUM_LIT:30>,<EOL>psd_segment_length=<NUM_LIT:4>,<EOL>psd_inverse_length=<NUM_LIT>,<EOL>trim_padding=<NUM_LIT>,<EOL>autogating_threshold=<NUM_LIT:100>,<EOL>autogating_cluster=<NUM_LIT>,<EOL>autogating_window=<NUM_LIT:0.5>,<EOL>autogating_pad=<NUM_LIT>,<EOL>state_channel=None,<EOL>data_quality_channel=None,<EOL>dyn_range_fac=pycbc.DYN_RANGE_FAC,<EOL>psd_abort_difference=None,<EOL>psd_recalculate_difference=None,<EOL>force_update_cache=True,<EOL>increment_update_cache=None,<EOL>analyze_flags=None,<EOL>data_quality_flags=None,<EOL>dq_padding=<NUM_LIT:0>): | super(StrainBuffer, self).__init__(frame_src, channel_name, start_time,<EOL>max_buffer=max_buffer,<EOL>force_update_cache=force_update_cache,<EOL>increment_update_cache=increment_update_cache)<EOL>self.low_frequency_cutoff = low_frequency_cutoff<EOL>self.analyze_flags = analyze_flags<EOL>self.data_quality_flags = data_quality_flags<EOL>self.state = None<EOL>self.dq = None<EOL>self.dq_padding = dq_padding<EOL>if state_channel is not None:<EOL><INDENT>valid_mask = pycbc.frame.flag_names_to_bitmask(self.analyze_flags)<EOL>logging.info('<STR_LIT>',<EOL>state_channel, bin(valid_mask))<EOL>self.state = pycbc.frame.StatusBuffer(<EOL>frame_src,<EOL>state_channel, start_time,<EOL>max_buffer=max_buffer,<EOL>valid_mask=valid_mask,<EOL>force_update_cache=force_update_cache,<EOL>increment_update_cache=increment_update_cache)<EOL><DEDENT>if data_quality_channel is not None:<EOL><INDENT>sb_kwargs = dict(max_buffer=max_buffer,<EOL>force_update_cache=force_update_cache,<EOL>increment_update_cache=increment_update_cache)<EOL>if len(self.data_quality_flags) == <NUM_LIT:1>and self.data_quality_flags[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>sb_kwargs['<STR_LIT>'] = True<EOL>logging.info('<STR_LIT>',<EOL>data_quality_channel)<EOL><DEDENT>else:<EOL><INDENT>sb_kwargs['<STR_LIT>'] = pycbc.frame.flag_names_to_bitmask(<EOL>self.data_quality_flags)<EOL>logging.info('<STR_LIT>',<EOL>data_quality_channel, bin(valid_mask))<EOL><DEDENT>self.dq = pycbc.frame.StatusBuffer(frame_src, data_quality_channel,<EOL>start_time, **sb_kwargs)<EOL><DEDENT>self.highpass_frequency = highpass_frequency<EOL>self.highpass_reduction = highpass_reduction<EOL>self.highpass_bandwidth = highpass_bandwidth<EOL>self.autogating_threshold = autogating_threshold<EOL>self.autogating_cluster = autogating_cluster<EOL>self.autogating_pad = autogating_pad<EOL>self.autogating_window = autogating_window<EOL>self.sample_rate = sample_rate<EOL>self.dyn_range_fac = dyn_range_fac<EOL>self.psd_abort_difference = psd_abort_difference<EOL>self.psd_recalculate_difference = psd_recalculate_difference<EOL>self.psd_segment_length = psd_segment_length<EOL>self.psd_samples = psd_samples<EOL>self.psd_inverse_length = psd_inverse_length<EOL>self.psd = None<EOL>self.psds = {}<EOL>strain_len = int(sample_rate * self.raw_buffer.delta_t * len(self.raw_buffer))<EOL>self.strain = TimeSeries(zeros(strain_len, dtype=numpy.float32),<EOL>delta_t=<NUM_LIT:1.0>/self.sample_rate,<EOL>epoch=start_time-max_buffer)<EOL>highpass_samples, self.beta = kaiserord(self.highpass_reduction,<EOL>self.highpass_bandwidth / self.raw_buffer.sample_rate * <NUM_LIT:2> * numpy.pi)<EOL>self.highpass_samples = int(highpass_samples / <NUM_LIT:2>)<EOL>resample_corruption = <NUM_LIT:10> <EOL>self.factor = int(<NUM_LIT:1.0> / self.raw_buffer.delta_t / self.sample_rate)<EOL>self.corruption = self.highpass_samples / self.factor + resample_corruption<EOL>self.psd_corruption = self.psd_inverse_length * self.sample_rate<EOL>self.total_corruption = self.corruption + self.psd_corruption<EOL>self.trim_padding = int(trim_padding * self.sample_rate)<EOL>if self.trim_padding > self.total_corruption:<EOL><INDENT>self.trim_padding = self.total_corruption<EOL><DEDENT>self.psd_duration = (psd_samples - <NUM_LIT:1>) / <NUM_LIT:2> * psd_segment_length<EOL>self.reduced_pad = int(self.total_corruption - self.trim_padding)<EOL>self.segments = {}<EOL>self.add_hard_count()<EOL>self.taper_immediate_strain = True<EOL> | Class to produce overwhitened strain incrementally
Parameters
----------
frame_src: str of list of strings
Strings that indicate where to read from files from. This can be a
list of frame files, a glob, etc.
channel_name: str
Name of the channel to read from the frame files
start_time:
Time to start reading from.
max_buffer: {int, 512}, Optional
Length of the buffer in seconds
sample_rate: {int, 2048}, Optional
Rate in Hz to sample the data.
low_frequency_cutoff: {float, 20}, Optional
The low frequency cutoff to use for inverse spectrum truncation
highpass_frequency: {float, 15}, Optional
The frequency to apply a highpass filter at before downsampling.
highpass_reduction: {float, 200}, Optional
The amount of reduction to apply to the low frequencies.
highpass_bandwidth: {float, 5}, Optional
The width of the transition region for the highpass filter.
psd_samples: {int, 30}, Optional
The number of sample to use for psd estimation
psd_segment_length: {float, 4}, Optional
The number of seconds in each psd sample.
psd_inverse_length: {float, 3.5}, Optional
The length in seconds for fourier transform of the inverse of the
PSD to be truncated to.
trim_padding: {float, 0.25}, Optional
Amount of padding in seconds to give for truncated the overwhitened
data stream.
autogating_threshold: {float, 100}, Optional
Sigma deviation required to cause gating of data
autogating_cluster: {float, 0.25}, Optional
Seconds to cluster possible gating locations
autogating_window: {float, 0.5}, Optional
Seconds to window out when gating a time
autogating_pad: {float, 0.25}, Optional
Seconds to pad either side of the gating window.
state_channel: {str, None}, Optional
Channel to use for state information about the strain
data_quality_channel: {str, None}, Optional
Channel to use for data quality information about the strain
dyn_range_fac: {float, pycbc.DYN_RANGE_FAC}, Optional
Scale factor to apply to strain
psd_abort_difference: {float, None}, Optional
The relative change in the inspiral range from the previous PSD
estimate to trigger the data to be considered invalid.
psd_recalculate_difference: {float, None}, Optional
the relative change in the inspiral range from the previous PSD
to trigger a re-estimatoin of the PSD.
force_update_cache: {boolean, True}, Optional
Re-check the filesystem for frame files on every attempt to
read more data.
analyze_flags: list of strs
The flags that must be on to mark the current data as valid for
*any* use.
data_quality_flags: list of strs
The flags used to determine if to keep triggers.
dq_padding: {float, 0}, optional
Extra seconds to consider invalid before/after times with bad DQ.
increment_update_cache: {str, None}, Optional
Pattern to look for frame files in a GPS dependent directory. This
is an alternate to the forced updated of the frame cache, and
apptempts to predict the next frame file name without probing the
filesystem. | f16024:c1:m0 |
@property<EOL><INDENT>def start_time(self):<DEDENT> | return self.end_time - self.blocksize<EOL> | Return the start time of the current valid segment of data | f16024:c1:m1 |
@property<EOL><INDENT>def end_time(self):<DEDENT> | return float(self.strain.start_time + (len(self.strain) - self.total_corruption) / self.sample_rate)<EOL> | Return the end time of the current valid segment of data | f16024:c1:m2 |
def add_hard_count(self): | self.wait_duration = int(numpy.ceil(self.total_corruption / self.sample_rate + self.psd_duration))<EOL>self.invalidate_psd()<EOL> | Reset the countdown timer, so that we don't analyze data long enough
to generate a new PSD. | f16024:c1:m3 |
def invalidate_psd(self): | self.psd = None<EOL>self.psds = {}<EOL> | Make the current PSD invalid. A new one will be generated when
it is next required | f16024:c1:m4 |
def recalculate_psd(self): | seg_len = self.sample_rate * self.psd_segment_length<EOL>e = len(self.strain)<EOL>s = e - ((self.psd_samples + <NUM_LIT:1>) * self.psd_segment_length / <NUM_LIT:2>) * self.sample_rate<EOL>psd = pycbc.psd.welch(self.strain[s:e], seg_len=seg_len, seg_stride=seg_len / <NUM_LIT:2>)<EOL>psd.dist = spa_distance(psd, <NUM_LIT>, <NUM_LIT>, self.low_frequency_cutoff) * pycbc.DYN_RANGE_FAC<EOL>if self.psd and self.psd_recalculate_difference:<EOL><INDENT>if abs(self.psd.dist - psd.dist) / self.psd.dist < self.psd_recalculate_difference:<EOL><INDENT>logging.info("<STR_LIT>",<EOL>self.detector, self.psd.dist, psd.dist)<EOL>return True<EOL><DEDENT><DEDENT>if self.psd and self.psd_abort_difference:<EOL><INDENT>if abs(self.psd.dist - psd.dist) / self.psd.dist > self.psd_abort_difference:<EOL><INDENT>logging.info("<STR_LIT>",<EOL>self.detector, self.psd.dist, psd.dist)<EOL>self.psd = psd<EOL>self.psds = {}<EOL>return False<EOL><DEDENT><DEDENT>self.psd = psd<EOL>self.psds = {}<EOL>logging.info("<STR_LIT>", self.detector, psd.dist)<EOL>return True<EOL> | Recalculate the psd | f16024:c1:m5 |
def overwhitened_data(self, delta_f): | <EOL>if delta_f not in self.segments:<EOL><INDENT>buffer_length = int(<NUM_LIT:1.0> / delta_f)<EOL>e = len(self.strain)<EOL>s = int(e - buffer_length * self.sample_rate - self.reduced_pad * <NUM_LIT:2>)<EOL>fseries = make_frequency_series(self.strain[s:e])<EOL>if delta_f not in self.psds:<EOL><INDENT>psdt = pycbc.psd.interpolate(self.psd, fseries.delta_f)<EOL>psdt = pycbc.psd.inverse_spectrum_truncation(psdt,<EOL>int(self.sample_rate * self.psd_inverse_length),<EOL>low_frequency_cutoff=self.low_frequency_cutoff)<EOL>psdt._delta_f = fseries.delta_f<EOL>psd = pycbc.psd.interpolate(self.psd, delta_f)<EOL>psd = pycbc.psd.inverse_spectrum_truncation(psd,<EOL>int(self.sample_rate * self.psd_inverse_length),<EOL>low_frequency_cutoff=self.low_frequency_cutoff)<EOL>psd.psdt = psdt<EOL>self.psds[delta_f] = psd<EOL><DEDENT>psd = self.psds[delta_f]<EOL>fseries /= psd.psdt<EOL>if self.reduced_pad != <NUM_LIT:0>:<EOL><INDENT>overwhite = TimeSeries(zeros(e-s, dtype=self.strain.dtype),<EOL>delta_t=self.strain.delta_t)<EOL>pycbc.fft.ifft(fseries, overwhite)<EOL>overwhite2 = overwhite[self.reduced_pad:len(overwhite)-self.reduced_pad]<EOL>taper_window = self.trim_padding / <NUM_LIT> / overwhite.sample_rate<EOL>gate_params = [(overwhite2.start_time, <NUM_LIT:0.>, taper_window),<EOL>(overwhite2.end_time, <NUM_LIT:0.>, taper_window)]<EOL>gate_data(overwhite2, gate_params)<EOL>fseries_trimmed = FrequencySeries(zeros(len(overwhite2) / <NUM_LIT:2> + <NUM_LIT:1>,<EOL>dtype=fseries.dtype), delta_f=delta_f)<EOL>pycbc.fft.fft(overwhite2, fseries_trimmed)<EOL>fseries_trimmed.start_time = fseries.start_time + self.reduced_pad * self.strain.delta_t<EOL><DEDENT>else:<EOL><INDENT>fseries_trimmed = fseries<EOL><DEDENT>fseries_trimmed.psd = psd<EOL>self.segments[delta_f] = fseries_trimmed<EOL><DEDENT>stilde = self.segments[delta_f]<EOL>return stilde<EOL> | Return overwhitened data
Parameters
----------
delta_f: float
The sample step to generate overwhitened frequency domain data for
Returns
-------
htilde: FrequencySeries
Overwhited strain data | f16024:c1:m6 |
def near_hwinj(self): | if not self.state:<EOL><INDENT>return False<EOL><DEDENT>if not self.state.is_extent_valid(self.start_time, self.blocksize, pycbc.frame.NO_HWINJ):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | Check that the current set of triggers could be influenced by
a hardware injection. | f16024:c1:m7 |
def null_advance_strain(self, blocksize): | sample_step = int(blocksize * self.sample_rate)<EOL>csize = sample_step + self.corruption * <NUM_LIT:2><EOL>self.strain.roll(-sample_step)<EOL>self.strain[len(self.strain) - csize + self.corruption:] = <NUM_LIT:0><EOL>self.strain.start_time += blocksize<EOL>self.taper_immediate_strain = True<EOL> | Advance and insert zeros
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel | f16024:c1:m8 |
def advance(self, blocksize, timeout=<NUM_LIT:10>): | ts = super(StrainBuffer, self).attempt_advance(blocksize, timeout=timeout)<EOL>self.blocksize = blocksize<EOL>if ts is None:<EOL><INDENT>logging.info("<STR_LIT>", self.detector)<EOL>self.null_advance_strain(blocksize)<EOL>if self.state:<EOL><INDENT>self.state.null_advance(blocksize)<EOL><DEDENT>if self.dq:<EOL><INDENT>self.dq.null_advance(blocksize)<EOL><DEDENT>return False<EOL><DEDENT>self.wait_duration -= blocksize<EOL>if self.state and self.state.advance(blocksize) is False:<EOL><INDENT>self.add_hard_count()<EOL>self.null_advance_strain(blocksize)<EOL>if self.dq:<EOL><INDENT>self.dq.null_advance(blocksize)<EOL><DEDENT>logging.info("<STR_LIT>",<EOL>self.detector)<EOL>return False<EOL><DEDENT>if self.dq:<EOL><INDENT>self.dq.advance(blocksize)<EOL><DEDENT>self.segments = {}<EOL>sample_step = int(blocksize * self.sample_rate)<EOL>csize = sample_step + self.corruption * <NUM_LIT:2><EOL>start = len(self.raw_buffer) - csize * self.factor<EOL>strain = self.raw_buffer[start:]<EOL>strain = pycbc.filter.highpass_fir(strain, self.highpass_frequency,<EOL>self.highpass_samples,<EOL>beta=self.beta)<EOL>strain = (strain * self.dyn_range_fac).astype(numpy.float32)<EOL>strain = pycbc.filter.resample_to_delta_t(strain,<EOL><NUM_LIT:1.0>/self.sample_rate, method='<STR_LIT>')<EOL>strain = strain[self.corruption:]<EOL>if self.taper_immediate_strain:<EOL><INDENT>logging.info("<STR_LIT>", self.detector)<EOL>strain = gate_data(strain, [(strain.start_time, <NUM_LIT:0.>, self.autogating_pad)])<EOL>self.taper_immediate_strain = False<EOL><DEDENT>self.strain.roll(-sample_step)<EOL>self.strain[len(self.strain) - csize + self.corruption:] = strain[:]<EOL>self.strain.start_time += blocksize<EOL>if self.psd is None and self.wait_duration <=<NUM_LIT:0>:<EOL><INDENT>self.recalculate_psd()<EOL><DEDENT>if self.wait_duration > <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT> | Advanced buffer blocksize seconds.
Add blocksize seconds more to the buffer, push blocksize seconds
from the beginning.
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel
Returns
-------
status: boolean
Returns True if this block is analyzable. | f16024:c1:m9 |
@classmethod<EOL><INDENT>def from_cli(cls, ifo, args, maxlen):<DEDENT> | state_channel = analyze_flags = None<EOL>if args.state_channel and ifo in args.state_channeland args.analyze_flags and ifo in args.analyze_flags:<EOL><INDENT>state_channel = '<STR_LIT::>'.join([ifo, args.state_channel[ifo]])<EOL>analyze_flags = args.analyze_flags[ifo].split('<STR_LIT:U+002C>')<EOL><DEDENT>dq_channel = dq_flags = None<EOL>if args.data_quality_channel and ifo in args.data_quality_channeland args.data_quality_flags and ifo in args.data_quality_flags:<EOL><INDENT>dq_channel = '<STR_LIT::>'.join([ifo, args.data_quality_channel[ifo]])<EOL>dq_flags = args.data_quality_flags[ifo].split('<STR_LIT:U+002C>')<EOL><DEDENT>if args.frame_type:<EOL><INDENT>frame_src = pycbc.frame.frame_paths(args.frame_type[ifo],<EOL>args.start_time,<EOL>args.end_time)<EOL><DEDENT>else:<EOL><INDENT>frame_src = [args.frame_src[ifo]]<EOL><DEDENT>strain_channel = '<STR_LIT::>'.join([ifo, args.channel_name[ifo]])<EOL>return cls(frame_src, strain_channel,<EOL>args.start_time, max_buffer=maxlen * <NUM_LIT:2>,<EOL>state_channel=state_channel,<EOL>data_quality_channel=dq_channel,<EOL>sample_rate=args.sample_rate,<EOL>low_frequency_cutoff=args.low_frequency_cutoff,<EOL>highpass_frequency=args.highpass_frequency,<EOL>highpass_reduction=args.highpass_reduction,<EOL>highpass_bandwidth=args.highpass_bandwidth,<EOL>psd_samples=args.psd_samples,<EOL>trim_padding=args.trim_padding,<EOL>psd_segment_length=args.psd_segment_length,<EOL>psd_inverse_length=args.psd_inverse_length,<EOL>autogating_threshold=args.autogating_threshold,<EOL>autogating_cluster=args.autogating_cluster,<EOL>autogating_window=args.autogating_window,<EOL>autogating_pad=args.autogating_pad,<EOL>psd_abort_difference=args.psd_abort_difference,<EOL>psd_recalculate_difference=args.psd_recalculate_difference,<EOL>force_update_cache=args.force_update_cache,<EOL>increment_update_cache=args.increment_update_cache[ifo],<EOL>analyze_flags=analyze_flags,<EOL>data_quality_flags=dq_flags,<EOL>dq_padding=args.data_quality_padding)<EOL> | Initialize a StrainBuffer object (data reader) for a particular
detector. | f16024:c1:m10 |
def _gates_from_cli(opts, gate_opt): | gates = {}<EOL>if getattr(opts, gate_opt) is None:<EOL><INDENT>return gates<EOL><DEDENT>for gate in getattr(opts, gate_opt):<EOL><INDENT>try:<EOL><INDENT>ifo, central_time, half_dur, taper_dur = gate.split('<STR_LIT::>')<EOL>central_time = float(central_time)<EOL>half_dur = float(half_dur)<EOL>taper_dur = float(taper_dur)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>gate) + "<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>gates[ifo].append((central_time, half_dur, taper_dur))<EOL><DEDENT>except KeyError:<EOL><INDENT>gates[ifo] = [(central_time, half_dur, taper_dur)]<EOL><DEDENT><DEDENT>return gates<EOL> | Parses the given `gate_opt` into something understandable by
`strain.gate_data`. | f16025:m0 |
def gates_from_cli(opts): | return _gates_from_cli(opts, '<STR_LIT>')<EOL> | Parses the --gate option into something understandable by
`strain.gate_data`. | f16025:m1 |
def psd_gates_from_cli(opts): | return _gates_from_cli(opts, '<STR_LIT>')<EOL> | Parses the --psd-gate option into something understandable by
`strain.gate_data`. | f16025:m2 |
def apply_gates_to_td(strain_dict, gates): | <EOL>outdict = dict(strain_dict.items())<EOL>for ifo in gates:<EOL><INDENT>outdict[ifo] = strain.gate_data(outdict[ifo], gates[ifo])<EOL><DEDENT>return outdict<EOL> | Applies the given dictionary of gates to the given dictionary of
strain.
Parameters
----------
strain_dict : dict
Dictionary of time-domain strain, keyed by the ifos.
gates : dict
Dictionary of gates. Keys should be the ifo to apply the data to,
values are a tuple giving the central time of the gate, the half
duration, and the taper duration.
Returns
-------
dict
Dictionary of time-domain strain with the gates applied. | f16025:m3 |
def apply_gates_to_fd(stilde_dict, gates): | <EOL>outdict = dict(stilde_dict.items())<EOL>strain_dict = dict([[ifo, outdict[ifo].to_timeseries()] for ifo in gates])<EOL>for ifo,d in apply_gates_to_td(strain_dict, gates).items():<EOL><INDENT>outdict[ifo] = d.to_frequencyseries()<EOL><DEDENT>return outdict<EOL> | Applies the given dictionary of gates to the given dictionary of
strain in the frequency domain.
Gates are applied by IFFT-ing the strain data to the time domain, applying
the gate, then FFT-ing back to the frequency domain.
Parameters
----------
stilde_dict : dict
Dictionary of frequency-domain strain, keyed by the ifos.
gates : dict
Dictionary of gates. Keys should be the ifo to apply the data to,
values are a tuple giving the central time of the gate, the half
duration, and the taper duration.
Returns
-------
dict
Dictionary of frequency-domain strain with the gates applied. | f16025:m4 |
def add_gate_option_group(parser): | gate_group = parser.add_argument_group("<STR_LIT>")<EOL>gate_group.add_argument("<STR_LIT>", nargs="<STR_LIT:+>", type=str,<EOL>metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>gate_group.add_argument("<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>gate_group.add_argument("<STR_LIT>", nargs="<STR_LIT:+>", type=str,<EOL>metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>return gate_group<EOL> | Adds the options needed to apply gates to data.
Parameters
----------
parser : object
ArgumentParser instance. | f16025:m5 |
@abstractmethod<EOL><INDENT>def apply_calibration(self, strain):<DEDENT> | return<EOL> | Apply calibration model
This method should be overwritten by subclasses
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain. | f16026:c0:m1 |
def map_to_adjust(self, strain, prefix='<STR_LIT>', **params): | self.params.update({<EOL>key[len(prefix):]: params[key]<EOL>for key in params if prefix in key and self.ifo_name in key})<EOL>strain_adjusted = self.apply_calibration(strain)<EOL>return strain_adjusted<EOL> | Map an input dictionary of sampling parameters to the
adjust_strain function by filtering the dictionary for the
calibration parameters, then calling adjust_strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
prefix: str
Prefix for calibration parameter names
params : dict
Dictionary of sampling parameters which includes
calibration parameters.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain. | f16026:c0:m2 |
@classmethod<EOL><INDENT>def from_config(cls, cp, ifo, section):<DEDENT> | all_params = dict(cp.items(section))<EOL>params = {key[len(ifo)+<NUM_LIT:1>:]: all_params[key]<EOL>for key in all_params if ifo.lower() in key}<EOL>params = {key: params[key] for key in params}<EOL>params.pop('<STR_LIT>')<EOL>params['<STR_LIT>'] = ifo.lower()<EOL>return cls(**params)<EOL> | Read a config file to get calibration options and transfer
functions which will be used to intialize the model.
Parameters
----------
cp : WorkflowConfigParser
An open config file.
ifo : string
The detector (H1, L1) for which the calibration model will
be loaded.
section : string
The section name in the config file from which to retrieve
the calibration options.
Return
------
instance
An instance of the class. | f16026:c0:m3 |
def apply_calibration(self, strain): | amplitude_parameters =[self.params['<STR_LIT>'.format(self.ifo_name, ii)]<EOL>for ii in range(self.n_points)]<EOL>amplitude_spline = UnivariateSpline(self.spline_points,<EOL>amplitude_parameters)<EOL>delta_amplitude = amplitude_spline(strain.sample_frequencies.numpy())<EOL>phase_parameters =[self.params['<STR_LIT>'.format(self.ifo_name, ii)]<EOL>for ii in range(self.n_points)]<EOL>phase_spline = UnivariateSpline(self.spline_points, phase_parameters)<EOL>delta_phase = phase_spline(strain.sample_frequencies.numpy())<EOL>strain_adjusted = strain * (<NUM_LIT:1.0> + delta_amplitude)* (<NUM_LIT> + <NUM_LIT> * delta_phase) / (<NUM_LIT> - <NUM_LIT> * delta_phase)<EOL>return strain_adjusted<EOL> | Apply calibration model
This applies cubic spline calibration to the strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain. | f16026:c1:m1 |
def update_c(self, fs=None, qinv=None, fc=None, kappa_c=<NUM_LIT:1.0>): | detuning_term = self.freq**<NUM_LIT:2> / (self.freq**<NUM_LIT:2> - <NUM_LIT> *self.freq*fs *qinv + fs**<NUM_LIT:2>)<EOL>return self.c_res * kappa_c / (<NUM_LIT:1> + <NUM_LIT> * self.freq/fc)*detuning_term<EOL> | Calculate the sensing function c(f,t) given the new parameters
kappa_c(t), kappa_a(t), f_c(t), fs, and qinv.
Parameters
----------
fc : float
Coupled-cavity (CC) pole at time t.
kappa_c : float
Scalar correction factor for sensing function at time t.
fs : float
Spring frequency for signal recycling cavity.
qinv : float
Inverse quality factor for signal recycling cavity.
Returns
-------
c : numpy.array
The new sensing function c(f,t). | f16026:c2:m1 |
def update_g(self, fs=None, qinv=None, fc=None, kappa_tst_re=<NUM_LIT:1.0>,<EOL>kappa_tst_im=<NUM_LIT:0.0>, kappa_pu_re=<NUM_LIT:1.0>, kappa_pu_im=<NUM_LIT:0.0>,<EOL>kappa_c=<NUM_LIT:1.0>): | c = self.update_c(fs=fs, qinv=qinv, fc=fc, kappa_c=kappa_c)<EOL>a_tst = self.a_tst0 * (kappa_tst_re + <NUM_LIT> * kappa_tst_im)<EOL>a_pu = self.a_pu0 * (kappa_pu_re + <NUM_LIT> * kappa_pu_im)<EOL>return c * self.d0 * (a_tst + a_pu)<EOL> | Calculate the open loop gain g(f,t) given the new parameters
kappa_c(t), kappa_a(t), f_c(t), fs, and qinv.
Parameters
----------
fc : float
Coupled-cavity (CC) pole at time t.
kappa_c : float
Scalar correction factor for sensing function c at time t.
kappa_tst_re : float
Real part of scalar correction factor for actuation function
a_tst0 at time t.
kappa_pu_re : float
Real part of scalar correction factor for actuation function
a_pu0 at time t.
kappa_tst_im : float
Imaginary part of scalar correction factor for actuation function
a_tst0 at time t.
kappa_pu_im : float
Imaginary part of scalar correction factor for actuation function
a_pu0 at time t.
fs : float
Spring frequency for signal recycling cavity.
qinv : float
Inverse quality factor for signal recycling cavity.
Returns
-------
g : numpy.array
The new open loop gain g(f,t). | f16026:c2:m2 |
def update_r(self, fs=None, qinv=None, fc=None, kappa_c=<NUM_LIT:1.0>,<EOL>kappa_tst_re=<NUM_LIT:1.0>, kappa_tst_im=<NUM_LIT:0.0>, kappa_pu_re=<NUM_LIT:1.0>,<EOL>kappa_pu_im=<NUM_LIT:0.0>): | c = self.update_c(fs=fs, qinv=qinv, fc=fc, kappa_c=kappa_c)<EOL>g = self.update_g(fs=fs, qinv=qinv, fc=fc, kappa_c=kappa_c,<EOL>kappa_tst_re=kappa_tst_re,<EOL>kappa_tst_im=kappa_tst_im,<EOL>kappa_pu_re=kappa_pu_re, kappa_pu_im=kappa_pu_im)<EOL>return (<NUM_LIT:1.0> + g) / c<EOL> | Calculate the response function R(f,t) given the new parameters
kappa_c(t), kappa_a(t), f_c(t), fs, and qinv.
Parameters
----------
fc : float
Coupled-cavity (CC) pole at time t.
kappa_c : float
Scalar correction factor for sensing function c at time t.
kappa_tst_re : float
Real part of scalar correction factor for actuation function
a_tst0 at time t.
kappa_pu_re : float
Real part of scalar correction factor for actuation function
a_pu0 at time t.
kappa_tst_im : float
Imaginary part of scalar correction factor for actuation function
a_tst0 at time t.
kappa_pu_im : float
Imaginary part of scalar correction factor for actuation function
a_pu0 at time t.
fs : float
Spring frequency for signal recycling cavity.
qinv : float
Inverse quality factor for signal recycling cavity.
Returns
-------
r : numpy.array
The new response function r(f,t). | f16026:c2:m3 |
def adjust_strain(self, strain, delta_fs=None, delta_qinv=None,<EOL>delta_fc=None, kappa_c=<NUM_LIT:1.0>, kappa_tst_re=<NUM_LIT:1.0>,<EOL>kappa_tst_im=<NUM_LIT:0.0>, kappa_pu_re=<NUM_LIT:1.0>, kappa_pu_im=<NUM_LIT:0.0>): | fc = self.fc0 + delta_fc if delta_fc else self.fc0<EOL>fs = self.fs0 + delta_fs if delta_fs else self.fs0<EOL>qinv = self.qinv0 + delta_qinv if delta_qinv else self.qinv0<EOL>r_adjusted = self.update_r(fs=fs, qinv=qinv, fc=fc, kappa_c=kappa_c,<EOL>kappa_tst_re=kappa_tst_re,<EOL>kappa_tst_im=kappa_tst_im,<EOL>kappa_pu_re=kappa_pu_re,<EOL>kappa_pu_im=kappa_pu_im)<EOL>k = r_adjusted / self.r0<EOL>k_amp = np.abs(k)<EOL>k_phase = np.unwrap(np.angle(k))<EOL>order = <NUM_LIT:1><EOL>k_amp_off = UnivariateSpline(self.freq, k_amp, k=order, s=<NUM_LIT:0>)<EOL>k_phase_off = UnivariateSpline(self.freq, k_phase, k=order, s=<NUM_LIT:0>)<EOL>freq_even = strain.sample_frequencies.numpy()<EOL>k_even_sample = k_amp_off(freq_even) *np.exp(<NUM_LIT> * k_phase_off(freq_even))<EOL>strain_adjusted = FrequencySeries(strain.numpy() *k_even_sample,<EOL>delta_f=strain.delta_f)<EOL>return strain_adjusted<EOL> | Adjust the FrequencySeries strain by changing the time-dependent
calibration parameters kappa_c(t), kappa_a(t), f_c(t), fs, and qinv.
Parameters
----------
strain : FrequencySeries
The strain data to be adjusted.
delta_fc : float
Change in coupled-cavity (CC) pole at time t.
kappa_c : float
Scalar correction factor for sensing function c0 at time t.
kappa_tst_re : float
Real part of scalar correction factor for actuation function
A_{tst0} at time t.
kappa_tst_im : float
Imaginary part of scalar correction factor for actuation function
A_tst0 at time t.
kappa_pu_re : float
Real part of scalar correction factor for actuation function
A_{pu0} at time t.
kappa_pu_im : float
Imaginary part of scalar correction factor for actuation function
A_{pu0} at time t.
fs : float
Spring frequency for signal recycling cavity.
qinv : float
Inverse quality factor for signal recycling cavity.
Returns
-------
strain_adjusted : FrequencySeries
The adjusted strain. | f16026:c2:m4 |
@classmethod<EOL><INDENT>def tf_from_file(cls, path, delimiter="<STR_LIT:U+0020>"):<DEDENT> | data = np.loadtxt(path, delimiter=delimiter)<EOL>freq = data[:, <NUM_LIT:0>]<EOL>h = data[:, <NUM_LIT:1>] + <NUM_LIT> * data[:, <NUM_LIT:2>]<EOL>return np.array([freq, h]).transpose()<EOL> | Convert the contents of a file with the columns
[freq, real(h), imag(h)] to a numpy.array with columns
[freq, real(h)+j*imag(h)].
Parameters
----------
path : string
delimiter : {" ", string}
Return
------
numpy.array | f16026:c2:m5 |
@classmethod<EOL><INDENT>def from_config(cls, cp, ifo, section):<DEDENT> | <EOL>tfs = []<EOL>tf_names = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT:c>", "<STR_LIT:d>"]<EOL>for tag in ['<STR_LIT:->'.join([ifo, "<STR_LIT>", name])<EOL>for name in tf_names]:<EOL><INDENT>tf_path = cp.get_opt_tag(section, tag, None)<EOL>tfs.append(cls.tf_from_file(tf_path))<EOL><DEDENT>a_tst0 = tfs[<NUM_LIT:0>][:, <NUM_LIT:1>]<EOL>a_pu0 = tfs[<NUM_LIT:1>][:, <NUM_LIT:1>]<EOL>c0 = tfs[<NUM_LIT:2>][:, <NUM_LIT:1>]<EOL>d0 = tfs[<NUM_LIT:3>][:, <NUM_LIT:1>]<EOL>freq = tfs[<NUM_LIT:0>][:, <NUM_LIT:0>]<EOL>uim_tag = '<STR_LIT:->'.join([ifo, '<STR_LIT>'])<EOL>if cp.has_option(section, uim_tag):<EOL><INDENT>tf_path = cp.get_opt_tag(section, uim_tag, None)<EOL>a_pu0 += cls.tf_from_file(tf_path)[:, <NUM_LIT:1>]<EOL><DEDENT>fc0 = cp.get_opt_tag(section, '<STR_LIT:->'.join([ifo, "<STR_LIT>"]), None)<EOL>fs0 = cp.get_opt_tag(section, '<STR_LIT:->'.join([ifo, "<STR_LIT>"]), None)<EOL>qinv0 = cp.get_opt_tag(section, '<STR_LIT:->'.join([ifo, "<STR_LIT>"]), None)<EOL>return cls(freq=freq, fc0=fc0, c0=c0, d0=d0, a_tst0=a_tst0,<EOL>a_pu0=a_pu0, fs0=fs0, qinv0=qinv0)<EOL> | Read a config file to get calibration options and transfer
functions which will be used to intialize the model.
Parameters
----------
cp : WorkflowConfigParser
An open config file.
ifo : string
The detector (H1, L1) for which the calibration model will
be loaded.
section : string
The section name in the config file from which to retrieve
the calibration options.
Return
------
instance
An instance of the Recalibrate class. | f16026:c2:m6 |
def map_to_adjust(self, strain, **params): | <EOL>arg_names = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']<EOL>arg_labels = ['<STR_LIT>'.join(['<STR_LIT>', name]) for name in arg_names]<EOL>default_values = [<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:1.0>, <NUM_LIT:1.0>, <NUM_LIT:0.0>, <NUM_LIT:1.0>, <NUM_LIT:0.0>]<EOL>calib_args = []<EOL>for arg, val in zip(arg_labels, default_values):<EOL><INDENT>if arg in params:<EOL><INDENT>calib_args.append(params[arg])<EOL><DEDENT>else:<EOL><INDENT>calib_args.append(val)<EOL><DEDENT><DEDENT>strain_adjusted = self.adjust_strain(strain, delta_fs=calib_args[<NUM_LIT:0>],<EOL>delta_fc=calib_args[<NUM_LIT:1>], delta_qinv=calib_args[<NUM_LIT:2>],<EOL>kappa_c=calib_args[<NUM_LIT:3>],<EOL>kappa_tst_re=calib_args[<NUM_LIT:4>],<EOL>kappa_tst_im=calib_args[<NUM_LIT:5>],<EOL>kappa_pu_re=calib_args[<NUM_LIT:6>],<EOL>kappa_pu_im=calib_args[<NUM_LIT:7>])<EOL>return strain_adjusted<EOL> | Map an input dictionary of sampling parameters to the
adjust_strain function by filtering the dictionary for the
calibration parameters, then calling adjust_strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
params : dict
Dictionary of sampling parameters which includes
calibration parameters.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain. | f16026:c2:m7 |
def check_status(status): | if status:<EOL><INDENT>msg = lib.DftiErrorMessage(status)<EOL>msg = ctypes.c_char_p(msg).value<EOL>raise RuntimeError(msg)<EOL><DEDENT> | Check the status of a mkl functions and raise a python exeption if
there is an error. | f16028:m0 |
def get_measure_level(): | return _default_measurelvl<EOL> | Get the current 'measure level' used in deciding how much effort to put into
creating FFTW plans. From least effort (and shortest planning time) to most
they are 0 to 3. No arguments. | f16031:m4 |
def set_measure_level(mlvl): | global _default_measurelvl<EOL>if mlvl not in (<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:3>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>_default_measurelvl = mlvl<EOL> | Set the current 'measure level' used in deciding how much effort to expend
creating FFTW plans. Must be an integer from 0 (least effort, shortest time)
to 3 (most effort and time). | f16031:m5 |
def insert_fft_options(optgroup): | optgroup.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>" + str([<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:3>]),<EOL>type=int, default=_default_measurelvl)<EOL>optgroup.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>default=None)<EOL>optgroup.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>default=None)<EOL>optgroup.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>default=None)<EOL>optgroup.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>default=None)<EOL>optgroup.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>",<EOL>default=None)<EOL>optgroup.add_argument("<STR_LIT>",<EOL>help = "<STR_LIT>",<EOL>action = "<STR_LIT:store_true>")<EOL> | Inserts the options that affect the behavior of this backend
Parameters
----------
optgroup: fft_option
OptionParser argument group whose options are extended | f16031:m17 |
def verify_fft_options(opt,parser): | if opt.fftw_measure_level not in [<NUM_LIT:0>,<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:3>]:<EOL><INDENT>parser.error("<STR_LIT>".format(opt.fftw_measure_level))<EOL><DEDENT>if opt.fftw_import_system_wisdom and ((opt.fftw_input_float_wisdom_file is not None)<EOL>or (opt.fftw_input_double_wisdom_file is not None)):<EOL><INDENT>parser.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if opt.fftw_threads_backend is not None:<EOL><INDENT>if opt.fftw_threads_backend not in ['<STR_LIT>','<STR_LIT>','<STR_LIT>']:<EOL><INDENT>parser.error("<STR_LIT>")<EOL><DEDENT><DEDENT> | Parses the FFT options and verifies that they are
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes.
parser : object
OptionParser instance. | f16031:m18 |
def insert_fft_option_group(parser): | fft_group = parser.add_argument_group("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>fft_group.add_argument("<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>" + str(get_backend_names()),<EOL>nargs='<STR_LIT:*>', default=[])<EOL>for backend in get_backend_modules():<EOL><INDENT>try:<EOL><INDENT>backend.insert_fft_options(fft_group)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT> | Adds the options used to choose an FFT backend. This should be used
if your program supports the ability to select the FFT backend; otherwise
you may simply call the fft and ifft functions and rely on default
choices. This function will also attempt to add any options exported
by available backends through a function called insert_fft_options.
These submodule functions should take the fft_group object as argument.
Parameters
----------
parser : object
OptionParser instance | f16033:m0 |
def verify_fft_options(opt, parser): | if len(opt.fft_backends) > <NUM_LIT:0>:<EOL><INDENT>_all_backends = get_backend_names()<EOL>for backend in opt.fft_backends:<EOL><INDENT>if backend not in _all_backends:<EOL><INDENT>parser.error("<STR_LIT>".format(backend))<EOL><DEDENT><DEDENT><DEDENT>for backend in get_backend_modules():<EOL><INDENT>try:<EOL><INDENT>backend.verify_fft_options(opt, parser)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT> | Parses the FFT options and verifies that they are
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes.
parser : object
OptionParser instance. | f16033:m1 |
def from_cli(opt): | set_backend(opt.fft_backends)<EOL>backend = get_backend()<EOL>try:<EOL><INDENT>backend.from_cli(opt)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT> | Parses the command line options and sets the FFT backend
for each (available) scheme. Aside from setting the default
backed for this context, this function will also call (if
it exists) the from_cli function of the specified backends in
the *current* scheme; typically one would only call this function
once inside of a scheme context manager, but if it is desired
to perform FFTs both inside and outside of a context, then
this function would need to be called again.
Parameters
----------
opt: object
Result of parsing the CLI with OptionParser, or any object with
the required attributes.
Returns | f16033:m2 |
def fft(invec, outvec): | prec, itype, otype = _check_fft_args(invec, outvec)<EOL>_check_fwd_args(invec, itype, outvec, otype, <NUM_LIT:1>, None)<EOL>backend = get_backend()<EOL>backend.fft(invec, outvec, prec, itype, otype)<EOL>if isinstance(invec, _TimeSeries):<EOL><INDENT>outvec._epoch = invec._epoch<EOL>outvec._delta_f = <NUM_LIT:1.0>/(invec._delta_t * len(invec))<EOL>outvec *= invec._delta_t<EOL><DEDENT>elif isinstance(invec, _FrequencySeries):<EOL><INDENT>outvec._epoch = invec._epoch<EOL>outvec._delta_t = <NUM_LIT:1.0>/(invec._delta_f * len(invec))<EOL>outvec *= invec._delta_f<EOL><DEDENT> | Fourier transform from invec to outvec.
Perform a fourier transform. The type of transform is determined
by the dtype of invec and outvec.
Parameters
----------
invec : TimeSeries or FrequencySeries
The input vector.
outvec : TimeSeries or FrequencySeries
The output. | f16034:m0 |
def ifft(invec, outvec): | prec, itype, otype = _check_fft_args(invec, outvec)<EOL>_check_inv_args(invec, itype, outvec, otype, <NUM_LIT:1>, None)<EOL>backend = get_backend()<EOL>backend.ifft(invec, outvec, prec, itype, otype)<EOL>if isinstance(invec, _TimeSeries):<EOL><INDENT>outvec._epoch = invec._epoch<EOL>outvec._delta_f = <NUM_LIT:1.0>/(invec._delta_t * len(outvec))<EOL>outvec *= invec._delta_t<EOL><DEDENT>elif isinstance(invec,_FrequencySeries):<EOL><INDENT>outvec._epoch = invec._epoch<EOL>outvec._delta_t = <NUM_LIT:1.0>/(invec._delta_f * len(outvec))<EOL>outvec *= invec._delta_f<EOL><DEDENT> | Inverse fourier transform from invec to outvec.
Perform an inverse fourier transform. The type of transform is determined
by the dtype of invec and outvec.
Parameters
----------
invec : TimeSeries or FrequencySeries
The input vector.
outvec : TimeSeries or FrequencySeries
The output. | f16034:m1 |
def execute(self): | pass<EOL> | Compute the (forward) FFT of the input vector specified at object
instantiation, putting the output into the output vector specified
at objet instantiation. The intention is that this method should
be called many times, with the contents of the input vector
changing between invocations, but not the locations in memory or
length of either input or output vector.
*Unlike* the function based API, the class based API does NOT rescale
its output by the input vector's delta_t (when input is a TimeSeries)
or delta_f (when input is a FrequencySeries). | f16039:c0:m1 |
def execute(self): | pass<EOL> | Compute the (backward) FFT of the input vector specified at object
instantiation, putting the output into the output vector specified
at objet instantiation. The intention is that this method should
be called many times, with the contents of the input vector
changing between invocations, but not the locations in memory or
length of either input or output vector.
*Unlike* the function based API, the class based API does NOT rescale
its output by the input vector's delta_t (when input is a TimeSeries)
or delta_f (when input is a FrequencySeries). | f16039:c1:m1 |
def plan_transpose(N1, N2): | rows = N1<EOL>cols = N2<EOL>iodim = numpy.zeros(<NUM_LIT:6>, dtype=numpy.int32)<EOL>iodim[<NUM_LIT:0>] = rows<EOL>iodim[<NUM_LIT:1>] = <NUM_LIT:1><EOL>iodim[<NUM_LIT:2>] = cols<EOL>iodim[<NUM_LIT:3>] = cols<EOL>iodim[<NUM_LIT:4>] = rows<EOL>iodim[<NUM_LIT:5>] = <NUM_LIT:1><EOL>N = N1*N2<EOL>vin = pycbc.types.zeros(N, dtype=numpy.complex64)<EOL>vout = pycbc.types.zeros(N, dtype=numpy.complex64)<EOL>f = float_lib.fftwf_plan_guru_dft<EOL>f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int,<EOL>ctypes.c_void_p, ctypes.c_void_p,<EOL>ctypes.c_void_p, ctypes.c_void_p,<EOL>ctypes.c_int]<EOL>f.restype = ctypes.c_void_p<EOL>return f(<NUM_LIT:0>, None, <NUM_LIT:2>, iodim.ctypes.data, vin.ptr, vout.ptr, None, FFTW_MEASURE)<EOL> | Create a plan for transposing internally to the pruned_FFT calculation.
(Alex to provide a write up with more details.)
Parameters
-----------
N1 : int
Number of rows.
N2 : int
Number of columns.
Returns
--------
plan : FFTWF plan
The plan for performing the FFTW transpose. | f16040:m0 |
def plan_first_phase(N1, N2): | N = N1*N2<EOL>vin = pycbc.types.zeros(N, dtype=numpy.complex64)<EOL>vout = pycbc.types.zeros(N, dtype=numpy.complex64)<EOL>f = float_lib.fftwf_plan_many_dft<EOL>f.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int,<EOL>ctypes.c_void_p, ctypes.c_void_p,<EOL>ctypes.c_int, ctypes.c_int,<EOL>ctypes.c_void_p, ctypes.c_void_p,<EOL>ctypes.c_int, ctypes.c_int,<EOL>ctypes.c_int, ctypes.c_int]<EOL>f.restype = ctypes.c_void_p<EOL>return f(<NUM_LIT:1>, ctypes.byref(ctypes.c_int(N2)), N1,<EOL>vin.ptr, None, <NUM_LIT:1>, N2,<EOL>vout.ptr, None, <NUM_LIT:1>, N2, FFTW_BACKWARD, FFTW_MEASURE)<EOL> | Create a plan for the first stage of the pruned FFT operation.
(Alex to provide a write up with more details.)
Parameters
-----------
N1 : int
Number of rows.
N2 : int
Number of columns.
Returns
--------
plan : FFTWF plan
The plan for performing the first phase FFT. | f16040:m1 |
def first_phase(invec, outvec, N1, N2): | global _theplan<EOL>if _theplan is None:<EOL><INDENT>_theplan = plan_first_phase(N1, N2)<EOL><DEDENT>fexecute(_theplan, invec.ptr, outvec.ptr)<EOL> | This implements the first phase of the FFT decomposition, using
the standard FFT many plans.
Parameters
-----------
invec : array
The input array.
outvec : array
The output array.
N1 : int
Number of rows.
N2 : int
Number of columns. | f16040:m2 |
def second_phase(invec, indices, N1, N2): | invec = numpy.array(invec.data, copy=False)<EOL>NI = len(indices) <EOL>N1=int(N1)<EOL>N2=int(N2)<EOL>out = numpy.zeros(len(indices), dtype=numpy.complex64)<EOL>code = """<STR_LIT>"""<EOL>weave.inline(code, ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>)<EOL>return out<EOL> | This is the second phase of the FFT decomposition that actually performs
the pruning. It is an explicit calculation for the subset of points. Note
that there seem to be some numerical accumulation issues at various values
of N1 and N2.
Parameters
----------
invec :
The result of the first phase FFT
indices : array of ints
The index locations to calculate the FFT
N1 : int
The length of the second phase "FFT"
N2 : int
The length of the first phase FFT
Returns
-------
out : array of floats | f16040:m3 |
def fast_second_phase(invec, indices, N1, N2): | invec = numpy.array(invec.data, copy=False)<EOL>NI = len(indices) <EOL>N1=int(N1)<EOL>N2=int(N2)<EOL>out = numpy.zeros(len(indices), dtype=numpy.complex64)<EOL>code = """<STR_LIT>"""<EOL>weave.inline(code, ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>extra_compile_args=[WEAVE_FLAGS])<EOL>return out<EOL> | This is the second phase of the FFT decomposition that actually performs
the pruning. It is an explicit calculation for the subset of points. Note
that there seem to be some numerical accumulation issues at various values
of N1 and N2.
Parameters
----------
invec :
The result of the first phase FFT
indices : array of ints
The index locations to calculate the FFT
N1 : int
The length of the second phase "FFT"
N2 : int
The length of the first phase FFT
Returns
-------
out : array of floats | f16040:m4 |
def fft_transpose_fftw(vec): | global _thetransposeplan<EOL>outvec = pycbc.types.zeros(len(vec), dtype=vec.dtype)<EOL>if _theplan is None:<EOL><INDENT>N1, N2 = splay(vec)<EOL>_thetransposeplan = plan_transpose(N1, N2)<EOL><DEDENT>ftexecute(_thetransposeplan, vec.ptr, outvec.ptr)<EOL>return outvec<EOL> | Perform an FFT transpose from vec into outvec.
(Alex to provide more details in a write-up.)
Parameters
-----------
vec : array
Input array.
Returns
--------
outvec : array
Transposed output array. | f16040:m5 |
def fft_transpose_numpy(vec): | N1, N2 = splay(vec)<EOL>return pycbc.types.Array(vec.data.copy().reshape(N2, N1).transpose().reshape(len(vec)).copy())<EOL> | Perform a numpy transpose from vec into outvec.
(Alex to provide more details in a write-up.)
Parameters
-----------
vec : array
Input array.
Returns
--------
outvec : array
Transposed output array. | f16040:m6 |
def splay(vec): | N2 = <NUM_LIT:2> ** int(numpy.log2( len(vec) ) / <NUM_LIT:2>)<EOL>N1 = len(vec) / N2<EOL>return N1, N2<EOL> | Determine two lengths to split stride the input vector by | f16040:m7 |
def pruned_c2cifft(invec, outvec, indices, pretransposed=False): | N1, N2 = splay(invec)<EOL>if not pretransposed:<EOL><INDENT>invec = fft_transpose(invec)<EOL><DEDENT>first_phase(invec, outvec, N1=N1, N2=N2)<EOL>out = fast_second_phase(outvec, indices, N1=N1, N2=N2)<EOL>return out<EOL> | Perform a pruned iFFT, only valid for power of 2 iffts as the
decomposition is easier to choose. This is not a strict requirement of the
functions, but it is unlikely to the optimal to use anything but power
of 2. (Alex to provide more details in write up.
Parameters
-----------
invec : array
The input vector. This should be the correlation between the data and
the template at full sample rate. Ideally this is pre-transposed, but
if not this will be transposed in this function.
outvec : array
The output of the first phase of the pruned FFT.
indices : array of ints
The indexes at which to calculate the full sample-rate SNR.
pretransposed : boolean, default=False
Used to indicate whether or not invec is pretransposed.
Returns
--------
SNRs : array
The complex SNRs at the indexes given by indices. | f16040:m8 |
def compile(source, name): | cache = os.path.join(pycbc._cache_dir_path, name)<EOL>hash_file = cache + "<STR_LIT>"<EOL>lib_file = cache + "<STR_LIT>"<EOL>obj_file = cache + "<STR_LIT>"<EOL>try:<EOL><INDENT>if int(open(hash_file, "<STR_LIT:r>").read()) == hash(source):<EOL><INDENT>return lib_file<EOL><DEDENT>raise ValueError<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>src_file = cache + "<STR_LIT>"<EOL>fsrc = open(src_file, "<STR_LIT:w>")<EOL>fsrc.write(source)<EOL>fsrc.close()<EOL>cmd = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", obj_file,<EOL>"<STR_LIT:-c>", src_file]<EOL>print("<STR_LIT:U+0020>".join(cmd))<EOL>subprocess.check_call(cmd)<EOL>cmd = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", lib_file, obj_file, "<STR_LIT>", "<STR_LIT>"]<EOL>print("<STR_LIT:U+0020>".join(cmd))<EOL>subprocess.check_call(cmd)<EOL>hash_file = cache + "<STR_LIT>"<EOL>fhash = open(hash_file, "<STR_LIT:w>")<EOL>fhash.write(str(hash(source)))<EOL>return lib_file<EOL> | Compile the string source code into a shared object linked against
the static version of cufft for callback support. | f16041:m0 |
def get_fn_plan(callback=None, out_callback=None, name='<STR_LIT>', parameters=None): | if parameters is None:<EOL><INDENT>parameters = []<EOL><DEDENT>source = fftsrc.render(input_callback=callback, output_callback=out_callback, parameters=parameters)<EOL>path = compile(source, name)<EOL>lib = ctypes.cdll.LoadLibrary(path)<EOL>fn = lib.execute<EOL>fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]<EOL>plan = lib.create_plan<EOL>plan.restype = ctypes.c_void_p<EOL>plan.argyptes = [ctypes.c_uint]<EOL>return fn, plan<EOL> | Get the IFFT execute and plan functions | f16041:m1 |
def ensurearray(*args): | input_is_array = any(isinstance(arg, numpy.ndarray) for arg in args)<EOL>args = numpy.broadcast_arrays(*args)<EOL>args.append(input_is_array)<EOL>return args<EOL> | Apply numpy's broadcast rules to the given arguments.
This will ensure that all of the arguments are numpy arrays and that they
all have the same shape. See ``numpy.broadcast_arrays`` for more details.
It also returns a boolean indicating whether any of the inputs were
originally arrays.
Parameters
----------
*args :
The arguments to check.
Returns
-------
list :
A list with length ``N+1`` where ``N`` is the number of given
arguments. The first N values are the input arguments as ``ndarrays``s.
The last value is a boolean indicating whether any of the
inputs was an array. | f16043:m0 |
def formatreturn(arg, input_is_array=False): | if not input_is_array and arg.size == <NUM_LIT:1>:<EOL><INDENT>arg = arg.item()<EOL><DEDENT>return arg<EOL> | If the given argument is a numpy array with shape (1,), just returns
that value. | f16043:m1 |
def sec_to_year(sec): | return sec / lal.YRJUL_SI<EOL> | Converts number of seconds to number of years | f16043:m2 |
def primary_mass(mass1, mass2): | mass1, mass2, input_is_array = ensurearray(mass1, mass2)<EOL>mp = copy.copy(mass1)<EOL>mask = mass1 < mass2<EOL>mp[mask] = mass2[mask]<EOL>return formatreturn(mp, input_is_array)<EOL> | Returns the larger of mass1 and mass2 (p = primary). | f16043:m3 |
def secondary_mass(mass1, mass2): | mass1, mass2, input_is_array = ensurearray(mass1, mass2)<EOL>if mass1.shape != mass2.shape:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>ms = copy.copy(mass2)<EOL>mask = mass1 < mass2<EOL>ms[mask] = mass1[mask]<EOL>return formatreturn(ms, input_is_array)<EOL> | Returns the smaller of mass1 and mass2 (s = secondary). | f16043:m4 |
def mtotal_from_mass1_mass2(mass1, mass2): | return mass1 + mass2<EOL> | Returns the total mass from mass1 and mass2. | f16043:m5 |
def q_from_mass1_mass2(mass1, mass2): | return primary_mass(mass1, mass2) / secondary_mass(mass1, mass2)<EOL> | Returns the mass ratio m1/m2, where m1 >= m2. | f16043:m6 |
def invq_from_mass1_mass2(mass1, mass2): | return secondary_mass(mass1, mass2) / primary_mass(mass1, mass2)<EOL> | Returns the inverse mass ratio m2/m1, where m1 >= m2. | f16043:m7 |
def eta_from_mass1_mass2(mass1, mass2): | return mass1*mass2 / (mass1+mass2)**<NUM_LIT><EOL> | Returns the symmetric mass ratio from mass1 and mass2. | f16043:m8 |
def mchirp_from_mass1_mass2(mass1, mass2): | return eta_from_mass1_mass2(mass1, mass2)**(<NUM_LIT>/<NUM_LIT:5>) * (mass1+mass2)<EOL> | Returns the chirp mass from mass1 and mass2. | f16043:m9 |
def mass1_from_mtotal_q(mtotal, q): | return q*mtotal / (<NUM_LIT:1.>+q)<EOL> | Returns a component mass from the given total mass and mass ratio.
If the mass ratio q is >= 1, the returned mass will be the primary
(heavier) mass. If q < 1, the returned mass will be the secondary
(lighter) mass. | f16043:m10 |
def mass2_from_mtotal_q(mtotal, q): | return mtotal / (<NUM_LIT:1.>+q)<EOL> | Returns a component mass from the given total mass and mass ratio.
If the mass ratio q is >= 1, the returned mass will be the secondary
(lighter) mass. If q < 1, the returned mass will be the primary (heavier)
mass. | f16043:m11 |
def mass1_from_mtotal_eta(mtotal, eta): | return <NUM_LIT:0.5> * mtotal * (<NUM_LIT:1.0> + (<NUM_LIT:1.0> - <NUM_LIT> * eta)**<NUM_LIT:0.5>)<EOL> | Returns the primary mass from the total mass and symmetric mass
ratio. | f16043:m12 |
def mass2_from_mtotal_eta(mtotal, eta): | return <NUM_LIT:0.5> * mtotal * (<NUM_LIT:1.0> - (<NUM_LIT:1.0> - <NUM_LIT> * eta)**<NUM_LIT:0.5>)<EOL> | Returns the secondary mass from the total mass and symmetric mass
ratio. | f16043:m13 |
def mtotal_from_mchirp_eta(mchirp, eta): | return mchirp / (eta**(<NUM_LIT>/<NUM_LIT>))<EOL> | Returns the total mass from the chirp mass and symmetric mass ratio. | f16043:m14 |
def mass1_from_mchirp_eta(mchirp, eta): | mtotal = mtotal_from_mchirp_eta(mchirp, eta)<EOL>return mass1_from_mtotal_eta(mtotal, eta)<EOL> | Returns the primary mass from the chirp mass and symmetric mass ratio. | f16043:m15 |
def mass2_from_mchirp_eta(mchirp, eta): | mtotal = mtotal_from_mchirp_eta(mchirp, eta)<EOL>return mass2_from_mtotal_eta(mtotal, eta)<EOL> | Returns the primary mass from the chirp mass and symmetric mass ratio. | f16043:m16 |
def _mass2_from_mchirp_mass1(mchirp, mass1): | a = mchirp**<NUM_LIT:5> / mass1**<NUM_LIT:3><EOL>roots = numpy.roots([<NUM_LIT:1>,<NUM_LIT:0>,-a,-a*mass1])<EOL>real_root = roots[(abs(roots - roots.real)).argmin()]<EOL>return real_root.real<EOL> | r"""Returns the secondary mass from the chirp mass and primary mass.
As this is a cubic equation this requires finding the roots and returning
the one that is real. Basically it can be shown that:
.. math::
m_2^3 - a(m_2 + m_1) = 0,
where
.. math::
a = \frac{\mathcal{M}^5}{m_1^3}.
This has 3 solutions but only one will be real. | f16043:m17 |
def _mass_from_knownmass_eta(known_mass, eta, known_is_secondary=False,<EOL>force_real=True): | roots = numpy.roots([eta, (<NUM_LIT:2>*eta - <NUM_LIT:1>)*known_mass, eta*known_mass**<NUM_LIT>])<EOL>if force_real:<EOL><INDENT>roots = numpy.real(roots)<EOL><DEDENT>if known_is_secondary:<EOL><INDENT>return roots[roots.argmax()]<EOL><DEDENT>else:<EOL><INDENT>return roots[roots.argmin()]<EOL><DEDENT> | r"""Returns the other component mass given one of the component masses
and the symmetric mass ratio.
This requires finding the roots of the quadratic equation:
.. math::
\eta m_2^2 + (2\eta - 1)m_1 m_2 + \eta m_1^2 = 0.
This has two solutions which correspond to :math:`m_1` being the heavier
mass or it being the lighter mass. By default, `known_mass` is assumed to
be the heavier (primary) mass, and the smaller solution is returned. Use
the `other_is_secondary` to invert.
Parameters
----------
known_mass : float
The known component mass.
eta : float
The symmetric mass ratio.
known_is_secondary : {False, bool}
Whether the known component mass is the primary or the secondary. If
True, `known_mass` is assumed to be the secondary (lighter) mass and
the larger solution is returned. Otherwise, the smaller solution is
returned. Default is False.
force_real : {True, bool}
Force the returned mass to be real.
Returns
-------
float
The other component mass. | f16043:m18 |
def mass2_from_mass1_eta(mass1, eta, force_real=True): | return mass_from_knownmass_eta(mass1, eta, known_is_secondary=False,<EOL>force_real=force_real)<EOL> | Returns the secondary mass from the primary mass and symmetric mass
ratio. | f16043:m19 |
def mass1_from_mass2_eta(mass2, eta, force_real=True): | return mass_from_knownmass_eta(mass2, eta, known_is_secondary=True,<EOL>force_real=force_real)<EOL> | Returns the primary mass from the secondary mass and symmetric mass
ratio. | f16043:m20 |
def eta_from_q(q): | return q / (<NUM_LIT:1.>+q)**<NUM_LIT:2><EOL> | r"""Returns the symmetric mass ratio from the given mass ratio.
This is given by:
.. math::
\eta = \frac{q}{(1+q)^2}.
Note that the mass ratio may be either < 1 or > 1. | f16043:m21 |
def mass1_from_mchirp_q(mchirp, q): | mass1 = (q**(<NUM_LIT>/<NUM_LIT>))*((<NUM_LIT:1.0> + q)**(<NUM_LIT:1.>/<NUM_LIT>))*mchirp<EOL>return mass1<EOL> | Returns the primary mass from the given chirp mass and mass ratio. | f16043:m22 |
def mass2_from_mchirp_q(mchirp, q): | mass2 = (q**(-<NUM_LIT>/<NUM_LIT>))*((<NUM_LIT:1.0> + q)**(<NUM_LIT:1.>/<NUM_LIT>))*mchirp<EOL>return mass2<EOL> | Returns the secondary mass from the given chirp mass and mass ratio. | f16043:m23 |
def _a0(f_lower): | return <NUM_LIT> / (<NUM_LIT> * (numpy.pi * f_lower)**(<NUM_LIT>/<NUM_LIT>))<EOL> | Used in calculating chirp times: see Cokelaer, arxiv.org:0706.4437
appendix 1, also lalinspiral/python/sbank/tau0tau3.py. | f16043:m24 |
def _a3(f_lower): | return numpy.pi / (<NUM_LIT> * (numpy.pi * f_lower)**(<NUM_LIT>/<NUM_LIT>))<EOL> | Another parameter used for chirp times | f16043:m25 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.