jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def get_power(wave, frame_rate, frame_length, frame_move, window_func=None):
    frame = frame_rate * frame_length
    overlap = frame_rate * frame_move
    step = frame - overlap
    frame_total = int(math.ceil(len(wave) / step))
    energy = np.zeros(frame_total)
    for i in range(frame_total):
        window = wave[np.arange(i * step, min(i * step + frame, len(wave)))]
        if window_func == "hanning":
            energy[i] = sum(np.multiply(window ** 2, scipy.signal.windows.hann(len(window))))
        else:
            energy[i] = sum(window ** 2)
    return energy
//  [python]
def istft(X,  T, hopsamp=64):
    x = scipy.zeros(T)
    weights = scipy.zeros(T)
    framesamp = X.shape[1]
    w = scipy.signal.hanning(framesamp, False)
    w = np.sqrt(w)

    for n,i in enumerate(range(0, len(x)-framesamp+1, hopsamp)):
        x[i:i+framesamp] += w*scipy.real(scipy.ifft(X[n]))
        weights[i:i+framesamp] += w**2

    weights[weights==0] = 1
    x = x/weights

    return x
//  [python]
def istft(X,  T, hopsamp=64):
    x = scipy.zeros(T)
    weights = scipy.zeros(T)
    framesamp = X.shape[1]
    w = scipy.signal.windows.hann(framesamp, False)
    w = np.sqrt(w)

    for n,i in enumerate(range(0, len(x)-framesamp+1, hopsamp)):
        x[i:i+framesamp] += w*scipy.real(scipy.ifft(X[n]))
        weights[i:i+framesamp] += w**2

    weights[weights==0] = 1
    x = x/weights

    return x
//  [python]
def onset_detection_fn(x, f_win_size, f_hop_size, f_bins_per_octave, f_octaves, f_fmin, sr, mean_filter_size):
    """
    Filter bank for onset pattern calculation
    """
    # calculate frequency constant-q transform
    f_win = scipy.signal.hanning(f_win_size)
    x_spec = librosa.stft(x,
                          n_fft=f_win_size,
                          hop_length=f_hop_size,
                          win_length=f_win_size,
                          window=f_win)
    x_spec = np.abs(x_spec) / (2 * np.sum(f_win))

    f_cq_mat = cq_matrix(f_bins_per_octave, f_octaves * f_bins_per_octave, f_fmin, f_win_size, sr)
    x_cq_spec = np.dot(f_cq_mat, x_spec[:-1, :])

    # subtract moving mean
    b = np.concatenate([[1], np.ones(mean_filter_size, dtype=float) / -mean_filter_size])
    od_fun = scipy.signal.lfilter(b, 1, x_cq_spec, axis=1)

    # half-wave rectify
    od_fun = np.maximum(0, od_fun)

    # post-process OPs
    od_fun = np.log10(1 + 1000*od_fun)
    return od_fun, x_cq_spec
//  [python]
def onset_detection_fn(x, f_win_size, f_hop_size, f_bins_per_octave, f_octaves, f_fmin, sr, mean_filter_size):
    """
    Filter bank for onset pattern calculation
    """
    # calculate frequency constant-q transform
    f_win = scipy.signal.windows.hann(f_win_size)
    x_spec = librosa.stft(x,
                          n_fft=f_win_size,
                          hop_length=f_hop_size,
                          win_length=f_win_size,
                          window=f_win)
    x_spec = np.abs(x_spec) / (2 * np.sum(f_win))

    f_cq_mat = cq_matrix(f_bins_per_octave, f_octaves * f_bins_per_octave, f_fmin, f_win_size, sr)
    x_cq_spec = np.dot(f_cq_mat, x_spec[:-1, :])

    # subtract moving mean
    b = np.concatenate([[1], np.ones(mean_filter_size, dtype=float) / -mean_filter_size])
    od_fun = scipy.signal.lfilter(b, 1, x_cq_spec, axis=1)

    # half-wave rectify
    od_fun = np.maximum(0, od_fun)

    # post-process OPs
    od_fun = np.log10(1 + 1000*od_fun)
    return od_fun, x_cq_spec
//  [python]
def compute(self):
        size = self.get_input("Window Size")
        out = NDArray()
        out.set_array(scipy.signal.hanning(size))
        self.set_output("Window", out)
//  [python]
def compute(self):
        size = self.get_input("Window Size")
        out = NDArray()
        out.set_array(scipy.signal.windows.hann(size))
        self.set_output("Window", out)
//  [python]
def WindowDataSeries(series, window=None):

  """
    Apply window function to data set, defaults to Hanning window.
  """

  # generate default window
  if window == None:
    window = scipy.signal.hanning(len(series))

  # check dimensions
  assert len(series)==len(window), 'Window and data must be same shape'

  # get sum of squares
  sumofsquares = (window**2).sum()
  assert sumofsquares > 0, 'Sum of squares of window non-positive.'

  # generate norm
  norm = (len(window)/sumofsquares)**(1/2)

  # apply window
  return series * window * norm
//  [python]
def WindowDataSeries(series, window=None):

  """
    Apply window function to data set, defaults to Hanning window.
  """

  # generate default window
  if window == None:
    window = scipy.signal.windows.hann(len(series))

  # check dimensions
  assert len(series)==len(window), 'Window and data must be same shape'

  # get sum of squares
  sumofsquares = (window**2).sum()
  assert sumofsquares > 0, 'Sum of squares of window non-positive.'

  # generate norm
  norm = (len(window)/sumofsquares)**(1/2)

  # apply window
  return series * window * norm
//  [python]
def smooth(x, window='boxcar', half_win=3):
    """ some window smoothing from MSnoise MWCS """
    window_len = 2*half_win+1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype(x.dtype)
    else:
        w = scipy.signal.hanning(window_len).astype(x.dtype)

    if x.ndim ==1:
        s = np.r_[x[window_len-1:0:-1], x, x[-1:-window_len:-1]]
        y = np.convolve(w/w.sum(), s, mode='valid')
        y = y[half_win:len(y)-half_win]
    elif x.ndim == 2:
        y = np.zeros(x.shape,x.dtype)
        for ii,row in enumerate(x):
            s = np.r_[row[window_len-1:0:-1], row, row[-1:-window_len:-1]]
            tmp = np.convolve(w/w.sum(), s, mode='valid')
            y[ii,:] = tmp[half_win:len(tmp)-half_win]
    return y
//  [python]
def smooth(x, window='boxcar', half_win=3):
    """ some window smoothing from MSnoise MWCS """
    window_len = 2*half_win+1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype(x.dtype)
    else:
        w = scipy.signal.windows.hann(window_len).astype(x.dtype)

    if x.ndim ==1:
        s = np.r_[x[window_len-1:0:-1], x, x[-1:-window_len:-1]]
        y = np.convolve(w/w.sum(), s, mode='valid')
        y = y[half_win:len(y)-half_win]
    elif x.ndim == 2:
        y = np.zeros(x.shape,x.dtype)
        for ii,row in enumerate(x):
            s = np.r_[row[window_len-1:0:-1], row, row[-1:-window_len:-1]]
            tmp = np.convolve(w/w.sum(), s, mode='valid')
            y[ii,:] = tmp[half_win:len(tmp)-half_win]
    return y
//  [python]
def __init__(self, ps, vox, PSSize):
        ps = ps.max(2)
        ps = ps - ps.min()

        ps = ps*scipy.signal.hanning(ps.shape[0])[:,None]*scipy.signal.hanning(ps.shape[1])[None,:]
        ps = ps/ps.sum()
        #PSFFileName = PSFFilename

        pw = (numpy.array(PSSize) - ps.shape)/2.
        pw1 = numpy.floor(pw)
        pw2 = numpy.ceil(pw)

        self.cachedPSF = pad.with_constant(ps, ((pw2[0], pw1[0]), (pw2[1], pw1[1])), (0,))
        self.cachedOTFH = (ifftn(self.cachedPSF)*self.cachedPSF.size).astype('complex64')
        self.cachedOTF2 = (self.cachedOTFH*fftn(self.cachedPSF)).astype('complex64')

        self.weinerFT = fftw3.create_aligned_array(self.cachedOTFH.shape, 'complex64')
        self.weinerR = fftw3.create_aligned_array(self.cachedOTFH.shape, 'float32')

        self.planForward = fftw3.Plan(self.weinerR, self.weinerFT, flags = FFTWFLAGS, nthreads=NTHREADS)
        self.planInverse = fftw3.Plan(self.weinerFT, self.weinerR, direction='reverse', flags = FFTWFLAGS, nthreads=NTHREADS)
        
        fftwWisdom.save_wisdom()
        
        self.otf2mean = self.cachedOTF2.mean()
//  [python]
def __init__(self, ps, vox, PSSize):
        ps = ps.max(2)
        ps = ps - ps.min()

        ps = ps*scipy.signal.windows.hann(ps.shape[0])[:,None]*scipy.signal.windows.hann(ps.shape[1])[None,:]
        ps = ps/ps.sum()
        #PSFFileName = PSFFilename

        pw = (numpy.array(PSSize) - ps.shape)/2.
        pw1 = numpy.floor(pw)
        pw2 = numpy.ceil(pw)

        self.cachedPSF = pad.with_constant(ps, ((pw2[0], pw1[0]), (pw2[1], pw1[1])), (0,))
        self.cachedOTFH = (ifftn(self.cachedPSF)*self.cachedPSF.size).astype('complex64')
        self.cachedOTF2 = (self.cachedOTFH*fftn(self.cachedPSF)).astype('complex64')

        self.weinerFT = fftw3.create_aligned_array(self.cachedOTFH.shape, 'complex64')
        self.weinerR = fftw3.create_aligned_array(self.cachedOTFH.shape, 'float32')

        self.planForward = fftw3.Plan(self.weinerR, self.weinerFT, flags = FFTWFLAGS, nthreads=NTHREADS)
        self.planInverse = fftw3.Plan(self.weinerFT, self.weinerR, direction='reverse', flags = FFTWFLAGS, nthreads=NTHREADS)
        
        fftwWisdom.save_wisdom()
        
        self.otf2mean = self.cachedOTF2.mean()
//  [python]
def analyze_spectrum(signal,npoints):
	"""Computes FFT for the signal, discards the zero freq and the
	above-Nyquist freqs. Auto-pads signals nonmultple of npoints,
	auto-averages results from streams longer than npoints.
	Thus, npoints results in npoints/2 bands.

	Returns a numpy array, each element represents the raw amplitude
	of a frequency band.
	"""

	signal = signal.copy()
	if divmod(len(signal),npoints)[1] != 0:
		round_up = len(signal) / npoints * npoints + npoints
		signal.resize( round_up )

	window = scipy.signal.hanning(npoints)
	window_blocks = scipy.vstack( [ window for x in xrange(len(signal) / npoints) ] )

	signal_blocks = signal.reshape((-1,npoints))

	windowed_signals = signal_blocks * window_blocks

	ffts = numpy.fft.rfft(windowed_signals)[:,1:]

	result = pow(abs(ffts),2) / npoints
	result = result.mean(0)

	return result
//  [python]
def analyze_spectrum(signal,npoints):
	"""Computes FFT for the signal, discards the zero freq and the
	above-Nyquist freqs. Auto-pads signals nonmultple of npoints,
	auto-averages results from streams longer than npoints.
	Thus, npoints results in npoints/2 bands.

	Returns a numpy array, each element represents the raw amplitude
	of a frequency band.
	"""

	signal = signal.copy()
	if divmod(len(signal),npoints)[1] != 0:
		round_up = len(signal) / npoints * npoints + npoints
		signal.resize( round_up )

	window = scipy.signal.windows.hann(npoints)
	window_blocks = scipy.vstack( [ window for x in xrange(len(signal) / npoints) ] )

	signal_blocks = signal.reshape((-1,npoints))

	windowed_signals = signal_blocks * window_blocks

	ffts = numpy.fft.rfft(windowed_signals)[:,1:]

	result = pow(abs(ffts),2) / npoints
	result = result.mean(0)

	return result
//  [python]
def _hanning(Ni,Nj):
    ''' Using Hanning window'''
    wdwi =  signal.hanning(Ni,sym=False)
    wdwj =  signal.hanning(Nj,sym=False)
    wdw = wdwi[np.newaxis,...]*wdwj[...,np.newaxis]
    return wdw
//  [python]
def _hanning(Ni,Nj):
    ''' Using Hanning window'''
    wdwi =  signal.windows.hann(Ni,sym=False)
    wdwj =  signal.windows.hann(Nj,sym=False)
    wdw = wdwi[np.newaxis,...]*wdwj[...,np.newaxis]
    return wdw
//  [python]
FLOATX = 'float32'
COMPLEXX = dict(float32='complex64', float64='complex128')[FLOATX]
FFT_SIZE = 256
FFT_STRIDE = 64
FFT_WND = np.sqrt(signal.hanning(FFT_SIZE))
//  [python]
FLOATX = 'float32'
COMPLEXX = dict(float32='complex64', float64='complex128')[FLOATX]
FFT_SIZE = 256
FFT_STRIDE = 64
FFT_WND = np.sqrt(signal.windows.hann(FFT_SIZE))
//  [python]
def inverse_stft(stfts,
                 frame_length=256,
                 frame_step=64,
                 fft_length=256):

    with tf.variable_scope("ISTFT"):

        fft_len = fft_length
        stfts = ops.convert_to_tensor(stfts, name='stfts')
        frame_length = ops.convert_to_tensor(frame_length, name='frame_length')
        frame_step = ops.convert_to_tensor(frame_step, name='frame_step')
        fft_length = ops.convert_to_tensor(fft_length, name='fft_length')
        real_frames = tf.signal.irfft(stfts, [fft_length])

        # Declare the window function.
        window = scipy.signal.hanning(fft_len, False)
        non_zero_value = window[1].astype('float32')
        tf_non_zero = tf.constant(non_zero_value, name="tf_non_zero", dtype=tf.float32)

        window = np.sqrt(window)
        window = window.reshape(1,1,fft_len).astype('float32')
        tf_window = tf.constant(window, name="tf_window", dtype=tf.float32)
        real_frames *= tf_window
        stft_weights = tf.ones_like(real_frames,dtype=tf.float32)
        stft_weights *= (tf_window * tf_window)

        time_sig = overlap_and_add(real_frames, frame_step)
        time_weights = overlap_and_add(stft_weights, frame_step)
        time_weights = tf.maximum(time_weights, non_zero_value)

        time_sig = time_sig /time_weights
        return time_sig
//  [python]
def inverse_stft(stfts,
                 frame_length=256,
                 frame_step=64,
                 fft_length=256):

    with tf.variable_scope("ISTFT"):

        fft_len = fft_length
        stfts = ops.convert_to_tensor(stfts, name='stfts')
        frame_length = ops.convert_to_tensor(frame_length, name='frame_length')
        frame_step = ops.convert_to_tensor(frame_step, name='frame_step')
        fft_length = ops.convert_to_tensor(fft_length, name='fft_length')
        real_frames = tf.signal.irfft(stfts, [fft_length])

        # Declare the window function.
        window = scipy.signal.windows.hann(fft_len, False)
        non_zero_value = window[1].astype('float32')
        tf_non_zero = tf.constant(non_zero_value, name="tf_non_zero", dtype=tf.float32)

        window = np.sqrt(window)
        window = window.reshape(1,1,fft_len).astype('float32')
        tf_window = tf.constant(window, name="tf_window", dtype=tf.float32)
        real_frames *= tf_window
        stft_weights = tf.ones_like(real_frames,dtype=tf.float32)
        stft_weights *= (tf_window * tf_window)

        time_sig = overlap_and_add(real_frames, frame_step)
        time_weights = overlap_and_add(stft_weights, frame_step)
        time_weights = tf.maximum(time_weights, non_zero_value)

        time_sig = time_sig /time_weights
        return time_sig
//  [python]
def win_sel(win_str, win_size):
    """
        Function returns a window vector based on window name.
        Note class can only use windows found in scipy.signal library.
    """
    if (win_str == 'blackmanharris'):
        win = sig.blackmanharris(win_size)
    elif (win_str == 'blackman'):
        win = sig.blackman(win_size)
    elif (win_str == 'bartlett'):
        win = sig.bartlett(win_size)
    elif (win_str == 'hamming'):
        win = sig.hamming(win_size)
    elif (win_str == 'hanning'):
        win = sig.hanning(win_size)
    elif (win_str == 'hann'):
        win = sig.hann(win_size)
    elif (win_str == 'barthann'):
        win = sig.barthann(win_size)
    elif (win_str == 'triang'):
        win = sig.triang(win_size)
    elif (win_str == 'rect'):
        win = np.ones(win_size)
    else:
        print('Invalid Window Defined')
        return -1
    return win
//  [python]
def win_sel(win_str, win_size):
    """
        Function returns a window vector based on window name.
        Note class can only use windows found in scipy.signal library.
    """
    if (win_str == 'blackmanharris'):
        win = sig.blackmanharris(win_size)
    elif (win_str == 'blackman'):
        win = sig.blackman(win_size)
    elif (win_str == 'bartlett'):
        win = sig.bartlett(win_size)
    elif (win_str == 'hamming'):
        win = sig.hamming(win_size)
    elif (win_str == 'hanning'):
        win = sig.windows.hann(win_size)
    elif (win_str == 'hann'):
        win = sig.windows.hann(win_size)
    elif (win_str == 'barthann'):
        win = sig.barthann(win_size)
    elif (win_str == 'triang'):
        win = sig.triang(win_size)
    elif (win_str == 'rect'):
        win = np.ones(win_size)
    else:
        print('Invalid Window Defined')
        return -1
    return win
//  [python]
def melody_extension_audio(SSM):
    melody_ext = np.zeros(SSM.shape[0])
    melody_ext[0] = 1
    for i in range(1,SSM.shape[0]):
        melody_ext[i] = (SSM[i,i]-np.amax(SSM[i,:i]))
        
    melody_ext = np.convolve(melody_ext, scipy.signal.hanning(20), mode='same')
    melody_ext = melody_ext/np.amax(melody_ext)
    return melody_ext
//  [python]
def melody_extension_audio(SSM):
    melody_ext = np.zeros(SSM.shape[0])
    melody_ext[0] = 1
    for i in range(1,SSM.shape[0]):
        melody_ext[i] = (SSM[i,i]-np.amax(SSM[i,:i]))
        
    melody_ext = np.convolve(melody_ext, scipy.signal.windows.hann(20), mode='same')
    melody_ext = melody_ext/np.amax(melody_ext)
    return melody_ext
//  [python]
def struct_boundary(SSM):
    sw = 40 # search width to find boundaries in the SSM
    M = SSM.shape[0]
    boundary = np.zeros(M)
    for i in range(7,M-7):      
        boundary[i] = np.mean(SSM[max(i-sw,0):i,max(i-sw,0):i])+np.mean(SSM[i+1:min(i+sw,M),i+1:min(i+sw,M)])-\
                    np.mean(SSM[max(i-sw,0):i,i+1:min(i+sw,M)])-np.mean(SSM[i+1:min(i+sw,M),max(i-sw,0):i])

    boundary = np.convolve(boundary, scipy.signal.hanning(sw)/sw, mode='same')
    boundary = boundary/np.amax(boundary)    
    print(boundary.shape)
    print(boundary)
    return boundary
//  [python]
def struct_boundary(SSM):
    sw = 40 # search width to find boundaries in the SSM
    M = SSM.shape[0]
    boundary = np.zeros(M)
    for i in range(7,M-7):      
        boundary[i] = np.mean(SSM[max(i-sw,0):i,max(i-sw,0):i])+np.mean(SSM[i+1:min(i+sw,M),i+1:min(i+sw,M)])-\
                    np.mean(SSM[max(i-sw,0):i,i+1:min(i+sw,M)])-np.mean(SSM[i+1:min(i+sw,M),max(i-sw,0):i])

    boundary = np.convolve(boundary, scipy.signal.windows.hann(sw)/sw, mode='same')
    boundary = boundary/np.amax(boundary)    
    print(boundary.shape)
    print(boundary)
    return boundary
//  [python]
def repetition(SSM):
    sw = 20 # The search range (search width) to find repetition in the SSM        
    qfactor = np.zeros(SSM.shape[0]) 
    for i in range(1,int(SSM.shape[0]-sw/2-1)):
        trigger = 0
        num_of_peaks = 0
        for j in range(i+1, min(i+sw, SSM.shape[0]-1)): #max(i-sw,1)
            if SSM[i,j]>SSM[i,j-1] and SSM[i,j]>=np.amax(SSM)/2.0:
                trigger = 1
            elif SSM[i,j]<SSM[i,j-1] and trigger == 1:
                num_of_peaks = num_of_peaks + 1
                trigger = 0
        qfactor[int(i+sw/2)]= np.mean(SSM[i,i+1:min(i+sw, SSM.shape[0]-1)])*(num_of_peaks) # max(i-sw,1)#        

    qfactor = np.convolve(qfactor, scipy.signal.hanning(sw*2)/sw, mode='same')
    qfactor = qfactor/np.amax(qfactor)
    
    return qfactor
//  [python]
def repetition(SSM):
    sw = 20 # The search range (search width) to find repetition in the SSM        
    qfactor = np.zeros(SSM.shape[0]) 
    for i in range(1,int(SSM.shape[0]-sw/2-1)):
        trigger = 0
        num_of_peaks = 0
        for j in range(i+1, min(i+sw, SSM.shape[0]-1)): #max(i-sw,1)
            if SSM[i,j]>SSM[i,j-1] and SSM[i,j]>=np.amax(SSM)/2.0:
                trigger = 1
            elif SSM[i,j]<SSM[i,j-1] and trigger == 1:
                num_of_peaks = num_of_peaks + 1
                trigger = 0
        qfactor[int(i+sw/2)]= np.mean(SSM[i,i+1:min(i+sw, SSM.shape[0]-1)])*(num_of_peaks) # max(i-sw,1)#        

    qfactor = np.convolve(qfactor, scipy.signal.windows.hann(sw*2)/sw, mode='same')
    qfactor = qfactor/np.amax(qfactor)
    
    return qfactor
//  [python]
plt.xlabel('Time (s)')
plt.ylabel('Signal')
plt.show()

nfft = N//10
win = signal.hanning(nfft)
//  [python]
plt.xlabel('Time (s)')
plt.ylabel('Signal')
plt.show()

nfft = N//10
win = signal.windows.hann(nfft)
//  [python]
def genhanning(n):
    w = s.hanning(n,sym=False)
    return(w)
//  [python]
def genhanning(n):
    w = win.hann(n,sym=False)
    return(w)
//  [python]
def printCsArrays(count: int):
    printCsArray("bartlett", scipy.signal.windows.bartlett(count))
    printCsArray("blackman", scipy.signal.windows.blackman(count))
    printCsArray("cosine", scipy.signal.windows.cosine(count))
    printCsArray("flattop", scipy.signal.windows.flattop(count))
    printCsArray("hamming",  scipy.signal.windows.hamming(count))
    printCsArray("hanning",  scipy.signal.windows.hann(count))
    printCsArray("kaiser14", scipy.signal.windows.kaiser(count, beta=14))
    printCsArray("tukey",  scipy.signal.windows.tukey(count))
//  [python]
def AC_transient_analysis(
        self,
        freq: float = 1000,
        amplitude: float = 1,
        t_ms: float = 5,
        outpath: str = None,
    ):
        """Plot transient analysis of Circuit's response to sine wave

        Args:
            freq (float, optional): frequency of sine wave. Defaults to 1000.
            amplitude (float, optional): amplitude of sine wave. Defaults to 1.
            t_ms (float, optional): time in ms of sine wave. Defaults to 5.
        """
        _, ax = plt.subplots(nrows=2, ncols=1, figsize=(10, 6.5))

        n_samples = int(t_ms * self.fs / 1000)

        n = np.arange(0, 2, 1 / self.fs)
        x = np.sin(2 * np.pi * freq * n) * amplitude
        y = self.process_signal(x)

        ax[0].plot(x[:n_samples], label="input signal")
        ax[0].plot(y[:n_samples], label="output signal", alpha=0.75)
        ax[0].set_xlabel("sample")
        ax[0].set_ylabel("amplitude")
        ax[0].set_title(loc="left", label="output signal vs input signal waveforms")
        ax[0].grid(True)
        ax[0].legend()

        N = len(n)
        w = np.hanning(len(n))
        y_fft = scipy.fft.fft(w * y)
        yf = scipy.fft.fftfreq(N, 1 / self.fs)[20 : N // 2]

        ax[1].plot(yf, 2.0 / N * np.abs(y_fft[20 : N // 2]))
        ax[1].set_xlabel("frequency [Hz]")
        ax[1].set_ylabel("magnitude")
        ax[1].set_title(loc="left", label="output signal spectrum")
        ax[1].grid(True)
        plt.tight_layout()
        if outpath:
            plt.savefig(outpath)

        plt.show()
//  [python]
def AC_transient_analysis(
        self,
        freq: float = 1000,
        amplitude: float = 1,
        t_ms: float = 5,
        outpath: str = None,
    ):
        """Plot transient analysis of Circuit's response to sine wave

        Args:
            freq (float, optional): frequency of sine wave. Defaults to 1000.
            amplitude (float, optional): amplitude of sine wave. Defaults to 1.
            t_ms (float, optional): time in ms of sine wave. Defaults to 5.
        """
        _, ax = plt.subplots(nrows=2, ncols=1, figsize=(10, 6.5))

        n_samples = int(t_ms * self.fs / 1000)

        n = np.arange(0, 2, 1 / self.fs)
        x = np.sin(2 * np.pi * freq * n) * amplitude
        y = self.process_signal(x)

        ax[0].plot(x[:n_samples], label="input signal")
        ax[0].plot(y[:n_samples], label="output signal", alpha=0.75)
        ax[0].set_xlabel("sample")
        ax[0].set_ylabel("amplitude")
        ax[0].set_title(loc="left", label="output signal vs input signal waveforms")
        ax[0].grid(True)
        ax[0].legend()

        N = len(n)
        w = scipy.signal.windows.hann((len(n)))
        y_fft = scipy.fft.fft(w * y)
        yf = scipy.fft.fftfreq(N, 1 / self.fs)[20 : N // 2]

        ax[1].plot(yf, 2.0 / N * np.abs(y_fft[20 : N // 2]))
        ax[1].set_xlabel("frequency [Hz]")
        ax[1].set_ylabel("magnitude")
        ax[1].set_title(loc="left", label="output signal spectrum")
        ax[1].grid(True)
        plt.tight_layout()
        if outpath:
            plt.savefig(outpath)

        plt.show()
//  [python]
def nlfer(signal, pitch, parameters):

    #---------------------------------------------------------------
    # Set parameters.
    #---------------------------------------------------------------
    N_f0_min = np.around((parameters['f0_min']*2/float(signal.new_fs))*pitch.nfft)
    N_f0_max = np.around((parameters['f0_max']/float(signal.new_fs))*pitch.nfft)

    window = s(pitch.frame_size+2)[1:-1]
    data = np.zeros((signal.size))  #Needs other array, otherwise stride and
    data[:] = signal.filtered     #windowing will modify signal.filtered

    #---------------------------------------------------------------
    # Main routine.
    #---------------------------------------------------------------
    samples = np.arange(int(np.fix(float(pitch.frame_size)/2)),
                        signal.size-int(np.fix(float(pitch.frame_size)/2)),
                        pitch.frame_jump)

    data_matrix = np.empty((len(samples), pitch.frame_size))
    data_matrix[:, :] = stride_matrix(data, len(samples),
                                    pitch.frame_size, pitch.frame_jump)
    data_matrix *= window

    specData = np.fft.rfft(data_matrix, pitch.nfft)

    frame_energy = np.abs(specData[:, int(N_f0_min-1):int(N_f0_max)]).sum(axis=1)
    pitch.set_energy(frame_energy, parameters['nlfer_thresh1'])
    pitch.set_frames_pos(samples)
//  [python]
def nlfer(signal, pitch, parameters):

    #---------------------------------------------------------------
    # Set parameters.
    #---------------------------------------------------------------
    N_f0_min = np.around((parameters['f0_min']*2/float(signal.new_fs))*pitch.nfft)
    N_f0_max = np.around((parameters['f0_max']/float(signal.new_fs))*pitch.nfft)

    window = hann(pitch.frame_size+2)[1:-1]
    data = np.zeros((signal.size))  #Needs other array, otherwise stride and
    data[:] = signal.filtered     #windowing will modify signal.filtered

    #---------------------------------------------------------------
    # Main routine.
    #---------------------------------------------------------------
    samples = np.arange(int(np.fix(float(pitch.frame_size)/2)),
                        signal.size-int(np.fix(float(pitch.frame_size)/2)),
                        pitch.frame_jump)

    data_matrix = np.empty((len(samples), pitch.frame_size))
    data_matrix[:, :] = stride_matrix(data, len(samples),
                                    pitch.frame_size, pitch.frame_jump)
    data_matrix *= window

    specData = np.fft.rfft(data_matrix, pitch.nfft)

    frame_energy = np.abs(specData[:, int(N_f0_min-1):int(N_f0_max)]).sum(axis=1)
    pitch.set_energy(frame_energy, parameters['nlfer_thresh1'])
    pitch.set_frames_pos(samples)
//  [python]
def get_binned_power(abf: pyabf.ABF, channel: int, freq_min: float, freq_max: float):
    ys = abf.getAllYs(channel)
    sample_rate = abf.sampleRate

    binsize_min = .5
    binsize_sec = binsize_min * 60
    binsize_points = int(binsize_sec * sample_rate)
    bin_count = int(abf.dataLengthSec / binsize_sec)
    bin_times = np.arange(bin_count) * binsize_min
    bin_edges = np.arange(bin_count) * binsize_points
    binned_power = [None] * bin_count

    for i, bin_edge in enumerate(bin_edges):

        # isolate a segment in time
        i1 = bin_edge
        i2 = bin_edge + binsize_points
        sample = ys[i1:i2]

        # apply a window
        window = scipy.signal.hanning(len(sample))
        sample = sample * window

        # calculate the FFT
        fft = scipy.fft.rfft(sample)
        fft[0] = 0
        fft_mag = np.abs(fft)[:-1]
        fft_power = np.log10(1+fft_mag)
        xf = scipy.fft.fftfreq(len(sample), 1/sample_rate)[:len(sample)//2]

        # isolate the frequency range of interest
        i1 = int(freq_min/xf[1])
        i2 = int(freq_max/xf[1])
        xf = xf[i1:i2]
        fft_mag = fft_mag[i1:i2]
        fft_power = fft_power[i1:i2]

        # accumulate
        binned_power[i] = np.sum(fft_mag)

    return bin_times, binned_power
//  [python]
def get_binned_power(abf: pyabf.ABF, channel: int, freq_min: float, freq_max: float):
    ys = abf.getAllYs(channel)
    sample_rate = abf.sampleRate

    binsize_min = .5
    binsize_sec = binsize_min * 60
    binsize_points = int(binsize_sec * sample_rate)
    bin_count = int(abf.dataLengthSec / binsize_sec)
    bin_times = np.arange(bin_count) * binsize_min
    bin_edges = np.arange(bin_count) * binsize_points
    binned_power = [None] * bin_count

    for i, bin_edge in enumerate(bin_edges):

        # isolate a segment in time
        i1 = bin_edge
        i2 = bin_edge + binsize_points
        sample = ys[i1:i2]

        # apply a window
        window = scipy.signal.windows.hann(len(sample))
        sample = sample * window

        # calculate the FFT
        fft = scipy.fft.rfft(sample)
        fft[0] = 0
        fft_mag = np.abs(fft)[:-1]
        fft_power = np.log10(1+fft_mag)
        xf = scipy.fft.fftfreq(len(sample), 1/sample_rate)[:len(sample)//2]

        # isolate the frequency range of interest
        i1 = int(freq_min/xf[1])
        i2 = int(freq_max/xf[1])
        xf = xf[i1:i2]
        fft_mag = fft_mag[i1:i2]
        fft_power = fft_power[i1:i2]

        # accumulate
        binned_power[i] = np.sum(fft_mag)

    return bin_times, binned_power
//  [python]
def config(self):
        """ """
        sampling_freq = self.wurb_recorder.sampling_freq_hz
        filter_min_khz = self.wurb_settings.get_setting("detection_limit_khz")
        threshold_dbfs = self.wurb_settings.get_setting("detection_sensitivity_dbfs")

        self.sampling_freq = float(sampling_freq)
        self.filter_min_hz = float(filter_min_khz) * 1000.0
        self.threshold_dbfs = float(threshold_dbfs)
        self.window_size = 2048
        self.jump_size = 1000

        # self.window_function = scipy.signal.blackmanharris(self.window_size)
        self.window_function = scipy.signal.hann(self.window_size)
        # Max db value in window. dbFS = db full scale. Half spectrum used.
        self.window_function_dbfs_max = np.sum(self.window_function) / 2
        self.freq_bins_hz = np.arange((self.window_size / 2) + 1) / (
            self.window_size / self.sampling_freq
        )
//  [python]
def config(self):
        """ """
        sampling_freq = self.wurb_recorder.sampling_freq_hz
        filter_min_khz = self.wurb_settings.get_setting("detection_limit_khz")
        threshold_dbfs = self.wurb_settings.get_setting("detection_sensitivity_dbfs")

        self.sampling_freq = float(sampling_freq)
        self.filter_min_hz = float(filter_min_khz) * 1000.0
        self.threshold_dbfs = float(threshold_dbfs)
        self.window_size = 2048
        self.jump_size = 1000

        # self.window_function = scipy.signal.blackmanharris(self.window_size)
        self.window_function = scipy.signal.windows.hann(self.window_size)
        # Max db value in window. dbFS = db full scale. Half spectrum used.
        self.window_function_dbfs_max = np.sum(self.window_function) / 2
        self.freq_bins_hz = np.arange((self.window_size / 2) + 1) / (
            self.window_size / self.sampling_freq
        )
//  [python]
x = np.linspace(-10*np.pi, 10*np.pi, 201)

# Create signal
s = np.sin(30*x)

# Initialize hann windows
w = list(np.hanning(len(s)))
//  [python]
x = np.linspace(-10*np.pi, 10*np.pi, 201)

# Create signal
s = np.sin(30*x)

# Initialize hann windows
w = list(wd.hann(len(s)))
//  [python]
def compute_activation_confidence(track_path, win_len=4096, lpf_cutoff=0.075,
                                 theta=0.15, var_lambda=20.0,
                                 amplitude_threshold=0.01):
    """Create the activation confidence annotation for a track. The final
    activation matrix is computed as:
        `C[i, t] = 1 - (1 / (1 + e**(var_lambda * (H[i, t] - theta))))`
    where H[i, t] is the energy of stem `i` at time `t`

    Parameters
    ----------
    track_path : Path
        Path object
    win_len : int, default=4096
        Number of samples in each window
    lpf_cutoff : float, default=0.075
        Lowpass frequency cutoff fraction
    theta : float
        Controls the threshold of activation.
    var_labmda : float
        Controls the slope of the threshold function.
    amplitude_threshold : float
        Energies below this value are set to 0.0

    Returns
    -------
    C : np.array
        Array of activation confidence values shape (n_conf, n_stems)
    """
    H = []

    # MATLAB equivalent to @hanning(win_len)
    win = np.hanning(win_len + 2)[1:-1]

    audio, rate = librosa.load(track_path, sr=44100, mono=True)
    H.append(track_energy(audio.T, win_len, win))

    # list to numpy array
    H = np.array(H)

    # normalization (to overall energy and # of sources)
    E0 = np.sum(H, axis=0)
    
    H /= np.max(E0)
    # binary thresholding for low overall energy events
    H[:, E0 < amplitude_threshold] = 0.0

    # LP filter
    b, a = scipy.signal.butter(2, lpf_cutoff, 'low')
    H = scipy.signal.filtfilt(b, a, H, axis=1)

    # logistic function to semi-binarize the output; confidence value
    C = 1.0 - (1.0 / (1.0 + np.exp(np.dot(var_lambda, (H - theta)))))

    # add time column
    time = librosa.core.frames_to_time(
        np.arange(C.shape[1]), sr=rate, hop_length=win_len // 2
    )

    # stack time column to matrix
    C_out = np.vstack((time, C))
    return C_out.T
//  [python]
def compute_activation_confidence(track_path, win_len=4096, lpf_cutoff=0.075,
                                 theta=0.15, var_lambda=20.0,
                                 amplitude_threshold=0.01):
    """Create the activation confidence annotation for a track. The final
    activation matrix is computed as:
        `C[i, t] = 1 - (1 / (1 + e**(var_lambda * (H[i, t] - theta))))`
    where H[i, t] is the energy of stem `i` at time `t`

    Parameters
    ----------
    track_path : Path
        Path object
    win_len : int, default=4096
        Number of samples in each window
    lpf_cutoff : float, default=0.075
        Lowpass frequency cutoff fraction
    theta : float
        Controls the threshold of activation.
    var_labmda : float
        Controls the slope of the threshold function.
    amplitude_threshold : float
        Energies below this value are set to 0.0

    Returns
    -------
    C : np.array
        Array of activation confidence values shape (n_conf, n_stems)
    """
    H = []

    # MATLAB equivalent to @hanning(win_len)
    win = scipy.signal.windows.hann(win_len + 2)[1:-1]

    audio, rate = librosa.load(track_path, sr=44100, mono=True)
    H.append(track_energy(audio.T, win_len, win))

    # list to numpy array
    H = np.array(H)

    # normalization (to overall energy and # of sources)
    E0 = np.sum(H, axis=0)
    
    H /= np.max(E0)
    # binary thresholding for low overall energy events
    H[:, E0 < amplitude_threshold] = 0.0

    # LP filter
    b, a = scipy.signal.butter(2, lpf_cutoff, 'low')
    H = scipy.signal.filtfilt(b, a, H, axis=1)

    # logistic function to semi-binarize the output; confidence value
    C = 1.0 - (1.0 / (1.0 + np.exp(np.dot(var_lambda, (H - theta)))))

    # add time column
    time = librosa.core.frames_to_time(
        np.arange(C.shape[1]), sr=rate, hop_length=win_len // 2
    )

    # stack time column to matrix
    C_out = np.vstack((time, C))
    return C_out.T
//  [python]
def test_fft_2d(self):
        """Test the discrete Fourier transform on 2D data"""
        N = 16
        da = xr.DataArray(
            np.random.rand(N, N), dims=["x", "y"], coords={"x": range(N), "y": range(N)}
        )
        ft = xrft.dft(da, shift=False)
        npt.assert_almost_equal(ft.values, np.fft.fftn(da.values))

        ft = xrft.dft(da, shift=False, window="hann", detrend="constant")
        dim = da.dims
        window = (
            np.hanning(N)
            * np.hanning(N)[:, np.newaxis]
        )
        da_prime = (da - da.mean(dim=dim)).values
        npt.assert_almost_equal(ft.values, np.fft.fftn(da_prime * window))

        da = xr.DataArray(
            np.random.rand(N, N),
            dims=["x", "y"],
            coords={"x": range(N, 0, -1), "y": range(N, 0, -1)},
        )
        assert (xrft.power_spectrum(da, shift=False, density=True) >= 0.0).all()
//  [python]
def test_fft_2d(self):
        """Test the discrete Fourier transform on 2D data"""
        N = 16
        da = xr.DataArray(
            np.random.rand(N, N), dims=["x", "y"], coords={"x": range(N), "y": range(N)}
        )
        ft = xrft.dft(da, shift=False)
        npt.assert_almost_equal(ft.values, np.fft.fftn(da.values))

        ft = xrft.dft(da, shift=False, window="hann", detrend="constant")
        dim = da.dims
        window = (
            sps.windows.hann(N, sym=False)
            * sps.windows.hann(N, sym=False)[:, np.newaxis]
        )
        da_prime = (da - da.mean(dim=dim)).values
        npt.assert_almost_equal(ft.values, np.fft.fftn(da_prime * window))

        da = xr.DataArray(
            np.random.rand(N, N),
            dims=["x", "y"],
            coords={"x": range(N, 0, -1), "y": range(N, 0, -1)},
        )
        assert (xrft.power_spectrum(da, shift=False, density=True) >= 0.0).all()
//  [python]
def spectrogram(sig, rate, shape=(64, 512), win_len=512, fmin=150, fmax=15000, frequency_scale='mel', magnitude_scale='nonlinear', bandpass=True, decompose=False):

    # Compute overlap
    hop_len = int(len(sig) / (shape[1] - 1)) 
    win_overlap = win_len - hop_len + 2
    #print 'WIN_LEN:', win_len, 'HOP_LEN:', hop_len, 'OVERLAP:', win_overlap

    # Adjust N_FFT?
    if frequency_scale == 'mel':
        n_fft = win_len
    else:
        n_fft = shape[1] * 2

    # Bandpass filter?
    if bandpass:
        sig = applyBandpassFilter(sig, rate, fmin, fmax)

    # Compute spectrogram
    f, t, spec = scipy.signal.spectrogram(sig,
                                          fs=rate,
                                          window=scipy.signal.hanning(win_len),
                                          nperseg=win_len,
                                          noverlap=win_overlap,
                                          nfft=n_fft,
                                          detrend=False,
                                          mode='magnitude')

    # Scale frequency?
    if frequency_scale == 'mel':

        # Determine the indices of where to clip the spec
        valid_f_idx_start = f.searchsorted(fmin, side='left')
        valid_f_idx_end = f.searchsorted(fmax, side='right') - 1

        # Get mel filter banks
        mel_filterbank, mel_f = get_mel_filterbanks(shape[0], fmin, fmax, f, dtype=spec.dtype)

        # Clip to non-zero range so that unnecessary multiplications can be avoided
        mel_filterbank = mel_filterbank[valid_f_idx_start:(valid_f_idx_end + 1), :]

        # Clip the spec representation and apply the mel filterbank.
        # Due to the nature of np.dot(), the spec needs to be transposed prior, and reverted after
        spec = np.transpose(spec[valid_f_idx_start:(valid_f_idx_end + 1), :], [1, 0])
        spec = np.dot(spec, mel_filterbank)
        spec = np.transpose(spec, [1, 0])        

    # Magnitude transformation
    if magnitude_scale == 'pcen':
        
        # Convert scale using per-channel energy normalization as proposed by Wang et al., 2017
        # We adjust the parameters for bird voice recognition based on Lostanlen, 2019
        spec = pcen(spec, rate, hop_len)
        
    elif magnitude_scale == 'log':
        
        # Convert power spec to dB scale (compute dB relative to peak power)
        spec = spec ** 2
        spec = 10.0 * np.log10(np.maximum(1e-10, spec) / np.max(spec))
        spec = np.maximum(spec, spec.max() - 100) # top_db = 100

    elif magnitude_scale == 'nonlinear':

        # Convert magnitudes using nonlinearity as proposed by Schlüter, 2018
        a = -1.2 # Higher values yield better noise suppression
        s = 1.0 / (1.0 + np.exp(-a))
        spec = spec ** s

    # Flip spectrum vertically (only for better visialization, low freq. at bottom)
    spec = spec[::-1, ...]

    # Trim to desired shape if too large
    spec = spec[:shape[0], :shape[1]]

    # Normalize values between 0 and 1
    spec -= spec.min()
    if not spec.max() == 0:
        spec /= spec.max()
    else:
        spec = np.clip(spec, 0, 1)

    return spec
//  [python]
def spectrogram(sig, rate, shape=(64, 512), win_len=512, fmin=150, fmax=15000, frequency_scale='mel', magnitude_scale='nonlinear', bandpass=True, decompose=False):

    # Compute overlap
    hop_len = int(len(sig) / (shape[1] - 1)) 
    win_overlap = win_len - hop_len + 2
    #print 'WIN_LEN:', win_len, 'HOP_LEN:', hop_len, 'OVERLAP:', win_overlap

    # Adjust N_FFT?
    if frequency_scale == 'mel':
        n_fft = win_len
    else:
        n_fft = shape[1] * 2

    # Bandpass filter?
    if bandpass:
        sig = applyBandpassFilter(sig, rate, fmin, fmax)

    # Compute spectrogram
    f, t, spec = scipy.signal.spectrogram(sig,
                                          fs=rate,
                                          window=scipy.signal.windows.hann(win_len),
                                          nperseg=win_len,
                                          noverlap=win_overlap,
                                          nfft=n_fft,
                                          detrend=False,
                                          mode='magnitude')

    # Scale frequency?
    if frequency_scale == 'mel':

        # Determine the indices of where to clip the spec
        valid_f_idx_start = f.searchsorted(fmin, side='left')
        valid_f_idx_end = f.searchsorted(fmax, side='right') - 1

        # Get mel filter banks
        mel_filterbank, mel_f = get_mel_filterbanks(shape[0], fmin, fmax, f, dtype=spec.dtype)

        # Clip to non-zero range so that unnecessary multiplications can be avoided
        mel_filterbank = mel_filterbank[valid_f_idx_start:(valid_f_idx_end + 1), :]

        # Clip the spec representation and apply the mel filterbank.
        # Due to the nature of np.dot(), the spec needs to be transposed prior, and reverted after
        spec = np.transpose(spec[valid_f_idx_start:(valid_f_idx_end + 1), :], [1, 0])
        spec = np.dot(spec, mel_filterbank)
        spec = np.transpose(spec, [1, 0])        

    # Magnitude transformation
    if magnitude_scale == 'pcen':
        
        # Convert scale using per-channel energy normalization as proposed by Wang et al., 2017
        # We adjust the parameters for bird voice recognition based on Lostanlen, 2019
        spec = pcen(spec, rate, hop_len)
        
    elif magnitude_scale == 'log':
        
        # Convert power spec to dB scale (compute dB relative to peak power)
        spec = spec ** 2
        spec = 10.0 * np.log10(np.maximum(1e-10, spec) / np.max(spec))
        spec = np.maximum(spec, spec.max() - 100) # top_db = 100

    elif magnitude_scale == 'nonlinear':

        # Convert magnitudes using nonlinearity as proposed by Schlüter, 2018
        a = -1.2 # Higher values yield better noise suppression
        s = 1.0 / (1.0 + np.exp(-a))
        spec = spec ** s

    # Flip spectrum vertically (only for better visialization, low freq. at bottom)
    spec = spec[::-1, ...]

    # Trim to desired shape if too large
    spec = spec[:shape[0], :shape[1]]

    # Normalize values between 0 and 1
    spec -= spec.min()
    if not spec.max() == 0:
        spec /= spec.max()
    else:
        spec = np.clip(spec, 0, 1)

    return spec
//  [python]
def decompose_audio_chunk(temp_audio_chunk : AudioChunk, trim_size : int) -> AudioChunk:
	frame_size = 7680
	frame_overlap = 6656
	voice_extractor_shape = get_voice_extractor().get_inputs()[0].shape
	window = scipy.signal.hann(frame_size)
	temp_audio_chunk = scipy.signal.stft(temp_audio_chunk, nperseg = frame_size, noverlap = frame_overlap, window = window)[2]
	temp_audio_chunk = numpy.stack((numpy.real(temp_audio_chunk), numpy.imag(temp_audio_chunk)), axis = -1).transpose((0, 3, 1, 2))
	temp_audio_chunk = temp_audio_chunk.reshape(-1, 2, 2, trim_size + 1, voice_extractor_shape[3]).reshape(-1, voice_extractor_shape[1], trim_size + 1, voice_extractor_shape[3])
	temp_audio_chunk = temp_audio_chunk[:, :, :voice_extractor_shape[2]]
	temp_audio_chunk /= numpy.sqrt(1.0 / window.sum() ** 2)
	return temp_audio_chunk
//  [python]
def decompose_audio_chunk(temp_audio_chunk : AudioChunk, trim_size : int) -> AudioChunk:
	frame_size = 7680
	frame_overlap = 6656
	voice_extractor_shape = get_voice_extractor().get_inputs()[0].shape
	window = scipy.signal.windows.hann(frame_size)
	temp_audio_chunk = scipy.signal.stft(temp_audio_chunk, nperseg = frame_size, noverlap = frame_overlap, window = window)[2]
	temp_audio_chunk = numpy.stack((numpy.real(temp_audio_chunk), numpy.imag(temp_audio_chunk)), axis = -1).transpose((0, 3, 1, 2))
	temp_audio_chunk = temp_audio_chunk.reshape(-1, 2, 2, trim_size + 1, voice_extractor_shape[3]).reshape(-1, voice_extractor_shape[1], trim_size + 1, voice_extractor_shape[3])
	temp_audio_chunk = temp_audio_chunk[:, :, :voice_extractor_shape[2]]
	temp_audio_chunk /= numpy.sqrt(1.0 / window.sum() ** 2)
	return temp_audio_chunk
//  [python]
xs = np.linspace(-20, 20, 300)
ys = np.sin(xs)
window = np.pad(scipy.signal.windows.hann(200), (50, 50))
//  [python]
def taper(data, max_percentage=0.05, type='hann', side='both'):

    side_valid = ['both', 'left', 'right']
    npts = len(data)
    if side not in side_valid:
        raise ValueError("'side' has to be one of: %s" % side_valid)

    # max_half_lenghts_1
    max_half_lenghts_1 = None
    if max_percentage is not None:
        max_half_lenghts_1 = int(max_percentage * npts)

    if 2 * max_half_lenghts_1 > npts:
        msg = "The requested taper is longer than the data. " \
                "The taper will be shortened to data length."
        warnings.warn(msg)

    # max_half_lenghts_2
    max_half_lenghts_2 = int(npts / 2)
    if max_half_lenghts_1 is None:
        wlen = max_half_lenghts_2
    else:
        wlen = min(max_half_lenghts_1, max_half_lenghts_2)

    if type == "hann":
        taper_sides = scipy.signal.windows.hann(2*wlen+1)
    elif type == "hamming":
        taper_sides = scipy.signal.windows.hamming(2*wlen+1)
    elif type == "bartlett":
        taper_sides = scipy.signal.windows.bartlett(2*wlen+1)
    elif type == "blackman":
        taper_sides = scipy.signal.windows.blackman(2*wlen+1)
    elif type == "flattop":
        taper_sides = scipy.signal.windows.flattop(2*wlen+1)
    elif type == "parzen":
        taper_sides = scipy.signal.windows.parzen(2*wlen+1)
    elif type == "bohman":
        taper_sides = scipy.signal.windows.bohman(2*wlen+1)
    elif type == "blackmanharris":
        taper_sides = scipy.signal.windows.blackmanharris(2*wlen+1)
    elif type == "nuttall":
        taper_sides = scipy.signal.windows.nuttall(2*wlen+1)
    elif type == "barthann":
        taper_sides = scipy.signal.windows.barthann(2*wlen+1)
    elif type == "kaiser":
        taper_sides = scipy.signal.windows.kaiser(2*wlen+1, beta=14)
    elif type == "gaussian":
        taper_sides = scipy.signal.windows.gaussian(2*wlen+1, std=14)
    elif type == "general_gaussian":
        taper_sides = scipy.signal.windows.general_gaussian(2*wlen+1, p=1, sig=14)
    else:
        raise ValueError("Unknown taper type: %s" % type)

    if side == 'left':
        taper = np.hstack((taper_sides[:wlen], np.ones(npts - wlen)))
    elif side == 'right':
        taper = np.hstack((np.ones(npts - wlen),
                            taper_sides[len(taper_sides) - wlen:]))
    else:
        taper = np.hstack((taper_sides[:wlen], np.ones(npts - 2 * wlen),
                            taper_sides[len(taper_sides) - wlen:]))

    # Convert data if it's not a floating point type.
    if not np.issubdtype(data.dtype, np.floating):
        data = np.require(data, dtype=np.float64)

    data *= taper