partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
spectral_bandwidth
Compute p'th-order spectral bandwidth: (sum_k S[k] * (freq[k] - centroid)**p)**(1/p) Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [scalar] audio sampling rate of `y` S : np.ndarray [shape=(d, t)] or None (optional) sp...
librosa/feature/spectral.py
def spectral_bandwidth(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', freq=None, centroid=None, norm=True, p=2): '''Compute p'th-order spectral bandwidth: (sum_k S[k] * (freq[k] - centroid)...
def spectral_bandwidth(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', freq=None, centroid=None, norm=True, p=2): '''Compute p'th-order spectral bandwidth: (sum_k S[k] * (freq[k] - centroid)...
[ "Compute", "p", "th", "-", "order", "spectral", "bandwidth", ":" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L171-L311
[ "def", "spectral_bandwidth", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "win_length", "=", "None", ",", "window", "=", "'hann'", ",", "center", "=", "True", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
spectral_contrast
Compute spectral contrast [1]_ .. [1] Jiang, Dan-Ning, Lie Lu, Hong-Jiang Zhang, Jian-Hua Tao, and Lian-Hong Cai. "Music type classification by spectral contrast feature." In Multimedia and Expo, 2002. ICME'02. Proceedings. 2002 IEEE International Conference on, vol. 1, ...
librosa/feature/spectral.py
def spectral_contrast(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', freq=None, fmin=200.0, n_bands=6, quantile=0.02, linear=False): '''Compute spectral contrast [1]_ .. [1]...
def spectral_contrast(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, win_length=None, window='hann', center=True, pad_mode='reflect', freq=None, fmin=200.0, n_bands=6, quantile=0.02, linear=False): '''Compute spectral contrast [1]_ .. [1]...
[ "Compute", "spectral", "contrast", "[", "1", "]", "_" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L314-L481
[ "def", "spectral_contrast", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "win_length", "=", "None", ",", "window", "=", "'hann'", ",", "center", "=", "True", "...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
spectral_rolloff
Compute roll-off frequency. The roll-off frequency is defined for each frame as the center frequency for a spectrogram bin such that at least roll_percent (0.85 by default) of the energy of the spectrum in this frame is contained in this bin and the bins below. This can be used to, e.g., approximate th...
librosa/feature/spectral.py
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...
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...
[ "Compute", "roll", "-", "off", "frequency", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L484-L623
[ "def", "spectral_rolloff", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "win_length", "=", "None", ",", "window", "=", "'hann'", ",", "center", "=", "True", ",...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
spectral_flatness
Compute spectral flatness Spectral flatness (or tonality coefficient) is a measure to quantify how much noise-like a sound is, as opposed to being tone-like [1]_. A high spectral flatness (closer to 1.0) indicates the spectrum is similar to white noise. It is often converted to decibel. .. [1]...
librosa/feature/spectral.py
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...
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...
[ "Compute", "spectral", "flatness" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L626-L737
[ "def", "spectral_flatness", "(", "y", "=", "None", ",", "S", "=", "None", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "win_length", "=", "None", ",", "window", "=", "'hann'", ",", "center", "=", "True", ",", "pad_mode", "=", "'refl...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
rms
Compute root-mean-square (RMS) value for each frame, either from the audio samples `y` or from a spectrogram `S`. Computing the RMS value from audio samples is faster as it doesn't require a STFT calculation. However, using a spectrogram will give a more accurate representation of energy over time beca...
librosa/feature/spectral.py
def rms(y=None, S=None, frame_length=2048, hop_length=512, center=True, pad_mode='reflect'): '''Compute root-mean-square (RMS) value for each frame, either from the audio samples `y` or from a spectrogram `S`. Computing the RMS value from audio samples is faster as it doesn't require a STFT cal...
def rms(y=None, S=None, frame_length=2048, hop_length=512, center=True, pad_mode='reflect'): '''Compute root-mean-square (RMS) value for each frame, either from the audio samples `y` or from a spectrogram `S`. Computing the RMS value from audio samples is faster as it doesn't require a STFT cal...
[ "Compute", "root", "-", "mean", "-", "square", "(", "RMS", ")", "value", "for", "each", "frame", "either", "from", "the", "audio", "samples", "y", "or", "from", "a", "spectrogram", "S", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L740-L828
[ "def", "rms", "(", "y", "=", "None", ",", "S", "=", "None", ",", "frame_length", "=", "2048", ",", "hop_length", "=", "512", ",", "center", "=", "True", ",", "pad_mode", "=", "'reflect'", ")", ":", "if", "y", "is", "not", "None", "and", "S", "is"...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
poly_features
Get coefficients of fitting an nth-order polynomial to the columns of a spectrogram. Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [scalar] audio sampling rate of `y` S : np.ndarray [shape=(d, t)] or None (optional) spectro...
librosa/feature/spectral.py
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 ----------...
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 ----------...
[ "Get", "coefficients", "of", "fitting", "an", "nth", "-", "order", "polynomial", "to", "the", "columns", "of", "a", "spectrogram", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L831-L958
[ "def", "poly_features", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "win_length", "=", "None", ",", "window", "=", "'hann'", ",", "center", "=", "True", ",", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
zero_crossing_rate
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 which to compute zero crossing rates hop_length : int > 0 Number of samples to advance for each frame...
librosa/feature/spectral.py
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...
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...
[ "Compute", "the", "zero", "-", "crossing", "rate", "of", "an", "audio", "time", "series", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L961-L1019
[ "def", "zero_crossing_rate", "(", "y", ",", "frame_length", "=", "2048", ",", "hop_length", "=", "512", ",", "center", "=", "True", ",", "*", "*", "kwargs", ")", ":", "util", ".", "valid_audio", "(", "y", ")", "if", "center", ":", "y", "=", "np", "...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
chroma_stft
Compute a chromagram from a waveform or power spectrogram. This implementation is derived from `chromagram_E` [1]_ .. [1] Ellis, Daniel P.W. "Chroma feature analysis and synthesis" 2007/04/21 http://labrosa.ee.columbia.edu/matlab/chroma-ansyn/ Parameters ---------- y : np.n...
librosa/feature/spectral.py
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...
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...
[ "Compute", "a", "chromagram", "from", "a", "waveform", "or", "power", "spectrogram", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L1023-L1162
[ "def", "chroma_stft", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "norm", "=", "np", ".", "inf", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "win_length", "=", "None", ",", "window", "=", "'hann'...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
chroma_cqt
r'''Constant-Q chromagram Parameters ---------- y : np.ndarray [shape=(n,)] audio time series sr : number > 0 sampling rate of `y` C : np.ndarray [shape=(d, t)] [Optional] a pre-computed constant-Q spectrogram hop_length : int > 0 number of samples between suc...
librosa/feature/spectral.py
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...
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...
[ "r", "Constant", "-", "Q", "chromagram" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L1165-L1280
[ "def", "chroma_cqt", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "C", "=", "None", ",", "hop_length", "=", "512", ",", "fmin", "=", "None", ",", "norm", "=", "np", ".", "inf", ",", "threshold", "=", "0.0", ",", "tuning", "=", "None", "...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
chroma_cens
r'''Computes the chroma variant "Chroma Energy Normalized" (CENS), following [1]_. To compute CENS features, following steps are taken after obtaining chroma vectors using `chroma_cqt`: 1. L-1 normalization of each chroma vector 2. Quantization of amplitude based on "log-like" amplitude thresholds 3. (...
librosa/feature/spectral.py
def chroma_cens(y=None, sr=22050, C=None, hop_length=512, fmin=None, tuning=None, n_chroma=12, n_octaves=7, bins_per_octave=None, cqt_mode='full', window=None, norm=2, win_len_smooth=41, smoothing_window='hann'): r'''Computes the chroma variant "Chroma Energy Normaliz...
def chroma_cens(y=None, sr=22050, C=None, hop_length=512, fmin=None, tuning=None, n_chroma=12, n_octaves=7, bins_per_octave=None, cqt_mode='full', window=None, norm=2, win_len_smooth=41, smoothing_window='hann'): r'''Computes the chroma variant "Chroma Energy Normaliz...
[ "r", "Computes", "the", "chroma", "variant", "Chroma", "Energy", "Normalized", "(", "CENS", ")", "following", "[", "1", "]", "_", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L1283-L1426
[ "def", "chroma_cens", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "C", "=", "None", ",", "hop_length", "=", "512", ",", "fmin", "=", "None", ",", "tuning", "=", "None", ",", "n_chroma", "=", "12", ",", "n_octaves", "=", "7", ",", "bins_p...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
tonnetz
Computes the tonal centroid features (tonnetz), following the method of [1]_. .. [1] Harte, C., Sandler, M., & Gasser, M. (2006). "Detecting Harmonic Change in Musical Audio." In Proceedings of the 1st ACM Workshop on Audio and Music Computing Multimedia (pp. 21-26). Santa Barb...
librosa/feature/spectral.py
def tonnetz(y=None, sr=22050, chroma=None): '''Computes the tonal centroid features (tonnetz), following the method of [1]_. .. [1] Harte, C., Sandler, M., & Gasser, M. (2006). "Detecting Harmonic Change in Musical Audio." In Proceedings of the 1st ACM Workshop on Audio and Music Comp...
def tonnetz(y=None, sr=22050, chroma=None): '''Computes the tonal centroid features (tonnetz), following the method of [1]_. .. [1] Harte, C., Sandler, M., & Gasser, M. (2006). "Detecting Harmonic Change in Musical Audio." In Proceedings of the 1st ACM Workshop on Audio and Music Comp...
[ "Computes", "the", "tonal", "centroid", "features", "(", "tonnetz", ")", "following", "the", "method", "of", "[", "1", "]", "_", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L1429-L1528
[ "def", "tonnetz", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "chroma", "=", "None", ")", ":", "if", "y", "is", "None", "and", "chroma", "is", "None", ":", "raise", "ParameterError", "(", "'Either the audio samples or the chromagram must be '", "'pa...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
mfcc
Mel-frequency cepstral coefficients (MFCCs) Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [scalar] sampling rate of `y` S : np.ndarray [shape=(d, t)] or None log-power Mel spectrogram n_mfcc: int > 0 [scalar] numbe...
librosa/feature/spectral.py
def mfcc(y=None, sr=22050, S=None, n_mfcc=20, dct_type=2, norm='ortho', **kwargs): """Mel-frequency cepstral coefficients (MFCCs) Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [scalar] sampling rate of `y` S : np.ndarray [shape=(d,...
def mfcc(y=None, sr=22050, S=None, n_mfcc=20, dct_type=2, norm='ortho', **kwargs): """Mel-frequency cepstral coefficients (MFCCs) Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [scalar] sampling rate of `y` S : np.ndarray [shape=(d,...
[ "Mel", "-", "frequency", "cepstral", "coefficients", "(", "MFCCs", ")" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L1532-L1628
[ "def", "mfcc", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "n_mfcc", "=", "20", ",", "dct_type", "=", "2", ",", "norm", "=", "'ortho'", ",", "*", "*", "kwargs", ")", ":", "if", "S", "is", "None", ":", "S", "=...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
melspectrogram
Compute a mel-scaled spectrogram. If a spectrogram input `S` is provided, then it is mapped directly onto the mel basis `mel_f` by `mel_f.dot(S)`. If a time-series input `y, sr` is provided, then its magnitude spectrogram `S` is first computed, and then mapped onto the mel scale by `mel_f.dot(S**p...
librosa/feature/spectral.py
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 ...
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 ...
[ "Compute", "a", "mel", "-", "scaled", "spectrogram", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/spectral.py#L1631-L1744
[ "def", "melspectrogram", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "win_length", "=", "None", ",", "window", "=", "'hann'", ",", "center", "=", "True", ",",...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
estimate_tuning
Load an audio file and estimate tuning (in cents)
examples/estimate_tuning.py
def estimate_tuning(input_file): '''Load an audio file and estimate tuning (in cents)''' print('Loading ', input_file) y, sr = librosa.load(input_file) print('Separating harmonic component ... ') y_harm = librosa.effects.harmonic(y) print('Estimating tuning ... ') # Just track the pitches...
def estimate_tuning(input_file): '''Load an audio file and estimate tuning (in cents)''' print('Loading ', input_file) y, sr = librosa.load(input_file) print('Separating harmonic component ... ') y_harm = librosa.effects.harmonic(y) print('Estimating tuning ... ') # Just track the pitches...
[ "Load", "an", "audio", "file", "and", "estimate", "tuning", "(", "in", "cents", ")" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/examples/estimate_tuning.py#L15-L28
[ "def", "estimate_tuning", "(", "input_file", ")", ":", "print", "(", "'Loading '", ",", "input_file", ")", "y", ",", "sr", "=", "librosa", ".", "load", "(", "input_file", ")", "print", "(", "'Separating harmonic component ... '", ")", "y_harm", "=", "librosa",...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__jaccard
Jaccard similarity between two intervals Parameters ---------- int_a, int_b : np.ndarrays, shape=(2,) Returns ------- Jaccard similarity between intervals
librosa/util/matching.py
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...
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...
[ "Jaccard", "similarity", "between", "two", "intervals" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/matching.py#L17-L45
[ "def", "__jaccard", "(", "int_a", ",", "int_b", ")", ":", "# pragma: no cover", "ends", "=", "[", "int_a", "[", "1", "]", ",", "int_b", "[", "1", "]", "]", "if", "ends", "[", "1", "]", "<", "ends", "[", "0", "]", ":", "ends", ".", "reverse", "(...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__match_interval_overlaps
Find the best Jaccard match from query to candidates
librosa/util/matching.py
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,...
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,...
[ "Find", "the", "best", "Jaccard", "match", "from", "query", "to", "candidates" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/matching.py#L49-L59
[ "def", "__match_interval_overlaps", "(", "query", ",", "intervals_to", ",", "candidates", ")", ":", "# pragma: no cover", "best_score", "=", "-", "1", "best_idx", "=", "-", "1", "for", "idx", "in", "candidates", ":", "score", "=", "__jaccard", "(", "query", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__match_intervals
Numba-accelerated interval matching algorithm.
librosa/util/matching.py
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[:, ...
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[:, ...
[ "Numba", "-", "accelerated", "interval", "matching", "algorithm", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/matching.py#L63-L113
[ "def", "__match_intervals", "(", "intervals_from", ",", "intervals_to", ",", "strict", "=", "True", ")", ":", "# pragma: no cover", "# sort index of the interval starts", "start_index", "=", "np", ".", "argsort", "(", "intervals_to", "[", ":", ",", "0", "]", ")", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
match_intervals
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 Jaccard similarity between the intervals: `max(0, |min(b, d...
librosa/util/matching.py
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 ...
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 ...
[ "Match", "one", "set", "of", "time", "intervals", "to", "another", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/matching.py#L116-L210
[ "def", "match_intervals", "(", "intervals_from", ",", "intervals_to", ",", "strict", "=", "True", ")", ":", "if", "len", "(", "intervals_from", ")", "==", "0", "or", "len", "(", "intervals_to", ")", "==", "0", ":", "raise", "ParameterError", "(", "'Attempt...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
match_events
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 events. Examples -------- >>> # Sources are multiples of 7 >...
librosa/util/matching.py
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...
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...
[ "Match", "one", "set", "of", "events", "to", "another", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/matching.py#L213-L298
[ "def", "match_events", "(", "events_from", ",", "events_to", ",", "left", "=", "True", ",", "right", "=", "True", ")", ":", "if", "len", "(", "events_from", ")", "==", "0", "or", "len", "(", "events_to", ")", "==", "0", ":", "raise", "ParameterError", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
salience
Harmonic salience function. Parameters ---------- S : np.ndarray [shape=(d, n)] input time frequency magnitude representation (stft, ifgram, etc). Must be real-valued and non-negative. freqs : np.ndarray, shape=(S.shape[axis]) The frequency values corresponding to S's elements a...
librosa/core/harmonic.py
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). ...
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). ...
[ "Harmonic", "salience", "function", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/harmonic.py#L13-L104
[ "def", "salience", "(", "S", ",", "freqs", ",", "h_range", ",", "weights", "=", "None", ",", "aggregate", "=", "None", ",", "filter_peaks", "=", "True", ",", "fill_value", "=", "np", ".", "nan", ",", "kind", "=", "'linear'", ",", "axis", "=", "0", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
interp_harmonics
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 axis. (See examples below.) The resulting harmonic array can then be used as in...
librosa/core/harmonic.py
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...
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...
[ "Compute", "the", "energy", "at", "harmonics", "of", "time", "-", "frequency", "representation", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/harmonic.py#L107-L218
[ "def", "interp_harmonics", "(", "x", ",", "freqs", ",", "h_range", ",", "kind", "=", "'linear'", ",", "fill_value", "=", "0", ",", "axis", "=", "0", ")", ":", "# X_out will be the same shape as X, plus a leading", "# axis that has length = len(h_range)", "out_shape", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
harmonics_1d
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 : np.ndarray The input energy freqs : np.ndarray, shape=(x.shape[axis]) The frequency value...
librosa/core/harmonic.py
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 ...
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 ...
[ "Populate", "a", "harmonic", "tensor", "from", "a", "time", "-", "frequency", "representation", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/harmonic.py#L221-L328
[ "def", "harmonics_1d", "(", "harmonic_out", ",", "x", ",", "freqs", ",", "h_range", ",", "kind", "=", "'linear'", ",", "fill_value", "=", "0", ",", "axis", "=", "0", ")", ":", "# Note: this only works for fixed-grid, 1d interpolation", "f_interp", "=", "scipy", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
harmonics_2d
Populate a harmonic tensor from a time-frequency representation with time-varying frequencies. Parameters ---------- harmonic_out : np.ndarray The output array to store harmonics x : np.ndarray The input energy freqs : np.ndarray, shape=x.shape The frequency values cor...
librosa/core/harmonic.py
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 ...
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 ...
[ "Populate", "a", "harmonic", "tensor", "from", "a", "time", "-", "frequency", "representation", "with", "time", "-", "varying", "frequencies", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/harmonic.py#L331-L382
[ "def", "harmonics_2d", "(", "harmonic_out", ",", "x", ",", "freqs", ",", "h_range", ",", "kind", "=", "'linear'", ",", "fill_value", "=", "0", ",", "axis", "=", "0", ")", ":", "idx_in", "=", "[", "slice", "(", "None", ")", "]", "*", "x", ".", "nd...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
load
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 `sr=None`. Parameters ---------- path : string, int, or file-like object path to the input file. ...
librosa/core/audio.py
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 ...
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 ...
[ "Load", "an", "audio", "file", "as", "a", "floating", "point", "time", "series", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L32-L152
[ "def", "load", "(", "path", ",", "sr", "=", "22050", ",", "mono", "=", "True", ",", "offset", "=", "0.0", ",", "duration", "=", "None", ",", "dtype", "=", "np", ".", "float32", ",", "res_type", "=", "'kaiser_best'", ")", ":", "try", ":", "with", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__audioread_load
Load an audio buffer using audioread. This loads one block at a time, and then concatenates the results.
librosa/core/audio.py
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...
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...
[ "Load", "an", "audio", "buffer", "using", "audioread", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L155-L208
[ "def", "__audioread_load", "(", "path", ",", "offset", ",", "duration", ",", "dtype", ")", ":", "y", "=", "[", "]", "with", "audioread", ".", "audio_open", "(", "path", ")", "as", "input_file", ":", "sr_native", "=", "input_file", ".", "samplerate", "n_c...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
to_mono
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 function caches at level ...
librosa/core/audio.py
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...
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...
[ "Force", "an", "audio", "signal", "down", "to", "mono", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L212-L246
[ "def", "to_mono", "(", "y", ")", ":", "# Validate the buffer. Stereo is ok here.", "util", ".", "valid_audio", "(", "y", ",", "mono", "=", "False", ")", "if", "y", ".", "ndim", ">", "1", ":", "y", "=", "np", ".", "mean", "(", "y", ",", "axis", "=", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
resample
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] original sampling rate of `y` target_sr : number > 0 [scalar] target sampling rate ...
librosa/core/audio.py
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] ...
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] ...
[ "Resample", "a", "time", "series", "from", "orig_sr", "to", "target_sr" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L250-L355
[ "def", "resample", "(", "y", ",", "orig_sr", ",", "target_sr", ",", "res_type", "=", "'kaiser_best'", ",", "fix", "=", "True", ",", "scale", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# First, validate the audio buffer", "util", ".", "valid_audio", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
get_duration
Compute the duration (in seconds) of an audio time series, feature matrix, or filename. Examples -------- >>> # Load the example audio file >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> librosa.get_duration(y=y, sr=sr) 61.45886621315193 >>> # Or directly from an audio...
librosa/core/audio.py
def get_duration(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, center=True, filename=None): """Compute the duration (in seconds) of an audio time series, feature matrix, or filename. Examples -------- >>> # Load the example audio file >>> y, sr = librosa.load(librosa.ut...
def get_duration(y=None, sr=22050, S=None, n_fft=2048, hop_length=512, center=True, filename=None): """Compute the duration (in seconds) of an audio time series, feature matrix, or filename. Examples -------- >>> # Load the example audio file >>> y, sr = librosa.load(librosa.ut...
[ "Compute", "the", "duration", "(", "in", "seconds", ")", "of", "an", "audio", "time", "series", "feature", "matrix", "or", "filename", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L358-L462
[ "def", "get_duration", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "n_fft", "=", "2048", ",", "hop_length", "=", "512", ",", "center", "=", "True", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "n...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
autocorrelate
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 axis along which to autocorrelate. By default, t...
librosa/core/audio.py
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...
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...
[ "Bounded", "auto", "-", "correlation" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L465-L533
[ "def", "autocorrelate", "(", "y", ",", "max_size", "=", "None", ",", "axis", "=", "-", "1", ")", ":", "if", "max_size", "is", "None", ":", "max_size", "=", "y", ".", "shape", "[", "axis", "]", "max_size", "=", "int", "(", "min", "(", "max_size", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
lpc
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 estimation by autocorrelation. ...
librosa/core/audio.py
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...
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...
[ "Linear", "Prediction", "Coefficients", "via", "Burg", "s", "method" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L536-L607
[ "def", "lpc", "(", "y", ",", "order", ")", ":", "if", "not", "isinstance", "(", "order", ",", "int", ")", "or", "order", "<", "1", ":", "raise", "ParameterError", "(", "\"order must be an integer > 0\"", ")", "util", ".", "valid_audio", "(", "y", ",", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
zero_crossings
Find the zero-crossings of a signal `y`: indices `i` such that `sign(y[i]) != sign(y[j])`. If `y` is multi-dimensional, then zero-crossings are computed along the specified `axis`. Parameters ---------- y : np.ndarray The input array threshold : float > 0 or None If speci...
librosa/core/audio.py
def zero_crossings(y, threshold=1e-10, ref_magnitude=None, pad=True, zero_pos=True, axis=-1): '''Find the zero-crossings of a signal `y`: indices `i` such that `sign(y[i]) != sign(y[j])`. If `y` is multi-dimensional, then zero-crossings are computed along the specified `axis`. ...
def zero_crossings(y, threshold=1e-10, ref_magnitude=None, pad=True, zero_pos=True, axis=-1): '''Find the zero-crossings of a signal `y`: indices `i` such that `sign(y[i]) != sign(y[j])`. If `y` is multi-dimensional, then zero-crossings are computed along the specified `axis`. ...
[ "Find", "the", "zero", "-", "crossings", "of", "a", "signal", "y", ":", "indices", "i", "such", "that", "sign", "(", "y", "[", "i", "]", ")", "!", "=", "sign", "(", "y", "[", "j", "]", ")", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L694-L815
[ "def", "zero_crossings", "(", "y", ",", "threshold", "=", "1e-10", ",", "ref_magnitude", "=", "None", ",", "pad", "=", "True", ",", "zero_pos", "=", "True", ",", "axis", "=", "-", "1", ")", ":", "# Clip within the threshold", "if", "threshold", "is", "No...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
clicks
Returns a signal with the signal `click` placed at each specified time Parameters ---------- times : np.ndarray or None times to place clicks, in seconds frames : np.ndarray or None frame indices to place clicks sr : number > 0 desired sampling rate of the output signal ...
librosa/core/audio.py
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 ...
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 ...
[ "Returns", "a", "signal", "with", "the", "signal", "click", "placed", "at", "each", "specified", "time" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L818-L949
[ "def", "clicks", "(", "times", "=", "None", ",", "frames", "=", "None", ",", "sr", "=", "22050", ",", "hop_length", "=", "512", ",", "click_freq", "=", "1000.0", ",", "click_duration", "=", "0.1", ",", "click", "=", "None", ",", "length", "=", "None"...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
tone
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 desired number of samples in the output signal. When both `duration` and `le...
librosa/core/audio.py
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 ...
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 ...
[ "Returns", "a", "pure", "tone", "signal", ".", "The", "signal", "generated", "is", "a", "cosine", "wave", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L952-L1017
[ "def", "tone", "(", "frequency", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "duration", "=", "None", ",", "phi", "=", "None", ")", ":", "if", "frequency", "is", "None", ":", "raise", "ParameterError", "(", "'\"frequency\" must be provided'",...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
chirp
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 desired sampling rate of the output signal length : int > 0 desired number of s...
librosa/core/audio.py
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 ...
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 ...
[ "Returns", "a", "chirp", "signal", "that", "goes", "from", "frequency", "fmin", "to", "frequency", "fmax" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/audio.py#L1020-L1118
[ "def", "chirp", "(", "fmin", ",", "fmax", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "duration", "=", "None", ",", "linear", "=", "False", ",", "phi", "=", "None", ")", ":", "if", "fmin", "is", "None", "or", "fmax", "is", "None", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
tempogram
Compute the tempogram: local autocorrelation of the onset strength envelope. [1]_ .. [1] Grosche, Peter, Meinard Müller, and Frank Kurth. "Cyclic tempogram - A mid-level tempo representation for music signals." ICASSP, 2010. Parameters ---------- y : np.ndarray [shape=(n,)] or None ...
librosa/feature/rhythm.py
def tempogram(y=None, sr=22050, onset_envelope=None, hop_length=512, win_length=384, center=True, window='hann', norm=np.inf): '''Compute the tempogram: local autocorrelation of the onset strength envelope. [1]_ .. [1] Grosche, Peter, Meinard Müller, and Frank Kurth. "Cyclic tempogram - A...
def tempogram(y=None, sr=22050, onset_envelope=None, hop_length=512, win_length=384, center=True, window='hann', norm=np.inf): '''Compute the tempogram: local autocorrelation of the onset strength envelope. [1]_ .. [1] Grosche, Peter, Meinard Müller, and Frank Kurth. "Cyclic tempogram - A...
[ "Compute", "the", "tempogram", ":", "local", "autocorrelation", "of", "the", "onset", "strength", "envelope", ".", "[", "1", "]", "_" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/feature/rhythm.py#L18-L178
[ "def", "tempogram", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "onset_envelope", "=", "None", ",", "hop_length", "=", "512", ",", "win_length", "=", "384", ",", "center", "=", "True", ",", "window", "=", "'hann'", ",", "norm", "=", "np", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
find_files
Get a sorted list of (audio) files in a directory or directory sub-tree. Examples -------- >>> # Get all audio files in a directory sub-tree >>> files = librosa.util.find_files('~/Music') >>> # Look only within a specific directory, not the sub-tree >>> files = librosa.util.find_files('~/Music...
librosa/util/files.py
def find_files(directory, ext=None, recurse=True, case_sensitive=False, limit=None, offset=0): '''Get a sorted list of (audio) files in a directory or directory sub-tree. Examples -------- >>> # Get all audio files in a directory sub-tree >>> files = librosa.util.find_files('~/Music'...
def find_files(directory, ext=None, recurse=True, case_sensitive=False, limit=None, offset=0): '''Get a sorted list of (audio) files in a directory or directory sub-tree. Examples -------- >>> # Get all audio files in a directory sub-tree >>> files = librosa.util.find_files('~/Music'...
[ "Get", "a", "sorted", "list", "of", "(", "audio", ")", "files", "in", "a", "directory", "or", "directory", "sub", "-", "tree", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/files.py#L49-L136
[ "def", "find_files", "(", "directory", ",", "ext", "=", "None", ",", "recurse", "=", "True", ",", "case_sensitive", "=", "False", ",", "limit", "=", "None", ",", "offset", "=", "0", ")", ":", "if", "ext", "is", "None", ":", "ext", "=", "[", "'aac'"...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__get_files
Helper function to get files in a single directory
librosa/util/files.py
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) ...
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) ...
[ "Helper", "function", "to", "get", "files", "in", "a", "single", "directory" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/files.py#L139-L151
[ "def", "__get_files", "(", "dir_name", ",", "extensions", ")", ":", "# Expand out the directory", "dir_name", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "dir_name", ")", ")", "myfiles", "=", "set", "(", ")", "...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
stretch_demo
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
examples/time_stretch.py
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...
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...
[ "Phase", "-", "vocoder", "time", "stretch", "demo", "function", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/examples/time_stretch.py#L13-L36
[ "def", "stretch_demo", "(", "input_file", ",", "output_file", ",", "speed", ")", ":", "# 1. Load the wav file, resample", "print", "(", "'Loading '", ",", "input_file", ")", "y", ",", "sr", "=", "librosa", ".", "load", "(", "input_file", ")", "# 2. Time-stretch ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
process_arguments
Argparse function to get the program parameters
examples/time_stretch.py
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...
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...
[ "Argparse", "function", "to", "get", "the", "program", "parameters" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/examples/time_stretch.py#L39-L59
[ "def", "process_arguments", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Time stretching example'", ")", "parser", ".", "add_argument", "(", "'input_file'", ",", "action", "=", "'store'", ",", "help", "=", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
hpss_demo
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)
examples/hpss.py
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) '...
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) '...
[ "HPSS", "demo", "function", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/examples/hpss.py#L13-L39
[ "def", "hpss_demo", "(", "input_file", ",", "output_harmonic", ",", "output_percussive", ")", ":", "# 1. Load the wav file, resample", "print", "(", "'Loading '", ",", "input_file", ")", "y", ",", "sr", "=", "librosa", ".", "load", "(", "input_file", ")", "# Sep...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
beat_track
r'''Dynamic programming beat tracker. Beats are detected in three stages, following the method of [1]_: 1. Measure onset strength 2. Estimate tempo from onset correlation 3. Pick peaks in onset strength approximately consistent with estimated tempo .. [1] Ellis, Daniel PW. "Beat tra...
librosa/beat.py
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 ...
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 ...
[ "r", "Dynamic", "programming", "beat", "tracker", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/beat.py#L26-L199
[ "def", "beat_track", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "onset_envelope", "=", "None", ",", "hop_length", "=", "512", ",", "start_bpm", "=", "120.0", ",", "tightness", "=", "100", ",", "trim", "=", "True", ",", "bpm", "=", "None", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
tempo
Estimate the tempo (beats per minute) Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [scalar] sampling rate of the time series onset_envelope : np.ndarray [shape=(n,)] pre-computed onset strength envelope hop_length : in...
librosa/beat.py
def tempo(y=None, sr=22050, onset_envelope=None, hop_length=512, start_bpm=120, std_bpm=1.0, ac_size=8.0, max_tempo=320.0, aggregate=np.mean): """Estimate the tempo (beats per minute) Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [sca...
def tempo(y=None, sr=22050, onset_envelope=None, hop_length=512, start_bpm=120, std_bpm=1.0, ac_size=8.0, max_tempo=320.0, aggregate=np.mean): """Estimate the tempo (beats per minute) Parameters ---------- y : np.ndarray [shape=(n,)] or None audio time series sr : number > 0 [sca...
[ "Estimate", "the", "tempo", "(", "beats", "per", "minute", ")" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/beat.py#L203-L340
[ "def", "tempo", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "onset_envelope", "=", "None", ",", "hop_length", "=", "512", ",", "start_bpm", "=", "120", ",", "std_bpm", "=", "1.0", ",", "ac_size", "=", "8.0", ",", "max_tempo", "=", "320.0", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__beat_tracker
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 [scalar] resolution of the fft (sr / hop_length) tightness: f...
librosa/beat.py
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 ...
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 ...
[ "Internal", "function", "that", "tracks", "beats", "in", "an", "onset", "strength", "envelope", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/beat.py#L343-L395
[ "def", "__beat_tracker", "(", "onset_envelope", ",", "bpm", ",", "fft_res", ",", "tightness", ",", "trim", ")", ":", "if", "bpm", "<=", "0", ":", "raise", "ParameterError", "(", "'bpm must be strictly positive'", ")", "# convert bpm to a sample period for searching", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__normalize_onsets
Maps onset strength function into the range [0, 1]
librosa/beat.py
def __normalize_onsets(onsets): '''Maps onset strength function into the range [0, 1]''' norm = onsets.std(ddof=1) if norm > 0: onsets = onsets / norm return onsets
def __normalize_onsets(onsets): '''Maps onset strength function into the range [0, 1]''' norm = onsets.std(ddof=1) if norm > 0: onsets = onsets / norm return onsets
[ "Maps", "onset", "strength", "function", "into", "the", "range", "[", "0", "1", "]" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/beat.py#L399-L405
[ "def", "__normalize_onsets", "(", "onsets", ")", ":", "norm", "=", "onsets", ".", "std", "(", "ddof", "=", "1", ")", "if", "norm", ">", "0", ":", "onsets", "=", "onsets", "/", "norm", "return", "onsets" ]
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__beat_local_score
Construct the local score for an onset envlope and given period
librosa/beat.py
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, ...
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, ...
[ "Construct", "the", "local", "score", "for", "an", "onset", "envlope", "and", "given", "period" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/beat.py#L408-L414
[ "def", "__beat_local_score", "(", "onset_envelope", ",", "period", ")", ":", "window", "=", "np", ".", "exp", "(", "-", "0.5", "*", "(", "np", ".", "arange", "(", "-", "period", ",", "period", "+", "1", ")", "*", "32.0", "/", "period", ")", "**", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__beat_track_dp
Core dynamic program for beat tracking
librosa/beat.py
def __beat_track_dp(localscore, period, tightness): """Core dynamic program for beat tracking""" backlink = np.zeros_like(localscore, dtype=int) cumscore = np.zeros_like(localscore) # Search range for previous beat window = np.arange(-2 * period, -np.round(period / 2) + 1, dtype=int) # Make a...
def __beat_track_dp(localscore, period, tightness): """Core dynamic program for beat tracking""" backlink = np.zeros_like(localscore, dtype=int) cumscore = np.zeros_like(localscore) # Search range for previous beat window = np.arange(-2 * period, -np.round(period / 2) + 1, dtype=int) # Make a...
[ "Core", "dynamic", "program", "for", "beat", "tracking" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/beat.py#L417-L459
[ "def", "__beat_track_dp", "(", "localscore", ",", "period", ",", "tightness", ")", ":", "backlink", "=", "np", ".", "zeros_like", "(", "localscore", ",", "dtype", "=", "int", ")", "cumscore", "=", "np", ".", "zeros_like", "(", "localscore", ")", "# Search ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__last_beat
Get the last beat from the cumulative score array
librosa/beat.py
def __last_beat(cumscore): """Get the last beat from the cumulative score array""" maxes = util.localmax(cumscore) med_score = np.median(cumscore[np.argwhere(maxes)]) # The last of these is the last beat (since score generally increases) return np.argwhere((cumscore * maxes * 2 > med_score)).max()
def __last_beat(cumscore): """Get the last beat from the cumulative score array""" maxes = util.localmax(cumscore) med_score = np.median(cumscore[np.argwhere(maxes)]) # The last of these is the last beat (since score generally increases) return np.argwhere((cumscore * maxes * 2 > med_score)).max()
[ "Get", "the", "last", "beat", "from", "the", "cumulative", "score", "array" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/beat.py#L462-L469
[ "def", "__last_beat", "(", "cumscore", ")", ":", "maxes", "=", "util", ".", "localmax", "(", "cumscore", ")", "med_score", "=", "np", ".", "median", "(", "cumscore", "[", "np", ".", "argwhere", "(", "maxes", ")", "]", ")", "# The last of these is the last ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
__trim_beats
Final post-processing: throw out spurious leading/trailing beats
librosa/beat.py
def __trim_beats(localscore, beats, trim): """Final post-processing: throw out spurious leading/trailing beats""" smooth_boe = scipy.signal.convolve(localscore[beats], scipy.signal.hann(5), 'same') if trim: threshold = 0...
def __trim_beats(localscore, beats, trim): """Final post-processing: throw out spurious leading/trailing beats""" smooth_boe = scipy.signal.convolve(localscore[beats], scipy.signal.hann(5), 'same') if trim: threshold = 0...
[ "Final", "post", "-", "processing", ":", "throw", "out", "spurious", "leading", "/", "trailing", "beats" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/beat.py#L472-L486
[ "def", "__trim_beats", "(", "localscore", ",", "beats", ",", "trim", ")", ":", "smooth_boe", "=", "scipy", ".", "signal", ".", "convolve", "(", "localscore", "[", "beats", "]", ",", "scipy", ".", "signal", ".", "hann", "(", "5", ")", ",", "'same'", "...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
recurrence_matrix
Compute a recurrence matrix from a data matrix. `rec[i, j]` is non-zero if (`data[:, i]`, `data[:, j]`) are k-nearest-neighbors and `|i - j| >= width` The specific value of `rec[i, j]` can have several forms, governed by the `mode` parameter below: - Connectivity: `rec[i, j] = 1 or 0` indicat...
librosa/segment.py
def recurrence_matrix(data, k=None, width=1, metric='euclidean', sym=False, sparse=False, mode='connectivity', bandwidth=None, self=False, axis=-1): '''Compute a recurrence matrix from a data matrix. `rec[i, j]` is non-zero if (`data[:, i]`, `data[:, j]`) are k-n...
def recurrence_matrix(data, k=None, width=1, metric='euclidean', sym=False, sparse=False, mode='connectivity', bandwidth=None, self=False, axis=-1): '''Compute a recurrence matrix from a data matrix. `rec[i, j]` is non-zero if (`data[:, i]`, `data[:, j]`) are k-n...
[ "Compute", "a", "recurrence", "matrix", "from", "a", "data", "matrix", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/segment.py#L54-L287
[ "def", "recurrence_matrix", "(", "data", ",", "k", "=", "None", ",", "width", "=", "1", ",", "metric", "=", "'euclidean'", ",", "sym", "=", "False", ",", "sparse", "=", "False", ",", "mode", "=", "'connectivity'", ",", "bandwidth", "=", "None", ",", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
recurrence_to_lag
Convert a recurrence matrix into a lag matrix. `lag[i, j] == rec[i+j, j]` Parameters ---------- rec : np.ndarray, or scipy.sparse.spmatrix [shape=(n, n)] A (binary) recurrence matrix, as returned by `recurrence_matrix` pad : bool If False, `lag` matrix is square, which is equi...
librosa/segment.py
def recurrence_to_lag(rec, pad=True, axis=-1): '''Convert a recurrence matrix into a lag matrix. `lag[i, j] == rec[i+j, j]` Parameters ---------- rec : np.ndarray, or scipy.sparse.spmatrix [shape=(n, n)] A (binary) recurrence matrix, as returned by `recurrence_matrix` pad : bool ...
def recurrence_to_lag(rec, pad=True, axis=-1): '''Convert a recurrence matrix into a lag matrix. `lag[i, j] == rec[i+j, j]` Parameters ---------- rec : np.ndarray, or scipy.sparse.spmatrix [shape=(n, n)] A (binary) recurrence matrix, as returned by `recurrence_matrix` pad : bool ...
[ "Convert", "a", "recurrence", "matrix", "into", "a", "lag", "matrix", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/segment.py#L290-L386
[ "def", "recurrence_to_lag", "(", "rec", ",", "pad", "=", "True", ",", "axis", "=", "-", "1", ")", ":", "axis", "=", "np", ".", "abs", "(", "axis", ")", "if", "rec", ".", "ndim", "!=", "2", "or", "rec", ".", "shape", "[", "0", "]", "!=", "rec"...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
lag_to_recurrence
Convert a lag matrix into a recurrence matrix. Parameters ---------- lag : np.ndarray or scipy.sparse.spmatrix A lag matrix, as produced by `recurrence_to_lag` axis : int The axis corresponding to the time dimension. The alternate axis will be interpreted in lag coordinates. ...
librosa/segment.py
def lag_to_recurrence(lag, axis=-1): '''Convert a lag matrix into a recurrence matrix. Parameters ---------- lag : np.ndarray or scipy.sparse.spmatrix A lag matrix, as produced by `recurrence_to_lag` axis : int The axis corresponding to the time dimension. The alternate axi...
def lag_to_recurrence(lag, axis=-1): '''Convert a lag matrix into a recurrence matrix. Parameters ---------- lag : np.ndarray or scipy.sparse.spmatrix A lag matrix, as produced by `recurrence_to_lag` axis : int The axis corresponding to the time dimension. The alternate axi...
[ "Convert", "a", "lag", "matrix", "into", "a", "recurrence", "matrix", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/segment.py#L389-L474
[ "def", "lag_to_recurrence", "(", "lag", ",", "axis", "=", "-", "1", ")", ":", "if", "axis", "not", "in", "[", "0", ",", "1", ",", "-", "1", "]", ":", "raise", "ParameterError", "(", "'Invalid target axis: {}'", ".", "format", "(", "axis", ")", ")", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
timelag_filter
Filtering in the time-lag domain. This is primarily useful for adapting image filters to operate on `recurrence_to_lag` output. Using `timelag_filter` is equivalent to the following sequence of operations: >>> data_tl = librosa.segment.recurrence_to_lag(data) >>> data_filtered_tl = function(d...
librosa/segment.py
def timelag_filter(function, pad=True, index=0): '''Filtering in the time-lag domain. This is primarily useful for adapting image filters to operate on `recurrence_to_lag` output. Using `timelag_filter` is equivalent to the following sequence of operations: >>> data_tl = librosa.segment.recur...
def timelag_filter(function, pad=True, index=0): '''Filtering in the time-lag domain. This is primarily useful for adapting image filters to operate on `recurrence_to_lag` output. Using `timelag_filter` is equivalent to the following sequence of operations: >>> data_tl = librosa.segment.recur...
[ "Filtering", "in", "the", "time", "-", "lag", "domain", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/segment.py#L477-L559
[ "def", "timelag_filter", "(", "function", ",", "pad", "=", "True", ",", "index", "=", "0", ")", ":", "def", "__my_filter", "(", "wrapped_f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "'''Decorator to wrap the filter'''", "# Map the input data into t...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
subsegment
Sub-divide a segmentation by feature clustering. Given a set of frame boundaries (`frames`), and a data matrix (`data`), each successive interval defined by `frames` is partitioned into `n_segments` by constrained agglomerative clustering. .. note:: If an interval spans fewer than `n_segments`...
librosa/segment.py
def subsegment(data, frames, n_segments=4, axis=-1): '''Sub-divide a segmentation by feature clustering. Given a set of frame boundaries (`frames`), and a data matrix (`data`), each successive interval defined by `frames` is partitioned into `n_segments` by constrained agglomerative clustering. .....
def subsegment(data, frames, n_segments=4, axis=-1): '''Sub-divide a segmentation by feature clustering. Given a set of frame boundaries (`frames`), and a data matrix (`data`), each successive interval defined by `frames` is partitioned into `n_segments` by constrained agglomerative clustering. .....
[ "Sub", "-", "divide", "a", "segmentation", "by", "feature", "clustering", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/segment.py#L563-L655
[ "def", "subsegment", "(", "data", ",", "frames", ",", "n_segments", "=", "4", ",", "axis", "=", "-", "1", ")", ":", "frames", "=", "util", ".", "fix_frames", "(", "frames", ",", "x_min", "=", "0", ",", "x_max", "=", "data", ".", "shape", "[", "ax...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
agglomerative
Bottom-up temporal segmentation. Use a temporally-constrained agglomerative clustering routine to partition `data` into `k` contiguous segments. Parameters ---------- data : np.ndarray data to cluster k : int > 0 [scalar] number of segments to produce clusterer...
librosa/segment.py
def agglomerative(data, k, clusterer=None, axis=-1): """Bottom-up temporal segmentation. Use a temporally-constrained agglomerative clustering routine to partition `data` into `k` contiguous segments. Parameters ---------- data : np.ndarray data to cluster k : int > 0 [...
def agglomerative(data, k, clusterer=None, axis=-1): """Bottom-up temporal segmentation. Use a temporally-constrained agglomerative clustering routine to partition `data` into `k` contiguous segments. Parameters ---------- data : np.ndarray data to cluster k : int > 0 [...
[ "Bottom", "-", "up", "temporal", "segmentation", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/segment.py#L658-L745
[ "def", "agglomerative", "(", "data", ",", "k", ",", "clusterer", "=", "None", ",", "axis", "=", "-", "1", ")", ":", "# Make sure we have at least two dimensions", "data", "=", "np", ".", "atleast_2d", "(", "data", ")", "# Swap data index to position 0", "data", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
path_enhance
Multi-angle path enhancement for self- and cross-similarity matrices. This function convolves multiple diagonal smoothing filters with a self-similarity (or recurrence) matrix R, and aggregates the result by an element-wise maximum. Technically, the output is a matrix R_smooth such that `R_smooth...
librosa/segment.py
def path_enhance(R, n, window='hann', max_ratio=2.0, min_ratio=None, n_filters=7, zero_mean=False, clip=True, **kwargs): '''Multi-angle path enhancement for self- and cross-similarity matrices. This function convolves multiple diagonal smoothing filters with a self-similarity (or recurrenc...
def path_enhance(R, n, window='hann', max_ratio=2.0, min_ratio=None, n_filters=7, zero_mean=False, clip=True, **kwargs): '''Multi-angle path enhancement for self- and cross-similarity matrices. This function convolves multiple diagonal smoothing filters with a self-similarity (or recurrenc...
[ "Multi", "-", "angle", "path", "enhancement", "for", "self", "-", "and", "cross", "-", "similarity", "matrices", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/segment.py#L748-L877
[ "def", "path_enhance", "(", "R", ",", "n", ",", "window", "=", "'hann'", ",", "max_ratio", "=", "2.0", ",", "min_ratio", "=", "None", ",", "n_filters", "=", "7", ",", "zero_mean", "=", "False", ",", "clip", "=", "True", ",", "*", "*", "kwargs", ")"...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
onset_detect
Onset detection function :parameters: - input_file : str Path to input audio file (wav, mp3, m4a, flac, etc.) - output_file : str Path to save onset timestamps as a CSV file
examples/onset_detector.py
def onset_detect(input_file, output_csv): '''Onset detection function :parameters: - input_file : str Path to input audio file (wav, mp3, m4a, flac, etc.) - output_file : str Path to save onset timestamps as a CSV file ''' # 1. load the wav file and resample to 22.050 ...
def onset_detect(input_file, output_csv): '''Onset detection function :parameters: - input_file : str Path to input audio file (wav, mp3, m4a, flac, etc.) - output_file : str Path to save onset timestamps as a CSV file ''' # 1. load the wav file and resample to 22.050 ...
[ "Onset", "detection", "function" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/examples/onset_detector.py#L16-L51
[ "def", "onset_detect", "(", "input_file", ",", "output_csv", ")", ":", "# 1. load the wav file and resample to 22.050 KHz", "print", "(", "'Loading '", ",", "input_file", ")", "y", ",", "sr", "=", "librosa", ".", "load", "(", "input_file", ",", "sr", "=", "22050...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
frame
Slice a time series into overlapping frames. This implementation uses low-level stride manipulation to avoid redundant copies of the time series data. Parameters ---------- y : np.ndarray [shape=(n,)] Time series to frame. Must be one-dimensional and contiguous in memory. fram...
librosa/util/utils.py
def frame(y, frame_length=2048, hop_length=512): '''Slice a time series into overlapping frames. This implementation uses low-level stride manipulation to avoid redundant copies of the time series data. Parameters ---------- y : np.ndarray [shape=(n,)] Time series to frame. Must be one...
def frame(y, frame_length=2048, hop_length=512): '''Slice a time series into overlapping frames. This implementation uses low-level stride manipulation to avoid redundant copies of the time series data. Parameters ---------- y : np.ndarray [shape=(n,)] Time series to frame. Must be one...
[ "Slice", "a", "time", "series", "into", "overlapping", "frames", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L34-L107
[ "def", "frame", "(", "y", ",", "frame_length", "=", "2048", ",", "hop_length", "=", "512", ")", ":", "if", "not", "isinstance", "(", "y", ",", "np", ".", "ndarray", ")", ":", "raise", "ParameterError", "(", "'Input must be of type numpy.ndarray, '", "'given ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
valid_audio
Validate whether a variable contains valid, mono audio data. Parameters ---------- y : np.ndarray The input data to validate mono : bool Whether or not to force monophonic audio Returns ------- valid : bool True if all tests pass Raises ------ ParameterEr...
librosa/util/utils.py
def valid_audio(y, mono=True): '''Validate whether a variable contains valid, mono audio data. Parameters ---------- y : np.ndarray The input data to validate mono : bool Whether or not to force monophonic audio Returns ------- valid : bool True if all tests pass ...
def valid_audio(y, mono=True): '''Validate whether a variable contains valid, mono audio data. Parameters ---------- y : np.ndarray The input data to validate mono : bool Whether or not to force monophonic audio Returns ------- valid : bool True if all tests pass ...
[ "Validate", "whether", "a", "variable", "contains", "valid", "mono", "audio", "data", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L111-L172
[ "def", "valid_audio", "(", "y", ",", "mono", "=", "True", ")", ":", "if", "not", "isinstance", "(", "y", ",", "np", ".", "ndarray", ")", ":", "raise", "ParameterError", "(", "'data must be of type numpy.ndarray'", ")", "if", "not", "np", ".", "issubdtype",...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
valid_int
Ensure that an input value is integer-typed. This is primarily useful for ensuring integrable-valued array indices. Parameters ---------- x : number A scalar value to be cast to int cast : function [optional] A function to modify `x` before casting. Default: `np.floor` ...
librosa/util/utils.py
def valid_int(x, cast=None): '''Ensure that an input value is integer-typed. This is primarily useful for ensuring integrable-valued array indices. Parameters ---------- x : number A scalar value to be cast to int cast : function [optional] A function to modify `x` before c...
def valid_int(x, cast=None): '''Ensure that an input value is integer-typed. This is primarily useful for ensuring integrable-valued array indices. Parameters ---------- x : number A scalar value to be cast to int cast : function [optional] A function to modify `x` before c...
[ "Ensure", "that", "an", "input", "value", "is", "integer", "-", "typed", ".", "This", "is", "primarily", "useful", "for", "ensuring", "integrable", "-", "valued", "array", "indices", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L175-L206
[ "def", "valid_int", "(", "x", ",", "cast", "=", "None", ")", ":", "if", "cast", "is", "None", ":", "cast", "=", "np", ".", "floor", "if", "not", "six", ".", "callable", "(", "cast", ")", ":", "raise", "ParameterError", "(", "'cast parameter must be cal...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
valid_intervals
Ensure that an array is a valid representation of time intervals: - intervals.ndim == 2 - intervals.shape[1] == 2 - intervals[i, 0] <= intervals[i, 1] for all i Parameters ---------- intervals : np.ndarray [shape=(n, 2)] set of time intervals Returns ------- va...
librosa/util/utils.py
def valid_intervals(intervals): '''Ensure that an array is a valid representation of time intervals: - intervals.ndim == 2 - intervals.shape[1] == 2 - intervals[i, 0] <= intervals[i, 1] for all i Parameters ---------- intervals : np.ndarray [shape=(n, 2)] set of time in...
def valid_intervals(intervals): '''Ensure that an array is a valid representation of time intervals: - intervals.ndim == 2 - intervals.shape[1] == 2 - intervals[i, 0] <= intervals[i, 1] for all i Parameters ---------- intervals : np.ndarray [shape=(n, 2)] set of time in...
[ "Ensure", "that", "an", "array", "is", "a", "valid", "representation", "of", "time", "intervals", ":" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L209-L233
[ "def", "valid_intervals", "(", "intervals", ")", ":", "if", "intervals", ".", "ndim", "!=", "2", "or", "intervals", ".", "shape", "[", "-", "1", "]", "!=", "2", ":", "raise", "ParameterError", "(", "'intervals must have shape (n, 2)'", ")", "if", "np", "."...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
pad_center
Wrapper for np.pad to automatically center an array prior to padding. This is analogous to `str.center()` Examples -------- >>> # Generate a vector >>> data = np.ones(5) >>> librosa.util.pad_center(data, 10, mode='constant') array([ 0., 0., 1., 1., 1., 1., 1., 0., 0., 0.]) >>>...
librosa/util/utils.py
def pad_center(data, size, axis=-1, **kwargs): '''Wrapper for np.pad to automatically center an array prior to padding. This is analogous to `str.center()` Examples -------- >>> # Generate a vector >>> data = np.ones(5) >>> librosa.util.pad_center(data, 10, mode='constant') array([ 0., ...
def pad_center(data, size, axis=-1, **kwargs): '''Wrapper for np.pad to automatically center an array prior to padding. This is analogous to `str.center()` Examples -------- >>> # Generate a vector >>> data = np.ones(5) >>> librosa.util.pad_center(data, 10, mode='constant') array([ 0., ...
[ "Wrapper", "for", "np", ".", "pad", "to", "automatically", "center", "an", "array", "prior", "to", "padding", ".", "This", "is", "analogous", "to", "str", ".", "center", "()" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L236-L306
[ "def", "pad_center", "(", "data", ",", "size", ",", "axis", "=", "-", "1", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'mode'", ",", "'constant'", ")", "n", "=", "data", ".", "shape", "[", "axis", "]", "lpad", "=", "int"...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
fix_length
Fix the length an array `data` to exactly `size`. If `data.shape[axis] < n`, pad according to the provided kwargs. By default, `data` is padded with trailing zeros. Examples -------- >>> y = np.arange(7) >>> # Default: pad with zeros >>> librosa.util.fix_length(y, 10) array([0, 1, 2, 3...
librosa/util/utils.py
def fix_length(data, size, axis=-1, **kwargs): '''Fix the length an array `data` to exactly `size`. If `data.shape[axis] < n`, pad according to the provided kwargs. By default, `data` is padded with trailing zeros. Examples -------- >>> y = np.arange(7) >>> # Default: pad with zeros >>...
def fix_length(data, size, axis=-1, **kwargs): '''Fix the length an array `data` to exactly `size`. If `data.shape[axis] < n`, pad according to the provided kwargs. By default, `data` is padded with trailing zeros. Examples -------- >>> y = np.arange(7) >>> # Default: pad with zeros >>...
[ "Fix", "the", "length", "an", "array", "data", "to", "exactly", "size", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L309-L367
[ "def", "fix_length", "(", "data", ",", "size", ",", "axis", "=", "-", "1", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'mode'", ",", "'constant'", ")", "n", "=", "data", ".", "shape", "[", "axis", "]", "if", "n", ">", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
fix_frames
Fix a list of frames to lie within [x_min, x_max] Examples -------- >>> # Generate a list of frame indices >>> frames = np.arange(0, 1000.0, 50) >>> frames array([ 0., 50., 100., 150., 200., 250., 300., 350., 400., 450., 500., 550., 600., 650., 700., 750., ...
librosa/util/utils.py
def fix_frames(frames, x_min=0, x_max=None, pad=True): '''Fix a list of frames to lie within [x_min, x_max] Examples -------- >>> # Generate a list of frame indices >>> frames = np.arange(0, 1000.0, 50) >>> frames array([ 0., 50., 100., 150., 200., 250., 300., 350., 40...
def fix_frames(frames, x_min=0, x_max=None, pad=True): '''Fix a list of frames to lie within [x_min, x_max] Examples -------- >>> # Generate a list of frame indices >>> frames = np.arange(0, 1000.0, 50) >>> frames array([ 0., 50., 100., 150., 200., 250., 300., 350., 40...
[ "Fix", "a", "list", "of", "frames", "to", "lie", "within", "[", "x_min", "x_max", "]" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L370-L452
[ "def", "fix_frames", "(", "frames", ",", "x_min", "=", "0", ",", "x_max", "=", "None", ",", "pad", "=", "True", ")", ":", "frames", "=", "np", ".", "asarray", "(", "frames", ")", "if", "np", ".", "any", "(", "frames", "<", "0", ")", ":", "raise...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
axis_sort
Sort an array along its rows or columns. Examples -------- Visualize NMF output for a spectrogram S >>> # Sort the columns of W by peak frequency bin >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> S = np.abs(librosa.stft(y)) >>> W, H = librosa.decompose.decompose(S, n_comp...
librosa/util/utils.py
def axis_sort(S, axis=-1, index=False, value=None): '''Sort an array along its rows or columns. Examples -------- Visualize NMF output for a spectrogram S >>> # Sort the columns of W by peak frequency bin >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> S = np.abs(librosa.st...
def axis_sort(S, axis=-1, index=False, value=None): '''Sort an array along its rows or columns. Examples -------- Visualize NMF output for a spectrogram S >>> # Sort the columns of W by peak frequency bin >>> y, sr = librosa.load(librosa.util.example_audio_file()) >>> S = np.abs(librosa.st...
[ "Sort", "an", "array", "along", "its", "rows", "or", "columns", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L455-L549
[ "def", "axis_sort", "(", "S", ",", "axis", "=", "-", "1", ",", "index", "=", "False", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "np", ".", "argmax", "if", "S", ".", "ndim", "!=", "2", ":", "raise", "...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
normalize
Normalize an array along a chosen axis. Given a norm (described below) and a target axis, the input array is scaled so that `norm(S, axis=axis) == 1` For example, `axis=0` normalizes each column of a 2-d array by aggregating over the rows (0-axis). Similarly, `axis=1` normalizes each row ...
librosa/util/utils.py
def normalize(S, norm=np.inf, axis=0, threshold=None, fill=None): '''Normalize an array along a chosen axis. Given a norm (described below) and a target axis, the input array is scaled so that `norm(S, axis=axis) == 1` For example, `axis=0` normalizes each column of a 2-d array by aggrega...
def normalize(S, norm=np.inf, axis=0, threshold=None, fill=None): '''Normalize an array along a chosen axis. Given a norm (described below) and a target axis, the input array is scaled so that `norm(S, axis=axis) == 1` For example, `axis=0` normalizes each column of a 2-d array by aggrega...
[ "Normalize", "an", "array", "along", "a", "chosen", "axis", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L553-L777
[ "def", "normalize", "(", "S", ",", "norm", "=", "np", ".", "inf", ",", "axis", "=", "0", ",", "threshold", "=", "None", ",", "fill", "=", "None", ")", ":", "# Avoid div-by-zero", "if", "threshold", "is", "None", ":", "threshold", "=", "tiny", "(", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
localmax
Find local maxima in an array `x`. An element `x[i]` is considered a local maximum if the following conditions are met: - `x[i] > x[i-1]` - `x[i] >= x[i+1]` Note that the first condition is strict, and that the first element `x[0]` will never be considered as a local maximum. Examples ...
librosa/util/utils.py
def localmax(x, axis=0): """Find local maxima in an array `x`. An element `x[i]` is considered a local maximum if the following conditions are met: - `x[i] > x[i-1]` - `x[i] >= x[i+1]` Note that the first condition is strict, and that the first element `x[0]` will never be considered as a...
def localmax(x, axis=0): """Find local maxima in an array `x`. An element `x[i]` is considered a local maximum if the following conditions are met: - `x[i] > x[i-1]` - `x[i] >= x[i+1]` Note that the first condition is strict, and that the first element `x[0]` will never be considered as a...
[ "Find", "local", "maxima", "in", "an", "array", "x", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L780-L835
[ "def", "localmax", "(", "x", ",", "axis", "=", "0", ")", ":", "paddings", "=", "[", "(", "0", ",", "0", ")", "]", "*", "x", ".", "ndim", "paddings", "[", "axis", "]", "=", "(", "1", ",", "1", ")", "x_pad", "=", "np", ".", "pad", "(", "x",...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
peak_pick
Uses a flexible heuristic to pick peaks in a signal. A sample n is selected as an peak if the corresponding x[n] fulfills the following three conditions: 1. `x[n] == max(x[n - pre_max:n + post_max])` 2. `x[n] >= mean(x[n - pre_avg:n + post_avg]) + delta` 3. `n - previous_n > wait` where `prev...
librosa/util/utils.py
def peak_pick(x, pre_max, post_max, pre_avg, post_avg, delta, wait): '''Uses a flexible heuristic to pick peaks in a signal. A sample n is selected as an peak if the corresponding x[n] fulfills the following three conditions: 1. `x[n] == max(x[n - pre_max:n + post_max])` 2. `x[n] >= mean(x[n - pre...
def peak_pick(x, pre_max, post_max, pre_avg, post_avg, delta, wait): '''Uses a flexible heuristic to pick peaks in a signal. A sample n is selected as an peak if the corresponding x[n] fulfills the following three conditions: 1. `x[n] == max(x[n - pre_max:n + post_max])` 2. `x[n] >= mean(x[n - pre...
[ "Uses", "a", "flexible", "heuristic", "to", "pick", "peaks", "in", "a", "signal", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L838-L1005
[ "def", "peak_pick", "(", "x", ",", "pre_max", ",", "post_max", ",", "pre_avg", ",", "post_avg", ",", "delta", ",", "wait", ")", ":", "if", "pre_max", "<", "0", ":", "raise", "ParameterError", "(", "'pre_max must be non-negative'", ")", "if", "pre_avg", "<"...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
sparsify_rows
Return a row-sparse matrix approximating the input `x`. Parameters ---------- x : np.ndarray [ndim <= 2] The input matrix to sparsify. quantile : float in [0, 1.0) Percentage of magnitude to discard in each row of `x` Returns ------- x_sparse : `scipy.sparse.csr_matrix` [s...
librosa/util/utils.py
def sparsify_rows(x, quantile=0.01): ''' Return a row-sparse matrix approximating the input `x`. Parameters ---------- x : np.ndarray [ndim <= 2] The input matrix to sparsify. quantile : float in [0, 1.0) Percentage of magnitude to discard in each row of `x` Returns --...
def sparsify_rows(x, quantile=0.01): ''' Return a row-sparse matrix approximating the input `x`. Parameters ---------- x : np.ndarray [ndim <= 2] The input matrix to sparsify. quantile : float in [0, 1.0) Percentage of magnitude to discard in each row of `x` Returns --...
[ "Return", "a", "row", "-", "sparse", "matrix", "approximating", "the", "input", "x", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L1009-L1098
[ "def", "sparsify_rows", "(", "x", ",", "quantile", "=", "0.01", ")", ":", "if", "x", ".", "ndim", "==", "1", ":", "x", "=", "x", ".", "reshape", "(", "(", "1", ",", "-", "1", ")", ")", "elif", "x", ".", "ndim", ">", "2", ":", "raise", "Para...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
roll_sparse
Sparse matrix roll This operation is equivalent to ``numpy.roll``, but operates on sparse matrices. Parameters ---------- x : scipy.sparse.spmatrix or np.ndarray The sparse matrix input shift : int The number of positions to roll the specified axis axis : (0, 1, -1) T...
librosa/util/utils.py
def roll_sparse(x, shift, axis=0): '''Sparse matrix roll This operation is equivalent to ``numpy.roll``, but operates on sparse matrices. Parameters ---------- x : scipy.sparse.spmatrix or np.ndarray The sparse matrix input shift : int The number of positions to roll the speci...
def roll_sparse(x, shift, axis=0): '''Sparse matrix roll This operation is equivalent to ``numpy.roll``, but operates on sparse matrices. Parameters ---------- x : scipy.sparse.spmatrix or np.ndarray The sparse matrix input shift : int The number of positions to roll the speci...
[ "Sparse", "matrix", "roll" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L1101-L1167
[ "def", "roll_sparse", "(", "x", ",", "shift", ",", "axis", "=", "0", ")", ":", "if", "not", "scipy", ".", "sparse", ".", "isspmatrix", "(", "x", ")", ":", "return", "np", ".", "roll", "(", "x", ",", "shift", ",", "axis", "=", "axis", ")", "# sh...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
buf_to_float
Convert an integer buffer to floating point values. This is primarily useful when loading integer-valued wav data into numpy arrays. See Also -------- buf_to_float Parameters ---------- x : np.ndarray [dtype=int] The integer-valued data buffer n_bytes : int [1, 2, 4] ...
librosa/util/utils.py
def buf_to_float(x, n_bytes=2, dtype=np.float32): """Convert an integer buffer to floating point values. This is primarily useful when loading integer-valued wav data into numpy arrays. See Also -------- buf_to_float Parameters ---------- x : np.ndarray [dtype=int] The inte...
def buf_to_float(x, n_bytes=2, dtype=np.float32): """Convert an integer buffer to floating point values. This is primarily useful when loading integer-valued wav data into numpy arrays. See Also -------- buf_to_float Parameters ---------- x : np.ndarray [dtype=int] The inte...
[ "Convert", "an", "integer", "buffer", "to", "floating", "point", "values", ".", "This", "is", "primarily", "useful", "when", "loading", "integer", "-", "valued", "wav", "data", "into", "numpy", "arrays", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L1170-L1203
[ "def", "buf_to_float", "(", "x", ",", "n_bytes", "=", "2", ",", "dtype", "=", "np", ".", "float32", ")", ":", "# Invert the scale of the data", "scale", "=", "1.", "/", "float", "(", "1", "<<", "(", "(", "8", "*", "n_bytes", ")", "-", "1", ")", ")"...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
index_to_slice
Generate a slice array from an index array. Parameters ---------- idx : list-like Array of index boundaries idx_min : None or int idx_max : None or int Minimum and maximum allowed indices step : None or int Step size for each slice. If `None`, then the default ...
librosa/util/utils.py
def index_to_slice(idx, idx_min=None, idx_max=None, step=None, pad=True): '''Generate a slice array from an index array. Parameters ---------- idx : list-like Array of index boundaries idx_min : None or int idx_max : None or int Minimum and maximum allowed indices step : N...
def index_to_slice(idx, idx_min=None, idx_max=None, step=None, pad=True): '''Generate a slice array from an index array. Parameters ---------- idx : list-like Array of index boundaries idx_min : None or int idx_max : None or int Minimum and maximum allowed indices step : N...
[ "Generate", "a", "slice", "array", "from", "an", "index", "array", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L1206-L1259
[ "def", "index_to_slice", "(", "idx", ",", "idx_min", "=", "None", ",", "idx_max", "=", "None", ",", "step", "=", "None", ",", "pad", "=", "True", ")", ":", "# First, normalize the index set", "idx_fixed", "=", "fix_frames", "(", "idx", ",", "idx_min", ",",...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
sync
Synchronous aggregation of a multi-dimensional array between boundaries .. note:: In order to ensure total coverage, boundary points may be added to `idx`. If synchronizing a feature matrix against beat tracker output, ensure that frame index numbers are properly aligned and use th...
librosa/util/utils.py
def sync(data, idx, aggregate=None, pad=True, axis=-1): """Synchronous aggregation of a multi-dimensional array between boundaries .. note:: In order to ensure total coverage, boundary points may be added to `idx`. If synchronizing a feature matrix against beat tracker output, ensure ...
def sync(data, idx, aggregate=None, pad=True, axis=-1): """Synchronous aggregation of a multi-dimensional array between boundaries .. note:: In order to ensure total coverage, boundary points may be added to `idx`. If synchronizing a feature matrix against beat tracker output, ensure ...
[ "Synchronous", "aggregation", "of", "a", "multi", "-", "dimensional", "array", "between", "boundaries" ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L1263-L1388
[ "def", "sync", "(", "data", ",", "idx", ",", "aggregate", "=", "None", ",", "pad", "=", "True", ",", "axis", "=", "-", "1", ")", ":", "if", "aggregate", "is", "None", ":", "aggregate", "=", "np", ".", "mean", "shape", "=", "list", "(", "data", ...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
softmask
Robustly compute a softmask operation. `M = X**power / (X**power + X_ref**power)` Parameters ---------- X : np.ndarray The (non-negative) input array corresponding to the positive mask elements X_ref : np.ndarray The (non-negative) array of reference or background elements. ...
librosa/util/utils.py
def softmask(X, X_ref, power=1, split_zeros=False): '''Robustly compute a softmask operation. `M = X**power / (X**power + X_ref**power)` Parameters ---------- X : np.ndarray The (non-negative) input array corresponding to the positive mask elements X_ref : np.ndarray The ...
def softmask(X, X_ref, power=1, split_zeros=False): '''Robustly compute a softmask operation. `M = X**power / (X**power + X_ref**power)` Parameters ---------- X : np.ndarray The (non-negative) input array corresponding to the positive mask elements X_ref : np.ndarray The ...
[ "Robustly", "compute", "a", "softmask", "operation", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L1391-L1507
[ "def", "softmask", "(", "X", ",", "X_ref", ",", "power", "=", "1", ",", "split_zeros", "=", "False", ")", ":", "if", "X", ".", "shape", "!=", "X_ref", ".", "shape", ":", "raise", "ParameterError", "(", "'Shape mismatch: {}!={}'", ".", "format", "(", "X...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
tiny
Compute the tiny-value corresponding to an input's data type. This is the smallest "usable" number representable in `x`'s data type (e.g., float32). This is primarily useful for determining a threshold for numerical underflow in division or multiplication operations. Parameters ---------- ...
librosa/util/utils.py
def tiny(x): '''Compute the tiny-value corresponding to an input's data type. This is the smallest "usable" number representable in `x`'s data type (e.g., float32). This is primarily useful for determining a threshold for numerical underflow in division or multiplication operations. Parameter...
def tiny(x): '''Compute the tiny-value corresponding to an input's data type. This is the smallest "usable" number representable in `x`'s data type (e.g., float32). This is primarily useful for determining a threshold for numerical underflow in division or multiplication operations. Parameter...
[ "Compute", "the", "tiny", "-", "value", "corresponding", "to", "an", "input", "s", "data", "type", "." ]
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L1510-L1574
[ "def", "tiny", "(", "x", ")", ":", "# Make sure we have an array view", "x", "=", "np", ".", "asarray", "(", "x", ")", "# Only floating types generate a tiny", "if", "np", ".", "issubdtype", "(", "x", ".", "dtype", ",", "np", ".", "floating", ")", "or", "n...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
fill_off_diagonal
Sets all cells of a matrix to a given ``value`` if they lie outside a constraint region. In this case, the constraint region is the Sakoe-Chiba band which runs with a fixed ``radius`` along the main diagonal. When ``x.shape[0] != x.shape[1]``, the radius will be expanded so that ``x[-1, -1] = 1`...
librosa/util/utils.py
def fill_off_diagonal(x, radius, value=0): """Sets all cells of a matrix to a given ``value`` if they lie outside a constraint region. In this case, the constraint region is the Sakoe-Chiba band which runs with a fixed ``radius`` along the main diagonal. When ``x.shape[0] != x.shape[1]``, the ra...
def fill_off_diagonal(x, radius, value=0): """Sets all cells of a matrix to a given ``value`` if they lie outside a constraint region. In this case, the constraint region is the Sakoe-Chiba band which runs with a fixed ``radius`` along the main diagonal. When ``x.shape[0] != x.shape[1]``, the ra...
[ "Sets", "all", "cells", "of", "a", "matrix", "to", "a", "given", "value", "if", "they", "lie", "outside", "a", "constraint", "region", ".", "In", "this", "case", "the", "constraint", "region", "is", "the", "Sakoe", "-", "Chiba", "band", "which", "runs", ...
librosa/librosa
python
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/util/utils.py#L1577-L1640
[ "def", "fill_off_diagonal", "(", "x", ",", "radius", ",", "value", "=", "0", ")", ":", "nx", ",", "ny", "=", "x", ".", "shape", "# Calculate the radius in indices, rather than proportion", "radius", "=", "np", ".", "round", "(", "radius", "*", "np", ".", "...
180e8e6eb8f958fa6b20b8cba389f7945d508247
test
frames2video
Read the frame images from a directory and join them as a video Args: frame_dir (str): The directory containing video frames. video_file (str): Output filename. fps (float): FPS of the output video. fourcc (str): Fourcc of the output video, this should be compatible with...
mmcv/video/io.py
def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True): """Read the frame images from a directory and join them as a video ...
def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True): """Read the frame images from a directory and join them as a video ...
[ "Read", "the", "frame", "images", "from", "a", "directory", "and", "join", "them", "as", "a", "video" ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/video/io.py#L288-L332
[ "def", "frames2video", "(", "frame_dir", ",", "video_file", ",", "fps", "=", "30", ",", "fourcc", "=", "'XVID'", ",", "filename_tmpl", "=", "'{:06d}.jpg'", ",", "start", "=", "0", ",", "end", "=", "0", ",", "show_progress", "=", "True", ")", ":", "if",...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
VideoReader.read
Read the next frame. If the next frame have been decoded before and in the cache, then return it directly, otherwise decode, cache and return it. Returns: ndarray or None: Return the frame if successful, otherwise None.
mmcv/video/io.py
def read(self): """Read the next frame. If the next frame have been decoded before and in the cache, then return it directly, otherwise decode, cache and return it. Returns: ndarray or None: Return the frame if successful, otherwise None. """ # pos = self._p...
def read(self): """Read the next frame. If the next frame have been decoded before and in the cache, then return it directly, otherwise decode, cache and return it. Returns: ndarray or None: Return the frame if successful, otherwise None. """ # pos = self._p...
[ "Read", "the", "next", "frame", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/video/io.py#L142-L166
[ "def", "read", "(", "self", ")", ":", "# pos = self._position", "if", "self", ".", "_cache", ":", "img", "=", "self", ".", "_cache", ".", "get", "(", "self", ".", "_position", ")", "if", "img", "is", "not", "None", ":", "ret", "=", "True", "else", ...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
VideoReader.get_frame
Get frame by index. Args: frame_id (int): Index of the expected frame, 0-based. Returns: ndarray or None: Return the frame if successful, otherwise None.
mmcv/video/io.py
def get_frame(self, frame_id): """Get frame by index. Args: frame_id (int): Index of the expected frame, 0-based. Returns: ndarray or None: Return the frame if successful, otherwise None. """ if frame_id < 0 or frame_id >= self._frame_cnt: ra...
def get_frame(self, frame_id): """Get frame by index. Args: frame_id (int): Index of the expected frame, 0-based. Returns: ndarray or None: Return the frame if successful, otherwise None. """ if frame_id < 0 or frame_id >= self._frame_cnt: ra...
[ "Get", "frame", "by", "index", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/video/io.py#L168-L194
[ "def", "get_frame", "(", "self", ",", "frame_id", ")", ":", "if", "frame_id", "<", "0", "or", "frame_id", ">=", "self", ".", "_frame_cnt", ":", "raise", "IndexError", "(", "'\"frame_id\" must be between 0 and {}'", ".", "format", "(", "self", ".", "_frame_cnt"...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
VideoReader.cvt2frames
Convert a video to frame images Args: frame_dir (str): Output directory to store all the frame images. file_start (int): Filenames will start from the specified number. filename_tmpl (str): Filename template with the index as the placeholder. star...
mmcv/video/io.py
def cvt2frames(self, frame_dir, file_start=0, filename_tmpl='{:06d}.jpg', start=0, max_num=0, show_progress=True): """Convert a video to frame images Args: frame_dir (str): Outp...
def cvt2frames(self, frame_dir, file_start=0, filename_tmpl='{:06d}.jpg', start=0, max_num=0, show_progress=True): """Convert a video to frame images Args: frame_dir (str): Outp...
[ "Convert", "a", "video", "to", "frame", "images" ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/video/io.py#L207-L250
[ "def", "cvt2frames", "(", "self", ",", "frame_dir", ",", "file_start", "=", "0", ",", "filename_tmpl", "=", "'{:06d}.jpg'", ",", "start", "=", "0", ",", "max_num", "=", "0", ",", "show_progress", "=", "True", ")", ":", "mkdir_or_exist", "(", "frame_dir", ...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
track_progress
Track the progress of tasks execution with a progress bar. Tasks are done with a simple for-loop. Args: func (callable): The function to be applied to each task. tasks (list or tuple[Iterable, int]): A list of tasks or (tasks, total num). bar_width (int): Width of progress ...
mmcv/utils/progressbar.py
def track_progress(func, tasks, bar_width=50, **kwargs): """Track the progress of tasks execution with a progress bar. Tasks are done with a simple for-loop. Args: func (callable): The function to be applied to each task. tasks (list or tuple[Iterable, int]): A list of tasks or ...
def track_progress(func, tasks, bar_width=50, **kwargs): """Track the progress of tasks execution with a progress bar. Tasks are done with a simple for-loop. Args: func (callable): The function to be applied to each task. tasks (list or tuple[Iterable, int]): A list of tasks or ...
[ "Track", "the", "progress", "of", "tasks", "execution", "with", "a", "progress", "bar", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/utils/progressbar.py#L63-L94
[ "def", "track_progress", "(", "func", ",", "tasks", ",", "bar_width", "=", "50", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "tasks", ",", "tuple", ")", ":", "assert", "len", "(", "tasks", ")", "==", "2", "assert", "isinstance", "(", ...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
track_parallel_progress
Track the progress of parallel task execution with a progress bar. The built-in :mod:`multiprocessing` module is used for process pools and tasks are done with :func:`Pool.map` or :func:`Pool.imap_unordered`. Args: func (callable): The function to be applied to each task. tasks (list or tu...
mmcv/utils/progressbar.py
def track_parallel_progress(func, tasks, nproc, initializer=None, initargs=None, bar_width=50, chunksize=1, skip_first=False...
def track_parallel_progress(func, tasks, nproc, initializer=None, initargs=None, bar_width=50, chunksize=1, skip_first=False...
[ "Track", "the", "progress", "of", "parallel", "task", "execution", "with", "a", "progress", "bar", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/utils/progressbar.py#L108-L174
[ "def", "track_parallel_progress", "(", "func", ",", "tasks", ",", "nproc", ",", "initializer", "=", "None", ",", "initargs", "=", "None", ",", "bar_width", "=", "50", ",", "chunksize", "=", "1", ",", "skip_first", "=", "False", ",", "keep_order", "=", "T...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
imflip
Flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical". Returns: ndarray: The flipped image.
mmcv/image/transforms/geometry.py
def imflip(img, direction='horizontal'): """Flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical". Returns: ndarray: The flipped image. """ assert direction in ['horizontal'...
def imflip(img, direction='horizontal'): """Flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical". Returns: ndarray: The flipped image. """ assert direction in ['horizontal'...
[ "Flip", "an", "image", "horizontally", "or", "vertically", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/geometry.py#L7-L21
[ "def", "imflip", "(", "img", ",", "direction", "=", "'horizontal'", ")", ":", "assert", "direction", "in", "[", "'horizontal'", ",", "'vertical'", "]", "if", "direction", "==", "'horizontal'", ":", "return", "np", ".", "flip", "(", "img", ",", "axis", "=...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
imrotate
Rotate an image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees, positive values mean clockwise rotation. center (tuple): Center of the rotation in the source image, by default it is the center of the image. scale (float): ...
mmcv/image/transforms/geometry.py
def imrotate(img, angle, center=None, scale=1.0, border_value=0, auto_bound=False): """Rotate an image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees, positive values mean clockwise...
def imrotate(img, angle, center=None, scale=1.0, border_value=0, auto_bound=False): """Rotate an image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees, positive values mean clockwise...
[ "Rotate", "an", "image", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/geometry.py#L24-L64
[ "def", "imrotate", "(", "img", ",", "angle", ",", "center", "=", "None", ",", "scale", "=", "1.0", ",", "border_value", "=", "0", ",", "auto_bound", "=", "False", ")", ":", "if", "center", "is", "not", "None", "and", "auto_bound", ":", "raise", "Valu...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
bbox_clip
Clip bboxes to fit the image shape. Args: bboxes (ndarray): Shape (..., 4*k) img_shape (tuple): (height, width) of the image. Returns: ndarray: Clipped bboxes.
mmcv/image/transforms/geometry.py
def bbox_clip(bboxes, img_shape): """Clip bboxes to fit the image shape. Args: bboxes (ndarray): Shape (..., 4*k) img_shape (tuple): (height, width) of the image. Returns: ndarray: Clipped bboxes. """ assert bboxes.shape[-1] % 4 == 0 clipped_bboxes = np.empty_like(bboxe...
def bbox_clip(bboxes, img_shape): """Clip bboxes to fit the image shape. Args: bboxes (ndarray): Shape (..., 4*k) img_shape (tuple): (height, width) of the image. Returns: ndarray: Clipped bboxes. """ assert bboxes.shape[-1] % 4 == 0 clipped_bboxes = np.empty_like(bboxe...
[ "Clip", "bboxes", "to", "fit", "the", "image", "shape", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/geometry.py#L67-L83
[ "def", "bbox_clip", "(", "bboxes", ",", "img_shape", ")", ":", "assert", "bboxes", ".", "shape", "[", "-", "1", "]", "%", "4", "==", "0", "clipped_bboxes", "=", "np", ".", "empty_like", "(", "bboxes", ",", "dtype", "=", "bboxes", ".", "dtype", ")", ...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
bbox_scaling
Scaling bboxes w.r.t the box center. Args: bboxes (ndarray): Shape(..., 4). scale (float): Scaling factor. clip_shape (tuple, optional): If specified, bboxes that exceed the boundary will be clipped according to the given shape (h, w). Returns: ndarray: Scaled bboxe...
mmcv/image/transforms/geometry.py
def bbox_scaling(bboxes, scale, clip_shape=None): """Scaling bboxes w.r.t the box center. Args: bboxes (ndarray): Shape(..., 4). scale (float): Scaling factor. clip_shape (tuple, optional): If specified, bboxes that exceed the boundary will be clipped according to the given ...
def bbox_scaling(bboxes, scale, clip_shape=None): """Scaling bboxes w.r.t the box center. Args: bboxes (ndarray): Shape(..., 4). scale (float): Scaling factor. clip_shape (tuple, optional): If specified, bboxes that exceed the boundary will be clipped according to the given ...
[ "Scaling", "bboxes", "w", ".", "r", ".", "t", "the", "box", "center", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/geometry.py#L86-L109
[ "def", "bbox_scaling", "(", "bboxes", ",", "scale", ",", "clip_shape", "=", "None", ")", ":", "if", "float", "(", "scale", ")", "==", "1.0", ":", "scaled_bboxes", "=", "bboxes", ".", "copy", "(", ")", "else", ":", "w", "=", "bboxes", "[", "...", ",...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
imcrop
Crop image patches. 3 steps: scale the bboxes -> clip bboxes -> crop and pad. Args: img (ndarray): Image to be cropped. bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes. scale (float, optional): Scale ratio of bboxes, the default value 1.0 means no paddin...
mmcv/image/transforms/geometry.py
def imcrop(img, bboxes, scale=1.0, pad_fill=None): """Crop image patches. 3 steps: scale the bboxes -> clip bboxes -> crop and pad. Args: img (ndarray): Image to be cropped. bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes. scale (float, optional): Scale ratio of...
def imcrop(img, bboxes, scale=1.0, pad_fill=None): """Crop image patches. 3 steps: scale the bboxes -> clip bboxes -> crop and pad. Args: img (ndarray): Image to be cropped. bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes. scale (float, optional): Scale ratio of...
[ "Crop", "image", "patches", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/geometry.py#L112-L163
[ "def", "imcrop", "(", "img", ",", "bboxes", ",", "scale", "=", "1.0", ",", "pad_fill", "=", "None", ")", ":", "chn", "=", "1", "if", "img", ".", "ndim", "==", "2", "else", "img", ".", "shape", "[", "2", "]", "if", "pad_fill", "is", "not", "None...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
impad
Pad an image to a certain shape. Args: img (ndarray): Image to be padded. shape (tuple): Expected padding shape. pad_val (number or sequence): Values to be filled in padding areas. Returns: ndarray: The padded image.
mmcv/image/transforms/geometry.py
def impad(img, shape, pad_val=0): """Pad an image to a certain shape. Args: img (ndarray): Image to be padded. shape (tuple): Expected padding shape. pad_val (number or sequence): Values to be filled in padding areas. Returns: ndarray: The padded image. """ if not i...
def impad(img, shape, pad_val=0): """Pad an image to a certain shape. Args: img (ndarray): Image to be padded. shape (tuple): Expected padding shape. pad_val (number or sequence): Values to be filled in padding areas. Returns: ndarray: The padded image. """ if not i...
[ "Pad", "an", "image", "to", "a", "certain", "shape", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/geometry.py#L166-L187
[ "def", "impad", "(", "img", ",", "shape", ",", "pad_val", "=", "0", ")", ":", "if", "not", "isinstance", "(", "pad_val", ",", "(", "int", ",", "float", ")", ")", ":", "assert", "len", "(", "pad_val", ")", "==", "img", ".", "shape", "[", "-", "1...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
impad_to_multiple
Pad an image to ensure each edge to be multiple to some number. Args: img (ndarray): Image to be padded. divisor (int): Padded image edges will be multiple to divisor. pad_val (number or sequence): Same as :func:`impad`. Returns: ndarray: The padded image.
mmcv/image/transforms/geometry.py
def impad_to_multiple(img, divisor, pad_val=0): """Pad an image to ensure each edge to be multiple to some number. Args: img (ndarray): Image to be padded. divisor (int): Padded image edges will be multiple to divisor. pad_val (number or sequence): Same as :func:`impad`. Returns: ...
def impad_to_multiple(img, divisor, pad_val=0): """Pad an image to ensure each edge to be multiple to some number. Args: img (ndarray): Image to be padded. divisor (int): Padded image edges will be multiple to divisor. pad_val (number or sequence): Same as :func:`impad`. Returns: ...
[ "Pad", "an", "image", "to", "ensure", "each", "edge", "to", "be", "multiple", "to", "some", "number", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/geometry.py#L190-L203
[ "def", "impad_to_multiple", "(", "img", ",", "divisor", ",", "pad_val", "=", "0", ")", ":", "pad_h", "=", "int", "(", "np", ".", "ceil", "(", "img", ".", "shape", "[", "0", "]", "/", "divisor", ")", ")", "*", "divisor", "pad_w", "=", "int", "(", ...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
_scale_size
Rescale a size by a ratio. Args: size (tuple): w, h. scale (float): Scaling factor. Returns: tuple[int]: scaled size.
mmcv/image/transforms/resize.py
def _scale_size(size, scale): """Rescale a size by a ratio. Args: size (tuple): w, h. scale (float): Scaling factor. Returns: tuple[int]: scaled size. """ w, h = size return int(w * float(scale) + 0.5), int(h * float(scale) + 0.5)
def _scale_size(size, scale): """Rescale a size by a ratio. Args: size (tuple): w, h. scale (float): Scaling factor. Returns: tuple[int]: scaled size. """ w, h = size return int(w * float(scale) + 0.5), int(h * float(scale) + 0.5)
[ "Rescale", "a", "size", "by", "a", "ratio", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/resize.py#L6-L17
[ "def", "_scale_size", "(", "size", ",", "scale", ")", ":", "w", ",", "h", "=", "size", "return", "int", "(", "w", "*", "float", "(", "scale", ")", "+", "0.5", ")", ",", "int", "(", "h", "*", "float", "(", "scale", ")", "+", "0.5", ")" ]
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
imresize
Resize image to a given size. Args: img (ndarray): The input image. size (tuple): Target (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, accepted values are "nearest", "bilinear", "bicubic", "area", "lanc...
mmcv/image/transforms/resize.py
def imresize(img, size, return_scale=False, interpolation='bilinear'): """Resize image to a given size. Args: img (ndarray): The input image. size (tuple): Target (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, a...
def imresize(img, size, return_scale=False, interpolation='bilinear'): """Resize image to a given size. Args: img (ndarray): The input image. size (tuple): Target (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, a...
[ "Resize", "image", "to", "a", "given", "size", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/resize.py#L29-L51
[ "def", "imresize", "(", "img", ",", "size", ",", "return_scale", "=", "False", ",", "interpolation", "=", "'bilinear'", ")", ":", "h", ",", "w", "=", "img", ".", "shape", "[", ":", "2", "]", "resized_img", "=", "cv2", ".", "resize", "(", "img", ","...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
imresize_like
Resize image to the same size of a given image. Args: img (ndarray): The input image. dst_img (ndarray): The target image. return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Same as :func:`resize`. Returns: tuple or ndarray: (`resized_i...
mmcv/image/transforms/resize.py
def imresize_like(img, dst_img, return_scale=False, interpolation='bilinear'): """Resize image to the same size of a given image. Args: img (ndarray): The input image. dst_img (ndarray): The target image. return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolat...
def imresize_like(img, dst_img, return_scale=False, interpolation='bilinear'): """Resize image to the same size of a given image. Args: img (ndarray): The input image. dst_img (ndarray): The target image. return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolat...
[ "Resize", "image", "to", "the", "same", "size", "of", "a", "given", "image", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/resize.py#L54-L68
[ "def", "imresize_like", "(", "img", ",", "dst_img", ",", "return_scale", "=", "False", ",", "interpolation", "=", "'bilinear'", ")", ":", "h", ",", "w", "=", "dst_img", ".", "shape", "[", ":", "2", "]", "return", "imresize", "(", "img", ",", "(", "w"...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
imrescale
Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float or tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image wi...
mmcv/image/transforms/resize.py
def imrescale(img, scale, return_scale=False, interpolation='bilinear'): """Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float or tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by...
def imrescale(img, scale, return_scale=False, interpolation='bilinear'): """Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float or tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by...
[ "Resize", "image", "while", "keeping", "the", "aspect", "ratio", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/image/transforms/resize.py#L71-L107
[ "def", "imrescale", "(", "img", ",", "scale", ",", "return_scale", "=", "False", ",", "interpolation", "=", "'bilinear'", ")", ":", "h", ",", "w", "=", "img", ".", "shape", "[", ":", "2", "]", "if", "isinstance", "(", "scale", ",", "(", "float", ",...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
load
Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file exte...
mmcv/fileio/io.py
def load(file, file_format=None, **kwargs): """Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file for...
def load(file, file_format=None, **kwargs): """Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file for...
[ "Load", "data", "from", "json", "/", "yaml", "/", "pickle", "files", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/fileio/io.py#L13-L40
[ "def", "load", "(", "file", ",", "file_format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "file_format", "is", "None", "and", "is_str", "(", "file", ")", ":", "file_format", "=", "file", ".", "split", "(", "'.'", ")", "[", "-", "1", "...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
dump
Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. file (str or file-like object, optional): If not specified, ...
mmcv/fileio/io.py
def dump(obj, file=None, file_format=None, **kwargs): """Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. ...
def dump(obj, file=None, file_format=None, **kwargs): """Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. ...
[ "Dump", "data", "to", "json", "/", "yaml", "/", "pickle", "strings", "or", "files", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/fileio/io.py#L43-L76
[ "def", "dump", "(", "obj", ",", "file", "=", "None", ",", "file_format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "file_format", "is", "None", ":", "if", "is_str", "(", "file", ")", ":", "file_format", "=", "file", ".", "split", "(", ...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
_register_handler
Register a handler for some file extensions. Args: handler (:obj:`BaseFileHandler`): Handler to be registered. file_formats (str or list[str]): File formats to be handled by this handler.
mmcv/fileio/io.py
def _register_handler(handler, file_formats): """Register a handler for some file extensions. Args: handler (:obj:`BaseFileHandler`): Handler to be registered. file_formats (str or list[str]): File formats to be handled by this handler. """ if not isinstance(handler, BaseFil...
def _register_handler(handler, file_formats): """Register a handler for some file extensions. Args: handler (:obj:`BaseFileHandler`): Handler to be registered. file_formats (str or list[str]): File formats to be handled by this handler. """ if not isinstance(handler, BaseFil...
[ "Register", "a", "handler", "for", "some", "file", "extensions", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/fileio/io.py#L79-L96
[ "def", "_register_handler", "(", "handler", ",", "file_formats", ")", ":", "if", "not", "isinstance", "(", "handler", ",", "BaseFileHandler", ")", ":", "raise", "TypeError", "(", "'handler must be a child of BaseFileHandler, not {}'", ".", "format", "(", "type", "("...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
get_priority
Get priority value. Args: priority (int or str or :obj:`Priority`): Priority. Returns: int: The priority value.
mmcv/runner/priority.py
def get_priority(priority): """Get priority value. Args: priority (int or str or :obj:`Priority`): Priority. Returns: int: The priority value. """ if isinstance(priority, int): if priority < 0 or priority > 100: raise ValueError('priority must be between 0 and 1...
def get_priority(priority): """Get priority value. Args: priority (int or str or :obj:`Priority`): Priority. Returns: int: The priority value. """ if isinstance(priority, int): if priority < 0 or priority > 100: raise ValueError('priority must be between 0 and 1...
[ "Get", "priority", "value", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/runner/priority.py#L35-L53
[ "def", "get_priority", "(", "priority", ")", ":", "if", "isinstance", "(", "priority", ",", "int", ")", ":", "if", "priority", "<", "0", "or", "priority", ">", "100", ":", "raise", "ValueError", "(", "'priority must be between 0 and 100'", ")", "return", "pr...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
quantize
Quantize an array of (-inf, inf) to [0, levels-1]. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. dtype (np.type): The type of the quantized array. Return...
mmcv/arraymisc/quantization.py
def quantize(arr, min_val, max_val, levels, dtype=np.int64): """Quantize an array of (-inf, inf) to [0, levels-1]. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. ...
def quantize(arr, min_val, max_val, levels, dtype=np.int64): """Quantize an array of (-inf, inf) to [0, levels-1]. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. ...
[ "Quantize", "an", "array", "of", "(", "-", "inf", "inf", ")", "to", "[", "0", "levels", "-", "1", "]", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/arraymisc/quantization.py#L4-L29
[ "def", "quantize", "(", "arr", ",", "min_val", ",", "max_val", ",", "levels", ",", "dtype", "=", "np", ".", "int64", ")", ":", "if", "not", "(", "isinstance", "(", "levels", ",", "int", ")", "and", "levels", ">", "1", ")", ":", "raise", "ValueError...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
dequantize
Dequantize an array. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. dtype (np.type): The type of the dequantized array. Returns: tuple: Dequantize...
mmcv/arraymisc/quantization.py
def dequantize(arr, min_val, max_val, levels, dtype=np.float64): """Dequantize an array. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. dtype (np.type): Th...
def dequantize(arr, min_val, max_val, levels, dtype=np.float64): """Dequantize an array. Args: arr (ndarray): Input array. min_val (scalar): Minimum value to be clipped. max_val (scalar): Maximum value to be clipped. levels (int): Quantization levels. dtype (np.type): Th...
[ "Dequantize", "an", "array", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/arraymisc/quantization.py#L32-L56
[ "def", "dequantize", "(", "arr", ",", "min_val", ",", "max_val", ",", "levels", ",", "dtype", "=", "np", ".", "float64", ")", ":", "if", "not", "(", "isinstance", "(", "levels", ",", "int", ")", "and", "levels", ">", "1", ")", ":", "raise", "ValueE...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
Config.auto_argparser
Generate argparser from config file automatically (experimental)
mmcv/utils/config.py
def auto_argparser(description=None): """Generate argparser from config file automatically (experimental) """ partial_parser = ArgumentParser(description=description) partial_parser.add_argument('config', help='config file path') cfg_file = partial_parser.parse_known_args()[0].co...
def auto_argparser(description=None): """Generate argparser from config file automatically (experimental) """ partial_parser = ArgumentParser(description=description) partial_parser.add_argument('config', help='config file path') cfg_file = partial_parser.parse_known_args()[0].co...
[ "Generate", "argparser", "from", "config", "file", "automatically", "(", "experimental", ")" ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/utils/config.py#L100-L110
[ "def", "auto_argparser", "(", "description", "=", "None", ")", ":", "partial_parser", "=", "ArgumentParser", "(", "description", "=", "description", ")", "partial_parser", ".", "add_argument", "(", "'config'", ",", "help", "=", "'config file path'", ")", "cfg_file...
0d77f61450aab4dde8b8585a577cc496acb95d7f
test
collate
Puts each data field into a tensor/DataContainer with outer dimension batch size. Extend default_collate to add support for :type:`~mmcv.parallel.DataContainer`. There are 3 cases. 1. cpu_only = True, e.g., meta data 2. cpu_only = False, stack = True, e.g., images tensors 3. cpu_only = False, ...
mmcv/parallel/collate.py
def collate(batch, samples_per_gpu=1): """Puts each data field into a tensor/DataContainer with outer dimension batch size. Extend default_collate to add support for :type:`~mmcv.parallel.DataContainer`. There are 3 cases. 1. cpu_only = True, e.g., meta data 2. cpu_only = False, stack = True, ...
def collate(batch, samples_per_gpu=1): """Puts each data field into a tensor/DataContainer with outer dimension batch size. Extend default_collate to add support for :type:`~mmcv.parallel.DataContainer`. There are 3 cases. 1. cpu_only = True, e.g., meta data 2. cpu_only = False, stack = True, ...
[ "Puts", "each", "data", "field", "into", "a", "tensor", "/", "DataContainer", "with", "outer", "dimension", "batch", "size", "." ]
open-mmlab/mmcv
python
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/parallel/collate.py#L10-L66
[ "def", "collate", "(", "batch", ",", "samples_per_gpu", "=", "1", ")", ":", "if", "not", "isinstance", "(", "batch", ",", "collections", ".", "Sequence", ")", ":", "raise", "TypeError", "(", "\"{} is not supported.\"", ".", "format", "(", "batch", ".", "dt...
0d77f61450aab4dde8b8585a577cc496acb95d7f