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: object

A matrix in compressed sparse row form.

data, indices and indptr are NumPy arrays with the usual meaning. toarray() gives the dense form without needing SciPy; tocsr() gives a scipy.sparse.csr_array and needs SciPy.

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 index is 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 float32 up to 3 bytes per sample, otherwise float64, so that the conversion loses no bits it need not.

Returns:

One float per sample.

Return type:

numpy.ndarray

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 length is 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:
  • data (array_like) – Values. float32 and complex64 keep their precision; anything else is computed in float64.

  • edge_order (int) – 1 or 2. Accepted for both orders: wrapped central differences have no edges, so the result does not depend on it.

  • axis (int) – The periodic axis. Default -1.

Returns:

Same shape as data.

Return type:

numpy.ndarray

audio_samples.arrays.dtype_c2r(d, *, default=None)

The real dtype of a complex dtype.

Parameters:
  • d (numpy.dtype) – A dtype, or anything numpy.dtype accepts. 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:

numpy.dtype

audio_samples.arrays.dtype_r2c(d, *, default=None)

The complex dtype of a real dtype.

Parameters:
  • d (numpy.dtype) – A dtype, or anything numpy.dtype accepts. A complex dtype is returned as it is.

  • default (numpy.dtype) – Returned for any other dtype. Default complex64.

Returns:

The complex dtype.

Return type:

numpy.dtype

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 axis i of x is always axis axes[i] of the result.

Returns:

A view of the same data.

Return type:

numpy.ndarray

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:

list[str]

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:
  • frames (array_like[int]) – Non-negative frame indices.

  • x_min (Optional[int]) – Lower bound. Default 0.

  • x_max (Optional[int]) – Upper bound.

  • pad (bool) – Clip to the bounds and include them, rather than only filter.

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:
  • idx (array_like[int]) – Boundary indices.

  • idx_min (Optional[int]) – Lower bound.

  • idx_max (Optional[int]) – Upper bound.

  • step (Optional[int]) – Step of each slice.

  • pad (bool) – Clip to the bounds and include them, rather than only filter.

Returns:

One slice per pair of consecutive boundaries.

Return type:

list[slice]

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; axis has 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 y that follows x. Default -1.

Returns:

y’s shape with axis replaced by the axes of xi, of float32 for float32 y, otherwise float64.

Return type:

numpy.ndarray

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 along axis.

  • x2 (array_like) – The second array.

  • x2_pos (array_like) – Its sample positions along axis.

  • 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; None returns 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 op is None.

Return type:

numpy.ndarray | tuple[numpy.ndarray, numpy.ndarray]

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 give False.

Returns:

The answer.

Return type:

bool

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:

numpy.ndarray[bool]

audio_samples.arrays.localmax(x, *, axis=0)

Local maxima along an axis.

x[i] > x[i - 1] and x[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:

numpy.ndarray[bool]

audio_samples.arrays.localmin(x, *, axis=0)

Local minima along an axis.

x[i] < x[i - 1] and x[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:

numpy.ndarray[bool]

audio_samples.arrays.match_events(events_from, events_to, left=True, right=True)

Matches each source event to the nearest target event.

Parameters:
  • events_from (array_like) – Source events, in any order.

  • events_to (array_like) – Target events, in any order.

  • left (bool) – A source event may match a target before it. Default true.

  • right (bool) – A source event may match a target after it. Default true.

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 strict an interval overlaps

  • no 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 axis in the result.

  • axis (int) – The axis to pad. Default -1.

  • **kwargs – mode and its arguments, as for numpy.pad. Default: zeros.

Returns:

The padded array, of the input’s dtype.

Return type:

numpy.ndarray

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 to angles.

Returns:

complex64 for float32 angles, otherwise complex128.

Return type:

complex | numpy.ndarray

audio_samples.arrays.shear(X, *, factor=1, axis=-1)

Circularly shifts each column (or row) of a matrix by factor times 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 quantile are 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:

numpy.ndarray

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 uses float32.

Returns:

The value, as a NumPy scalar of that type.

Return type:

numpy.floating

audio_samples.arrays.tone(frequency, *, sr=22050, length=None, duration=None, phi=None)

A cosine of a given frequency and phase, as float64.

Parameters:
  • frequency (float) – In Hz.

  • sr (float) – Sample rate in Hz. Default 22050.

  • length (Optional[int]) – Samples.

  • duration (Optional[float]) – Seconds, if length is None.

  • phi (Optional[float]) – Phase offset in radians. None means -pi / 2, which starts like a sine.

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:

bool

Raises:
  • TypeError – y is not a floating-point numpy.ndarray.

  • ValueError – y is 0-D or holds a NaN or infinity.

audio_samples.arrays.valid_int(x, *, cast=None)

Converts a number to an int with a chosen rounding.

Parameters:
  • x (float) – The value.

  • cast (Optional[Callable]) – Rounds x before conversion. Default: floor.

Returns:

The integer.

Return type:

int

Raises:

TypeError – cast is not callable.

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:

bool

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 receives numpy.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:

numpy.ndarray[bool]