Return 2-pole Butterworth lowpass filter coefficients for center frequncy f_c (relative to sampling frequency)
770082
function filterCoeffs(f_c) {
  if (f_c > 0.5) {  // we can't lowpass above the nyquist frequency...
    f_c = 0.5;
  }
  var wct = Math.sqrt(2) * Math.PI * f_c;
  var e = Math.exp(-wct);
  var c = e * Math.cos(wct);
  var gain = (1 - 2*c + e*e) / 2;
  return [gain, 2*c, -e*e];
}
508213
def _fourier(self):
        

        freq_bin_upper = 2000
        freq_bin_lower = 40
        fs = self._metadata['fs']
        Y_transformed = {}
        for key in self.Y_dict.keys():
            # normalize by fs, bins have units strain/Hz
            fs = self._metadata["fs"]
            Y_transformed[key] = (1./fs)*np.fft.fft(self.Y_dict[key])[freq_bin_lower:freq_bin_upper]
        self.Y_transformed = Y_transformed
        # add in transform metadata
        self._metadata["dF"] = 1./self._metadata["T"]

        # because we are in the fourier domain, we will need the psd
        self.psd = load_psd()[freq_bin_lower:freq_bin_upper]
        dF = self._metadata['dF']
        self.sigma = convert_psd_to_sigma(self.psd, dF)
1219160
def _resample_obspy(samples, sr, newsr, window='hanning', lowpass=True):
    # type: (np.ndarray, int, int, str, bool) -> np.ndarray
    
    from scipy.signal import resample
    from math import ceil
    factor = sr/float(newsr)
    if newsr < sr and lowpass:
        # be sure filter still behaves good
        if factor > 16:
            logger.info("Automatic filter design is unstable for resampling "
                        "factors (current sampling rate/new sampling rate) " 
                        "above 16. Manual resampling is necessary.")
        freq = min(sr, newsr) * 0.5 / float(factor)
        logger.debug(f"resample_obspy: lowpass {freq}")
        samples = lowpass_cheby2(samples, freq=freq, sr=sr, maxorder=12)
    num = int(ceil(len(samples) / factor))

    return _applyMultichan(samples, 
                           lambda S: resample(S, num, window=window))
1310427
def pgv(self, centimeters=False):
        """"""
        if self._pgv is None:
            # Compute transfer function -- only over non-zero frequencies
            mask = ~np.isclose(self.angular_freqs, 0)
            tf = np.zeros_like(mask, dtype=np.complex)
            tf[mask] = 1 / (self.angular_freqs[mask] * 1j)
            if centimeters:
                self._pgv = GRAVITY * 100 * self.calc_peak(tf)
            else:
                self._pgv = GRAVITY * self.calc_peak(tf)
        return self._pgv
715485
def stSpectralCentroidAndSpread(X, fs):
    """"""
    ind = (numpy.arange(1, len(X) + 1)) * (fs/(2.0 * len(X)))

    Xt = X.copy()
    Xt = Xt / Xt.max()
    NUM = numpy.sum(ind * Xt)
    DEN = numpy.sum(Xt) + eps

    # Centroid:
    C = (NUM / DEN)

    # Spread:
    S = numpy.sqrt(numpy.sum(((ind - C) ** 2) * Xt) / DEN)

    # Normalize:
    C = C / (fs / 2.0)
    S = S / (fs / 2.0)

    return (C, S)
145848
def two_gaussian(freq, freq0_1, freq0_2, sigma1, sigma2, amp1, amp2,
                   offset, drift):
   
   return (gaussian(freq, freq0_1, sigma1, amp1, offset, drift) +
           gaussian(freq, freq0_2, sigma2, amp2, offset, drift))
49240
def get_waveform_filter_norm(approximant, psd, length, delta_f, f_lower):
    
    if approximant in _filter_norms:
        return _filter_norms[approximant](psd, length, delta_f, f_lower)
    else:
        return None
403428
def bandpass_filter(rate=None, low=None, high=None, order=None):
    """"""
    assert low < high
    assert order >= 1
    return signal.butter(order,
                         (low / (rate / 2.), high / (rate / 2.)),
                         'pass')
1192102
def highPassFilter(self, threshold):
        '''
        
        '''
        if not threshold:
            return
        rows, cols = self.img.shape
        tx = int(cols * threshold)
        ty = int(rows * threshold)
        # middle:
        crow, ccol = rows // 2, cols // 2
        # square in the middle to zero
        self.fshift[crow - tx:crow + tx, ccol - ty:ccol + ty] = 0
948197
def frequency_axis_ppm(self):
        
        return numpy.linspace(self.hertz_to_ppm(-self.sw / 2.0),
                              self.hertz_to_ppm(self.sw / 2.0),
                              self.np, endpoint=False)
1088391
def generate_with_delta_f_and_max_freq(self, t_num, max_freq, delta_f,
                                           low_frequency_cutoff=None,
                                           cached_mem=None):
        """"""
        approximant = self.approximant(t_num)
        # Don't want to use INTERP waveforms in here
        if approximant.endswith('_INTERP'):
            approximant = approximant.replace('_INTERP', '')
        # Using SPAtmplt here is bad as the stored cbrt and logv get
        # recalculated as we change delta_f values. Fall back to TaylorF2
        # in lalsimulation.
        if approximant == 'SPAtmplt':
            approximant = 'TaylorF2'
        if cached_mem is None:
            wav_len = int(max_freq / delta_f) + 1
            cached_mem = zeros(wav_len, dtype=np.complex64)
        if self.has_compressed_waveforms and self.enable_compressed_waveforms:
            htilde = self.get_decompressed_waveform(cached_mem, t_num,
                                                    f_lower=low_frequency_cutoff,
                                                    approximant=approximant,
                                                    df=delta_f)
        else :
            htilde = pycbc.waveform.get_waveform_filter(
                cached_mem, self.table[t_num], approximant=approximant,
                f_lower=low_frequency_cutoff, f_final=max_freq, delta_f=delta_f,
                distance=1./DYN_RANGE_FAC, delta_t=1./(2.*max_freq))
        return htilde
628829
def lowpass(var, key, factor):
    ''''''
    global lowpass_data
    if not key in lowpass_data:
        lowpass_data[key] = var
    else:
        lowpass_data[key] = factor*lowpass_data[key] + (1.0 - factor)*var
    return lowpass_data[key]
654557
def get_waveform_filter(out, template=None, **kwargs):
    
    n = len(out)

    input_params = props(template, **kwargs)

    if input_params['approximant'] in filter_approximants(_scheme.mgr.state):
        wav_gen = filter_wav[type(_scheme.mgr.state)]
        htilde = wav_gen[input_params['approximant']](out=out, **input_params)
        htilde.resize(n)
        htilde.chirp_length = get_waveform_filter_length_in_time(**input_params)
        htilde.length_in_time = htilde.chirp_length
        return htilde

    if input_params['approximant'] in fd_approximants(_scheme.mgr.state):
        wav_gen = fd_wav[type(_scheme.mgr.state)]

        duration = get_waveform_filter_length_in_time(**input_params)
        hp, _ = wav_gen[input_params['approximant']](duration=duration,
                                               return_hc=False, **input_params)

        hp.resize(n)
        out[0:len(hp)] = hp[:]
        hp = FrequencySeries(out, delta_f=hp.delta_f, copy=False)

        hp.length_in_time = hp.chirp_length = duration
        return hp

    elif input_params['approximant'] in td_approximants(_scheme.mgr.state):
        wav_gen = td_wav[type(_scheme.mgr.state)]
        hp, _ = wav_gen[input_params['approximant']](**input_params)
        # taper the time series hp if required
        if 'taper' in input_params.keys() and \
                input_params['taper'] is not None:
            hp = wfutils.taper_timeseries(hp, input_params['taper'],
                                          return_lal=False)
        return td_waveform_to_fd_waveform(hp, out=out)

    else:
        raise ValueError("Approximant %s not available" %
                            (input_params['approximant']))
65548
def gaussian(freq, freq0, sigma, amp, offset, drift):
    
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return (amp * np.exp(- ((freq - freq0)**2) / (sigma**2) ) +
                drift * freq + offset)
654706
def _get_sampling_freq(self, r):
        """"""

        samplingFrequencyIndex = r.bits(4)
        if samplingFrequencyIndex == 0xf:
            samplingFrequency = r.bits(24)
        else:
            try:
                samplingFrequency = self._FREQS[samplingFrequencyIndex]
            except IndexError:
                samplingFrequency = 0
        return samplingFrequency
1192579
def getPermutedTensors(W, kw, n, m2, noisePct):
  
  W2 = W.repeat(m2, 1)
  nz = W[0].nonzero()
  numberToZero = int(round(noisePct * kw))
  for i in range(m2):
    indices = np.random.permutation(kw)[0:numberToZero]
    for j in indices:
      W2[i,nz[j]] = 0
  return W2
595924
def find_variable_start_frequency(approximant, parameters, f_start, max_length,
                                  delta_f = 1):
    
    l = max_length + 1
    f = f_start - delta_f
    while l > max_length:
        f += delta_f
        l = pycbc.waveform.get_waveform_filter_length_in_time(approximant,
                                                      parameters, f_lower=f)
    return f