jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def check_aec_output(audio_in, audio_ref, audio_out, start_s, end_s, criteria,
                     frequencies, Fs=16000, debug=True):
    success = True
    start = Fs * start_s
    end = Fs * end_s
    window = np.hanning(end - start)
    In = np.abs(np.fft.rfft(audio_in[start:end] * window))
    Ref = np.abs(np.fft.rfft(audio_ref[start:end] * window))
    Out = np.abs(np.fft.rfft(audio_out[start:end] * window))
    # Check for near-end frequencies
    for f in frequencies:
        in_mag = get_magnitude(f, In, Fs, 10, normalise=True)
        out_mag = get_magnitude(f, Out, Fs, 10, normalise=True)
        db_out = db(out_mag, in_mag)
        suppression_max = int(criteria['near_end_max_suppression'])
        if db_out < suppression_max:
            print("Check failed! Near-end Frequency: %d, db: %f (< %ddB)"\
                  % (f, db_out, suppression_max))
            success = False
        if debug:
            print("freq: %d, in: %f, out: %f, db: %f"\
                  % (f, in_mag, out_mag, db_out))
    # Check magnitude of suppressed frequencies
    band_min = int(criteria['suppression_band_min'])
    band_max = int(criteria['suppression_band_max'])
    max_suppressed_magnitude, freq = get_suppressed_magnitude(frequencies, Out,
                                                              Fs, 10,
                                                              band_min=band_min,
                                                              band_max=band_max)
    suppression_min = int(criteria['far_end_min_suppression'])
    db_suppressed = db(max_suppressed_magnitude, np.max(In))
    if db_suppressed > suppression_min:
        print("Check failed! Suppression at freq %d is %fdB (> %ddB)"\
                % (freq, db_suppressed, suppression_min))
        success = False
    else:
        print("Suppression check passed.")
    if success:
        print("Check passed!")
    return success
//  [python]
def check_aec_output(audio_in, audio_ref, audio_out, start_s, end_s, criteria,
                     frequencies, Fs=16000, debug=True):
    success = True
    start = Fs * start_s
    end = Fs * end_s
    window = scipy.signal.windows.hann(end - start, sym=True)
    In = np.abs(np.fft.rfft(audio_in[start:end] * window))
    Ref = np.abs(np.fft.rfft(audio_ref[start:end] * window))
    Out = np.abs(np.fft.rfft(audio_out[start:end] * window))
    # Check for near-end frequencies
    for f in frequencies:
        in_mag = get_magnitude(f, In, Fs, 10, normalise=True)
        out_mag = get_magnitude(f, Out, Fs, 10, normalise=True)
        db_out = db(out_mag, in_mag)
        suppression_max = int(criteria['near_end_max_suppression'])
        if db_out < suppression_max:
            print("Check failed! Near-end Frequency: %d, db: %f (< %ddB)"\
                  % (f, db_out, suppression_max))
            success = False
        if debug:
            print("freq: %d, in: %f, out: %f, db: %f"\
                  % (f, in_mag, out_mag, db_out))
    # Check magnitude of suppressed frequencies
    band_min = int(criteria['suppression_band_min'])
    band_max = int(criteria['suppression_band_max'])
    max_suppressed_magnitude, freq = get_suppressed_magnitude(frequencies, Out,
                                                              Fs, 10,
                                                              band_min=band_min,
                                                              band_max=band_max)
    suppression_min = int(criteria['far_end_min_suppression'])
    db_suppressed = db(max_suppressed_magnitude, np.max(In))
    if db_suppressed > suppression_min:
        print("Check failed! Suppression at freq %d is %fdB (> %ddB)"\
                % (freq, db_suppressed, suppression_min))
        success = False
    else:
        print("Suppression check passed.")
    if success:
        print("Check passed!")
    return success
//  [python]
def compose_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 = numpy.pad(temp_audio_chunk, ((0, 0), (0, 0), (0, trim_size + 1 - voice_extractor_shape[2]), (0, 0)))
	temp_audio_chunk = temp_audio_chunk.reshape(-1, 2, trim_size + 1, voice_extractor_shape[3]).transpose((0, 2, 3, 1))
	temp_audio_chunk = temp_audio_chunk[:, :, :, 0] + 1j * temp_audio_chunk[:, :, :, 1]
	temp_audio_chunk = scipy.signal.istft(temp_audio_chunk, nperseg = frame_size, noverlap = frame_overlap, window = window)[1]
	temp_audio_chunk *= numpy.sqrt(1.0 / window.sum() ** 2)
	return temp_audio_chunk
//  [python]
def compose_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 = numpy.pad(temp_audio_chunk, ((0, 0), (0, 0), (0, trim_size + 1 - voice_extractor_shape[2]), (0, 0)))
	temp_audio_chunk = temp_audio_chunk.reshape(-1, 2, trim_size + 1, voice_extractor_shape[3]).transpose((0, 2, 3, 1))
	temp_audio_chunk = temp_audio_chunk[:, :, :, 0] + 1j * temp_audio_chunk[:, :, :, 1]
	temp_audio_chunk = scipy.signal.istft(temp_audio_chunk, nperseg = frame_size, noverlap = frame_overlap, window = window)[1]
	temp_audio_chunk *= numpy.sqrt(1.0 / window.sum() ** 2)
	return temp_audio_chunk
//  [python]
def process(self, *, src: Symbolic.DataSource, **kwargs: typing.Any) -> _ProcessingResult:
        src_xdata = src.xdata
        if src_xdata and  src_xdata.datum_dimension_count == 1:
            return src_xdata * scipy.signal.hann(src_xdata.datum_dimension_shape[0])  # type: ignore
        elif src_xdata and src_xdata.datum_dimension_count == 2:
            # uses outer product approach of generating 2D filter from 1D
            h, w = src_xdata.datum_dimension_shape
            w0 = numpy.reshape(scipy.signal.hann(w), (1, w))
            w1 = numpy.reshape(scipy.signal.hann(h), (h, 1))
            return src_xdata * w0 * w1
        return None
//  [python]
def process(self, *, src: Symbolic.DataSource, **kwargs: typing.Any) -> _ProcessingResult:
        src_xdata = src.xdata
        if src_xdata and  src_xdata.datum_dimension_count == 1:
            return src_xdata * scipy.signal.hann(src_xdata.datum_dimension_shape[0])  # type: ignore
        elif src_xdata and src_xdata.datum_dimension_count == 2:
            # uses outer product approach of generating 2D filter from 1D
            h, w = src_xdata.datum_dimension_shape
            w0 = numpy.reshape(scipy.signal.windows.hann(w), (1, w))
            w1 = numpy.reshape(scipy.signal.windows.hann(h), (h, 1))
            return src_xdata * w0 * w1
        return None
//  [python]
def __init__(self, modelfile, cfg=None):
        super().__init__()
        """Instantiate NSnet2 given a trained model path."""
        self.cfg = cfg
        self.frameShift = float(self.cfg['winlen'])* float(self.cfg["hopfrac"])
        self.fs = int(self.cfg['fs'])
        self.mingain = 10**(self.cfg['mingain']/20)
        self.N_win = int(float(self.cfg['winlen']) * self.fs)
        if 'nfft' in cfg:
            self.N_fft = int(self.cfg['nfft'])
        else:
            self.N_fft = self.N_win
        self.N_hop = int(self.N_fft * float(cfg["hopfrac"]))
        
        """load onnx model"""
        # self.ort = ort.InferenceSession(modelfile)
        self.model = ConvertModel(onnx.load(modelfile))
        self.dtype = np.float32
        self.win = np.sqrt(s.hann(self.N_win, sym=False))
        self.win_buf = torch.from_numpy(self.win).float()        
        L = len(self.win)
        awin = np.zeros_like(self.win)
        for k in range(0, self.N_hop):
            idx = range(k, L, self.N_hop)
            H = self.win[idx]
            awin[idx] = np.linalg.pinv(H[:,np.newaxis])
        self.awin = torch.from_numpy(awin).float()
//  [python]
def __init__(self, modelfile, cfg=None):
        super().__init__()
        """Instantiate NSnet2 given a trained model path."""
        self.cfg = cfg
        self.frameShift = float(self.cfg['winlen'])* float(self.cfg["hopfrac"])
        self.fs = int(self.cfg['fs'])
        self.mingain = 10**(self.cfg['mingain']/20)
        self.N_win = int(float(self.cfg['winlen']) * self.fs)
        if 'nfft' in cfg:
            self.N_fft = int(self.cfg['nfft'])
        else:
            self.N_fft = self.N_win
        self.N_hop = int(self.N_fft * float(cfg["hopfrac"]))
        
        """load onnx model"""
        # self.ort = ort.InferenceSession(modelfile)
        self.model = ConvertModel(onnx.load(modelfile))
        self.dtype = np.float32
        self.win = np.sqrt(scipy.signal.windows.hann(self.N_win, sym=False))
        self.win_buf = torch.from_numpy(self.win).float()        
        L = len(self.win)
        awin = np.zeros_like(self.win)
        for k in range(0, self.N_hop):
            idx = range(k, L, self.N_hop)
            H = self.win[idx]
            awin[idx] = np.linalg.pinv(H[:,np.newaxis])
        self.awin = torch.from_numpy(awin).float()
//  [python]
def _window(
    order: int,
    window: Literal["hamming", "hann", "blackman", "blackman-harris", "chebyshev", "kaiser"]
    | npt.ArrayLike
    | None = None,
    atten: float = 60,
) -> npt.NDArray[np.float64]:
    if window is None:
        h_window = np.ones(order + 1)
    elif isinstance(window, str):
        if window == "hamming":
            h_window = scipy.signal.windows.hamming(order + 1)
        elif window == "hann":
            h_window = scipy.signal.hanning(order + 1)
        elif window == "blackman":
            h_window = scipy.signal.windows.blackman(order + 1)
        elif window == "blackman-harris":
            h_window = scipy.signal.windows.blackmanharris(order + 1)
        elif window == "chebyshev":
            h_window = scipy.signal.windows.chebwin(order + 1, at=atten)
        elif window == "kaiser":
            beta = scipy.signal.kaiser_beta(atten)
            h_window = scipy.signal.windows.kaiser(order + 1, beta=beta)
        else:
            raise ValueError(
                f"Argument 'window' must be in ['hamming', 'hann', 'blackman', 'blackman-harris', 'chebyshev', 'kaiser'], not {window!r}."
            )
    else:
        h_window = np.asarray(window)
        if not h_window.shape == (order + 1,):
            raise ValueError(f"Argument 'window' must be a length-{order + 1} vector, not {h_window.shape}.")

    return h_window
//  [python]
def _window(
    order: int,
    window: Literal["hamming", "hann", "blackman", "blackman-harris", "chebyshev", "kaiser"]
    | npt.ArrayLike
    | None = None,
    atten: float = 60,
) -> npt.NDArray[np.float64]:
    if window is None:
        h_window = np.ones(order + 1)
    elif isinstance(window, str):
        if window == "hamming":
            h_window = scipy.signal.windows.hamming(order + 1)
        elif window == "hann":
            h_window = scipy.signal.windows.hann(order + 1)
        elif window == "blackman":
            h_window = scipy.signal.windows.blackman(order + 1)
        elif window == "blackman-harris":
            h_window = scipy.signal.windows.blackmanharris(order + 1)
        elif window == "chebyshev":
            h_window = scipy.signal.windows.chebwin(order + 1, at=atten)
        elif window == "kaiser":
            beta = scipy.signal.kaiser_beta(atten)
            h_window = scipy.signal.windows.kaiser(order + 1, beta=beta)
        else:
            raise ValueError(
                f"Argument 'window' must be in ['hamming', 'hann', 'blackman', 'blackman-harris', 'chebyshev', 'kaiser'], not {window!r}."
            )
    else:
        h_window = np.asarray(window)
        if not h_window.shape == (order + 1,):
            raise ValueError(f"Argument 'window' must be a length-{order + 1} vector, not {h_window.shape}.")

    return h_window
//  [python]
def plot_hann_window(window_size=1024, ax=None):
    show_needed = ax is None
    if show_needed:
        fig, ax = plt.subplots(figsize=(15, 5))

    hann_weights = scipy.signal.windows.hann(window_size, sym=False)

    ax.plot(hann_weights)
    ax.grid()
    ax.set_title(f"Hann window")
    ax.set_xlabel("Weights' indices")
    ax.set_ylabel("Weights")
    if show_needed:
        fig.show()
//  [python]
def smooth(x, window='boxcar', half_win=3):
    """ some window smoothing """
    # TODO: docsting
    window_len = 2 * half_win + 1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
    if window == "boxcar":
        w = scipy.signal.windows.boxcar(window_len).astype('complex')
    else:
        w = scipy.signal.hanning(window_len).astype('complex')
    y = np.convolve(w / w.sum(), s, mode='valid')
    return y[half_win:len(y) - half_win]
//  [python]
def smooth(x, window='boxcar', half_win=3):
    """ some window smoothing """
    # TODO: docsting
    window_len = 2 * half_win + 1
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
    if window == "boxcar":
        w = scipy.signal.windows.boxcar(window_len).astype('complex')
    else:
        w = scipy.signal.windows.hann(window_len).astype('complex')
    y = np.convolve(w / w.sum(), s, mode='valid')
    return y[half_win:len(y) - half_win]
//  [python]
plt.loglog(frequencies, psd_array_qpo)
plt.loglog(series_signal.frequency_array, np.abs(fd_data_signal) / np.sqrt(series_signal.frequency_array))
# plt.loglog(freqs_white_noise, np.abs(fd_data_white_noise)/np.sqrt(freqs_white_noise))
plt.loglog(freqs_signal_periodogram, powers_signal_periodogram)
plt.show()

if duration_white_noise == duration_signal:
    td_data_signal_windowed = td_data_signal
else:
    td_data_signal_windowed = td_data_signal * scipy.signal.hann(len(td_data_signal))
//  [python]
plt.loglog(frequencies, psd_array_qpo)
plt.loglog(series_signal.frequency_array, np.abs(fd_data_signal) / np.sqrt(series_signal.frequency_array))
# plt.loglog(freqs_white_noise, np.abs(fd_data_white_noise)/np.sqrt(freqs_white_noise))
plt.loglog(freqs_signal_periodogram, powers_signal_periodogram)
plt.show()

if duration_white_noise == duration_signal:
    td_data_signal_windowed = td_data_signal
else:
    td_data_signal_windowed = td_data_signal * scipy.signal.windows.hann(len(td_data_signal))
//  [python]
def _cross_fade(first, second, indices):
    """Cross-fade two numpy arrays by multiplication with a raised cosine
    window inside the range specified by the indices. Outside the range, the
    result will be the respective first or second array, without distortions.

    Parameters
    ----------
    first : array, double
        The first array.
    second : array, double
        The second array.
    indices : array-like, tuple, int
        The lower and upper cross-fade indices.

    Returns
    -------
    result : array, double
        The resulting array after cross-fading.
    """
    indices = np.asarray(indices)
    if np.shape(first)[-1] != np.shape(second)[-1]:
        raise ValueError("Both arrays need to be of same length.")
    len_arrays = np.shape(first)[-1]
    if np.any(indices > np.shape(first)[-1]):
        raise IndexError("Index is out of range.")

    len_xfade = np.squeeze(np.abs(np.diff(indices)))
    window = s.hann(len_xfade*2 + 1, sym=True)
    window_rising = window[:len_xfade]
    window_falling = window[len_xfade+1:]

    window_first = np.concatenate(
        (np.ones(indices[0]), window_falling, np.zeros(len_arrays-indices[1])))
    window_second = np.concatenate(
        (np.zeros(indices[0]), window_rising, np.ones(len_arrays-indices[1])))

    result = first * window_first + second * window_second

    return result
//  [python]
def _cross_fade(first, second, indices):
    """Cross-fade two numpy arrays by multiplication with a raised cosine
    window inside the range specified by the indices. Outside the range, the
    result will be the respective first or second array, without distortions.

    Parameters
    ----------
    first : array, double
        The first array.
    second : array, double
        The second array.
    indices : array-like, tuple, int
        The lower and upper cross-fade indices.

    Returns
    -------
    result : array, double
        The resulting array after cross-fading.
    """
    indices = np.asarray(indices)
    if np.shape(first)[-1] != np.shape(second)[-1]:
        raise ValueError("Both arrays need to be of same length.")
    len_arrays = np.shape(first)[-1]
    if np.any(indices > np.shape(first)[-1]):
        raise IndexError("Index is out of range.")

    len_xfade = np.squeeze(np.abs(np.diff(indices)))
    window = sgn.windows.hann(len_xfade*2 + 1, sym=True)
    window_rising = window[:len_xfade]
    window_falling = window[len_xfade+1:]

    window_first = np.concatenate(
        (np.ones(indices[0]), window_falling, np.zeros(len_arrays-indices[1])))
    window_second = np.concatenate(
        (np.zeros(indices[0]), window_rising, np.ones(len_arrays-indices[1])))

    result = first * window_first + second * window_second

    return result
//  [python]
def bsd(clean_speech, processed_speech, fs, frameLen=0.03, overlap=0.75):
    
    pre_emphasis_coeff = 0.95
    b = np.array([1])
    a = np.array([1,pre_emphasis_coeff])
    clean_speech = scipy.signal.lfilter(b,a,clean_speech)
    processed_speech = scipy.signal.lfilter(b,a,processed_speech)

    winlength   = round(frameLen*fs) #window length in samples
    skiprate    = int(np.floor((1-overlap)*frameLen*fs)) #window skip in samples
    max_freq    = fs/2 #maximum bandwidth
    n_fft       = 2**np.ceil(np.log2(2*winlength))
    n_fftby2    = int(n_fft/2)
    num_frames = len(clean_speech)/skiprate-(winlength/skiprate)# number of frames
    
    hannWin=np.hanning(winlength)#0.5*(1-np.cos(2*np.pi*np.arange(1,winlength+1)/(winlength+1)))
    f,t,Zxx=stft(clean_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False)
    clean_power_spec=np.square(np.sum(hannWin)*np.abs(Zxx))
    f,t,Zxx=stft(processed_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False)
    enh_power_spec=np.square(np.sum(hannWin)*np.abs(Zxx))

    bark_filt = barks(fs, n_fft, n_barks=32)
    clean_power_spec_bark= np.dot(bark_filt,clean_power_spec)
    enh_power_spec_bark= np.dot(bark_filt,enh_power_spec)
    
    clean_power_spec_bark_2=np.square(clean_power_spec_bark)
    diff_power_spec_2 = np.square(clean_power_spec_bark-enh_power_spec_bark)
    
    bsd = np.mean(np.sum(diff_power_spec_2,axis=0)/np.sum(clean_power_spec_bark_2,axis=0))
    return bsd
//  [python]
def bsd(clean_speech, processed_speech, fs, frameLen=0.03, overlap=0.75):
    
    pre_emphasis_coeff = 0.95
    b = np.array([1])
    a = np.array([1,pre_emphasis_coeff])
    clean_speech = scipy.signal.lfilter(b,a,clean_speech)
    processed_speech = scipy.signal.lfilter(b,a,processed_speech)

    winlength   = round(frameLen*fs) #window length in samples
    skiprate    = int(np.floor((1-overlap)*frameLen*fs)) #window skip in samples
    max_freq    = fs/2 #maximum bandwidth
    n_fft       = 2**np.ceil(np.log2(2*winlength))
    n_fftby2    = int(n_fft/2)
    num_frames = len(clean_speech)/skiprate-(winlength/skiprate)# number of frames
    
    hannWin=scipy.signal.windows.hann(winlength)#0.5*(1-np.cos(2*np.pi*np.arange(1,winlength+1)/(winlength+1)))
    f,t,Zxx=stft(clean_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False)
    clean_power_spec=np.square(np.sum(hannWin)*np.abs(Zxx))
    f,t,Zxx=stft(processed_speech[0:int(num_frames)*skiprate+int(winlength-skiprate)], fs=fs, window=hannWin, nperseg=winlength, noverlap=winlength-skiprate, nfft=n_fft, detrend=False, return_onesided=True, boundary=None, padded=False)
    enh_power_spec=np.square(np.sum(hannWin)*np.abs(Zxx))

    bark_filt = barks(fs, n_fft, n_barks=32)
    clean_power_spec_bark= np.dot(bark_filt,clean_power_spec)
    enh_power_spec_bark= np.dot(bark_filt,enh_power_spec)
    
    clean_power_spec_bark_2=np.square(clean_power_spec_bark)
    diff_power_spec_2 = np.square(clean_power_spec_bark-enh_power_spec_bark)
    
    bsd = np.mean(np.sum(diff_power_spec_2,axis=0)/np.sum(clean_power_spec_bark_2,axis=0))
    return bsd
//  [python]
def audio_to_melspectrum(cls, audio, sampling_rate):
        assert sampling_rate == 16000, "Only 16 KHz audio supported"
        preemph = 0.97
        preemphased = np.concatenate([audio[:1], audio[1:] - preemph * audio[:-1].astype(np.float32)])

        win_length = round(sampling_rate * 0.02)
        spec = np.abs(librosa.stft(preemphased, n_fft=512, hop_length=round(sampling_rate * 0.01),
            win_length=win_length, center=True, window=scipy.signal.hann(win_length), pad_mode='reflect'))
        mel_basis = librosa.filters.mel(sr=sampling_rate, n_fft=512, n_mels=64, fmin=0.0, fmax=8000.0, norm='slaney', htk=False)
        log_melspectrum = np.log(np.dot(mel_basis, np.power(spec, 2)) + 2 ** -24)

        normalized = (log_melspectrum - log_melspectrum.mean(1)[:, None]) / (log_melspectrum.std(1)[:, None] + 1e-5)
        remainder = normalized.shape[1] % cls.pad_to
        if remainder != 0:
            return np.pad(normalized, ((0, 0), (0, cls.pad_to - remainder)))[None]
        return normalized[None]
//  [python]
def audio_to_melspectrum(cls, audio, sampling_rate):
        assert sampling_rate == 16000, "Only 16 KHz audio supported"
        preemph = 0.97
        preemphased = np.concatenate([audio[:1], audio[1:] - preemph * audio[:-1].astype(np.float32)])

        win_length = round(sampling_rate * 0.02)
        spec = np.abs(librosa.stft(preemphased, n_fft=512, hop_length=round(sampling_rate * 0.01),
            win_length=win_length, center=True, window=scipy.signal.windows.hann(win_length), pad_mode='reflect'))
        mel_basis = librosa.filters.mel(sr=sampling_rate, n_fft=512, n_mels=64, fmin=0.0, fmax=8000.0, norm='slaney', htk=False)
        log_melspectrum = np.log(np.dot(mel_basis, np.power(spec, 2)) + 2 ** -24)

        normalized = (log_melspectrum - log_melspectrum.mean(1)[:, None]) / (log_melspectrum.std(1)[:, None] + 1e-5)
        remainder = normalized.shape[1] % cls.pad_to
        if remainder != 0:
            return np.pad(normalized, ((0, 0), (0, cls.pad_to - remainder)))[None]
        return normalized[None]
//  [python]
def plot_fft(audio, fs, title="output spectrum"):
    _, ax = plt.subplots(1, 1, figsize=(10, 4))
    N = len(audio)
    w = np.hanning(N)
    w_fft = scipy.fft.fft(w * audio)
    xf = scipy.fft.fftfreq(N, 1 / fs)[: N // 2]
    ax.plot(xf, 2.0 / N * np.abs(w_fft[0 : N // 2]), label="fft hann window")
    plt.title(title)
    plt.legend()
    plt.show()
//  [python]
def plot_fft(audio, fs, title="output spectrum"):
    _, ax = plt.subplots(1, 1, figsize=(10, 4))
    N = len(audio)
    w = scipy.signal.windows.hann((N))
    w_fft = scipy.fft.fft(w * audio)
    xf = scipy.fft.fftfreq(N, 1 / fs)[: N // 2]
    ax.plot(xf, 2.0 / N * np.abs(w_fft[0 : N // 2]), label="fft hann window")
    plt.title(title)
    plt.legend()
    plt.show()
//  [python]
window_ecg = list(s.hann(len(ecg_sample_complex)))
window_ppg = list(s.hann(len(ppg_sample_complex)))
//  [python]
window_ecg = list(wd.hann(len(ecg_sample_complex)))
window_ppg = list(wd.hann(len(ppg_sample_complex)))
//  [python]
def cadzow_np1(wav, fs=30000, rank=5, niter=1, fmax=7500):
    """
    Apply Fxy rank-denoiser to a full recording of Neuropixel 1 probe geometry
    :param wav: ntr, ns
    :param fs:
    :return:
    """
    # ntr - nswx has to be a multiple of (nswx - ovx)
    ntr, ns = wav.shape
    """
    try some window sizes:
     ovx is the overlap in x
     nswx is the size of the window in x
     npad is the padding
    """
    # ovx, nswx, npad = (int(5), int(33), int(6))
    ovx, nswx, npad = (int(16), int(32), int(0))
    # ovx, nswx, npad = (int(32), int(64), int(0))
    # ovx, nswx, npad = (int(24), int(64), int(0))
    # ovx, nswx, npad = (int(8), int(16), int(0))
    nwinx = int(np.ceil((ntr + npad * 2 - ovx) / (nswx - ovx)))
    fscale = scipy.fft.rfftfreq(ns, d=1 / fs)
    imax = np.searchsorted(fscale, fmax)
    WAV = scipy.fft.rfft(wav[:, :])
    padgain = s.hanning(npad * 2)[:npad]
    WAV = np.r_[np.flipud(WAV[1:npad + 1, :]) * padgain[:, np.newaxis],
                WAV,
                np.flipud(WAV[-npad - 2: - 1, :]) * np.flipud(np.r_[padgain, 1])[:, np.newaxis]]  # apply padding
    x = np.r_[np.flipud(h['x'][1:npad + 1]), h['x'],  np.flipud(h['x'][-npad - 2: - 1])]
    y = np.r_[np.flipud(h['y'][1:npad + 1]) - 120, h['y'],  np.flipud(h['y'][-npad - 2: - 1]) + 120]
    WAV_ = np.zeros_like(WAV)
    gain = np.zeros(ntr + npad *2 + 1)
    hanning = s.hanning(ovx * 2 - 1)[0:ovx]
    assert np.all(np.isclose(hanning + np.flipud(hanning), 1))
    gain_window = np.r_[hanning, np.ones(nswx - ovx * 2), np.flipud(hanning)]
    for firstx in np.arange(nwinx) * (nswx - ovx):
        lastx = int(firstx + nswx)
        if firstx == 0:
            gw = np.r_[hanning * 0 + 1, np.ones(nswx - ovx * 2) , np.flipud(hanning)]
        elif lastx == ntr:
            gw = np.r_[hanning, np.ones(nswx - ovx * 2), hanning * 0 + 1]
        else:
            gw = gain_window
        gain[firstx:lastx] += gw
        T, it, itr, trcount = cadzow.trajectory(x=x[firstx:lastx], y=y[firstx:lastx])
        array = WAV[firstx:lastx, :]
        print(firstx, lastx, x[firstx:lastx].shape, WAV[firstx:lastx, :].shape, T.shape)
        array = cadzow.denoise(array, x=x[firstx:lastx], y=y[firstx:lastx], r=rank, imax=imax, niter=niter)
        WAV_[firstx:lastx, :] += array * gw[:, np.newaxis]

    WAV_ = WAV_[npad:-npad - 1]  # remove padding
    wav_ = scipy.fft.irfft(WAV_)
    return wav_
//  [python]
def cadzow_np1(wav, fs=30000, rank=5, niter=1, fmax=7500):
    """
    Apply Fxy rank-denoiser to a full recording of Neuropixel 1 probe geometry
    :param wav: ntr, ns
    :param fs:
    :return:
    """
    # ntr - nswx has to be a multiple of (nswx - ovx)
    ntr, ns = wav.shape
    """
    try some window sizes:
     ovx is the overlap in x
     nswx is the size of the window in x
     npad is the padding
    """
    # ovx, nswx, npad = (int(5), int(33), int(6))
    ovx, nswx, npad = (int(16), int(32), int(0))
    # ovx, nswx, npad = (int(32), int(64), int(0))
    # ovx, nswx, npad = (int(24), int(64), int(0))
    # ovx, nswx, npad = (int(8), int(16), int(0))
    nwinx = int(np.ceil((ntr + npad * 2 - ovx) / (nswx - ovx)))
    fscale = scipy.fft.rfftfreq(ns, d=1 / fs)
    imax = np.searchsorted(fscale, fmax)
    WAV = scipy.fft.rfft(wav[:, :])
    padgain = scipy.signal.windows.hann(npad * 2)[:npad]
    WAV = np.r_[np.flipud(WAV[1:npad + 1, :]) * padgain[:, np.newaxis],
                WAV,
                np.flipud(WAV[-npad - 2: - 1, :]) * np.flipud(np.r_[padgain, 1])[:, np.newaxis]]  # apply padding
    x = np.r_[np.flipud(h['x'][1:npad + 1]), h['x'],  np.flipud(h['x'][-npad - 2: - 1])]
    y = np.r_[np.flipud(h['y'][1:npad + 1]) - 120, h['y'],  np.flipud(h['y'][-npad - 2: - 1]) + 120]
    WAV_ = np.zeros_like(WAV)
    gain = np.zeros(ntr + npad *2 + 1)
    hanning = scipy.signal.windows.hann(ovx * 2 - 1)[0:ovx]
    assert np.all(np.isclose(hanning + np.flipud(hanning), 1))
    gain_window = np.r_[hanning, np.ones(nswx - ovx * 2), np.flipud(hanning)]
    for firstx in np.arange(nwinx) * (nswx - ovx):
        lastx = int(firstx + nswx)
        if firstx == 0:
            gw = np.r_[hanning * 0 + 1, np.ones(nswx - ovx * 2) , np.flipud(hanning)]
        elif lastx == ntr:
            gw = np.r_[hanning, np.ones(nswx - ovx * 2), hanning * 0 + 1]
        else:
            gw = gain_window
        gain[firstx:lastx] += gw
        T, it, itr, trcount = cadzow.trajectory(x=x[firstx:lastx], y=y[firstx:lastx])
        array = WAV[firstx:lastx, :]
        print(firstx, lastx, x[firstx:lastx].shape, WAV[firstx:lastx, :].shape, T.shape)
        array = cadzow.denoise(array, x=x[firstx:lastx], y=y[firstx:lastx], r=rank, imax=imax, niter=niter)
        WAV_[firstx:lastx, :] += array * gw[:, np.newaxis]

    WAV_ = WAV_[npad:-npad - 1]  # remove padding
    wav_ = scipy.fft.irfft(WAV_)
    return wav_
//  [python]
def spectrogram(x, window=1024, step=512, wf=s.hann(1024), n_oversample=13):

    n_spec = int((len(x) - window) / step)

    # n_oversample has to be odd
    if n_oversample % 2 == 0:
        n_oversample += 1

    n_substep = int(step / n_oversample)
    substep_idx = np.arange(n_oversample, dtype=int) - \
        int((n_oversample - 1) / 2)

    S = np.zeros([n_spec, window], dtype=np.float64)
    for i in range(n_spec):
        n_avg = 0.0
        for j in range(n_oversample):
            i0 = i * step + substep_idx[j] * n_substep
            i1 = i * step + substep_idx[j] * n_substep + window
#            print("%d %d"%(i0,step))

            if (i0 >= 0) and (i1 < len(x)):
                freq_pwr = np.abs(np.fft.fftshift(
                    np.fft.fft(wf * x[i0:i1])))**2.0
                std_est = np.nanmedian(np.abs(freq_pwr - n.nanmedian(freq_pwr)))
#                print(std_est)
                if std_est > 0:
                    # *np.abs(np.fft.fftshift(np.fft.fft(wf*x[i0:i1])))**2.0
                    S[i, :] += (1.0 / (std_est**2.0)) * freq_pwr
                    n_avg += 1.0 / (std_est**2.0)

        S[i, :] = S[i, :] / n_avg

    # normalize scale to float16
    S = 5e4 * S / n.nanmax(S)
    return (S)
//  [python]
def spectrogram(x, window=1024, step=512, wf=ss.hann(1024), n_oversample=13):

    n_spec = int((len(x) - window) / step)

    # n_oversample has to be odd
    if n_oversample % 2 == 0:
        n_oversample += 1

    n_substep = int(step / n_oversample)
    substep_idx = np.arange(n_oversample, dtype=int) - \
        int((n_oversample - 1) / 2)

    S = np.zeros([n_spec, window], dtype=np.float64)
    for i in range(n_spec):
        n_avg = 0.0
        for j in range(n_oversample):
            i0 = i * step + substep_idx[j] * n_substep
            i1 = i * step + substep_idx[j] * n_substep + window
#            print("%d %d"%(i0,step))

            if (i0 >= 0) and (i1 < len(x)):
                freq_pwr = np.abs(np.fft.fftshift(
                    np.fft.fft(wf * x[i0:i1])))**2.0
                std_est = np.nanmedian(np.abs(freq_pwr - n.nanmedian(freq_pwr)))
#                print(std_est)
                if std_est > 0:
                    # *np.abs(np.fft.fftshift(np.fft.fft(wf*x[i0:i1])))**2.0
                    S[i, :] += (1.0 / (std_est**2.0)) * freq_pwr
                    n_avg += 1.0 / (std_est**2.0)

        S[i, :] = S[i, :] / n_avg

    # normalize scale to float16
    S = 5e4 * S / n.nanmax(S)
    return (S)
//  [python]
def fft(self, num_bins, decimate=1):
        if self.last_fft_bins != num_bins:
            print(f"creating new FFTW object: {num_bins} bins")
            self.last_fft_bins = num_bins
            self.fft_input = pyfftw.empty_aligned(num_bins, dtype='complex128')
            self.fft_output = pyfftw.empty_aligned(num_bins, dtype='complex128')
            self.fftw = pyfftw.FFTW(self.fft_input, self.fft_output)

        num_samples = num_bins * decimate

        if self.last_window_size != num_bins:
            print(f"creating new window function: n={num_bins}")
            self.window = s.hanning(num_bins)
            self.last_window_size = num_bins

        signal = self.provider.get_samples(num_samples)
        if decimate == 1:
            signal *= self.window
            self.fft_input[:] = signal
        else:
            self.fft_input[:] = scipy.signal.decimate(signal, decimate, zero_phase=False) * self.window
        self.fftw()
        fft = np.fft.fftshift(self.fft_output)
        fft = np.absolute(fft)
        return fft
//  [python]
def fft(self, num_bins, decimate=1):
        if self.last_fft_bins != num_bins:
            print(f"creating new FFTW object: {num_bins} bins")
            self.last_fft_bins = num_bins
            self.fft_input = pyfftw.empty_aligned(num_bins, dtype='complex128')
            self.fft_output = pyfftw.empty_aligned(num_bins, dtype='complex128')
            self.fftw = pyfftw.FFTW(self.fft_input, self.fft_output)

        num_samples = num_bins * decimate

        if self.last_window_size != num_bins:
            print(f"creating new window function: n={num_bins}")
            self.window = scipy.signal.windows.hann(num_bins, sym=False)
            self.last_window_size = num_bins

        signal = self.provider.get_samples(num_samples)
        if decimate == 1:
            signal *= self.window
            self.fft_input[:] = signal
        else:
            self.fft_input[:] = scipy.signal.decimate(signal, decimate, zero_phase=False) * self.window
        self.fftw()
        fft = np.fft.fftshift(self.fft_output)
        fft = np.absolute(fft)
        return fft
//  [python]
def __init__(self, format: str, sampling_frequency: int, frame_sample_count: int, channel_count: int) -> None:
        self.frame_info = FrameInfo(
            format, sampling_frequency, frame_sample_count, channel_count)
        self.window = np.sqrt(scipy.signal.windows.hann(frame_sample_count))
        self.buffer = np.zeros(
            (channel_count, int(self.frame_info.frame_sample_count * 3 / 2)))
//  [python]
def __init__(
        self, rate: Union[int, float], window_size: int, shift: int = 1,
        pad_type: str = 'both',
    ):
        """
        Extract local speech rate from acoustic units (phonemes, syllables,
        words, ...) according to [1].

        [1]: Pfitzinger, Hartmut R. "Reducing Segmental Duration Variation by
        Local Speech Rate Normalization of Large Spoken Language Resources."
        In LREC. 2002.

        Args:
            rate: Input rate of the signal.
            window_size: Total number of context samples or frames.
            shift: Shift between successive windows. Defaults to 1.
            pad_type: Controls convolution behavior.
                    None: No padding.
                    front: Causal convolution.
                    end: Append zeros before convolution.
                    both: Add window_length / 2 zeros to both sides of the
                        signal.
                When padding is None, the output length is
                `(T - self.window_size + 1) / self.shift`, where `T` is the
                input length of the signal. Otherwise, the output length is
                `T / self.shift`.
        """
        super().__init__()
        self.sr = rate
        window_size = int(window_size / shift)
        if window_size % 2 == 0:
            # Ensure odd number of samples in window
            window_size += 1
        self.window_size = window_size
        self.shift = shift
        w = torch.from_numpy(
            np.hanning(self.window_size)
        )[None, None].float()
        self.register_buffer('window', w)
        self.pad_type = pad_type
//  [python]
def __init__(
        self, rate: Union[int, float], window_size: int, shift: int = 1,
        pad_type: str = 'both',
    ):
        """
        Extract local speech rate from acoustic units (phonemes, syllables,
        words, ...) according to [1].

        [1]: Pfitzinger, Hartmut R. "Reducing Segmental Duration Variation by
        Local Speech Rate Normalization of Large Spoken Language Resources."
        In LREC. 2002.

        Args:
            rate: Input rate of the signal.
            window_size: Total number of context samples or frames.
            shift: Shift between successive windows. Defaults to 1.
            pad_type: Controls convolution behavior.
                    None: No padding.
                    front: Causal convolution.
                    end: Append zeros before convolution.
                    both: Add window_length / 2 zeros to both sides of the
                        signal.
                When padding is None, the output length is
                `(T - self.window_size + 1) / self.shift`, where `T` is the
                input length of the signal. Otherwise, the output length is
                `T / self.shift`.
        """
        super().__init__()
        self.sr = rate
        window_size = int(window_size / shift)
        if window_size % 2 == 0:
            # Ensure odd number of samples in window
            window_size += 1
        self.window_size = window_size
        self.shift = shift
        w = torch.from_numpy(
            signal.windows.hann(self.window_size, sym=False)
        )[None, None].float()
        self.register_buffer('window', w)
        self.pad_type = pad_type
//  [python]
def get_window(window="boxcar", half_win=3):
    window_len = 2 * half_win + 1
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype('complex')
    else:
        w = scipy.signal.hann(window_len).astype('complex')
    return w / window_len
//  [python]
def get_window(window="boxcar", half_win=3):
    window_len = 2 * half_win + 1
    if window == "boxcar":
        w = scipy.signal.boxcar(window_len).astype('complex')
    else:
        w = scipy.signal.windows.hann(window_len).astype('complex')
    return w / window_len
//  [python]
def compute_activation_confidence(mtrack, 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 multitrack. 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
    ----------
    mtrack : MultiTrack
        Multitrack 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)
    stem_index_list : list
        List of stem indices in the order they appear in C

    """
    H = []
    stem_index_list = []

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

    for stem_idx, track in mtrack.stems.items():
        audio, rate = librosa.load(track.audio_path, sr=44100, mono=True)
        H.append(track_energy(audio.T, win_len, win))
        stem_index_list.append(stem_idx)

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

    # normalization (to overall energy and # of sources)
    E0 = np.sum(H, axis=0)
    
    H = len(mtrack.stems) * 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, stem_index_list
//  [python]
def compute_activation_confidence(mtrack, 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 multitrack. 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
    ----------
    mtrack : MultiTrack
        Multitrack 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)
    stem_index_list : list
        List of stem indices in the order they appear in C

    """
    H = []
    stem_index_list = []

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

    for stem_idx, track in mtrack.stems.items():
        audio, rate = librosa.load(track.audio_path, sr=44100, mono=True)
        H.append(track_energy(audio.T, win_len, win))
        stem_index_list.append(stem_idx)

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

    # normalization (to overall energy and # of sources)
    E0 = np.sum(H, axis=0)
    
    H = len(mtrack.stems) * 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, stem_index_list
//  [python]
def __init__(self, fs = 48000):
        """Instantiate NSnet2 given a trained model path."""
        self.cfg, modelfile = self._config(fs)
        self.frameShift = float(self.cfg['winlen'])* float(self.cfg["hopfrac"])
        self.fs = int(self.cfg['fs'])
        self.mingain = 10**(self.cfg['mingain']/20)
        self.N_win = int(float(self.cfg['winlen']) * self.fs)
        if 'nfft' in self.cfg:
            self.N_fft = int(self.cfg['nfft'])
        else:
            self.N_fft = self.N_win
        self.N_hop = int(self.N_fft * float(self.cfg["hopfrac"]))
        
        """load onnx model"""
        modelfile = dirname(__file__)+"/" + modelfile
        self.ort = ort.InferenceSession(modelfile)
        self.dtype = np.float32
        self.win = np.sqrt(s.hann(self.N_win, sym=False))
        self.win_buf = torch.from_numpy(self.win).float()        
        L = len(self.win)
        awin = np.zeros_like(self.win)
        for k in range(0, self.N_hop):
            idx = range(k, L, self.N_hop)
            H = self.win[idx]
            awin[idx] = np.linalg.pinv(H[:,np.newaxis])
        self.awin = torch.from_numpy(awin).float()
//  [python]
def __init__(self, fs = 48000):
        """Instantiate NSnet2 given a trained model path."""
        self.cfg, modelfile = self._config(fs)
        self.frameShift = float(self.cfg['winlen'])* float(self.cfg["hopfrac"])
        self.fs = int(self.cfg['fs'])
        self.mingain = 10**(self.cfg['mingain']/20)
        self.N_win = int(float(self.cfg['winlen']) * self.fs)
        if 'nfft' in self.cfg:
            self.N_fft = int(self.cfg['nfft'])
        else:
            self.N_fft = self.N_win
        self.N_hop = int(self.N_fft * float(self.cfg["hopfrac"]))
        
        """load onnx model"""
        modelfile = dirname(__file__)+"/" + modelfile
        self.ort = ort.InferenceSession(modelfile)
        self.dtype = np.float32
        self.win = np.sqrt(scipy.signal.windows.hann(self.N_win, sym=False))
        self.win_buf = torch.from_numpy(self.win).float()        
        L = len(self.win)
        awin = np.zeros_like(self.win)
        for k in range(0, self.N_hop):
            idx = range(k, L, self.N_hop)
            H = self.win[idx]
            awin[idx] = np.linalg.pinv(H[:,np.newaxis])
        self.awin = torch.from_numpy(awin).float()
//  [python]
def make_ramps(samples, fs, onramp_ms, offramp_ms, ramp_type):
    """Internal function used to create on- and offramps. Supports 'linear' and 'raised-cosine' ramps."""

    # Create onramp
    onramp_samples_len = int(onramp_ms / 1000 * fs)
    offramp_samples_len = int(offramp_ms / 1000 * fs)

    if onramp_ms < 0 or offramp_ms < 0:
        raise ValueError("Ramp duration must be positive.")
    elif onramp_ms == 0 and offramp_ms == 0:
        return samples
    elif onramp_samples_len > len(samples):
        raise ValueError("Onramp is longer than stimulus")
    elif offramp_samples_len > len(samples):
        raise ValueError("Offramp is longer than stimulus")

    # ONRAMP
    if ramp_type == "linear":
        onramp_amps = np.linspace(0, 1, onramp_samples_len)

    elif ramp_type == "raised-cosine":
        hann_complete = scipy.signal.windows.hann(onramp_samples_len * 2)
        onramp_amps = hann_complete[: hann_complete.shape[0] // 2]

    else:
        raise ValueError("Unknown ramp type. Use 'linear' or 'raised-cosine'")

    end_point = onramp_samples_len

    if samples.ndim == 1:
        samples[:end_point] *= onramp_amps
    elif samples.ndim == 2:
        samples[:end_point, 0] *= onramp_amps
        samples[:end_point, 1] *= onramp_amps

    # OFFRAMP
    start_point = len(samples) - offramp_samples_len

    if ramp_type == "linear":
        offramp_amps = np.linspace(1, 0, int(offramp_ms / 1000 * fs))
    elif ramp_type == "raised-cosine":
        hann_complete = scipy.signal.windows.hann(offramp_samples_len * 2)
        offramp_amps = hann_complete[hann_complete.shape[0] // 2:]
    else:
        raise ValueError("Unknown ramp type. Use 'linear' or 'raised-cosine'")

    if samples.ndim == 1:
        samples[start_point:] *= offramp_amps
    elif samples.ndim == 2:
        samples[start_point:, 0] *= offramp_amps
        samples[start_point:, 1] *= offramp_amps

    return samples
//  [python]
def test_numeric_types(self):
        # Check itemfreq works for all dtypes (adapted from np.unique tests)
        def _check_itemfreq(dt):
            a = np.array(self.a, dt)
            with suppress_warnings() as sup:
                sup.filter(DeprecationWarning)
                v = stats.itemfreq(a)
            assert_array_equal(v[:, 0], [1, 2, 5, 7])
            assert_array_equal(v[:, 1], np.array([20, 10, 20, 20], dtype=dt))

        dtypes = [np.int32, np.int64, np.float32, np.float64,
                  np.complex64, np.complex128]
        for dt in dtypes:
            _check_itemfreq(dt)
//  [python]
def test_numeric_types(self):
        # Check itemfreq works for all dtypes (adapted from np.unique tests)
        def _check_itemfreq(dt):
            a = np.array(self.a, dt)
            with suppress_warnings() as sup:
                sup.filter(DeprecationWarning)
                v = stats.binned_statistic(a, a, statistic='count', bins=np.arange(min(a)-.5, max(a)+1.5))
                v = np.array([v[0][np.where(v[0]>0)], v[1][np.where(v[0]>0)]]).T

            assert_array_equal(v[:, 0], [1, 2, 5, 7])
            assert_array_equal(v[:, 1], np.array([20, 10, 20, 20], dtype=dt))

        dtypes = [np.int32, np.int64, np.float32, np.float64,
                  np.complex64, np.complex128]
        for dt in dtypes:
            _check_itemfreq(dt)
//  [python]
def test_object_arrays(self):
        a, b = self.a, self.b
        dt = 'O'
        aa = np.empty(len(a), dt)
        aa[:] = a
        bb = np.empty(len(b), dt)
        bb[:] = b
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            v = stats.itemfreq(aa)
        assert_array_equal(v[:, 0], bb)
//  [python]
def test_object_arrays(self):
        a, b = self.a, self.b
        dt = 'O'
        aa = np.empty(len(a), dt)
        aa[:] = a
        bb = np.empty(len(b), dt)
        bb[:] = b
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            v = stats.binned_statistic(aa, aa, statistic='count')
        assert_array_equal(v[:, 0], bb)