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
XandY((n_features, N)and(n_features, M); 1-D input is one feature), or a precomputed cost matrixCof 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)); withbacktrack=Truethe tuple(D, wp)wherewpis an int64 array of shape(path_length, 2)ordered from the end of the alignment to its start; withreturn_steps=Truethe step matrix (int64, same shape asD) 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:
- Returns:
shape
(path_length, 2), end first.- Return type:
numpy.ndarray[int64]
Transition matrices
- audio_samples.sequence.transition_uniform(n_states)
Uniform transition matrix: every entry
1 / n_states.- Returns:
(n_states, n_states)filled with1 / n_states.- Return type:
numpy.ndarray[float64]
- audio_samples.sequence.transition_loop(n_states, prob)
Self-loop transition matrix.
- Parameters:
- Returns:
(n_states, n_states).- Return type:
numpy.ndarray[float64]
- audio_samples.sequence.transition_cycle(n_states, prob)
Cyclic transition matrix.
- Parameters:
- 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:
- 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.SparseRowsrather 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 indata’s precision.- Return type:
- 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.SparseRowsrather 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 indata’s precision.- Return type:
- audio_samples.sequence.recurrence_to_lag(rec, *, pad=True, axis=-1)
Convert a (dense) recurrence matrix to a time-lag matrix.
- Parameters:
- Returns:
(2t, t)or(t, t); bool ifrecis bool, elserec’s precision.- Return type:
- 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) or0/-2(rows; a padded lag matrix is then(t, 2t)).
- Returns:
(t, t); bool iflagis bool, elselag’s precision.- Return type:
- 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)withpathan 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 callablef(x, axis=-1) -> floatapplied to each 1-D segment.pad (bool) – Add 0 and
n_framesto the boundaries. Default True. Not used with slices.
- Returns:
datawith 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)