_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q267900
A_weighting
test
def A_weighting(frequencies, min_db=-80.0): # pylint: disable=invalid-name '''Compute the A-weighting of a set of frequencies. Parameters ---------- frequencies : scalar or np.ndarray [shape=(n,)] One or more frequencies (in Hz) min_db : float [scalar] or None Clip weights belo...
python
{ "resource": "" }
q267901
times_like
test
def times_like(X, sr=22050, hop_length=512, n_fft=None, axis=-1): """Return an array of time values to match the time axis from a feature matrix. Parameters ---------- X : np.ndarray or scalar - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram. - If scalar, X...
python
{ "resource": "" }
q267902
samples_like
test
def samples_like(X, hop_length=512, n_fft=None, axis=-1): """Return an array of sample indices to match the time axis from a feature matrix. Parameters ---------- X : np.ndarray or scalar - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram. - If scalar, X repr...
python
{ "resource": "" }
q267903
hybrid_cqt
test
def hybrid_cqt(y, sr=22050, hop_length=512, fmin=None, n_bins=84, bins_per_octave=12, tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann', scale=True, pad_mode='reflect', res_type=None): '''Compute the hybrid constant-Q transform of an audio signal. Her...
python
{ "resource": "" }
q267904
pseudo_cqt
test
def pseudo_cqt(y, sr=22050, hop_length=512, fmin=None, n_bins=84, bins_per_octave=12, tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann', scale=True, pad_mode='reflect'): '''Compute the pseudo constant-Q transform of an audio signal. This uses a single...
python
{ "resource": "" }
q267905
icqt
test
def icqt(C, sr=22050, hop_length=512, fmin=None, bins_per_octave=12, tuning=0.0, filter_scale=1, norm=1, sparsity=0.01, window='hann', scale=True, length=None, amin=util.Deprecated(), res_type='fft'): '''Compute the inverse constant-Q transform. Given a constant-Q transform representation `C`...
python
{ "resource": "" }
q267906
__cqt_filter_fft
test
def __cqt_filter_fft(sr, fmin, n_bins, bins_per_octave, tuning, filter_scale, norm, sparsity, hop_length=None, window='hann'): '''Generate the frequency domain constant-Q filter basis.''' basis, lengths = filters.constant_q(sr, f...
python
{ "resource": "" }
q267907
__trim_stack
test
def __trim_stack(cqt_resp, n_bins): '''Helper function to trim and stack a collection of CQT responses''' # cleanup any framing errors at the boundaries max_col = min(x.shape[1] for x in cqt_resp) cqt_resp = np.vstack([x[:, :max_col] for x in cqt_resp][::-1]) # Finally, clip out any bottom freque...
python
{ "resource": "" }
q267908
__cqt_response
test
def __cqt_response(y, n_fft, hop_length, fft_basis, mode): '''Compute the filter response with a target STFT hop.''' # Compute the STFT matrix D = stft(y, n_fft=n_fft, hop_length=hop_length, window='ones', pad_mode=mode) # And filter response energy return fft_basis.dot(D...
python
{ "resource": "" }
q267909
__early_downsample_count
test
def __early_downsample_count(nyquist, filter_cutoff, hop_length, n_octaves): '''Compute the number of early downsampling operations''' downsample_count1 = max(0, int(np.ceil(np.log2(audio.BW_FASTEST * nyquist / filter_cutoff)) - 1) - 1) num_twos = __num_t...
python
{ "resource": "" }
q267910
__early_downsample
test
def __early_downsample(y, sr, hop_length, res_type, n_octaves, nyquist, filter_cutoff, scale): '''Perform early downsampling on an audio signal, if it applies.''' downsample_count = __early_downsample_count(nyquist, filter_cutoff, hop_lengt...
python
{ "resource": "" }
q267911
__dtw_calc_accu_cost
test
def __dtw_calc_accu_cost(C, D, D_steps, step_sizes_sigma, weights_mul, weights_add, max_0, max_1): # pragma: no cover '''Calculate the accumulated cost matrix D. Use dynamic programming to calculate the accumulated costs. Parameters ---------- C : np.ndarray [shape=(N, M)...
python
{ "resource": "" }
q267912
__dtw_backtracking
test
def __dtw_backtracking(D_steps, step_sizes_sigma): # pragma: no cover '''Backtrack optimal warping path. Uses the saved step sizes from the cost accumulation step to backtrack the index pairs for an optimal warping path. Parameters ---------- D_steps : np.ndarray [shape=(N, M)] S...
python
{ "resource": "" }
q267913
_viterbi
test
def _viterbi(log_prob, log_trans, log_p_init, state, value, ptr): # pragma: no cover '''Core Viterbi algorithm. This is intended for internal use only. Parameters ---------- log_prob : np.ndarray [shape=(T, m)] `log_prob[t, s]` is the conditional log-likelihood log P[X = X(t) | St...
python
{ "resource": "" }
q267914
viterbi_discriminative
test
def viterbi_discriminative(prob, transition, p_state=None, p_init=None, return_logp=False): '''Viterbi decoding from discriminative state predictions. Given a sequence of conditional state predictions `prob[s, t]`, indicating the conditional likelihood of state `s` given the observation at time `t`, an...
python
{ "resource": "" }
q267915
transition_uniform
test
def transition_uniform(n_states): '''Construct a uniform transition matrix over `n_states`. Parameters ---------- n_states : int > 0 The number of states Returns ------- transition : np.ndarray [shape=(n_states, n_states)] `transition[i, j] = 1./n_states` Examples ...
python
{ "resource": "" }
q267916
transition_loop
test
def transition_loop(n_states, prob): '''Construct a self-loop transition matrix over `n_states`. The transition matrix will have the following properties: - `transition[i, i] = p` for all i - `transition[i, j] = (1 - p) / (n_states - 1)` for all `j != i` This type of transition matrix is ...
python
{ "resource": "" }
q267917
transition_cycle
test
def transition_cycle(n_states, prob): '''Construct a cyclic transition matrix over `n_states`. The transition matrix will have the following properties: - `transition[i, i] = p` - `transition[i, i + 1] = (1 - p)` This type of transition matrix is appropriate for state spaces with cycl...
python
{ "resource": "" }
q267918
transition_local
test
def transition_local(n_states, width, window='triangle', wrap=False): '''Construct a localized transition matrix. The transition matrix will have the following properties: - `transition[i, j] = 0` if `|i - j| > width` - `transition[i, i]` is maximal - `transition[i, i - width//2 : i + ...
python
{ "resource": "" }
q267919
onset_detect
test
def onset_detect(y=None, sr=22050, onset_envelope=None, hop_length=512, backtrack=False, energy=None, units='frames', **kwargs): """Basic onset detector. Locate note onset events by picking peaks in an onset strength envelope. The `peak_pick` parameters were chosen by lar...
python
{ "resource": "" }
q267920
onset_strength
test
def onset_strength(y=None, sr=22050, S=None, lag=1, max_size=1, ref=None, detrend=False, center=True, feature=None, aggregate=None, centering=None, **kwargs): """Compute a spectral flux onset strength envelope. Onset...
python
{ "resource": "" }
q267921
onset_backtrack
test
def onset_backtrack(events, energy): '''Backtrack detected onset events to the nearest preceding local minimum of an energy function. This function can be used to roll back the timing of detected onsets from a detected peak amplitude to the preceding minimum. This is most useful when using onsets ...
python
{ "resource": "" }
q267922
onset_strength_multi
test
def onset_strength_multi(y=None, sr=22050, S=None, lag=1, max_size=1, ref=None, detrend=False, center=True, feature=None, aggregate=None, channels=None, **kwargs): """Compute a spectral flux onset strength envelope across multiple channels. Onset strength for c...
python
{ "resource": "" }
q267923
times_csv
test
def times_csv(path, times, annotations=None, delimiter=',', fmt='%0.3f'): r"""Save time steps as in CSV format. This can be used to store the output of a beat-tracker or segmentation algorithm. If only `times` are provided, the file will contain each value of `times` on a row:: times[0]\n ...
python
{ "resource": "" }
q267924
write_wav
test
def write_wav(path, y, sr, norm=False): """Output a time series as a .wav file Note: only mono or stereo, floating-point data is supported. For more advanced and flexible output options, refer to `soundfile`. Parameters ---------- path : str path to save the output wav file...
python
{ "resource": "" }
q267925
cmap
test
def cmap(data, robust=True, cmap_seq='magma', cmap_bool='gray_r', cmap_div='coolwarm'): '''Get a default colormap from the given data. If the data is boolean, use a black and white colormap. If the data has both positive and negative values, use a diverging colormap. Otherwise, use a sequential c...
python
{ "resource": "" }
q267926
waveplot
test
def waveplot(y, sr=22050, max_points=5e4, x_axis='time', offset=0.0, max_sr=1000, ax=None, **kwargs): '''Plot the amplitude envelope of a waveform. If `y` is monophonic, a filled curve is drawn between `[-abs(y), abs(y)]`. If `y` is stereo, the curve is drawn between `[-abs(y[1]), abs(y[0])]`...
python
{ "resource": "" }
q267927
__set_current_image
test
def __set_current_image(ax, img): '''Helper to set the current image in pyplot mode. If the provided `ax` is not `None`, then we assume that the user is using the object API. In this case, the pyplot current image is not set. ''' if ax is None: import matplotlib.pyplot as plt plt.s...
python
{ "resource": "" }
q267928
__mesh_coords
test
def __mesh_coords(ax_type, coords, n, **kwargs): '''Compute axis coordinates''' if coords is not None: if len(coords) < n: raise ParameterError('Coordinate shape mismatch: ' '{}<{}'.format(len(coords), n)) return coords coord_map = {'linear': __...
python
{ "resource": "" }
q267929
__check_axes
test
def __check_axes(axes): '''Check if "axes" is an instance of an axis object. If not, use `gca`.''' if axes is None: import matplotlib.pyplot as plt axes = plt.gca() elif not isinstance(axes, Axes): raise ValueError("`axes` must be an instance of matplotlib.axes.Axes. " ...
python
{ "resource": "" }
q267930
__scale_axes
test
def __scale_axes(axes, ax_type, which): '''Set the axis scaling''' kwargs = dict() if which == 'x': thresh = 'linthreshx' base = 'basex' scale = 'linscalex' scaler = axes.set_xscale limit = axes.set_xlim else: thresh = 'linthreshy' base = 'basey' ...
python
{ "resource": "" }
q267931
__coord_fft_hz
test
def __coord_fft_hz(n, sr=22050, **_kwargs): '''Get the frequencies for FFT bins''' n_fft = 2 * (n - 1) # The following code centers the FFT bins at their frequencies # and clips to the non-negative frequency range [0, nyquist] basis = core.fft_frequencies(sr=sr, n_fft=n_fft) fmax = basis[-1] ...
python
{ "resource": "" }
q267932
__coord_mel_hz
test
def __coord_mel_hz(n, fmin=0, fmax=11025.0, **_kwargs): '''Get the frequencies for Mel bins''' if fmin is None: fmin = 0 if fmax is None: fmax = 11025.0 basis = core.mel_frequencies(n, fmin=fmin, fmax=fmax) basis[1:] -= 0.5 * np.diff(basis) basis = np.append(np.maximum(0, basis...
python
{ "resource": "" }
q267933
__coord_cqt_hz
test
def __coord_cqt_hz(n, fmin=None, bins_per_octave=12, **_kwargs): '''Get CQT bin frequencies''' if fmin is None: fmin = core.note_to_hz('C1') # we drop by half a bin so that CQT bins are centered vertically return core.cqt_frequencies(n+1, fmin=fmin / 2.0**(0.5/bi...
python
{ "resource": "" }
q267934
__coord_chroma
test
def __coord_chroma(n, bins_per_octave=12, **_kwargs): '''Get chroma bin numbers''' return np.linspace(0, (12.0 * n) / bins_per_octave, num=n+1, endpoint=True)
python
{ "resource": "" }
q267935
__coord_time
test
def __coord_time(n, sr=22050, hop_length=512, **_kwargs): '''Get time coordinates from frames''' return core.frames_to_time(np.arange(n+1), sr=sr, hop_length=hop_length)
python
{ "resource": "" }
q267936
estimate_tuning
test
def estimate_tuning(y=None, sr=22050, S=None, n_fft=2048, resolution=0.01, bins_per_octave=12, **kwargs): '''Estimate the tuning of an audio time series or spectrogram input. Parameters ---------- y: np.ndarray [shape=(n,)] or None audio signal sr : number > 0 [scalar] ...
python
{ "resource": "" }
q267937
piptrack
test
def piptrack(y=None, sr=22050, S=None, n_fft=2048, hop_length=None, fmin=150.0, fmax=4000.0, threshold=0.1, win_length=None, window='hann', center=True, pad_mode='reflect', ref=None): '''Pitch tracking on thresholded parabolically-interpolated STFT. This implementation us...
python
{ "resource": "" }
q267938
hpss
test
def hpss(y, **kwargs): '''Decompose an audio time series into harmonic and percussive components. This function automates the STFT->HPSS->ISTFT pipeline, and ensures that the output waveforms have equal length to the input waveform `y`. Parameters ---------- y : np.ndarray [shape=(n,)] ...
python
{ "resource": "" }
q267939
harmonic
test
def harmonic(y, **kwargs): '''Extract harmonic elements from an audio time-series. Parameters ---------- y : np.ndarray [shape=(n,)] audio time series kwargs : additional keyword arguments. See `librosa.decompose.hpss` for details. Returns ------- y_harmonic : np.ndarra...
python
{ "resource": "" }
q267940
percussive
test
def percussive(y, **kwargs): '''Extract percussive elements from an audio time-series. Parameters ---------- y : np.ndarray [shape=(n,)] audio time series kwargs : additional keyword arguments. See `librosa.decompose.hpss` for details. Returns ------- y_percussive : np....
python
{ "resource": "" }
q267941
time_stretch
test
def time_stretch(y, rate): '''Time-stretch an audio series by a fixed rate. Parameters ---------- y : np.ndarray [shape=(n,)] audio time series rate : float > 0 [scalar] Stretch factor. If `rate > 1`, then the signal is sped up. If `rate < 1`, then the signal is slowed d...
python
{ "resource": "" }
q267942
pitch_shift
test
def pitch_shift(y, sr, n_steps, bins_per_octave=12, res_type='kaiser_best'): '''Pitch-shift the waveform by `n_steps` half-steps. Parameters ---------- y : np.ndarray [shape=(n,)] audio time-series sr : number > 0 [scalar] audio sampling rate of `y` n_steps : float [scalar] ...
python
{ "resource": "" }
q267943
remix
test
def remix(y, intervals, align_zeros=True): '''Remix an audio signal by re-ordering time intervals. Parameters ---------- y : np.ndarray [shape=(t,) or (2, t)] Audio time series intervals : iterable of tuples (start, end) An iterable (list-like or generator) where the `i`th item ...
python
{ "resource": "" }
q267944
_signal_to_frame_nonsilent
test
def _signal_to_frame_nonsilent(y, frame_length=2048, hop_length=512, top_db=60, ref=np.max): '''Frame-wise non-silent indicator for audio input. This is a helper function for `trim` and `split`. Parameters ---------- y : np.ndarray, shape=(n,) or (2,n) Audio ...
python
{ "resource": "" }
q267945
trim
test
def trim(y, top_db=60, ref=np.max, frame_length=2048, hop_length=512): '''Trim leading and trailing silence from an audio signal. Parameters ---------- y : np.ndarray, shape=(n,) or (2,n) Audio signal, can be mono or stereo top_db : number > 0 The threshold (in decibels) below refe...
python
{ "resource": "" }
q267946
split
test
def split(y, top_db=60, ref=np.max, frame_length=2048, hop_length=512): '''Split an audio signal into non-silent intervals. Parameters ---------- y : np.ndarray, shape=(n,) or (2, n) An audio signal top_db : number > 0 The threshold (in decibels) below reference to consider as ...
python
{ "resource": "" }
q267947
phase_vocoder
test
def phase_vocoder(D, rate, hop_length=None): """Phase vocoder. Given an STFT matrix D, speed up by a factor of `rate` Based on the implementation provided by [1]_. .. [1] Ellis, D. P. W. "A phase vocoder in Matlab." Columbia University, 2002. http://www.ee.columbia.edu/~dpwe/resources/mat...
python
{ "resource": "" }
q267948
amplitude_to_db
test
def amplitude_to_db(S, ref=1.0, amin=1e-5, top_db=80.0): '''Convert an amplitude spectrogram to dB-scaled spectrogram. This is equivalent to ``power_to_db(S**2)``, but is provided for convenience. Parameters ---------- S : np.ndarray input amplitude ref : scalar or callable If...
python
{ "resource": "" }
q267949
_spectrogram
test
def _spectrogram(y=None, S=None, n_fft=2048, hop_length=512, power=1, win_length=None, window='hann', center=True, pad_mode='reflect'): '''Helper function to retrieve a magnitude spectrogram. This is primarily used in feature extraction functions that can operate on either audio time-serie...
python
{ "resource": "" }
q267950
hpss_beats
test
def hpss_beats(input_file, output_csv): '''HPSS beat tracking :parameters: - input_file : str Path to input audio file (wav, mp3, m4a, flac, etc.) - output_file : str Path to save beat event timestamps as a CSV file ''' # Load the file print('Loading ', input_file...
python
{ "resource": "" }
q267951
decompose
test
def decompose(S, n_components=None, transformer=None, sort=False, fit=True, **kwargs): """Decompose a feature matrix. Given a spectrogram `S`, produce a decomposition into `components` and `activations` such that `S ~= components.dot(activations)`. By default, this is done with with non-negative matri...
python
{ "resource": "" }
q267952
nn_filter
test
def nn_filter(S, rec=None, aggregate=None, axis=-1, **kwargs): '''Filtering by nearest-neighbors. Each data point (e.g, spectrogram column) is replaced by aggregating its nearest neighbors in feature space. This can be useful for de-noising a spectrogram or feature matrix. The non-local means met...
python
{ "resource": "" }
q267953
__nn_filter_helper
test
def __nn_filter_helper(R_data, R_indices, R_ptr, S, aggregate): '''Nearest-neighbor filter helper function. This is an internal function, not for use outside of the decompose module. It applies the nearest-neighbor filter to S, assuming that the first index corresponds to observations. Parameters...
python
{ "resource": "" }
q267954
mel
test
def mel(sr, n_fft, n_mels=128, fmin=0.0, fmax=None, htk=False, norm=1, dtype=np.float32): """Create a Filterbank matrix to combine FFT bins into Mel-frequency bins Parameters ---------- sr : number > 0 [scalar] sampling rate of the incoming signal n_fft : int > 0 [scalar...
python
{ "resource": "" }
q267955
chroma
test
def chroma(sr, n_fft, n_chroma=12, A440=440.0, ctroct=5.0, octwidth=2, norm=2, base_c=True, dtype=np.float32): """Create a Filterbank matrix to convert STFT to chroma Parameters ---------- sr : number > 0 [scalar] audio sampling rate n_fft : int > 0 [scalar] ...
python
{ "resource": "" }
q267956
__float_window
test
def __float_window(window_spec): '''Decorator function for windows with fractional input. This function guarantees that for fractional `x`, the following hold: 1. `__float_window(window_function)(x)` has length `np.ceil(x)` 2. all values from `np.floor(x)` are set to 0. For integer-valued `x`, th...
python
{ "resource": "" }
q267957
constant_q
test
def constant_q(sr, fmin=None, n_bins=84, bins_per_octave=12, tuning=0.0, window='hann', filter_scale=1, pad_fft=True, norm=1, dtype=np.complex64, **kwargs): r'''Construct a constant-Q basis. This uses the filter bank described by [1]_. .. [1] McVicar, Matthew. "A ...
python
{ "resource": "" }
q267958
constant_q_lengths
test
def constant_q_lengths(sr, fmin, n_bins=84, bins_per_octave=12, tuning=0.0, window='hann', filter_scale=1): r'''Return length of each filter in a constant-Q basis. Parameters ---------- sr : number > 0 [scalar] Audio sampling rate fmin : float > 0 [scalar] Mi...
python
{ "resource": "" }
q267959
cq_to_chroma
test
def cq_to_chroma(n_input, bins_per_octave=12, n_chroma=12, fmin=None, window=None, base_c=True, dtype=np.float32): '''Convert a Constant-Q basis to Chroma. Parameters ---------- n_input : int > 0 [scalar] Number of input components (CQT bins) bins_per_octave : int > 0 [sc...
python
{ "resource": "" }
q267960
window_bandwidth
test
def window_bandwidth(window, n=1000): '''Get the equivalent noise bandwidth of a window function. Parameters ---------- window : callable or string A window function, or the name of a window function. Examples: - scipy.signal.hann - 'boxcar' n : int > 0 The...
python
{ "resource": "" }
q267961
get_window
test
def get_window(window, Nx, fftbins=True): '''Compute a window function. This is a wrapper for `scipy.signal.get_window` that additionally supports callable or pre-computed windows. Parameters ---------- window : string, tuple, number, callable, or list-like The window specification: ...
python
{ "resource": "" }
q267962
_multirate_fb
test
def _multirate_fb(center_freqs=None, sample_rates=None, Q=25.0, passband_ripple=1, stopband_attenuation=50, ftype='ellip', flayout='ba'): r'''Helper function to construct a multirate filterbank. A filter bank consists of multiple band-pass filters which divide the input signal into subb...
python
{ "resource": "" }
q267963
mr_frequencies
test
def mr_frequencies(tuning): r'''Helper function for generating center frequency and sample rate pairs. This function will return center frequency and corresponding sample rates to obtain similar pitch filterbank settings as described in [1]_. Instead of starting with MIDI pitch `A0`, we start with `C0`...
python
{ "resource": "" }
q267964
__window_ss_fill
test
def __window_ss_fill(x, win_sq, n_frames, hop_length): # pragma: no cover '''Helper function for window sum-square calculation.''' n = len(x) n_fft = len(win_sq) for i in range(n_frames): sample = i * hop_length x[sample:min(n, sample + n_fft)] += win_sq[:max(0, min(n_fft, n - sample))...
python
{ "resource": "" }
q267965
window_sumsquare
test
def window_sumsquare(window, n_frames, hop_length=512, win_length=None, n_fft=2048, dtype=np.float32, norm=None): ''' Compute the sum-square envelope of a window function at a given hop length. This is used to estimate modulation effects induced by windowing observations in short-t...
python
{ "resource": "" }
q267966
diagonal_filter
test
def diagonal_filter(window, n, slope=1.0, angle=None, zero_mean=False): '''Build a two-dimensional diagonal filter. This is primarily used for smoothing recurrence or self-similarity matrices. Parameters ---------- window : string, tuple, number, callable, or list-like The window function ...
python
{ "resource": "" }
q267967
spectral_centroid
test
def spectral_centroid(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, freq=None, win_length=None, window='hann', center=True, pad_mode='reflect'): '''Compute the spectral centroid. Each frame of a magnitude spectrogram is normalized and treated as a distrib...
python
{ "resource": "" }
q267968
spectral_rolloff
test
def spectral_rolloff(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', freq=None, roll_percent=0.85): '''Compute roll-off frequency. The roll-off frequency is defined for each frame as the center freq...
python
{ "resource": "" }
q267969
spectral_flatness
test
def spectral_flatness(y=None, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', amin=1e-10, power=2.0): '''Compute spectral flatness Spectral flatness (or tonality coefficient) is a measure to quantify how much n...
python
{ "resource": "" }
q267970
poly_features
test
def poly_features(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', order=1, freq=None): '''Get coefficients of fitting an nth-order polynomial to the columns of a spectrogram. Parameters ----------...
python
{ "resource": "" }
q267971
zero_crossing_rate
test
def zero_crossing_rate(y, frame_length=2048, hop_length=512, center=True, **kwargs): '''Compute the zero-crossing rate of an audio time series. Parameters ---------- y : np.ndarray [shape=(n,)] Audio time series frame_length : int > 0 Length of the frame over...
python
{ "resource": "" }
q267972
chroma_stft
test
def chroma_stft(y=None, sr=22050, S=None, norm=np.inf, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', tuning=None, **kwargs): """Compute a chromagram from a waveform or power spectrogram. This implementation is derived from `chromagr...
python
{ "resource": "" }
q267973
chroma_cqt
test
def chroma_cqt(y=None, sr=22050, C=None, hop_length=512, fmin=None, norm=np.inf, threshold=0.0, tuning=None, n_chroma=12, n_octaves=7, window=None, bins_per_octave=None, cqt_mode='full'): r'''Constant-Q chromagram Parameters ---------- y : np.ndarray [shape=(n,)] a...
python
{ "resource": "" }
q267974
melspectrogram
test
def melspectrogram(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', power=2.0, **kwargs): """Compute a mel-scaled spectrogram. If a spectrogram input `S` is provided, then it is mapped directly onto ...
python
{ "resource": "" }
q267975
__jaccard
test
def __jaccard(int_a, int_b): # pragma: no cover '''Jaccard similarity between two intervals Parameters ---------- int_a, int_b : np.ndarrays, shape=(2,) Returns ------- Jaccard similarity between intervals ''' ends = [int_a[1], int_b[1]] if ends[1] < ends[0]: ends.reve...
python
{ "resource": "" }
q267976
__match_interval_overlaps
test
def __match_interval_overlaps(query, intervals_to, candidates): # pragma: no cover '''Find the best Jaccard match from query to candidates''' best_score = -1 best_idx = -1 for idx in candidates: score = __jaccard(query, intervals_to[idx]) if score > best_score: best_score,...
python
{ "resource": "" }
q267977
__match_intervals
test
def __match_intervals(intervals_from, intervals_to, strict=True): # pragma: no cover '''Numba-accelerated interval matching algorithm. ''' # sort index of the interval starts start_index = np.argsort(intervals_to[:, 0]) # sort index of the interval ends end_index = np.argsort(intervals_to[:, ...
python
{ "resource": "" }
q267978
match_intervals
test
def match_intervals(intervals_from, intervals_to, strict=True): '''Match one set of time intervals to another. This can be useful for tasks such as mapping beat timings to segments. Each element `[a, b]` of `intervals_from` is matched to the element `[c, d]` of `intervals_to` which maximizes the ...
python
{ "resource": "" }
q267979
match_events
test
def match_events(events_from, events_to, left=True, right=True): '''Match one set of events to another. This is useful for tasks such as matching beats to the nearest detected onsets, or frame-aligned events to the nearest zero-crossing. .. note:: A target event may be matched to multiple source event...
python
{ "resource": "" }
q267980
salience
test
def salience(S, freqs, h_range, weights=None, aggregate=None, filter_peaks=True, fill_value=np.nan, kind='linear', axis=0): """Harmonic salience function. Parameters ---------- S : np.ndarray [shape=(d, n)] input time frequency magnitude representation (stft, ifgram, etc). ...
python
{ "resource": "" }
q267981
interp_harmonics
test
def interp_harmonics(x, freqs, h_range, kind='linear', fill_value=0, axis=0): '''Compute the energy at harmonics of time-frequency representation. Given a frequency-based energy representation such as a spectrogram or tempogram, this function computes the energy at the chosen harmonics of the frequency...
python
{ "resource": "" }
q267982
harmonics_1d
test
def harmonics_1d(harmonic_out, x, freqs, h_range, kind='linear', fill_value=0, axis=0): '''Populate a harmonic tensor from a time-frequency representation. Parameters ---------- harmonic_out : np.ndarray, shape=(len(h_range), X.shape) The output array to store harmonics X ...
python
{ "resource": "" }
q267983
harmonics_2d
test
def harmonics_2d(harmonic_out, x, freqs, h_range, kind='linear', fill_value=0, axis=0): '''Populate a harmonic tensor from a time-frequency representation with time-varying frequencies. Parameters ---------- harmonic_out : np.ndarray The output array to store harmonics ...
python
{ "resource": "" }
q267984
load
test
def load(path, sr=22050, mono=True, offset=0.0, duration=None, dtype=np.float32, res_type='kaiser_best'): """Load an audio file as a floating point time series. Audio will be automatically resampled to the given rate (default `sr=22050`). To preserve the native sampling rate of the file, use ...
python
{ "resource": "" }
q267985
__audioread_load
test
def __audioread_load(path, offset, duration, dtype): '''Load an audio buffer using audioread. This loads one block at a time, and then concatenates the results. ''' y = [] with audioread.audio_open(path) as input_file: sr_native = input_file.samplerate n_channels = input_file.chann...
python
{ "resource": "" }
q267986
to_mono
test
def to_mono(y): '''Force an audio signal down to mono. Parameters ---------- y : np.ndarray [shape=(2,n) or shape=(n,)] audio time series, either stereo or mono Returns ------- y_mono : np.ndarray [shape=(n,)] `y` as a monophonic time-series Notes ----- This fu...
python
{ "resource": "" }
q267987
resample
test
def resample(y, orig_sr, target_sr, res_type='kaiser_best', fix=True, scale=False, **kwargs): """Resample a time series from orig_sr to target_sr Parameters ---------- y : np.ndarray [shape=(n,) or shape=(2, n)] audio time series. Can be mono or stereo. orig_sr : number > 0 [scalar] ...
python
{ "resource": "" }
q267988
autocorrelate
test
def autocorrelate(y, max_size=None, axis=-1): """Bounded auto-correlation Parameters ---------- y : np.ndarray array to autocorrelate max_size : int > 0 or None maximum correlation lag. If unspecified, defaults to `y.shape[axis]` (unbounded) axis : int The axi...
python
{ "resource": "" }
q267989
lpc
test
def lpc(y, order): """Linear Prediction Coefficients via Burg's method This function applies Burg's method to estimate coefficients of a linear filter on `y` of order `order`. Burg's method is an extension to the Yule-Walker approach, which are both sometimes referred to as LPC parameter estimatio...
python
{ "resource": "" }
q267990
clicks
test
def clicks(times=None, frames=None, sr=22050, hop_length=512, click_freq=1000.0, click_duration=0.1, click=None, length=None): """Returns a signal with the signal `click` placed at each specified time Parameters ---------- times : np.ndarray or None times to place clicks, in seconds ...
python
{ "resource": "" }
q267991
tone
test
def tone(frequency, sr=22050, length=None, duration=None, phi=None): """Returns a pure tone signal. The signal generated is a cosine wave. Parameters ---------- frequency : float > 0 frequency sr : number > 0 desired sampling rate of the output signal length : int > 0 ...
python
{ "resource": "" }
q267992
chirp
test
def chirp(fmin, fmax, sr=22050, length=None, duration=None, linear=False, phi=None): """Returns a chirp signal that goes from frequency `fmin` to frequency `fmax` Parameters ---------- fmin : float > 0 initial frequency fmax : float > 0 final frequency sr : number > 0 ...
python
{ "resource": "" }
q267993
__get_files
test
def __get_files(dir_name, extensions): '''Helper function to get files in a single directory''' # Expand out the directory dir_name = os.path.abspath(os.path.expanduser(dir_name)) myfiles = set() for sub_ext in extensions: globstr = os.path.join(dir_name, '*' + os.path.extsep + sub_ext) ...
python
{ "resource": "" }
q267994
stretch_demo
test
def stretch_demo(input_file, output_file, speed): '''Phase-vocoder time stretch demo function. :parameters: - input_file : str path to input audio - output_file : str path to save output (wav) - speed : float > 0 speed up by this factor ''' # 1. Load the...
python
{ "resource": "" }
q267995
process_arguments
test
def process_arguments(args): '''Argparse function to get the program parameters''' parser = argparse.ArgumentParser(description='Time stretching example') parser.add_argument('input_file', action='store', help='path to the input file (wav, mp3, etc)') p...
python
{ "resource": "" }
q267996
hpss_demo
test
def hpss_demo(input_file, output_harmonic, output_percussive): '''HPSS demo function. :parameters: - input_file : str path to input audio - output_harmonic : str path to save output harmonic (wav) - output_percussive : str path to save output harmonic (wav) '...
python
{ "resource": "" }
q267997
beat_track
test
def beat_track(y=None, sr=22050, onset_envelope=None, hop_length=512, start_bpm=120.0, tightness=100, trim=True, bpm=None, units='frames'): r'''Dynamic programming beat tracker. Beats are detected in three stages, following the method of [1]_: 1. Measure onset strength ...
python
{ "resource": "" }
q267998
__beat_tracker
test
def __beat_tracker(onset_envelope, bpm, fft_res, tightness, trim): """Internal function that tracks beats in an onset strength envelope. Parameters ---------- onset_envelope : np.ndarray [shape=(n,)] onset strength envelope bpm : float [scalar] tempo estimate fft_res : float ...
python
{ "resource": "" }
q267999
__beat_local_score
test
def __beat_local_score(onset_envelope, period): '''Construct the local score for an onset envlope and given period''' window = np.exp(-0.5 * (np.arange(-period, period+1)*32.0/period)**2) return scipy.signal.convolve(__normalize_onsets(onset_envelope), window, ...
python
{ "resource": "" }