Array Helpers
audio_samples.arrays holds array helpers: local extrema, event and interval matching, one-dimensional interpolation, padding, reordering, compressed sparse rows, zero crossings, generated tones and sweeps, and argument checks.
Array helpers: local extrema, event and interval matching, one-dimensional interpolation, padding, reordering, compressed sparse rows and argument checks.
- audio_samples.arrays.MAX_MEM_BLOCK = 262144
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int(‘0b100’, base=0) 4
- class audio_samples.arrays.SparseRows
Bases:
objectA matrix in compressed sparse row form.
data,indicesandindptrareNumPyarrays with the usual meaning.toarray()gives the dense form without needingSciPy;tocsr()gives ascipy.sparse.csr_arrayand needsSciPy.- data
Stored values.
- indices
Column of each stored value.
- indptr
Where each row starts in
data, with one extra entry at the end.
- nnz
Number of stored values.
- shape
(rows, columns).
- toarray()
The dense matrix.
- tocsr()
The matrix as a
scipy.sparse.csr_array.
- audio_samples.arrays.abs2(x, dtype=None)
Squared magnitude.
- Parameters:
x (
complex|array_like) – Values. Complex input gives its real type; real input keeps its dtype.dtype (Optional[numpy.dtype]) – Output dtype.
- Returns:
x.real ** 2 + x.imag ** 2.- Return type:
float | int | numpy.ndarray
- audio_samples.arrays.axis_sort(S, *, axis=-1, index=False, value=None)
Sorts the rows or columns of a matrix by a key computed from them.
- Parameters:
S (numpy.ndarray) – The matrix.
axis (int) – The axis to reorder: -1 reorders columns, 0 rows. Default -1.
index (bool) – Also return the permutation.
value (Optional[Callable]) –
value(S, axis=other_axis)gives the sort key. Default: the position of the peak (numpy.argmax). Equal keys keep their order.
- Returns:
The sorted matrix, and the permutation when
indexis true.- Return type:
numpy.ndarray | tuple[numpy.ndarray, numpy.ndarray[int64]]
- audio_samples.arrays.buf_to_float(x, *, n_bytes=2, dtype=None)
Decodes little-endian signed integer PCM to floats in
[-1, 1).- Parameters:
x (bytes-like | numpy.ndarray) – The buffer.
n_bytes (int) – Bytes per sample: 1, 2, 3, 4 or 8. Default 2.
dtype (Optional[numpy.dtype]) – Output dtype. Default
float32up to 3 bytes per sample, otherwisefloat64, so that the conversion loses no bits it need not.
- Returns:
One float per sample.
- Return type:
- audio_samples.arrays.chirp(*, fmin, fmax, sr=22050, length=None, duration=None, linear=False, phi=None)
A swept cosine, as float64.
- Parameters:
fmin (float) – Starting frequency in Hz.
fmax (float) – Frequency at the end in Hz.
sr (float) – Sample rate in Hz. Default 22050.
length (Optional[int]) – Samples.
duration (Optional[float]) – Seconds, if
lengthis None.linear (bool) – Sweep linearly; otherwise exponentially. Default False.
phi (Optional[float]) – Phase offset in radians. None means
-pi / 2.
- Returns:
The samples.
- Return type:
numpy.ndarray[float64]
- audio_samples.arrays.count_unique(data, *, axis=-1)
Counts the distinct values in each lane along an axis.
- Parameters:
data (
array_like) – Values of any numeric dtype. All NaNs count as one value.axis (int) – The axis of the lanes. Default -1.
- Returns:
The input’s shape without
axis.- Return type:
numpy.ndarray[int64]
- audio_samples.arrays.cyclic_gradient(data, *, edge_order=1, axis=-1)
Central-difference gradient of periodic data along one axis.
- Parameters:
- Returns:
Same shape as
data.- Return type:
- audio_samples.arrays.dtype_c2r(d, *, default=None)
The real dtype of a complex dtype.
- Parameters:
d (numpy.dtype) – A dtype, or anything
numpy.dtypeaccepts. A real floating dtype is returned as it is.default (numpy.dtype) – Returned for any other dtype. Default
float32.
- Returns:
The real dtype.
- Return type:
- audio_samples.arrays.dtype_r2c(d, *, default=None)
The complex dtype of a real dtype.
- Parameters:
d (numpy.dtype) – A dtype, or anything
numpy.dtypeaccepts. A complex dtype is returned as it is.default (numpy.dtype) – Returned for any other dtype. Default
complex64.
- Returns:
The complex dtype.
- Return type:
- audio_samples.arrays.expand_to(x, *, ndim, axes)
Places the axes of an array at given positions of a higher-dimensional view.
- Parameters:
x (numpy.ndarray) – The array.
ndim (int) – Dimensions of the result.
axes (int | sequence of int) – Position of each axis of
x; negative counts from the end. Positions out of order reorder the axes, so axisiofxis always axisaxes[i]of the result.
- Returns:
A view of the same data.
- Return type:
- audio_samples.arrays.fill_off_diagonal(x, *, radius, value=None)
Sets the entries of a matrix outside a diagonal band to a value, in place.
- Parameters:
x (numpy.ndarray) – The 2-D matrix, changed in place.
radius (float) – Half-width of the band as a fraction of the shorter side.
value (number) – The value written outside the band. Default 0.
- audio_samples.arrays.find_files(directory, *, ext=None, recurse=True, case_sensitive=False, limit=None, offset=0)
Lists audio files under a directory.
- Parameters:
directory (str | os.PathLike) – Where to look;
~expands to the home directory.ext (Optional[str | list[str]]) – Extensions without the dot. Default:
aac,au,flac,m4a,mp3,ogg,wav.recurse (bool) – Search subdirectories. Default true.
case_sensitive (bool) – Compare extensions exactly; otherwise any letter case matches. Default false.
limit (Optional[int]) – Keep at most this many paths after
offset; a negative value drops that many from the end.offset (int) – Skip this many paths; a negative value counts from the end.
- Returns:
Sorted absolute paths.
- Return type:
- audio_samples.arrays.fix_frames(frames, *, x_min=0, x_max=None, pad=True)
Normalises frame indices: clips, optionally adds the bounds, removes duplicates and sorts.
- Parameters:
- Returns:
Sorted, unique indices.
- Return type:
numpy.ndarray[int64]
- audio_samples.arrays.index_to_slice(idx, *, idx_min=None, idx_max=None, step=None, pad=True)
Converts boundary indices to the slices between consecutive boundaries.
- Parameters:
- Returns:
One slice per pair of consecutive boundaries.
- Return type:
- audio_samples.arrays.interp1d(x, y, xi, *, kind=None, fill_value=0.0, axis=-1)
Interpolates sampled data along one axis.
- Parameters:
x (
array_like) – Sample positions, 1-D, in any order.y (
array_like) – Samples;axishas one element per position.xi (
array_like) – Query positions, of any shape.kind (str | int) –
"linear","nearest","nearest-up","zero","slinear","quadratic","cubic","previous","next", or a spline order 0 to 3. Default"linear".fill_value (float) – Result outside the range of
x. Default 0.axis (int) – The axis of
ythat followsx. Default -1.
- Returns:
y’s shape withaxisreplaced by the axes ofxi, offloat32forfloat32y, otherwisefloat64.- Return type:
- audio_samples.arrays.interp_broadcast(*, x1, x1_pos, x2, x2_pos, interp_pos=None, op='multiply', kind=None, fill_value=0.0, axis=-2)
Interpolates two arrays sampled on different grids onto one grid and combines them.
- Parameters:
x1 (
array_like) – The first array.x1_pos (
array_like) – Its sample positions alongaxis.x2 (
array_like) – The second array.x2_pos (
array_like) – Its sample positions alongaxis.interp_pos (Optional[array_like]) – The common positions. Default
x1_pos.op (Callable | str | None) – Combines the two interpolated arrays.
"multiply"(the default) multiplies with broadcasting;Nonereturns both arrays.kind (str | int) – As for
interp1d(). Default"linear".fill_value (float) – Result outside the range of each grid. Default 0.
axis (int) – The interpolated axis. Default -2.
- Returns:
The combined array, or both arrays when
opisNone.- Return type:
- audio_samples.arrays.is_positive_int(x)
Whether a value is an integer above zero.
- Parameters:
x (Any) – The value.
None, floats and everything else that is not an integer giveFalse.- Returns:
The answer.
- Return type:
- audio_samples.arrays.is_unique(data, *, axis=-1)
Tells for each lane along an axis whether all its values are distinct.
- Parameters:
data (
array_like) – Values of any numeric dtype. All NaNs count as one value.axis (int) – The axis of the lanes. Default -1.
- Returns:
The input’s shape without
axis.- Return type:
- audio_samples.arrays.localmax(x, *, axis=0)
Local maxima along an axis.
x[i] > x[i - 1]andx[i] >= x[i + 1]. The first element is never a maximum; the last is when it exceeds its neighbour.- Parameters:
x (
array_like) – Values of any real dtype.axis (int) – Axis to compare along. Default 0.
- Returns:
Same shape as
x.- Return type:
- audio_samples.arrays.localmin(x, *, axis=0)
Local minima along an axis.
x[i] < x[i - 1]andx[i] <= x[i + 1]. The first element is never a minimum; the last is when it is below its neighbour.- Parameters:
x (
array_like) – Values of any real dtype.axis (int) – Axis to compare along. Default 0.
- Returns:
Same shape as
x.- Return type:
- audio_samples.arrays.match_events(events_from, events_to, left=True, right=True)
Matches each source event to the nearest target event.
- Parameters:
- Returns:
For each source event, an index into
events_to. A source event half-way between two targets goes to the later one.- Return type:
numpy.ndarray[int64]
- Raises:
ValueError – A list is empty, or the restrictions leave an event without a match.
- audio_samples.arrays.match_intervals(intervals_from, intervals_to, strict=True)
Matches each source interval to the target interval it overlaps most.
Overlap is the Jaccard index; on a tie the lowest target index wins.
- Parameters:
intervals_from (
array_like) – Source intervals,(n, 2).intervals_to (
array_like) – Target intervals,(m, 2).strict (bool) – A source interval that overlaps nothing is an error; when false it matches the nearest target (the earlier at equal distance). Default true.
- Returns:
For each source interval, an index into
intervals_to.- Return type:
numpy.ndarray[int64]
- Raises:
ValueError – A list is empty or invalid, or with
strictan interval overlapsno target. –
- audio_samples.arrays.pad_center(data, *, size, axis=-1, **kwargs)
Pads an array along one axis to a given length, keeping the data centred.
- Parameters:
data (numpy.ndarray) – The array.
size (int) – Length of
axisin the result.axis (int) – The axis to pad. Default -1.
**kwargs –
modeand its arguments, as fornumpy.pad. Default: zeros.
- Returns:
The padded array, of the input’s dtype.
- Return type:
- audio_samples.arrays.phasor(angles, *, mag=None)
Complex phasors
mag * (cos(angles) + 1j * sin(angles)).- Parameters:
angles (float |
array_like) – Angles in radians.mag (Optional[
complex|array_like]) – Multiplier, broadcast toangles.
- Returns:
complex64forfloat32angles, otherwisecomplex128.- Return type:
complex| numpy.ndarray
- audio_samples.arrays.shear(X, *, factor=1, axis=-1)
Circularly shifts each column (or row) of a matrix by
factortimes its index.- Parameters:
X (numpy.ndarray | scipy.sparse array or matrix | SparseRows) – The matrix.
factor (int) – Shift per index. Default 1.
axis (int) – -1 shifts columns by their column index, 0 shifts rows by their row index. Default -1.
- Returns:
The sheared matrix, in the input’s form and dtype.
- audio_samples.arrays.sparsify_rows(x, *, quantile=0.01, dtype=None)
Removes the smallest values of each row, keeping a sparse matrix.
In each row the sorted magnitudes are divided by the row’s total and summed cumulatively; entries below the first magnitude whose running total reaches
quantileare dropped.- Parameters:
x (
array_like) – 1-D or 2-D values; 1-D is one row.quantile (float) – Fraction of each row’s total magnitude that may be discarded, in
[0, 1). Default 0.01.dtype (Optional[numpy.dtype]) – dtype of the stored values. Default: the input’s.
- Returns:
The kept entries.
- Return type:
SparseRows
- audio_samples.arrays.stack(arrays, *, axis=0)
Stacks arrays of one shape along a new axis.
- Parameters:
arrays (sequence of
array_like) – At least one array.axis (int) – Position of the new axis. Default 0.
- Returns:
The stacked array, of the arrays’ common dtype.
- Return type:
- audio_samples.arrays.tiny(x)
The smallest positive normal value of the input’s floating-point type.
- Parameters:
x (
complex|array_like| numpy.dtype-bearing value) – Determines the type. Complex types use their real type; non-float input usesfloat32.- Returns:
The value, as a
NumPyscalar of that type.- Return type:
- audio_samples.arrays.tone(frequency, *, sr=22050, length=None, duration=None, phi=None)
A cosine of a given frequency and phase, as float64.
- Parameters:
- Returns:
The samples.
- Return type:
numpy.ndarray[float64]
- audio_samples.arrays.valid_audio(y)
Checks that audio samples are a floating-point array, at least 1-D, finite everywhere.
- Parameters:
y (numpy.ndarray) – The samples.
- Returns:
True.- Return type:
- Raises:
TypeError –
yis not a floating-pointnumpy.ndarray.ValueError –
yis 0-D or holds a NaN or infinity.
- audio_samples.arrays.valid_int(x, *, cast=None)
Converts a number to an
intwith a chosen rounding.
- audio_samples.arrays.valid_intervals(intervals)
Checks that intervals have shape
(n, 2)and non-negative durations.- Parameters:
intervals (
array_like) – One[start, end]row per interval.- Returns:
True.- Return type:
- Raises:
ValueError – The shape is wrong or a duration is negative.
- audio_samples.arrays.zero_crossings(y, *, threshold=1e-10, ref_magnitude=None, pad=True, zero_pos=True, axis=-1)
Marks the sign changes of a signal along one axis.
- Parameters:
y (
array_like) – The signal, of any dimension.threshold (Optional[float]) – Magnitudes up to this count as zero. None means 0. Default 1e-10.
ref_magnitude (Optional[float | Callable]) – Scales
threshold. A callable receivesnumpy.abs(y)and returns the scale.pad (bool) – The mark of the first element. Default True.
zero_pos (bool) – Zero counts as positive; otherwise it is a sign of its own. Default True.
axis (int) – The time axis. Default -1.
- Returns:
The marks, of the shape of
y.- Return type: