Sequence Alignment and Decoding

audio_samples.sequence holds dynamic time warping, Viterbi decoding, transition matrices, recurrence quantification, recurrence and cross-similarity matrices, lag conversions and frame synchronisation (sync). Feature matrices are (n_features, n_frames); probability matrices (n_states, n_steps).

sparse=True returns arrays.SparseRows, integer outputs are int64, sync with an empty index list aggregates the whole signal into one segment, and rqa backtracking follows the move actually taken.

Sequence alignment and decoding: DTW, Viterbi, transition matrices, RQA, recurrence and cross-similarity matrices, lag conversions and sync. float32 / complex64 arrays are processed in float32 and give float32 output; any other input is converted to float64.

Dynamic time warping

audio_samples.sequence.dtw(X=None, Y=None, *, C=None, metric='euclidean', step_sizes_sigma=None, weights_add=None, weights_mul=None, subseq=False, backtrack=True, global_constraints=False, band_rad=0.25, return_steps=False)

Dynamic time warping.

Pass either the feature sequences X and Y ((n_features, N) and (n_features, M); 1-D input is one feature), or a precomputed cost matrix C of shape (N, M).

Parameters:
  • X (Optional[array_like]) – Feature sequences.

  • Y (Optional[array_like]) – Feature sequences.

  • C (Optional[array_like]) – Precomputed local cost matrix.

  • metric (str) – "euclidean" (default), "sqeuclidean", "cosine", "cityblock" or "chebyshev" (used with X/Y only).

  • step_sizes_sigma (Optional[array_like]) – Extra steps, shape (n, 2); appended to the default steps [[1, 1], [0, 1], [1, 0]].

  • weights_add (Optional[array_like]) – Per-step weights.

  • weights_mul (Optional[array_like]) – Per-step weights.

  • subseq (bool) – Subsequence alignment. Default False.

  • backtrack (bool) – Compute the warping path. Default True.

  • global_constraints (bool) – Sakoe-Chiba band. Default False.

  • band_rad (float) – Band radius (fraction of the shorter length). Default 0.25.

  • return_steps (bool) – Also return the step matrix. Default False.

Returns:

D (numpy.ndarray[float32 | float64], shape (N, M)); with backtrack=True the tuple (D, wp) where wp is an int64 array of shape (path_length, 2) ordered from the end of the alignment to its start; with return_steps=True the step matrix (int64, same shape as D) is appended.

Raises:

ValueError – Incompatible inputs, NaN costs, or no valid path.

audio_samples.sequence.dtw_backtracking(steps, *, step_sizes_sigma=None, subseq=False, start=None)

Backtrack a warping path from a DTW step matrix.

Parameters:
  • steps (array_like[int]) – Step matrix from dtw(..., return_steps=True).

  • step_sizes_sigma (Optional[array_like]) – The custom steps passed to dtw.

  • subseq (bool) – Whether dtw ran with subseq=True.

  • start (Optional[int]) – Column of the last row to start from (subseq only).

Returns:

shape (path_length, 2), end first.

Return type:

numpy.ndarray[int64]

Hidden Markov model decoding

audio_samples.sequence.viterbi(prob, transition, *, p_init=None, return_logp=False, transition_min_prob=None)

Viterbi decoding of a generative HMM.

Parameters:
  • prob (array_like) – (n_states, n_steps) observation likelihoods in [0, 1].

  • transition (array_like) – (n_states, n_states) row-stochastic matrix.

  • p_init (Optional[array_like]) – Initial distribution; None = uniform.

  • return_logp (bool) – Also return the log-likelihood. Default False.

  • transition_min_prob (Optional[float]) – Prune transitions below this probability (approximate, faster). None = exact.

Returns:

numpy.ndarray[int64] of shape (n_steps,), or (states, logp) with logp a float when return_logp=True.

Raises:

ValueError – Shape mismatch or invalid probabilities.

audio_samples.sequence.viterbi_discriminative(prob, transition, *, p_state=None, p_init=None, return_logp=False, transition_min_prob=None)

Viterbi decoding from discriminative (posterior) state probabilities; each column of prob sums to 1.

Parameters:
  • prob (array_like) – (n_states, n_steps); each column sums to 1.

  • transition (array_like) – (n_states, n_states) row-stochastic matrix.

  • p_state (Optional[array_like]) – Marginal state distribution; None = uniform.

  • p_init (Optional[array_like]) – Initial distribution; None = uniform.

  • return_logp (bool) – Also return the (unnormalised) log-likelihood.

  • transition_min_prob (Optional[float]) – As viterbi.

Returns:

numpy.ndarray[int64] (n_steps,) or (states, logp).

audio_samples.sequence.viterbi_binary(prob, transition, *, p_state=None, p_init=None, return_logp=False, transition_min_prob=None, dtype=None)

Independent binary (off/on) Viterbi decoding per state.

Parameters:
  • prob (array_like) – (n_states, n_steps) activation probabilities (a 1-D array is one state).

  • transition (array_like) – (2, 2) shared or (n_states, 2, 2) per state.

  • p_state (Optional[float | array_like]) – Marginal P[on] per state; None = 0.5.

  • p_init (Optional[float | array_like]) – Initial P[on] per state; None = 0.5.

  • return_logp (bool) – Also return per-state log-likelihoods.

  • transition_min_prob (Optional[float]) – As viterbi.

  • dtype (Optional[numpy.dtype]) – dtype of the states: bool (default None, one byte per entry), numpy.uint16 or numpy.int64.

Returns:

numpy.ndarray[bool | uint16 | int64] (n_states, n_steps), true or 1 where the state is on, or (states, logp) with logp of shape (n_states,).

Transition matrices

audio_samples.sequence.transition_uniform(n_states)

Uniform transition matrix: every entry 1 / n_states.

Returns:

(n_states, n_states) filled with 1 / n_states.

Return type:

numpy.ndarray[float64]

audio_samples.sequence.transition_loop(n_states, prob)

Self-loop transition matrix.

Parameters:
  • n_states (int) – Number of states (> 1).

  • prob (float | array_like) – Self-loop probability, one value or one per state.

Returns:

(n_states, n_states).

Return type:

numpy.ndarray[float64]

audio_samples.sequence.transition_cycle(n_states, prob)

Cyclic transition matrix.

Parameters:
  • n_states (int) – Number of states (> 1).

  • prob (float | array_like) – Self-loop probability, one value or one per state.

Returns:

(n_states, n_states).

Return type:

numpy.ndarray[float64]

audio_samples.sequence.transition_local(n_states, width, *, window='triangle', wrap=False)

Localised transition matrix (row-stochastic).

Parameters:
  • n_states (int) – Number of states (> 1).

  • width (int | array_like[int]) – Neighbourhood width, one value or one per state.

  • window (str) – "triangle" (default, also "triang"), "hann", "hamming", "blackman" or "boxcar".

  • wrap (bool) – Circular state space. Default False.

Returns:

(n_states, n_states), row-stochastic.

Return type:

numpy.ndarray[float64]

Recurrence and similarity

audio_samples.sequence.recurrence_matrix(data, *, k=None, width=1, metric='euclidean', sym=False, sparse=False, mode='connectivity', bandwidth=None, self=False, axis=-1, full=False, self_links=False)

Recurrence (self-similarity) matrix of a feature sequence.

Parameters:
  • data (array_like) – (n_features, t) features (1-D = one feature).

  • k (Optional[int]) – Neighbours per frame; None = 2 * ceil(sqrt(t - 2 * width + 1)).

  • width (int) – Minimum time separation of linked frames. Default 1.

  • metric (str) – Distance metric (see dtw). Default “euclidean”.

  • sym (bool) – Keep only mutual links. Default False.

  • sparse (bool) – Return arrays.SparseRows rather than a dense array. Default False.

  • mode (str) – "connectivity" (default, bool output), "distance" or "affinity".

  • bandwidth – Affinity bandwidth: None ("med_k_scalar"), a heuristic name, a positive number, or a (t, t) array.

  • self_links (bool) – Link each frame to itself. self=... is an equivalent keyword.

  • axis (int) – Must be -1 (frames on the last axis).

  • full (bool) – Link every pair in distance/affinity mode. Default False.

Returns:

(t, t); bool for connectivity, otherwise float in data’s precision.

Return type:

numpy.ndarray

audio_samples.sequence.cross_similarity(data, data_ref, *, k=None, metric='euclidean', sparse=False, mode='connectivity', bandwidth=None, full=False)

Cross-similarity matrix between a query and a reference feature sequence.

Parameters:
  • data (array_like) – Query features (n_features, n).

  • data_ref (array_like) – Reference features (n_features, n_ref).

  • k (Optional[int]) – Reference neighbours per query frame; None = min(n_ref, 2 * ceil(sqrt(n_ref))).

  • metric (str) – Distance metric. Default “euclidean”.

  • sparse (bool) – Return arrays.SparseRows rather than a dense array. Default False.

  • mode (str) – "connectivity" (bool output), "distance" or "affinity".

  • bandwidth – As recurrence_matrix (array shape (n, n_ref)).

  • full (bool) – Link every query frame to its min(n_ref, n) nearest. Default False.

Returns:

(n_ref, n); bool for connectivity, otherwise float in data’s precision.

Return type:

numpy.ndarray

audio_samples.sequence.recurrence_to_lag(rec, *, pad=True, axis=-1)

Convert a (dense) recurrence matrix to a time-lag matrix.

Parameters:
  • rec (array_like) – (t, t) recurrence matrix (bool or float).

  • pad (bool) – Zero-pad to (2t, t) first. Default True.

  • axis (int) – The time axis: -1/1 (columns, default) or 0/-2 (rows; the result is then (t, 2t)).

Returns:

(2t, t) or (t, t); bool if rec is bool, else rec’s precision.

Return type:

numpy.ndarray

audio_samples.sequence.lag_to_recurrence(lag, *, axis=-1)

Convert a (dense) time-lag matrix back to a recurrence matrix.

Parameters:
  • lag (array_like) – (t, t) or (2t, t) lag matrix.

  • axis (int) – The time axis: -1/1 (columns, default) or 0/-2 (rows; a padded lag matrix is then (t, 2t)).

Returns:

(t, t); bool if lag is bool, else lag’s precision.

Return type:

numpy.ndarray

audio_samples.sequence.rqa(sim, *, gap_onset=1.0, gap_extend=1.0, knight_moves=True, backtrack=True)

Recurrence quantification analysis.

Parameters:
  • sim (array_like) – (N, M) similarity / recurrence matrix (bool or float).

  • gap_onset (float) – Gap opening penalty. Default 1.

  • gap_extend (float) – Gap extension penalty. Default 1.

  • knight_moves (bool) – Allow (1, 2) / (2, 1) moves. Default True.

  • backtrack (bool) – Return the best path too. Default True.

Returns:

score (numpy.ndarray[float32 | float64], shape (N, M)), or (score, path) with path an int64 (length, 2) array ordered from start to end (empty when there is no recurrence).

Aggregation

audio_samples.sequence.sync(data, idx, *, aggregate=None, pad=True, axis=-1)

Aggregate frames between boundaries (e.g. beats) along the last axis.

Parameters:
  • data (array_like) – Any shape with frames on the last axis.

  • idx (array_like[int] | Sequence[slice]) – Boundary frame indices (sorted and de-duplicated internally), or one slice of the frames per output entry.

  • aggregate – None / numpy.mean (default), numpy.median, numpy.max, numpy.min, numpy.sum, the same names as strings, or any callable f(x, axis=-1) -> float applied to each 1-D segment.

  • pad (bool) – Add 0 and n_frames to the boundaries. Default True. Not used with slices.

Returns:

data with the last axis replaced by one entry per segment.

Return type:

numpy.ndarray[float32 | float64]

Raises:

ValueError – Negative indices or 0-d data.

Example

import numpy as np
from audio_samples import sequence

X = np.random.rand(12, 40)          # e.g. chroma of a reference
Y = np.random.rand(12, 55)          # chroma of a performance
D, wp = sequence.dtw(X, Y, metric="cosine")
# wp[::-1] runs from (0, 0) to (39, 54)

trans = sequence.transition_loop(2, 0.9)
voiced = sequence.viterbi_binary(np.random.rand(1, 100), trans)