INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Converts time stamps into STFT frames.
def time_to_frames(times, sr=22050, hop_length=512, n_fft=None): """Converts time stamps into STFT frames. Parameters ---------- times : np.ndarray [shape=(n,)] time (in seconds) or vector of time values sr : number > 0 [scalar] audio sampling rate hop_length : int > 0 [scalar...
Convert one or more spelled notes to MIDI number ( s ).
def note_to_midi(note, round_midi=True): '''Convert one or more spelled notes to MIDI number(s). Notes may be spelled out with optional accidentals or octave numbers. The leading note name is case-insensitive. Sharps are indicated with ``#``, flats may be indicated with ``!`` or ``b``. Parameter...
Convert one or more MIDI numbers to note strings.
def midi_to_note(midi, octave=True, cents=False): '''Convert one or more MIDI numbers to note strings. MIDI numbers will be rounded to the nearest integer. Notes will be of the format 'C0', 'C#0', 'D0', ... Examples -------- >>> librosa.midi_to_note(0) 'C-1' >>> librosa.midi_to_note(3...
Convert Hz to Mels
def hz_to_mel(frequencies, htk=False): """Convert Hz to Mels Examples -------- >>> librosa.hz_to_mel(60) 0.9 >>> librosa.hz_to_mel([110, 220, 440]) array([ 1.65, 3.3 , 6.6 ]) Parameters ---------- frequencies : number or np.ndarray [shape=(n,)] , float scalar or arr...
Convert mel bin numbers to frequencies
def mel_to_hz(mels, htk=False): """Convert mel bin numbers to frequencies Examples -------- >>> librosa.mel_to_hz(3) 200. >>> librosa.mel_to_hz([1,2,3,4,5]) array([ 66.667, 133.333, 200. , 266.667, 333.333]) Parameters ---------- mels : np.ndarray [shape=(n,)],...
Convert frequencies ( Hz ) to ( fractional ) octave numbers.
def hz_to_octs(frequencies, A440=440.0): """Convert frequencies (Hz) to (fractional) octave numbers. Examples -------- >>> librosa.hz_to_octs(440.0) 4. >>> librosa.hz_to_octs([32, 64, 128, 256]) array([ 0.219, 1.219, 2.219, 3.219]) Parameters ---------- frequencies : numbe...
Alternative implementation of np. fft. fftfreq
def fft_frequencies(sr=22050, n_fft=2048): '''Alternative implementation of `np.fft.fftfreq` Parameters ---------- sr : number > 0 [scalar] Audio sampling rate n_fft : int > 0 [scalar] FFT window size Returns ------- freqs : np.ndarray [shape=(1 + n_fft/2,)] F...
Compute the center frequencies of Constant - Q bins.
def cqt_frequencies(n_bins, fmin, bins_per_octave=12, tuning=0.0): """Compute the center frequencies of Constant-Q bins. Examples -------- >>> # Get the CQT frequencies for 24 notes, starting at C2 >>> librosa.cqt_frequencies(24, fmin=librosa.note_to_hz('C2')) array([ 65.406, 69.296, 73.41...
Compute an array of acoustic frequencies tuned to the mel scale.
def mel_frequencies(n_mels=128, fmin=0.0, fmax=11025.0, htk=False): """Compute an array of acoustic frequencies tuned to the mel scale. The mel scale is a quasi-logarithmic function of acoustic frequency designed such that perceptually similar pitch intervals (e.g. octaves) appear equal in width over t...
Compute the frequencies ( in beats - per - minute ) corresponding to an onset auto - correlation or tempogram matrix.
def tempo_frequencies(n_bins, hop_length=512, sr=22050): '''Compute the frequencies (in beats-per-minute) corresponding to an onset auto-correlation or tempogram matrix. Parameters ---------- n_bins : int > 0 The number of lag bins hop_length : int > 0 The number of samples bet...
Compute the A - weighting of a set of frequencies.
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...
Return an array of time values to match the time axis from a feature matrix.
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...
Return an array of sample indices to match the time axis from a feature matrix.
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...
Compute the constant - Q transform of an audio signal.
def 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 constant-Q transform of an audio signal. This implementation is based on the re...
Compute the hybrid constant - Q transform of an audio signal.
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...
Compute the pseudo constant - Q transform of an audio signal.
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...
Compute the inverse constant - Q transform.
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`...
Generate the frequency domain constant - Q filter basis.
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...
Helper function to trim and stack a collection of CQT responses
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...
Compute the filter response with a target STFT hop.
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...
Compute the number of early downsampling operations
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...
Perform early downsampling on an audio signal if it applies.
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...
r Compute delta features: local estimate of the derivative of the input data along the selected axis.
def delta(data, width=9, order=1, axis=-1, mode='interp', **kwargs): r'''Compute delta features: local estimate of the derivative of the input data along the selected axis. Delta features are computed Savitsky-Golay filtering. Parameters ---------- data : np.ndarray the input data...
Short - term history embedding: vertically concatenate a data vector or matrix with delayed copies of itself.
def stack_memory(data, n_steps=2, delay=1, **kwargs): """Short-term history embedding: vertically concatenate a data vector or matrix with delayed copies of itself. Each column `data[:, i]` is mapped to:: data[:, i] -> [data[:, i], data[:, i - delay], ...
Dynamic time warping ( DTW ).
def dtw(X=None, Y=None, C=None, metric='euclidean', step_sizes_sigma=None, weights_add=None, weights_mul=None, subseq=False, backtrack=True, global_constraints=False, band_rad=0.25): '''Dynamic time warping (DTW). This function performs a DTW and path backtracking on two sequences. We follo...
Calculate the accumulated cost matrix D.
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)...
Backtrack optimal warping path.
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...
Core Viterbi algorithm.
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...
Viterbi decoding from discriminative state predictions.
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...
Viterbi decoding from binary ( multi - label ) discriminative state predictions.
def viterbi_binary(prob, transition, p_state=None, p_init=None, return_logp=False): '''Viterbi decoding from binary (multi-label), discriminative state predictions. Given a sequence of conditional state predictions `prob[s, t]`, indicating the conditional likelihood of state `s` being active conditiona...
Construct a uniform transition matrix over n_states.
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 ...
Construct a self - loop transition matrix over n_states.
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 ...
Construct a cyclic transition matrix over n_states.
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...
Construct a localized transition matrix.
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 + ...
Basic onset detector. Locate note onset events by picking peaks in an onset strength envelope.
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...
Compute a spectral flux onset strength envelope.
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...
Backtrack detected onset events to the nearest preceding local minimum of an energy function.
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 ...
Compute a spectral flux onset strength envelope across multiple channels.
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...
r Save annotations in a 3 - column format::
def annotation(path, intervals, annotations=None, delimiter=',', fmt='%0.3f'): r'''Save annotations in a 3-column format:: intervals[0, 0],intervals[0, 1],annotations[0]\n intervals[1, 0],intervals[1, 1],annotations[1]\n intervals[2, 0],intervals[2, 1],annotations[2]\n ... This...
r Save time steps as in CSV format. This can be used to store the output of a beat - tracker or segmentation algorithm.
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 ...
Output a time series as a. wav file
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...
Get a default colormap from the given data.
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...
Compute the max - envelope of x at a stride/ frame length of h
def __envelope(x, hop): '''Compute the max-envelope of x at a stride/frame length of h''' return util.frame(x, hop_length=hop, frame_length=hop).max(axis=0)
Plot the amplitude envelope of a waveform.
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])]`...
Display a spectrogram/ chromagram/ cqt/ etc.
def specshow(data, x_coords=None, y_coords=None, x_axis=None, y_axis=None, sr=22050, hop_length=512, fmin=None, fmax=None, bins_per_octave=12, ax=None, **kwargs): '''Display a spectrogram/chromagram/cqt/etc. Parameters ---------...
Helper to set the current image in pyplot mode.
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...
Compute axis coordinates
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': __...
Check if axes is an instance of an axis object. If not use gca.
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. " ...
Set the axis scaling
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' ...
Configure axis tickers locators and labels
def __decorate_axis(axis, ax_type): '''Configure axis tickers, locators, and labels''' if ax_type == 'tonnetz': axis.set_major_formatter(TonnetzFormatter()) axis.set_major_locator(FixedLocator(0.5 + np.arange(6))) axis.set_label_text('Tonnetz') elif ax_type == 'chroma': axi...
Get the frequencies for FFT bins
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] ...
Get the frequencies for Mel bins
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...
Get CQT bin frequencies
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...
Get chroma bin numbers
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)
Tempo coordinates
def __coord_tempo(n, sr=22050, hop_length=512, **_kwargs): '''Tempo coordinates''' basis = core.tempo_frequencies(n+2, sr=sr, hop_length=hop_length)[1:] edges = np.arange(1, n+2) return basis * (edges + 0.5) / edges
Get time coordinates from frames
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)
Estimate the tuning of an audio time series or spectrogram input.
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] ...
Given a collection of pitches estimate its tuning offset ( in fractions of a bin ) relative to A440 = 440. 0Hz.
def pitch_tuning(frequencies, resolution=0.01, bins_per_octave=12): '''Given a collection of pitches, estimate its tuning offset (in fractions of a bin) relative to A440=440.0Hz. Parameters ---------- frequencies : array-like, float A collection of frequencies detected in the signal. ...
Pitch tracking on thresholded parabolically - interpolated STFT.
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...
Decompose an audio time series into harmonic and percussive components.
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,)] ...
Extract harmonic elements from an audio time - series.
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...
Extract percussive elements from an audio time - series.
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....
Time - stretch an audio series by a fixed rate.
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...
Pitch - shift the waveform by n_steps half - steps.
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] ...
Remix an audio signal by re - ordering time intervals.
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 ...
Frame - wise non - silent indicator for audio input.
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 ...
Trim leading and trailing silence from an audio signal.
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...
Split an audio signal into non - silent intervals.
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 ...
Short - time Fourier transform ( STFT )
def stft(y, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, dtype=np.complex64, pad_mode='reflect'): """Short-time Fourier transform (STFT) Returns a complex-valued matrix D such that `np.abs(D[f, t])` is the magnitude of frequency bin `f` at frame `t` ...
Inverse short - time Fourier transform ( ISTFT ).
def istft(stft_matrix, hop_length=None, win_length=None, window='hann', center=True, dtype=np.float32, length=None): """ Inverse short-time Fourier transform (ISTFT). Converts a complex-valued spectrogram `stft_matrix` to time-series `y` by minimizing the mean squared error between `stft_matr...
Compute the instantaneous frequency ( as a proportion of the sampling rate ) obtained as the time - derivative of the phase of the complex spectrum as described by [ 1 ] _.
def ifgram(y, sr=22050, n_fft=2048, hop_length=None, win_length=None, window='hann', norm=False, center=True, ref_power=1e-6, clip=True, dtype=np.complex64, pad_mode='reflect'): '''Compute the instantaneous frequency (as a proportion of the sampling rate) obtained as the time-derivative of...
Separate a complex - valued spectrogram D into its magnitude ( S ) and phase ( P ) components so that D = S * P.
def magphase(D, power=1): """Separate a complex-valued spectrogram D into its magnitude (S) and phase (P) components, so that `D = S * P`. Parameters ---------- D : np.ndarray [shape=(d, t), dtype=complex] complex-valued spectrogram power : float > 0 Exponent for the magnitude ...
Phase vocoder. Given an STFT matrix D speed up by a factor of rate
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...
r Time - frequency representation using IIR filters [ 1 ] _.
def iirt(y, sr=22050, win_length=2048, hop_length=None, center=True, tuning=0.0, pad_mode='reflect', flayout=None, **kwargs): r'''Time-frequency representation using IIR filters [1]_. This function will return a time-frequency representation using a multirate filter bank consisting of IIR filters....
Convert a power spectrogram ( amplitude squared ) to decibel ( dB ) units
def power_to_db(S, ref=1.0, amin=1e-10, top_db=80.0): """Convert a power spectrogram (amplitude squared) to decibel (dB) units This computes the scaling ``10 * log10(S / ref)`` in a numerically stable way. Parameters ---------- S : np.ndarray input power ref : scalar or callable ...
Convert an amplitude spectrogram to dB - scaled spectrogram.
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...
Perceptual weighting of a power spectrogram:
def perceptual_weighting(S, frequencies, **kwargs): '''Perceptual weighting of a power spectrogram: `S_p[f] = A_weighting(f) + 10*log(S[f] / ref)` Parameters ---------- S : np.ndarray [shape=(d, t)] Power spectrogram frequencies : np.ndarray [shape=(d,)] Center frequency for e...
The fast Mellin transform ( FMT ) [ 1 ] _ of a uniformly sampled signal y.
def fmt(y, t_min=0.5, n_fmt=None, kind='cubic', beta=0.5, over_sample=1, axis=-1): """The fast Mellin transform (FMT) [1]_ of a uniformly sampled signal y. When the Mellin parameter (beta) is 1/2, it is also known as the scale transform [2]_. The scale transform can be useful for audio analysis because its...
Per - channel energy normalization ( PCEN ) [ 1 ] _
def pcen(S, sr=22050, hop_length=512, gain=0.98, bias=2, power=0.5, time_constant=0.400, eps=1e-6, b=None, max_size=1, ref=None, axis=-1, max_axis=None, zi=None, return_zf=False): '''Per-channel energy normalization (PCEN) [1]_ This function normalizes a time-frequency representation `S` by ...
Helper function to retrieve a magnitude spectrogram.
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...
HPSS beat tracking
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...
Decompose a feature matrix.
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...
Median - filtering harmonic percussive source separation ( HPSS ).
def hpss(S, kernel_size=31, power=2.0, mask=False, margin=1.0): """Median-filtering harmonic percussive source separation (HPSS). If `margin = 1.0`, decomposes an input spectrogram `S = H + P` where `H` contains the harmonic components, and `P` contains the percussive components. If `margin > 1.0`...
Filtering by nearest - neighbors.
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...
Nearest - neighbor filter helper function.
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...
Create a Filterbank matrix to combine FFT bins into Mel - frequency bins
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...
Create a Filterbank matrix to convert STFT to chroma
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] ...
Decorator function for windows with fractional input.
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...
r Construct a constant - Q basis.
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 ...
r Return length of each filter in a constant - Q basis.
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...
Convert a Constant - Q basis to Chroma.
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...
Get the equivalent noise bandwidth of a window function.
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...
Compute a window function.
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: ...
r Helper function to construct a multirate filterbank.
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...
r Helper function for generating center frequency and sample rate pairs.
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`...
r Constructs a multirate filterbank of infinite - impulse response ( IIR ) band - pass filters at user - defined center frequencies and sample rates.
def semitone_filterbank(center_freqs=None, tuning=0.0, sample_rates=None, flayout='ba', **kwargs): r'''Constructs a multirate filterbank of infinite-impulse response (IIR) band-pass filters at user-defined center frequencies and sample rates. By default, these center frequencies are set equal to the 88 fun...
Helper function for window sum - square calculation.
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))...
Compute the sum - square envelope of a window function at a given hop length.
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...
Build a two - dimensional diagonal filter.
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 ...
Compute the spectral centroid.
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...