Generates a simple linear chirp.

    :param npts: Number of samples.
    :type npts: int
    :returns: Generated signal
    :rtype: numpy.ndarray
352984
def linear_chirp(npts=2000):
    
    time = np.linspace(0, 20, npts)
    chirp = np.sin(0.2 * np.pi * (0.1 + 24.0 / 2.0 * time) * time)
    return chirp
869159
def basic_generator(in_size:int, n_channels:int, noise_sz:int=100, n_features:int=64, n_extra_layers=0, **conv_kwargs):
    ""
    cur_size, cur_ftrs = 4, n_features//2
    while cur_size < in_size:  cur_size *= 2; cur_ftrs *= 2
    layers = [conv_layer(noise_sz, cur_ftrs, 4, 1, transpose=True, **conv_kwargs)]
    cur_size = 4
    while cur_size < in_size // 2:
        layers.append(conv_layer(cur_ftrs, cur_ftrs//2, 4, 2, 1, transpose=True, **conv_kwargs))
        cur_ftrs //= 2; cur_size *= 2
    layers += [conv_layer(cur_ftrs, cur_ftrs, 3, 1, 1, transpose=True, **conv_kwargs) for _ in range(n_extra_layers)]
    layers += [conv2d_trans(cur_ftrs, n_channels, 4, 2, 1, bias=False), nn.Tanh()]
    return nn.Sequential(*layers)
797996
def sinusoid(freq, phase=0.):
  
  # When at 44100 samples / sec, 5 seconds of this leads to an error of 8e-14
  # peak to peak. That's fairly enough.
  for n in modulo_counter(start=phase, modulo=2 * pi, step=freq):
    yield sin(n)
915354
def noise(params, amplitude=1, offset=0):
    '''
    
    '''
    amplitude = create_buffer(params, amplitude)
    offset = create_buffer(params, offset)
    output = offset + amplitude * (np.random.random(params.length)*2 - 1)
    return output
622672
def _resample_samplerate(samples, sr, newsr):
    # type: (np.ndarray, int, int, str) -> np.ndarray
    
    try:
        from samplerate import resample
    except ImportError:
        return None

    ratio = newsr/sr
    return _applyMultichan(samples,
                           lambda S: resample(S, ratio, 'sinc_best'))
777449
def calc_spectrum(signal, rate):
    """"""
    npts = len(signal)
    padto = 1 << (npts - 1).bit_length()
    # print 'length of signal {}, pad to {}'.format(npts, padto)
    npts = padto

    sp = np.fft.rfft(signal, n=padto) / npts
    # print('sp len ', len(sp))
    freq = np.arange((npts / 2) + 1) / (npts / rate)
    # print('freq len ', len(freq))
    return freq, abs(sp)
407639
def multiply_frequencies(signal, fs, frange, calibration_frequencies, attendB):
    """"""
    npts = len(signal)
    padto = 1 << (npts - 1).bit_length()

    X = np.fft.rfft(signal, n=padto)

    npts = padto
    f = np.arange((npts / 2) + 1) / (npts / fs)

    fidx_low = (np.abs(f - frange[0])).argmin()
    fidx_high = (np.abs(f - frange[1])).argmin()

    cal_func = interp1d(calibration_frequencies, attendB)
    roi = f[fidx_low:fidx_high]
    Hroi = cal_func(roi)
    H = np.zeros((len(X),))
    H[fidx_low:fidx_high] = Hroi

    H = smooth(H)
    # print 'H dB max', np.amax(H)

    H = 10 ** ((H).astype(float) / 20)
    # print 'H amp max', np.amax(H)

    # Xadjusted = X.copy()
    # Xadjusted[fidx_low:fidx_high] *= H
    # Xadjusted = smooth(Xadjusted)

    Xadjusted = X * H
    # print 'X max', np.amax(abs(X))
    # print 'Xadjusted max', np.amax(abs(Xadjusted))

    signal_calibrated = np.fft.irfft(Xadjusted)
    return signal_calibrated[:len(signal)]
622172
def impulse_response(self, impulse_length=30):
        
        from scipy.signal import dimpulse
        sys = self.ma_poly, self.ar_poly, 1
        times, psi = dimpulse(sys, n=impulse_length)
        psi = psi[0].flatten()  # Simplify return value into flat array

        return psi
1163746
def rms(signal, fs):
    
    # if a signal contains a some silence, taking the RMS of the whole
    # signal will be calculated as less loud as a signal without a silent
    # period. I don't like this, so I am going to chunk the signals, and
    # take the value of the most intense chunk
    chunk_time = 0.001  # 1 ms chunk
    chunk_samps = int(chunk_time * fs)
    amps = []
    if chunk_samps > 10:
        for i in range(0, len(signal) - chunk_samps, chunk_samps):
            amps.append(np.sqrt(np.mean(pow(signal[i:i + chunk_samps], 2))))
        amps.append(np.sqrt(np.mean(pow(signal[len(signal) - chunk_samps:], 2))))
        return np.amax(amps)
    else:
        # samplerate low, just rms the whole thing
        return np.sqrt(np.mean(pow(signal, 2)))
303643
def pseudosample(x):
    
#
    BXs = []
    for k in range(len(x)):
        ind = random.randint(0, len(x) - 1)
        BXs.append(x[ind])
    return BXs
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
424521
def gtlike_spectrum_to_vectors(spectrum):
    


    parameters = pyLike.ParameterVector()
    spectrum.getParams(parameters)

    npar = max(parameters.size(), 10)
    o = {'param_names': np.zeros(npar, dtype='S32'),
         'param_values': np.empty(npar, dtype=float) * np.nan,
         'param_errors': np.empty(npar, dtype=float) * np.nan,
         }

    for i, p in enumerate(parameters):
        o['param_names'][i] = p.getName()
        o['param_values'][i] = p.getTrueValue()
        perr = abs(p.error() * p.getScale()) if p.isFree() else np.nan
        o['param_errors'][i] = perr

    return o
242204
def ttotdev(data, rate=1.0, data_type="phase", taus=None):
    

    (taus, mtotdevs, mde, ns) = mtotdev(data, data_type=data_type,
                                        rate=rate, taus=taus)
    td = taus*mtotdevs / np.sqrt(3.0)
    tde = td / np.sqrt(ns)
    return taus, td, tde, ns
49550
def gen_psi(self, x):
        
   
        if isinstance(x, np.ndarray):
            x = x[:,None]
        return np.exp(-self.h * (x - self.c)**2)
1030258
def _create_waveforms(self):
        

        # find eccentricity and semi major axis over time until e=0.
        e_vals, a_vals, t_vals = self._t_of_e(a0=self.a0, f0=self.f0,
                                              t_start=self.t_start, ef=None,
                                              t_obs=self.t_obs)

        f_mrg = 0.02/(self.m1 + self.m2)
        a_mrg = ((self.m1+self.m2)/f_mrg**2)**(1/3)

        # limit highest frequency to ISCO even though this is not innermost orbit for eccentric
        # binaries
        # find where binary goes farther than observation time or merger frequency limit.
        a_ind_start = np.asarray([np.where(a_vals[i] > a_mrg[i])[0][0] for i in range(len(a_vals))])
        t_ind_start = np.asarray([np.where(t_vals[i] < self.t_obs[i])[0][0]
                                 for i in range(len(t_vals))])

        ind_start = (a_ind_start*(a_ind_start >= t_ind_start)
                     + t_ind_start*(a_ind_start < t_ind_start))

        self.ef = np.asarray([e_vals[i][ind] for i, ind in enumerate(ind_start)])

        # higher resolution over the eccentricities seen during observation
        self.e_vals, self.a_vals, self.t_vals = self._t_of_e(a0=a_vals[:, -1],
                                                             ef=self.ef,
                                                             t_obs=self.t_obs)

        self.freqs_orb = np.sqrt((self.m1[:, np.newaxis]+self.m2[:, np.newaxis])/self.a_vals**3)

        # tile for efficient calculation across modes.
        for attr in ['e_vals', 'a_vals', 't_vals', 'freqs_orb']:
            arr = getattr(self, attr)
            new_arr = (np.flip(
                       np.tile(arr, self.n_max).reshape(len(arr)*self.n_max, len(arr[0])), -1))
            setattr(self, attr, new_arr)

        for attr in ['m1', 'm2', 'z', 'dist']:
            arr = getattr(self, attr)
            new_arr = np.repeat(arr, self.n_max)[:, np.newaxis]
            setattr(self, attr, new_arr)

        # setup modes
        self.n = np.tile(np.arange(1, self.n_max + 1), self.length)[:, np.newaxis]

        self._hcn_func()

        # reshape hc
        self.hc = self.hc.reshape(self.length, self.n_max, self.hc.shape[-1])
        self.freqs = np.reshape(self.n*self.freqs_orb/(1+self.z)
                                * ct.c,
                                (self.length, self.n_max, self.freqs_orb.shape[-1]))

        self.hc, self.freqs = np.squeeze(self.hc), np.squeeze(self.freqs)
        return
944505
def run(self):
        

        eta = self.settings['noise_strength']
        gamma = 2 * np.pi * self.settings['noise_bandwidth']
        dt = 1. / self.settings['update frequency']
        control = self.settings['control']

        self._state = self._output
        while self._stop is False:

            A = -gamma * dt

            noise = np.sqrt(2*gamma*eta)*np.random.randn()
            self._state *= (1. + A)
            self._state += noise + control
            self._output =  self._state

            self.msleep(int(1e3 / self.settings['update frequency']))
1315741
def resample(self, target_sr):
        
        y_hat = librosa.core.resample(self.y, self.sr, target_sr)
        return Sound(y_hat, target_sr)