-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsequence.py
More file actions
2051 lines (1678 loc) Β· 67.5 KB
/
sequence.py
File metadata and controls
2051 lines (1678 loc) Β· 67.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Sequential modeling
===================
Sequence alignment
------------------
.. autosummary::
:toctree: generated/
dtw
rqa
Viterbi decoding
----------------
.. autosummary::
:toctree: generated/
viterbi
viterbi_discriminative
viterbi_binary
Transition matrices
-------------------
.. autosummary::
:toctree: generated/
transition_uniform
transition_loop
transition_cycle
transition_local
"""
from __future__ import annotations
import numpy as np
from scipy.spatial.distance import cdist
from numba import jit
from .util import pad_center, fill_off_diagonal, is_positive_int, tiny, expand_to
from .util.exceptions import ParameterError
from .filters import get_window
from typing import Any, Iterable, List, Optional, Tuple, Union, overload
from typing_extensions import Literal
from ._typing import _WindowSpec
__all__ = [
"dtw",
"dtw_backtracking",
"rqa",
"viterbi",
"viterbi_discriminative",
"viterbi_binary",
"transition_uniform",
"transition_loop",
"transition_cycle",
"transition_local",
]
@overload
def dtw(
X: np.ndarray,
Y: np.ndarray,
*,
metric: str = ...,
step_sizes_sigma: Optional[np.ndarray] = ...,
weights_add: Optional[np.ndarray] = ...,
weights_mul: Optional[np.ndarray] = ...,
subseq: bool = ...,
backtrack: Literal[False],
global_constraints: bool = ...,
band_rad: float = ...,
return_steps: Literal[False] = ...,
) -> np.ndarray:
...
@overload
def dtw(
*,
C: np.ndarray,
metric: str = ...,
step_sizes_sigma: Optional[np.ndarray] = ...,
weights_add: Optional[np.ndarray] = ...,
weights_mul: Optional[np.ndarray] = ...,
subseq: bool = ...,
backtrack: Literal[False],
global_constraints: bool = ...,
band_rad: float = ...,
return_steps: Literal[False] = ...,
) -> np.ndarray:
...
@overload
def dtw(
X: np.ndarray,
Y: np.ndarray,
*,
metric: str = ...,
step_sizes_sigma: Optional[np.ndarray] = ...,
weights_add: Optional[np.ndarray] = ...,
weights_mul: Optional[np.ndarray] = ...,
subseq: bool = ...,
backtrack: Literal[False],
global_constraints: bool = ...,
band_rad: float = ...,
return_steps: Literal[True],
) -> Tuple[np.ndarray, np.ndarray]:
...
@overload
def dtw(
*,
C: np.ndarray,
metric: str = ...,
step_sizes_sigma: Optional[np.ndarray] = ...,
weights_add: Optional[np.ndarray] = ...,
weights_mul: Optional[np.ndarray] = ...,
subseq: bool = ...,
backtrack: Literal[False],
global_constraints: bool = ...,
band_rad: float = ...,
return_steps: Literal[True],
) -> Tuple[np.ndarray, np.ndarray]:
...
@overload
def dtw(
X: np.ndarray,
Y: np.ndarray,
*,
metric: str = ...,
step_sizes_sigma: Optional[np.ndarray] = ...,
weights_add: Optional[np.ndarray] = ...,
weights_mul: Optional[np.ndarray] = ...,
subseq: bool = ...,
backtrack: Literal[True] = ...,
global_constraints: bool = ...,
band_rad: float = ...,
return_steps: Literal[False] = ...,
) -> Tuple[np.ndarray, np.ndarray]:
...
@overload
def dtw(
*,
C: np.ndarray,
metric: str = ...,
step_sizes_sigma: Optional[np.ndarray] = ...,
weights_add: Optional[np.ndarray] = ...,
weights_mul: Optional[np.ndarray] = ...,
subseq: bool = ...,
backtrack: Literal[True] = ...,
global_constraints: bool = ...,
band_rad: float = ...,
return_steps: Literal[False] = ...,
) -> Tuple[np.ndarray, np.ndarray]:
...
@overload
def dtw(
X: np.ndarray,
Y: np.ndarray,
*,
metric: str = ...,
step_sizes_sigma: Optional[np.ndarray] = ...,
weights_add: Optional[np.ndarray] = ...,
weights_mul: Optional[np.ndarray] = ...,
subseq: bool = ...,
backtrack: Literal[True] = ...,
global_constraints: bool = ...,
band_rad: float = ...,
return_steps: Literal[True],
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
...
@overload
def dtw(
*,
C: np.ndarray,
metric: str = ...,
step_sizes_sigma: Optional[np.ndarray] = ...,
weights_add: Optional[np.ndarray] = ...,
weights_mul: Optional[np.ndarray] = ...,
subseq: bool = ...,
backtrack: Literal[True] = ...,
global_constraints: bool = ...,
band_rad: float = ...,
return_steps: Literal[True],
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
...
def dtw(
X: Optional[np.ndarray] = None,
Y: Optional[np.ndarray] = None,
*,
C: Optional[np.ndarray] = None,
metric: str = "euclidean",
step_sizes_sigma: Optional[np.ndarray] = None,
weights_add: Optional[np.ndarray] = None,
weights_mul: Optional[np.ndarray] = None,
subseq: bool = False,
backtrack: bool = True,
global_constraints: bool = False,
band_rad: float = 0.25,
return_steps: bool = False,
) -> Union[
np.ndarray, Tuple[np.ndarray, np.ndarray], Tuple[np.ndarray, np.ndarray, np.ndarray]
]:
"""Dynamic time warping (DTW).
This function performs a DTW and path backtracking on two sequences.
We follow the nomenclature and algorithmic approach as described in [#]_.
.. [#] Meinard Mueller
Fundamentals of Music Processing β Audio, Analysis, Algorithms, Applications
Springer Verlag, ISBN: 978-3-319-21944-8, 2015.
Parameters
----------
X : np.ndarray [shape=(..., K, N)]
audio feature matrix (e.g., chroma features)
If ``X`` has more than two dimensions (e.g., for multi-channel inputs), all leading
dimensions are used when computing distance to ``Y``.
Y : np.ndarray [shape=(..., K, M)]
audio feature matrix (e.g., chroma features)
C : np.ndarray [shape=(N, M)]
Precomputed distance matrix. If supplied, X and Y must not be supplied and
``metric`` will be ignored.
metric : str
Identifier for the cost-function as documented
in `scipy.spatial.distance.cdist()`
step_sizes_sigma : np.ndarray [shape=[n, 2]]
Specifies allowed step sizes as used by the DTW.
weights_add : np.ndarray [shape=[n, ]]
Additive weights to penalize certain step sizes.
weights_mul : np.ndarray [shape=[n, ]]
Multiplicative weights to penalize certain step sizes.
subseq : bool
Enable subsequence DTW, e.g., for retrieval tasks.
backtrack : bool
Enable backtracking in accumulated cost matrix.
global_constraints : bool
Applies global constraints to the cost matrix ``C`` (Sakoe-Chiba band).
band_rad : float
The Sakoe-Chiba band radius (1/2 of the width) will be
``int(radius*min(C.shape))``.
return_steps : bool
If true, the function returns ``steps``, the step matrix, containing
the indices of the used steps from the cost accumulation step.
Returns
-------
D : np.ndarray [shape=(N, M)]
accumulated cost matrix.
The value at the final index position ``D[-1, -1]`` is the total alignment cost.
wp : np.ndarray [shape=(L, 2)]
Warping path with index pairs.
Each row of the array contains an index pair (n, m).
Only returned when ``backtrack`` is True.
Note that the length ``L`` of the warping path need not match the
lengths of the input data, depending on the ``step_sizes_sigma`` values
and ``subseq``.
steps : np.ndarray [shape=(N, M)]
Step matrix, containing the indices of the used steps from the cost
accumulation step.
Only returned when ``return_steps`` is True.
Raises
------
ParameterError
If you are doing diagonal matching and Y is shorter than X or if an
incompatible combination of X, Y, and C are supplied.
If your input dimensions are incompatible.
If the cost matrix has NaN values.
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> y, sr = librosa.load(librosa.ex('brahms'), offset=10, duration=15)
>>> X = librosa.feature.chroma_cens(y=y, sr=sr)
>>> noise = np.random.rand(X.shape[0], 200)
>>> Y = np.concatenate((noise, noise, X, noise), axis=1)
>>> D, wp = librosa.sequence.dtw(X, Y, subseq=True)
>>> fig, ax = plt.subplots(nrows=2, sharex=True)
>>> img = librosa.display.specshow(D, x_axis='frames', y_axis='frames',
... ax=ax[0])
>>> ax[0].set(title='DTW cost', xlabel='Noisy sequence', ylabel='Target')
>>> ax[0].plot(wp[:, 1], wp[:, 0], label='Optimal path', color='y')
>>> ax[0].legend()
>>> fig.colorbar(img, ax=ax[0])
>>> ax[1].plot(D[-1, :] / wp.shape[0])
>>> ax[1].set(xlim=[0, Y.shape[1]], ylim=[0, 2],
... title='Matching cost function')
"""
# Default Parameters
default_steps = np.array([[1, 1], [0, 1], [1, 0]], dtype=np.uint32)
default_weights_add = np.zeros(3, dtype=np.float64)
default_weights_mul = np.ones(3, dtype=np.float64)
if step_sizes_sigma is None:
# Use the default steps
step_sizes_sigma = default_steps
# Use default weights if none are provided
if weights_add is None:
weights_add = default_weights_add
if weights_mul is None:
weights_mul = default_weights_mul
else:
# If we have custom steps but no weights, construct them here
if weights_add is None:
weights_add = np.zeros(len(step_sizes_sigma), dtype=np.float64)
if weights_mul is None:
weights_mul = np.ones(len(step_sizes_sigma), dtype=np.float64)
# Make the default step weights infinite so that they are never
# preferred over custom steps
default_weights_add.fill(np.inf)
default_weights_mul.fill(np.inf)
# Append custom steps and weights to our defaults
step_sizes_sigma = np.concatenate((default_steps, step_sizes_sigma))
weights_add = np.concatenate((default_weights_add, weights_add))
weights_mul = np.concatenate((default_weights_mul, weights_mul))
# These asserts are bad, but mypy cannot trace the code paths properly
assert step_sizes_sigma is not None
assert weights_add is not None
assert weights_mul is not None
if np.any(step_sizes_sigma < 0):
raise ParameterError("step_sizes_sigma cannot contain negative values")
if len(step_sizes_sigma) != len(weights_add):
raise ParameterError("len(weights_add) must be equal to len(step_sizes_sigma)")
if len(step_sizes_sigma) != len(weights_mul):
raise ParameterError("len(weights_mul) must be equal to len(step_sizes_sigma)")
if C is None and (X is None or Y is None):
raise ParameterError("If C is not supplied, both X and Y must be supplied")
if C is not None and (X is not None or Y is not None):
raise ParameterError("If C is supplied, both X and Y must not be supplied")
c_is_transposed = False
# calculate pair-wise distances, unless already supplied.
# C_local will keep track of whether the distance matrix was supplied
# by the user (False) or constructed locally (True)
C_local = False
if C is None:
C_local = True
# mypy can't figure out that this case does not happen
assert X is not None and Y is not None
# take care of dimensions
X = np.atleast_2d(X)
Y = np.atleast_2d(Y)
# Perform some shape-squashing here
# Put the time axes around front
# Suppress types because mypy doesn't know these are ndarrays
X = np.swapaxes(X, -1, 0) # type: ignore
Y = np.swapaxes(Y, -1, 0) # type: ignore
# Flatten the remaining dimensions
# Use F-ordering to preserve columns
X = X.reshape((X.shape[0], -1), order="F")
Y = Y.reshape((Y.shape[0], -1), order="F")
try:
C = cdist(X, Y, metric=metric)
except ValueError as exc:
raise ParameterError(
"scipy.spatial.distance.cdist returned an error.\n"
"Please provide your input in the form X.shape=(K, N) "
"and Y.shape=(K, M).\n 1-dimensional sequences should "
"be reshaped to X.shape=(1, N) and Y.shape=(1, M)."
) from exc
# for subsequence matching:
# if N > M, Y can be a subsequence of X
if subseq and (X.shape[0] > Y.shape[0]):
C = C.T
c_is_transposed = True
C = np.atleast_2d(C)
# if diagonal matching, Y has to be longer than X
# (X simply cannot be contained in Y)
if np.array_equal(step_sizes_sigma, np.array([[1, 1]])) and (
C.shape[0] > C.shape[1]
):
raise ParameterError(
"For diagonal matching: Y.shape[-1] >= X.shape[-11] "
"(C.shape[1] >= C.shape[0])"
)
max_0 = step_sizes_sigma[:, 0].max()
max_1 = step_sizes_sigma[:, 1].max()
# check C here for nans before building global constraints
if np.any(np.isnan(C)):
raise ParameterError("DTW cost matrix C has NaN values. ")
if global_constraints:
# Apply global constraints to the cost matrix
if not C_local:
# If C was provided as input, make a copy here
C = np.copy(C)
fill_off_diagonal(C, radius=band_rad, value=np.inf)
# initialize whole matrix with infinity values
D = np.ones(C.shape + np.array([max_0, max_1])) * np.inf
# set starting point to C[0, 0]
D[max_0, max_1] = C[0, 0]
if subseq:
D[max_0, max_1:] = C[0, :]
# initialize step matrix with -1
# will be filled in calc_accu_cost() with indices from step_sizes_sigma
steps = np.zeros(D.shape, dtype=np.int32)
# these steps correspond to left- (first row) and up-(first column) moves
steps[0, :] = 1
steps[:, 0] = 2
# calculate accumulated cost matrix
D: np.ndarray
steps: np.ndarray
D, steps = __dtw_calc_accu_cost(
C, D, steps, step_sizes_sigma, weights_mul, weights_add, max_0, max_1
)
# delete infinity rows and columns
D = D[max_0:, max_1:]
steps = steps[max_0:, max_1:]
return_values: List[np.ndarray]
if backtrack:
wp: np.ndarray
if subseq:
if np.all(np.isinf(D[-1])):
raise ParameterError(
"No valid sub-sequence warping path could "
"be constructed with the given step sizes."
)
start = np.argmin(D[-1, :])
_wp = __dtw_backtracking(steps, step_sizes_sigma, subseq, start)
else:
# perform warping path backtracking
if np.isinf(D[-1, -1]):
raise ParameterError(
"No valid sub-sequence warping path could "
"be constructed with the given step sizes."
)
_wp = __dtw_backtracking(steps, step_sizes_sigma, subseq)
if _wp[-1] != (0, 0):
raise ParameterError(
"Unable to compute a full DTW warping path. "
"You may want to try again with subseq=True."
)
wp = np.asarray(_wp, dtype=int)
# since we transposed in the beginning, we have to adjust the index pairs back
if subseq and (
(X is not None and Y is not None and X.shape[0] > Y.shape[0])
or c_is_transposed
or C.shape[0] > C.shape[1]
):
wp = np.fliplr(wp)
return_values = [D, wp]
else:
return_values = [D]
if return_steps:
return_values.append(steps)
if len(return_values) > 1:
# Suppressing type check here because mypy can't
# infer the exact length of the tuple
return tuple(return_values) # type: ignore
else:
return return_values[0]
@jit(nopython=True, cache=True) # type: ignore
def __dtw_calc_accu_cost(
C: np.ndarray,
D: np.ndarray,
steps: np.ndarray,
step_sizes_sigma: np.ndarray,
weights_mul: np.ndarray,
weights_add: np.ndarray,
max_0: int,
max_1: int,
) -> Tuple[np.ndarray, np.ndarray]: # pragma: no cover
"""Calculate the accumulated cost matrix D.
Use dynamic programming to calculate the accumulated costs.
Parameters
----------
C : np.ndarray [shape=(N, M)]
pre-computed cost matrix
D : np.ndarray [shape=(N, M)]
accumulated cost matrix
steps : np.ndarray [shape=(N, M)]
Step matrix, containing the indices of the used steps from the cost
accumulation step.
step_sizes_sigma : np.ndarray [shape=[n, 2]]
Specifies allowed step sizes as used by the dtw.
weights_add : np.ndarray [shape=[n, ]]
Additive weights to penalize certain step sizes.
weights_mul : np.ndarray [shape=[n, ]]
Multiplicative weights to penalize certain step sizes.
max_0 : int
maximum number of steps in step_sizes_sigma in dim 0.
max_1 : int
maximum number of steps in step_sizes_sigma in dim 1.
Returns
-------
D : np.ndarray [shape=(N, M)]
accumulated cost matrix.
D[N, M] is the total alignment cost.
When doing subsequence DTW, D[N,:] indicates a matching function.
steps : np.ndarray [shape=(N, M)]
Step matrix, containing the indices of the used steps from the cost
accumulation step.
See Also
--------
dtw
"""
for cur_n in range(max_0, D.shape[0]):
for cur_m in range(max_1, D.shape[1]):
# accumulate costs
for cur_step_idx, cur_w_add, cur_w_mul in zip(
range(step_sizes_sigma.shape[0]), weights_add, weights_mul
):
cur_D = D[
cur_n - step_sizes_sigma[cur_step_idx, 0],
cur_m - step_sizes_sigma[cur_step_idx, 1],
]
cur_C = cur_w_mul * C[cur_n - max_0, cur_m - max_1]
cur_C += cur_w_add
cur_cost = cur_D + cur_C
# check if cur_cost is smaller than the one stored in D
if cur_cost < D[cur_n, cur_m]:
D[cur_n, cur_m] = cur_cost
# save step-index
steps[cur_n, cur_m] = cur_step_idx
return D, steps
@jit(nopython=True, cache=True) # type: ignore
def __dtw_backtracking(
steps: np.ndarray,
step_sizes_sigma: np.ndarray,
subseq: bool,
start: Optional[int] = None,
) -> List[Tuple[int, int]]: # pragma: no cover
"""Backtrack optimal warping path.
Uses the saved step sizes from the cost accumulation
step to backtrack the index pairs for an optimal
warping path.
Parameters
----------
steps : np.ndarray [shape=(N, M)]
Step matrix, containing the indices of the used steps from the cost
accumulation step.
step_sizes_sigma : np.ndarray [shape=[n, 2]]
Specifies allowed step sizes as used by the dtw.
subseq : bool
Enable subsequence DTW, e.g., for retrieval tasks.
start : int
Start column index for backtraing (only allowed for ``subseq=True``)
Returns
-------
wp : list [shape=(N,)]
Warping path with index pairs.
Each list entry contains an index pair
(n, m) as a tuple
See Also
--------
dtw
"""
if start is None:
cur_idx = (steps.shape[0] - 1, steps.shape[1] - 1)
else:
cur_idx = (steps.shape[0] - 1, start)
wp = []
# Set starting point D(N, M) and append it to the path
wp.append((cur_idx[0], cur_idx[1]))
# Loop backwards.
# Stop criteria:
# Setting it to (0, 0) does not work for the subsequence dtw,
# so we only ask to reach the first row of the matrix.
while (subseq and cur_idx[0] > 0) or (not subseq and cur_idx != (0, 0)):
cur_step_idx = steps[(cur_idx[0], cur_idx[1])]
# save tuple with minimal acc. cost in path
cur_idx = (
cur_idx[0] - step_sizes_sigma[cur_step_idx][0],
cur_idx[1] - step_sizes_sigma[cur_step_idx][1],
)
# If we run off the side of the cost matrix, break here
if min(cur_idx) < 0:
break
# append to warping path
wp.append((cur_idx[0], cur_idx[1]))
return wp
def dtw_backtracking(
steps: np.ndarray,
*,
step_sizes_sigma: Optional[np.ndarray] = None,
subseq: bool = False,
start: Optional[Union[int, np.integer[Any]]] = None,
) -> np.ndarray:
"""Backtrack a warping path.
Uses the saved step sizes from the cost accumulation
step to backtrack the index pairs for a warping path.
Parameters
----------
steps : np.ndarray [shape=(N, M)]
Step matrix, containing the indices of the used steps from the cost
accumulation step.
step_sizes_sigma : np.ndarray [shape=[n, 2]]
Specifies allowed step sizes as used by the dtw.
subseq : bool
Enable subsequence DTW, e.g., for retrieval tasks.
start : int
Start column index for backtraing (only allowed for ``subseq=True``)
Returns
-------
wp : list [shape=(N,)]
Warping path with index pairs.
Each list entry contains an index pair
(n, m) as a tuple
See Also
--------
dtw
"""
if subseq is False and start is not None:
raise ParameterError(
f"start is only allowed to be set if subseq is True (start={start}, subseq={subseq})"
)
# Default Parameters
default_steps = np.array([[1, 1], [0, 1], [1, 0]], dtype=np.uint32)
if step_sizes_sigma is None:
# Use the default steps
step_sizes_sigma = default_steps
else:
# Append custom steps and weights to our defaults
step_sizes_sigma = np.concatenate((default_steps, step_sizes_sigma))
wp = __dtw_backtracking(steps, step_sizes_sigma, subseq, start)
return np.asarray(wp, dtype=int)
@overload
def rqa(
sim: np.ndarray,
*,
gap_onset: float = ...,
gap_extend: float = ...,
knight_moves: bool = ...,
backtrack: Literal[False],
) -> np.ndarray:
...
@overload
def rqa(
sim: np.ndarray,
*,
gap_onset: float = ...,
gap_extend: float = ...,
knight_moves: bool = ...,
backtrack: Literal[True] = ...,
) -> Tuple[np.ndarray, np.ndarray]:
...
@overload
def rqa(
sim: np.ndarray,
*,
gap_onset: float = ...,
gap_extend: float = ...,
knight_moves: bool = ...,
backtrack: bool = ...,
) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
...
def rqa(
sim: np.ndarray,
*,
gap_onset: float = 1,
gap_extend: float = 1,
knight_moves: bool = True,
backtrack: bool = True,
) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
"""Recurrence quantification analysis (RQA)
This function implements different forms of RQA as described by
Serra, Serra, and Andrzejak (SSA). [#]_ These methods take as input
a self- or cross-similarity matrix ``sim``, and calculate the value
of path alignments by dynamic programming.
Note that unlike dynamic time warping (`dtw`), alignment paths here are
maximized, not minimized, so the input should measure similarity rather
than distance.
The simplest RQA method, denoted as `L` (SSA equation 3) and equivalent
to the method described by Eckman, Kamphorst, and Ruelle [#]_, accumulates
the length of diagonal paths with positive values in the input:
- ``score[i, j] = score[i-1, j-1] + 1`` if ``sim[i, j] > 0``
- ``score[i, j] = 0`` otherwise.
The second method, denoted as `S` (SSA equation 4), is similar to the first,
but allows for "knight moves" (as in the chess piece) in addition to strict
diagonal moves:
- ``score[i, j] = max(score[i-1, j-1], score[i-2, j-1], score[i-1, j-2]) + 1`` if ``sim[i, j] >
0``
- ``score[i, j] = 0`` otherwise.
The third method, denoted as `Q` (SSA equations 5 and 6) extends this by
allowing gaps in the alignment that incur some cost, rather than a hard
reset to 0 whenever ``sim[i, j] == 0``.
Gaps are penalized by two additional parameters, ``gap_onset`` and ``gap_extend``,
which are subtracted from the value of the alignment path every time a gap
is introduced or extended (respectively).
Note that setting ``gap_onset`` and ``gap_extend`` to `np.inf` recovers the second
method, and disabling knight moves recovers the first.
.. [#] SerrΓ , Joan, Xavier Serra, and Ralph G. Andrzejak.
"Cross recurrence quantification for cover song identification."
New Journal of Physics 11, no. 9 (2009): 093017.
.. [#] Eckmann, J. P., S. Oliffson Kamphorst, and D. Ruelle.
"Recurrence plots of dynamical systems."
World Scientific Series on Nonlinear Science Series A 16 (1995): 441-446.
Parameters
----------
sim : np.ndarray [shape=(N, M), non-negative]
The similarity matrix to use as input.
This can either be a recurrence matrix (self-similarity)
or a cross-similarity matrix between two sequences.
gap_onset : float > 0
Penalty for introducing a gap to an alignment sequence
gap_extend : float > 0
Penalty for extending a gap in an alignment sequence
knight_moves : bool
If ``True`` (default), allow for "knight moves" in the alignment,
e.g., ``(n, m) => (n + 1, m + 2)`` or ``(n + 2, m + 1)``.
If ``False``, only allow for diagonal moves ``(n, m) => (n + 1, m + 1)``.
backtrack : bool
If ``True``, return the alignment path.
If ``False``, only return the score matrix.
Returns
-------
score : np.ndarray [shape=(N, M)]
The alignment score matrix. ``score[n, m]`` is the cumulative value of
the best alignment sequence ending in frames ``n`` and ``m``.
path : np.ndarray [shape=(k, 2)] (optional)
If ``backtrack=True``, ``path`` contains a list of pairs of aligned frames
in the best alignment sequence.
``path[i] = [n, m]`` indicates that row ``n`` aligns to column ``m``.
See Also
--------
librosa.segment.recurrence_matrix
librosa.segment.cross_similarity
dtw
Examples
--------
Simple diagonal path enhancement (L-mode)
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> y, sr = librosa.load(librosa.ex('nutcracker'), duration=30)
>>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
>>> # Use time-delay embedding to reduce noise
>>> chroma_stack = librosa.feature.stack_memory(chroma, n_steps=10, delay=3)
>>> # Build recurrence, suppress self-loops within 1 second
>>> rec = librosa.segment.recurrence_matrix(chroma_stack, width=43,
... mode='affinity',
... metric='cosine')
>>> # using infinite cost for gaps enforces strict path continuation
>>> L_score, L_path = librosa.sequence.rqa(rec,
... gap_onset=np.inf,
... gap_extend=np.inf,
... knight_moves=False)
>>> fig, ax = plt.subplots(ncols=2)
>>> librosa.display.specshow(rec, x_axis='frames', y_axis='frames', ax=ax[0])
>>> ax[0].set(title='Recurrence matrix')
>>> librosa.display.specshow(L_score, x_axis='frames', y_axis='frames', ax=ax[1])
>>> ax[1].set(title='Alignment score matrix')
>>> ax[1].plot(L_path[:, 1], L_path[:, 0], label='Optimal path', color='c')
>>> ax[1].legend()
>>> ax[1].label_outer()
Full alignment using gaps and knight moves
>>> # New gaps cost 5, extending old gaps cost 10 for each step
>>> score, path = librosa.sequence.rqa(rec, gap_onset=5, gap_extend=10)
>>> fig, ax = plt.subplots(ncols=2, sharex=True, sharey=True)
>>> librosa.display.specshow(rec, x_axis='frames', y_axis='frames', ax=ax[0])
>>> ax[0].set(title='Recurrence matrix')
>>> librosa.display.specshow(score, x_axis='frames', y_axis='frames', ax=ax[1])
>>> ax[1].set(title='Alignment score matrix')
>>> ax[1].plot(path[:, 1], path[:, 0], label='Optimal path', color='c')
>>> ax[1].legend()
>>> ax[1].label_outer()
"""
if gap_onset < 0:
raise ParameterError("gap_onset={} must be strictly positive")
if gap_extend < 0:
raise ParameterError("gap_extend={} must be strictly positive")
score: np.ndarray
pointers: np.ndarray
score, pointers = __rqa_dp(sim, gap_onset, gap_extend, knight_moves)
if backtrack:
path = __rqa_backtrack(score, pointers)
return score, path
return score
@jit(nopython=True, cache=True) # type: ignore
def __rqa_dp(
sim: np.ndarray, gap_onset: float, gap_extend: float, knight: bool
) -> Tuple[np.ndarray, np.ndarray]: # pragma: no cover
"""RQA dynamic programming implementation"""
# The output array
score = np.zeros(sim.shape, dtype=sim.dtype)
# The backtracking array
backtrack = np.zeros(sim.shape, dtype=np.int8)
# These are place-holder arrays to limit the points being considered
# at each step of the DP
#
# If knight moves are enabled, values are indexed according to
# [(-1,-1), (-1, -2), (-2, -1)]
#
# If knight moves are disabled, then only the first entry is used.
#
# Using placeholder vectors here makes the code a bit cleaner down below.
sim_values = np.zeros(3)
score_values = np.zeros(3)
vec = np.zeros(3)
if knight:
# Initial limit is for the base case: diagonal + one knight
init_limit = 2
# Otherwise, we have 3 positions
limit = 3
else:
init_limit = 1
limit = 1
# backtracking rubric:
# 0 ==> diagonal move
# 1 ==> knight move up
# 2 ==> knight move left
# -1 ==> reset without inclusion
# -2 ==> reset with inclusion (ie positive value at init)
# Initialize the first row and column with the data
score[0, :] = sim[0, :]
score[:, 0] = sim[:, 0]
# backtracking initialization: the first row and column are all resets
# if there's a positive link here, it's an inclusive reset
for i in range(sim.shape[0]):
if sim[i, 0]:
backtrack[i, 0] = -2
else:
backtrack[i, 0] = -1
for j in range(sim.shape[1]):
if sim[0, j]:
backtrack[0, j] = -2
else:
backtrack[0, j] = -1
# Initialize the 1-1 case using only the diagonal
if sim[1, 1] > 0:
score[1, 1] = score[0, 0] + sim[1, 1]
backtrack[1, 1] = 0
else:
link = sim[0, 0] > 0
score[1, 1] = max(0, score[0, 0] - (link) * gap_onset - (~link) * gap_extend)
if score[1, 1] > 0:
backtrack[1, 1] = 0
else:
backtrack[1, 1] = -1
# Initialize the second row with diagonal and left-knight moves
i = 1
for j in range(2, sim.shape[1]):
score_values[:-1] = (score[i - 1, j - 1], score[i - 1, j - 2])
sim_values[:-1] = (sim[i - 1, j - 1], sim[i - 1, j - 2])
t_values = sim_values > 0
if sim[i, j] > 0:
backtrack[i, j] = np.argmax(score_values[:init_limit])
score[i, j] = score_values[backtrack[i, j]] + sim[i, j] # or + 1 for binary
else:
vec[:init_limit] = (
score_values[:init_limit]
- t_values[:init_limit] * gap_onset
- (~t_values[:init_limit]) * gap_extend
)
backtrack[i, j] = np.argmax(vec[:init_limit])
score[i, j] = max(0, vec[backtrack[i, j]])
# Is it a reset?
if score[i, j] == 0:
backtrack[i, j] = -1
# Initialize the second column with diagonal and up-knight moves
j = 1
for i in range(2, sim.shape[0]):
score_values[:-1] = (score[i - 1, j - 1], score[i - 2, j - 1])
sim_values[:-1] = (sim[i - 1, j - 1], sim[i - 2, j - 1])
t_values = sim_values > 0
if sim[i, j] > 0:
backtrack[i, j] = np.argmax(score_values[:init_limit])
score[i, j] = score_values[backtrack[i, j]] + sim[i, j] # or + 1 for binary
else:
vec[:init_limit] = (