dtwrb 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 46ff5e2b8f1059ffe352f4499f9858ca31a6503ac3f63c1ab17f79615be514a1
4
- data.tar.gz: 6de49d664f809e686bd47902a4485162bcaef6ccc991814503af2dc7ee19bcd2
3
+ metadata.gz: 93e1a306802cd104a8f23244e12de9db11eafded71804c5bcf9a3819131f4fea
4
+ data.tar.gz: 1a12b5c4f2e1f81dfd7f9c5061a1f50eeba5953ac4b8cd72665280c05309f5f1
5
5
  SHA512:
6
- metadata.gz: 9a9397d37e53c60dcaff865ba61e6acce1e1f1bdd93b7455d001f0755546078d68df1c45f5b8d80246472741df30ce2953fe9efef27ca27372b1ac6315fd9094
7
- data.tar.gz: 9813d307282cffda759a1178cabb2062f7f55705be0bee415abda0e63d089e18a01fb436b3394a235bb63d659db24aed9620a1867e54a565606275d5cd89bda8
6
+ metadata.gz: 6d015fee295da90e2e199d9b15e7f8d6f11265af6f968bf65c0e2b75335db529d2d9a70eda8a8b4b559a090e97259227f7764c2cefa797023a80689c835707a1
7
+ data.tar.gz: 1c6dbe175b7ea20a4b1adc0091dbb26be0648c42bdd650e23e978cb1eafabdfaa5f80de7de607ffee9d73de057eca59ed6e3f3f2b96a98334ef308f61a2034bf
data/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0 — 2026-12-06
4
+
5
+ - `DTW::Statistics.robust_sigma` and the estimator key `:robust_sigma`: 1.4826 × MAD, a robust
6
+ estimate of the standard deviation. The raw MAD is `robust_sigma / 1.4826`. It is the new default
7
+ `dispersion:` of `DTW::BarycenterAveraging`, with values identical to 1.1.0.
8
+ - Deprecated `DTW::Statistics.median_absolute_deviation` and the estimator keys
9
+ `:median_absolute_deviation` and `:mad`. They return the same scaled value as `robust_sigma` for
10
+ the whole 1.x line and warn under `Warning[:deprecated]`; the name suggested the raw MAD.
11
+ - `DTW::Aligner#align` returns `DTW::Alignment::UNDEFINED` when the accumulated end cost is not
12
+ finite. A custom band could leave the end cell unreachable, which returned cost `Infinity` with a
13
+ non-empty path and `undefined?` false. A custom band with only `#radius` is widened to `|n − m|`
14
+ when its radius is smaller. Built-in bands are unchanged.
15
+ - `DTW::Sequence.vectorize`, and with it `DTW::Sample.of`, raises `DTW::InvalidSequenceError` for
16
+ NaN, ±Infinity, complex and non-numeric values, and sequences that mix scalars with vector
17
+ frames. These previously produced a NaN cost with a truncated path, an `ArgumentError` from the
18
+ median, or a `TypeError`. The check adds about 1 µs per `DTW.distance` call on 12 × 13 sequences
19
+ under YJIT (23.3 → 24.4 µs).
20
+ - `DTW::Resampler.call` accepts scalar sequences and returns a scalar sequence; it raised
21
+ `NoMethodError` before.
22
+ - README: the slanted band is asymmetric for unequal lengths; DBA runs at most `iterations` passes
23
+ and may stop earlier.
24
+ - Requires Ruby 3.4 or later.
25
+ - Relicensed from WTFPL to MIT.
26
+ - `CITATION.cff`.
27
+
3
28
  ## 1.1.0 — 2026-08-22
4
29
 
5
30
  - `DTW::Bands::Slanted`: a global constraint that follows the diagonal of the rectangle, so the
data/CITATION.cff ADDED
@@ -0,0 +1,30 @@
1
+ cff-version: 1.2.0
2
+ title: "dtwrb: dynamic time warping and DTW barycenter averaging in pure Ruby"
3
+ message: "If you use this software, please cite it."
4
+ type: software
5
+ authors:
6
+ - family-names: Patin
7
+ given-names: Den
8
+ alias: 丁丹旭
9
+ email: hi@dpat.in
10
+ orcid: "https://orcid.org/0009-0009-6496-382X"
11
+ affiliation: Independent researcher
12
+ city: Taipei
13
+ country: TW
14
+ repository-code: "https://github.com/taiwancards/dtwrb"
15
+ repository-artifact: "https://rubygems.org/gems/dtwrb"
16
+ abstract: >-
17
+ Dynamic time warping alignment of scalar and multivariate numeric sequences under Sakoe-Chiba,
18
+ slanted or custom band constraints, with Euclidean, Manhattan, Chebyshev and cosine local
19
+ distances. DTW barycenter averaging with median or mean aggregation, approximate medoid
20
+ selection, linear resampling and robust dispersion estimation, in pure Ruby without runtime
21
+ dependencies.
22
+ keywords:
23
+ - dynamic time warping
24
+ - DTW barycenter averaging
25
+ - time series alignment
26
+ - robust statistics
27
+ - Ruby
28
+ license: MIT
29
+ version: 1.2.0
30
+ date-released: "2026-12-06"
data/LICENSE CHANGED
@@ -1,13 +1,19 @@
1
- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
2
- Version 2, December 2004
1
+ MIT License
3
2
 
4
- Copyright (C) 2026 Den Patin <hi@dpat.in>
3
+ Copyright (c) 2026 Den Patin 丁丹旭 <hi@dpat.in>
5
4
 
6
- Everyone is permitted to copy and distribute verbatim or modified
7
- copies of this license document, and changing it is allowed as long
8
- as the name is changed.
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this
6
+ software and associated documentation files (the "Software"), to deal in the Software
7
+ without restriction, including without limitation the rights to use, copy, modify, merge,
8
+ publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
9
+ to whom the Software is furnished to do so, subject to the following conditions:
9
10
 
10
- DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
11
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
11
+ The above copyright notice and this permission notice shall be included in all copies or
12
+ substantial portions of the Software.
12
13
 
13
- 0. You just DO WHAT THE FUCK YOU WANT TO.
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
15
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
16
+ PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
17
+ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19
+ DEALINGS IN THE SOFTWARE.
data/README.md CHANGED
@@ -1,30 +1,47 @@
1
- # dtwrb
1
+ # dtwrb · Ruby 的動態時間扭曲(DTW)函式庫
2
2
 
3
- Dynamic Time Warping (DTW), DTW Barycenter Averaging (DBA), and robust dispersion estimation for
4
- numeric sequences. Pure Ruby, no runtime dependencies.
3
+ Dynamic time warping (DTW), DTW barycenter averaging (DBA) and robust dispersion for numeric
4
+ sequences: align two sequences of different length, average many into one prototype, and measure
5
+ how far they spread around it. Pure Ruby, no runtime dependencies.
5
6
 
6
- Extracted from [taiwancards](https://github.com/taiwancards/taiwancards), where it drives acoustic
7
- pronunciation scoring.
7
+ 給數值序列用的動態時間扭曲(DTW,也有人翻成動態時間校正)、DTW 重心平均(DBA)跟穩健的離散程度估計:
8
+ 把兩條長度不同的序列對齊、把很多條序列平均成一條原型,再算出它們在原型周圍分散多少。純 Ruby,沒有任何
9
+ 相依套件。
8
10
 
9
- ## The problem
11
+ **English** · [中文](#中文)
10
12
 
11
- Point-to-point comparison — Euclidean distance between samples at equal indices — assumes that two
12
- sequences have the same length and the same phase. Repeated observations of one process violate
13
- both assumptions: two utterances of the same syllable, two executions of the same gesture, and two
14
- runs of the same machine cycle differ in duration and in local timing.
13
+ ## English
15
14
 
16
- DTW drops the assumption. It computes the minimum-cost monotone, continuous alignment between two
17
- sequences, letting either one stretch or compress locally. DBA lifts the idea from comparison to
18
- estimation: given many variable-length observations of one process, it returns a single prototype
19
- sequence in the DTW sense.
15
+ Comparing two sequences point by point assumes the same length and the same timing. Repeated
16
+ observations of one process break both: two utterances of one syllable, two executions of one
17
+ gesture or two runs of one machine cycle differ in duration and in local timing. DTW finds the
18
+ cheapest monotone, continuous alignment of two sequences, letting either stretch or compress
19
+ locally. DBA uses those alignments to average many variable-length observations into one
20
+ prototype sequence.
20
21
 
21
- ## Install
22
+ ### Install
23
+
24
+ Ruby 3.4 or later.
22
25
 
23
26
  ```ruby
24
27
  gem "dtwrb"
25
28
  ```
26
29
 
27
- ## Alignment
30
+ ```ruby
31
+ require "dtwrb"
32
+ ```
33
+
34
+ Everything is under the `DTW` module.
35
+
36
+ ### Sequences
37
+
38
+ A sequence is an Array of frames, one per time step: scalar (`[0.0, 1.0, ...]`) or multivariate
39
+ (`[[0.0, 9.0], [1.0, 8.0], ...]`). Scalar input is read as one-dimensional frames and gives scalar
40
+ output. Frames compared with each other must have the same dimension. Every value must be a
41
+ finite number: NaN, ±Infinity, a non-numeric value, or a sequence that mixes scalars with vector
42
+ frames raises `DTW::InvalidSequenceError`.
43
+
44
+ ### Alignment
28
45
 
29
46
  Accumulated cost follows the standard recurrence with the symmetric step pattern
30
47
  `{(1,1), (1,0), (0,1)}`:
@@ -33,13 +50,9 @@ Accumulated cost follows the standard recurrence with the symmetric step pattern
33
50
  D(i, j) = d(a_i, b_j) + min{ D(i-1, j), D(i, j-1), D(i-1, j-1) }
34
51
  ```
35
52
 
36
- `d` is the local distance between two frames. `Alignment#cost` is `D(n, m)`. `Alignment#distance`
37
- divides it by the number of path cells, which removes the bias that longer warping paths accumulate
38
- more terms.
53
+ `d` is the local distance between two frames.
39
54
 
40
55
  ```ruby
41
- require "dtwrb"
42
-
43
56
  a = [0.0, 1.0, 2.0, 3.0, 4.0]
44
57
  b = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0]
45
58
 
@@ -50,26 +63,38 @@ DTW.align(a, b).path
50
63
  # => [[0, 0], [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [4, 6]]
51
64
  ```
52
65
 
53
- `b` is `a` with its first and last frame repeated. Euclidean comparison cannot even be formed here,
54
- since the lengths differ; DTW reports exact identity and returns the path that proves it.
66
+ `b` is `a` with its first and last frame repeated. The lengths differ, so point-by-point
67
+ comparison is not defined; DTW reports a distance of zero and the path that shows it.
55
68
 
56
- A sequence is either scalar (`[0.0, 1.0, ...]`) or multivariate (`[[0.0, 9.0], [1.0, 8.0], ...]`).
57
- Scalar input is read as one-dimensional frames and yields scalar output.
69
+ `DTW.align` returns a `DTW::Alignment`:
58
70
 
59
- ## Barycenter averaging
71
+ | Method | Value |
72
+ | ------------ | --------------------------------------------------------------------------- |
73
+ | `path` | 0-based index pairs `[i, j]` from `[0, 0]` to `[n − 1, m − 1]`; also `to_a` |
74
+ | `cost` | `D(n, m)` |
75
+ | `steps` | number of cells on the path |
76
+ | `distance` | `cost / steps`, so a longer path is not penalized for adding more terms |
77
+ | `undefined?` | true when no alignment exists |
60
78
 
61
- `DTW::BarycenterAveraging` implements DBA (Petitjean, Ketterlin & Gançarski, 2011):
79
+ `DTW.distance(a, b)` is `DTW.align(a, b).distance`. If either sequence is empty, or no path with a
80
+ finite cost exists (see [Global constraint](#global-constraint)), the result is
81
+ `DTW::Alignment::UNDEFINED`: empty path, infinite `cost` and `distance`.
62
82
 
63
- 1. initialize the prototype from the medoid of the sample, resampled to the requested length;
83
+ ### Barycenter averaging
84
+
85
+ `DTW.barycenter` implements DBA (Petitjean, Ketterlin & Gançarski, 2011):
86
+
87
+ 1. start from the medoid of the sample, resampled to the requested length;
64
88
  2. align every observation to the prototype;
65
- 3. for each prototype frame and coordinate, aggregate the observation frames that the warping paths
66
- associated with it;
67
- 4. repeat until the mean absolute update falls below `tolerance`.
89
+ 3. for each prototype frame and coordinate, aggregate the observation values that the warping
90
+ paths associated with it;
91
+ 4. repeat steps 2–3 at most `iterations` times, stopping earlier once the mean absolute update of
92
+ a pass falls below `tolerance`.
68
93
 
69
- The default aggregator is the **median**, not the arithmetic mean of the original formulation. Its
94
+ The default aggregator is the median, not the arithmetic mean of the original formulation. Its
70
95
  breakdown point is 50%, so a minority of corrupt observations cannot displace the prototype.
71
- Dispersion is reported per frame and coordinate as the median absolute deviation scaled by 1.4826,
72
- a consistent estimator of σ under normality.
96
+ Dispersion is reported per frame and coordinate as `DTW::Statistics.robust_sigma`: the median
97
+ absolute deviation scaled by 1.4826, a consistent estimator of σ under normality.
73
98
 
74
99
  ```ruby
75
100
  observations = [
@@ -81,35 +106,49 @@ observations = [
81
106
 
82
107
  prototype = DTW.barycenter(observations, length: 5)
83
108
 
84
- prototype.center # => [0.0, 1.05, 2.0, 3.05, 4.0]
85
- prototype.dispersion # => [0.0, 0.148, 0.0, 0.148, 0.0]
86
- prototype.count # => 4
87
- prototype.length # => 5
109
+ prototype.center # => [0.0, 1.05, 2.0, 3.05, 4.0]
110
+ prototype.dispersion.map { |s| s.round(3) } # => [0.0, 0.148, 0.0, 0.148, 0.0]
111
+ prototype.count # => 4
112
+ prototype.length # => 5
88
113
  ```
89
114
 
90
- Length defaults to the rounded mean length of the sample. The classic mean-based formulation is one
91
- argument away:
115
+ | Option | Default | Meaning |
116
+ | ------------------ | -------------------------- | ----------------------------------------------------------------- |
117
+ | `length:` | mean input length, rounded | frames in the prototype |
118
+ | `aggregator:` | `:median` | `:median`, `:mean` or any object with `#call(values) -> Float` |
119
+ | `dispersion:` | `:robust_sigma` | `:robust_sigma`, `:standard_deviation` or any object with `#call` |
120
+ | `iterations:` | `4` | most refinement passes |
121
+ | `tolerance:` | `1e-4` | mean absolute update of a pass that ends refinement early |
122
+ | `sample_size:` | `12` | medoid candidates, see [Medoid](#medoid) |
123
+ | `metric:`, `band:` | `:euclidean`, `0.25` | as in `DTW.align` |
124
+
125
+ The result is a `DTW::Barycenter` with `center`, `dispersion` (same shape as `center`), `count`
126
+ (non-empty input sequences), `length`, `dimension` and `scalar?`. `nil` and empty arrays in the
127
+ input are skipped; if none is left, `DTW::EmptyInputError` is raised.
128
+
129
+ The mean-based formulation of the original paper:
92
130
 
93
131
  ```ruby
94
132
  DTW.barycenter(observations, length: 5, aggregator: :mean).center
95
133
  # => [0.02, 1.05, 2.02, 3.05, 4.05]
96
134
  ```
97
135
 
98
- ## Medoid
136
+ ### Medoid
99
137
 
100
- The medoid is the observation with the smallest total DTW distance to all others — the most central
138
+ The medoid is the observation with the smallest total DTW distance to all others: the most central
101
139
  real sequence, as opposed to a synthetic one. Exact selection costs O(k²) alignments, so candidates
102
- are drawn as a uniform subsample of size `sample_size` (12 by default). Selection is deterministic;
103
- no pseudo-random number generator is used anywhere in this library.
140
+ are a uniform subsample of size `sample_size` (12 by default). Selection is deterministic; the
141
+ library uses no random numbers anywhere.
104
142
 
105
143
  ```ruby
106
144
  DTW.medoid(observations)
107
145
  # => [0.0, 0.0, 1.2, 2.0, 3.1, 4.0]
108
146
  ```
109
147
 
110
- ## Local distances
148
+ ### Local distances
111
149
 
112
- Any object that responds to `#call(frame_a, frame_b) -> Float` is accepted.
150
+ Any object that responds to `#call(frame_a, frame_b) -> Float` is accepted. Frames reach it as
151
+ Arrays, also for scalar sequences.
113
152
 
114
153
  | Name | Definition | Notes |
115
154
  | ------------ | ----------------------- | ---------------------------------------- |
@@ -123,7 +162,7 @@ DTW.distance(a, b, metric: :manhattan)
123
162
  DTW.distance(a, b, metric: ->(x, y) { (x.first - y.first).abs })
124
163
  ```
125
164
 
126
- ## Global constraint
165
+ ### Global constraint
127
166
 
128
167
  The Sakoe–Chiba band (Sakoe & Chiba, 1978) restricts the alignment to cells with `|i − j| ≤ r`,
129
168
  which bounds the admissible warping and reduces the cost matrix to a diagonal strip:
@@ -132,72 +171,107 @@ which bounds the admissible warping and reduces the cost matrix to a diagonal st
132
171
  r = max( ⌈ratio · max(n, m)⌉, |n − m| + 1 )
133
172
  ```
134
173
 
135
- The second term guarantees that at least one path stays feasible. It also means that the band
136
- stops constraining once the lengths diverge: at `n = 40, m = 140` the radius is at least 101
137
- whatever ratio is asked for, because the strip must reach the far corner from the main diagonal.
174
+ The second term keeps at least one path feasible. It also means the band stops constraining once
175
+ the lengths diverge: at `n = 40, m = 140` the radius is at least 101 whatever the ratio, because
176
+ the strip must reach the far corner from the main diagonal.
138
177
 
139
- The slanted band removes that limitation by following the diagonal of the rectangle rather than
140
- the main diagonal, so the radius keeps its meaning at any length ratio:
178
+ The slanted band follows the diagonal of the rectangle instead of the main diagonal, so the
179
+ radius keeps its meaning at any length ratio:
141
180
 
142
181
  ```text
143
- centre(i) = 1 + (i − 1) · (m − 1) / (n − 1), |j − centre(i)| ≤ r
182
+ center(i) = 1 + (i − 1) · (m − 1) / (n − 1), |j − center(i)| ≤ r
144
183
  r = max( ⌈ratio · max(n, m)⌉, ⌈½ · (m − 1) / (n − 1)⌉, 1 )
145
184
  ```
146
185
 
147
186
  The second term is half a step of the diagonal, below which consecutive rows no longer overlap
148
187
  and no path exists. On the same `40 × 140` pair a ratio of `0.25` gives `r = 35` instead of `101`.
149
188
 
150
- | Value | Meaning |
151
- | ---------------- | ----------------------------------------------------------------------------------------------------------- |
152
- | `0.25` | default ratio |
153
- | any `Numeric` | Sakoe–Chiba band with that ratio |
154
- | `:sakoe_chiba` | Sakoe–Chiba band at the default ratio |
155
- | `:slanted` | slanted band at the default ratio |
156
- | `:unconstrained` | full cost matrix |
157
- | custom | any object that responds to `#radius(n, m) -> Integer`, optionally `#bounds(i, n, m) -> [Integer, Integer]` |
158
-
159
- Narrowing the band can only raise the accumulated cost, never lower it.
189
+ The slanted band is asymmetric: the first sequence indexes the rows and the radius is measured
190
+ along the second, so for `n ≠ m` swapping the arguments changes the admissible cells. On `[6, 6, 0]`
191
+ and `[9, 8, 4, 7, 0, 0, 7, 1]` the distance is `2.75` one way and `2.0` the other, and `DTW.medoid`
192
+ with this band depends on the order of its input.
193
+
194
+ | `band:` | Meaning |
195
+ | ------------------------- | ----------------------------------------------------------------------------------------------------------- |
196
+ | `0.25` | default ratio |
197
+ | any `Numeric` | Sakoe–Chiba band with that ratio |
198
+ | `:sakoe_chiba` | Sakoe–Chiba band at the default ratio |
199
+ | `:slanted` | slanted band at the default ratio |
200
+ | `:unconstrained` or `nil` | full cost matrix |
201
+ | custom | any object that responds to `#radius(n, m) -> Integer`, optionally `#bounds(i, n, m) -> [Integer, Integer]` |
202
+
203
+ Narrowing the band can only raise the accumulated cost, never lower it. `#radius(n, m)` receives
204
+ the lengths of the first and second sequence; a radius below `|n − m|`, the minimum at which the
205
+ end cell is reachable, is widened to `|n − m|`. `#bounds(i, n, m)`, when defined, takes precedence
206
+ and returns the first and last admissible column of row `i`, all 1-based and inclusive. If custom
207
+ bounds leave the end cell unreachable, or the accumulated cost is not finite, `align` returns
208
+ `DTW::Alignment::UNDEFINED`.
160
209
 
161
210
  ```ruby
162
211
  DTW::Bands::SakoeChiba.new(ratio: 0.25).radius(40, 140) # => 101
163
212
  DTW::Bands::Slanted.new(ratio: 0.25).radius(40, 140) # => 35
164
213
  ```
165
214
 
166
- ## Statistics and resampling
215
+ ### Statistics and resampling
167
216
 
168
217
  ```ruby
169
218
  DTW::Statistics.median([5.0, 1.0, 3.0]) # => 3.0
170
- DTW::Statistics.median_absolute_deviation([10.0, 11.0, 12.0, 13.0, 1000.0]) # => 1.4826
219
+ DTW::Statistics.robust_sigma([10.0, 11.0, 12.0, 13.0, 1000.0]) # => 1.4826
171
220
  DTW::Statistics.standard_deviation([2.0, 4.0, 4.0, 4.0, 5.0]) # => 1.0954451150103321
172
221
 
173
222
  DTW::Resampler.call([[0.0], [10.0]], 3) # => [[0.0], [5.0], [10.0]]
223
+ DTW::Resampler.call([0.0, 10.0], 3) # => [0.0, 5.0, 10.0]
174
224
  ```
175
225
 
176
- ## In practice
226
+ `median` and `mean` return `nil` for an empty array; `robust_sigma` and `standard_deviation`
227
+ (Bessel-corrected) return `0.0` for fewer than two values. Where an estimator is expected
228
+ (`aggregator:`, `dispersion:`), the names `:median`, `:mean`, `:robust_sigma` and
229
+ `:standard_deviation` are accepted.
230
+
231
+ `robust_sigma` returns 1.4826 × MAD, a robust estimate of the standard deviation; the raw median
232
+ absolute deviation is `robust_sigma / 1.4826`. `median_absolute_deviation` and the estimator keys
233
+ `:median_absolute_deviation` and `:mad` are deprecated aliases that return the same scaled value
234
+ throughout 1.x. They warn only when deprecation warnings are enabled (`Warning[:deprecated] = true`
235
+ or `ruby -W:deprecated`).
236
+
237
+ `DTW::Resampler.call(sequence, length)` resamples linearly to `length` frames, keeping the first
238
+ and last frame; a scalar sequence comes back scalar.
239
+
240
+ ### Errors
241
+
242
+ | Error | Raised when |
243
+ | ----------------------------- | ---------------------------------------------------------------------------------------------------------- |
244
+ | `DTW::InvalidSequenceError` | a sequence is not an Array, holds a value that is not a finite number, or mixes scalars with vector frames |
245
+ | `DTW::DimensionMismatchError` | two frames compared have different dimensions |
246
+ | `DTW::EmptyInputError` | `medoid` or `barycenter` receives no non-empty sequence |
247
+ | `DTW::UnknownStrategyError` | a metric, band or estimator name is unknown |
248
+ | `ArgumentError` | a band ratio, `iterations` or `tolerance` is negative; `length` or `sample_size` is not positive |
249
+
250
+ The `DTW::` errors inherit from `DTW::Error`.
251
+
252
+ ### In practice
177
253
 
178
254
  [taiwancards](https://github.com/taiwancards/taiwancards) teaches Taiwanese Mandarin and scores
179
- learner recordings against native templates. The library is used at two stages.
255
+ learner recordings against native templates. It uses this library at two stages.
180
256
 
181
- **Template construction, offline.** For every syllable-and-tone key the corpus pipeline gathers
182
- recordings from many speakers. Speaking rate differs, so the MFCC matrices (13 coefficients per
183
- frame) and the F0 tone contours arrive at different lengths. `DTW.barycenter` reduces each set to
184
- one prototype — 12 frames for MFCC, 16 for the tone contour — plus the per-frame dispersion that
185
- becomes the tolerance band.
257
+ **Template construction, offline.** For every syllable-and-tone key, the corpus pipeline gathers
258
+ recordings from many speakers and resamples each to a fixed length: 12 MFCC frames of 13
259
+ coefficients and a 16-point F0 contour. `DTW.barycenter` aligns each set to a prototype of that
260
+ length and returns the per-frame dispersion that becomes the tolerance band. The warping path
261
+ absorbs the timing differences inside the syllable that fixed-length resampling leaves.
186
262
 
187
- **Scoring, online.** A learner utterance is framed into its own MFCC matrix. `DTW.distance` to the
188
- prototype center gives a rate-invariant timbre score, so a slow speaker is not penalized for being
189
- slow. The stored dispersion turns that raw distance into a z-score, so syllables whose realization
190
- is naturally variable do not raise false alarms.
263
+ **Scoring, online.** A learner utterance is reduced to the same 12 × 13 MFCC matrix. `DTW.distance`
264
+ to the prototype center gives the timbre score, and the stored dispersion turns that distance into
265
+ a z-score, so syllables that vary naturally do not raise false alarms.
191
266
 
192
- Field recordings contain clipped, truncated, and mislabeled tokens. Median aggregation keeps such a
193
- minority from dragging the prototype away from the actual articulation target — the property that
194
- motivated the robust default.
267
+ Field recordings contain clipped, truncated and mislabeled tokens. Median aggregation keeps such a
268
+ minority from dragging the prototype away from the articulation target.
195
269
 
196
- Speech is one instance of the general case. Anything sampled as a variable-rate numeric sequence —
197
- gesture traces, biosignals, machine cycles, pen trajectories — poses the same alignment and
270
+ Speech is one case of the general problem. Gesture traces, biosignals, machine cycles and pen
271
+ trajectories are numeric sequences produced at varying speed and pose the same alignment and
198
272
  prototyping problem.
199
273
 
200
- ## Complexity
274
+ ### Complexity
201
275
 
202
276
  | Operation | Time | Memory |
203
277
  | ------------------------ | ------------------------ | -------------- |
@@ -209,12 +283,12 @@ prototyping problem.
209
283
  `n` and `m` are sequence lengths, `D` the frame dimension, `r` the band radius, `s` the medoid
210
284
  sample size, `L` the prototype length.
211
285
 
212
- ## Design
286
+ ### Design
213
287
 
214
288
  Strategies are injected, never hard-coded: the local distance (`DTW::Metrics`), the global
215
- constraint (`DTW::Bands`), the central-tendency aggregator, and the dispersion estimator
216
- (`DTW::Statistics`). `DTW::Aligner`, `DTW::Medoid`, and `DTW::BarycenterAveraging` are immutable and
217
- reusable; build them once when aligning many pairs.
289
+ constraint (`DTW::Bands`), the aggregator and the dispersion estimator (`DTW::Statistics`).
290
+ `DTW::Aligner`, `DTW::Medoid` and `DTW::BarycenterAveraging` are immutable and reusable; build them
291
+ once when aligning many pairs.
218
292
 
219
293
  ```ruby
220
294
  aligner = DTW::Aligner.new(metric: :cosine, band: 0.1)
@@ -223,9 +297,280 @@ averaging = DTW::BarycenterAveraging.new(aligner: aligner, aggregator: :mean, it
223
297
  averaging.call(observations, length: 32)
224
298
  ```
225
299
 
226
- `DTW::Alignment`, `DTW::Barycenter`, and `DTW::Sample` are `Data` value objects: frozen, compared by
300
+ `DTW::Alignment`, `DTW::Barycenter` and `DTW::Sample` are `Data` value objects: frozen, compared by
227
301
  value, copied with `#with`.
228
302
 
229
- ## License
303
+ Developed and maintained in Taipei, Taiwan by Den Patin 丁丹旭 (<hi@dpat.in>), independent researcher, linguist and software engineer.
304
+
305
+ ### License
306
+
307
+ MIT — see [LICENSE](LICENSE).
308
+
309
+ ## 中文
310
+
311
+ 兩條序列一個點一個點直接比,前提是長度一樣、時間也對得上。可是同一個過程重複觀察好幾次,這兩個前提
312
+ 通常都不成立:同一個音節唸兩次、同一個手勢做兩次、機器的同一個循環跑兩次,總長度不一樣,中間哪裡快
313
+ 哪裡慢也不一樣。DTW 會找出兩條序列之間成本最低、單調又連續的對齊方式,讓任何一邊都可以局部拉長或壓縮。
314
+ DBA 再利用這些對齊結果,把很多條長度不一的觀測平均成一條原型序列。
315
+
316
+ ### 安裝
317
+
318
+ 需要 Ruby 3.4 以上。
319
+
320
+ ```ruby
321
+ gem "dtwrb"
322
+ ```
323
+
324
+ ```ruby
325
+ require "dtwrb"
326
+ ```
327
+
328
+ 所有功能都在 `DTW` 模組底下。
329
+
330
+ ### 序列
331
+
332
+ 序列就是一個陣列,每個元素是一個時間點(frame)的值:可以是純量(`[0.0, 1.0, ...]`),也可以是
333
+ 多維向量(`[[0.0, 9.0], [1.0, 8.0], ...]`)。純量序列會當成每個時間點只有一維來算,結果也會是純量。
334
+ 互相比較的時間點維度要一樣。每個值都要是有限的數字;遇到 NaN、±Infinity、不是數字的值,或是同一條
335
+ 序列裡純量跟向量混在一起,會丟出 `DTW::InvalidSequenceError`。
336
+
337
+ ### 對齊
338
+
339
+ 累積成本用標準的遞迴式,步進模式是對稱的 `{(1,1), (1,0), (0,1)}`:
340
+
341
+ ```text
342
+ D(i, j) = d(a_i, b_j) + min{ D(i-1, j), D(i, j-1), D(i-1, j-1) }
343
+ ```
344
+
345
+ `d` 是兩個時間點之間的局部距離。
346
+
347
+ ```ruby
348
+ a = [0.0, 1.0, 2.0, 3.0, 4.0]
349
+ b = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0]
350
+
351
+ DTW.distance(a, b)
352
+ # => 0.0
353
+
354
+ DTW.align(a, b).path
355
+ # => [[0, 0], [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [4, 6]]
356
+ ```
357
+
358
+ `b` 就是把 `a` 的第一個跟最後一個值各多重複一次。兩條長度不一樣,沒辦法逐點比較;DTW 算出來的距離是
359
+ 0,還附上可以看出這一點的對齊路徑。
360
+
361
+ `DTW.align` 回傳 `DTW::Alignment`:
362
+
363
+ | 方法 | 內容 |
364
+ | ------------ | ----------------------------------------------------------------------------- |
365
+ | `path` | 從 `[0, 0]` 到 `[n − 1, m − 1]` 的索引對 `[i, j]`,從 0 開始算;`to_a` 也一樣 |
366
+ | `cost` | `D(n, m)` |
367
+ | `steps` | 路徑經過幾格 |
368
+ | `distance` | `cost / steps`,路徑比較長的不會因為加總的項比較多而吃虧 |
369
+ | `undefined?` | 找不到對齊的時候是 true |
370
+
371
+ `DTW.distance(a, b)` 就是 `DTW.align(a, b).distance`。任何一邊是空序列,或是找不到成本有限的路徑
372
+ (見[全域限制](#全域限制)),會回傳 `DTW::Alignment::UNDEFINED`:路徑是空的,`cost` 跟 `distance`
373
+ 都是無限大。
374
+
375
+ ### 重心平均(DBA)
376
+
377
+ `DTW.barycenter` 實作的是 DBA(Petitjean、Ketterlin 跟 Gançarski,2011):
378
+
379
+ 1. 先取樣本的 medoid,重新取樣到指定長度,當作一開始的原型;
380
+ 2. 把每條觀測序列跟原型對齊;
381
+ 3. 原型的每個時間點、每個維度,把對齊路徑對應到這裡的觀測值彙整起來;
382
+ 4. 第 2、3 步最多重複 `iterations` 次;如果某一輪更新量的平均絕對值小於 `tolerance`,就提早停下來。
383
+
384
+ 預設的彙整方式是中位數,不是原始論文用的算術平均。中位數的崩潰點是 50%,所以少數壞掉的觀測拉不動原型。
385
+ 離散程度是每個時間點、每個維度各算一個,用的是 `DTW::Statistics.robust_sigma`:中位數絕對偏差(MAD)
386
+ 乘上 1.4826,在常態分布下是標準差 σ 的一致估計量。
387
+
388
+ ```ruby
389
+ observations = [
390
+ [0.0, 1.0, 2.1, 3.0, 4.0],
391
+ [0.0, 0.0, 1.2, 2.0, 3.1, 4.0],
392
+ [0.0, 0.9, 2.0, 2.0, 2.9, 4.2],
393
+ [0.1, 1.1, 2.0, 3.2, 4.0]
394
+ ]
395
+
396
+ prototype = DTW.barycenter(observations, length: 5)
397
+
398
+ prototype.center # => [0.0, 1.05, 2.0, 3.05, 4.0]
399
+ prototype.dispersion.map { |s| s.round(3) } # => [0.0, 0.148, 0.0, 0.148, 0.0]
400
+ prototype.count # => 4
401
+ prototype.length # => 5
402
+ ```
403
+
404
+ | 參數 | 預設 | 說明 |
405
+ | ------------------ | ---------------------------- | --------------------------------------------------------------- |
406
+ | `length:` | 輸入序列的平均長度,四捨五入 | 原型有幾個時間點 |
407
+ | `aggregator:` | `:median` | `:median`、`:mean`,或任何有 `#call(values) -> Float` 的物件 |
408
+ | `dispersion:` | `:robust_sigma` | `:robust_sigma`、`:standard_deviation`,或任何有 `#call` 的物件 |
409
+ | `iterations:` | `4` | 最多修正幾輪 |
410
+ | `tolerance:` | `1e-4` | 一輪的平均絕對更新量小於這個值,就提早停 |
411
+ | `sample_size:` | `12` | 挑 medoid 時最多看幾條候選,見下面的 Medoid |
412
+ | `metric:`、`band:` | `:euclidean`、`0.25` | 跟 `DTW.align` 一樣 |
413
+
414
+ 回傳的是 `DTW::Barycenter`,有 `center`、`dispersion`(形狀跟 `center` 一樣)、`count`(非空輸入序列
415
+ 的條數)、`length`、`dimension` 跟 `scalar?`。輸入裡的 `nil` 跟空陣列會直接跳過;跳過以後一條都不剩,
416
+ 就丟出 `DTW::EmptyInputError`。
417
+
418
+ 想用原始論文的平均數版本,加一個參數就好:
419
+
420
+ ```ruby
421
+ DTW.barycenter(observations, length: 5, aggregator: :mean).center
422
+ # => [0.02, 1.05, 2.02, 3.05, 4.05]
423
+ ```
424
+
425
+ ### Medoid
426
+
427
+ medoid 是樣本裡跟其他所有序列的 DTW 距離加起來最小的那一條:它是最中心的真實序列,不是算出來的合成
428
+ 序列。精確地挑要做 O(k²) 次對齊,所以候選只取大小為 `sample_size`(預設 12)的均勻子樣本。挑出來的
429
+ 結果是固定的,整個函式庫完全沒有用到亂數。
430
+
431
+ ```ruby
432
+ DTW.medoid(observations)
433
+ # => [0.0, 0.0, 1.2, 2.0, 3.1, 4.0]
434
+ ```
435
+
436
+ ### 局部距離
437
+
438
+ 任何有 `#call(frame_a, frame_b) -> Float` 的物件都可以用。傳進去的時間點一定是陣列,純量序列也一樣。
439
+
440
+ | 名稱 | 定義 | 說明 |
441
+ | ------------ | ---------------------- | ---------------------------- |
442
+ | `:euclidean` | L² | 預設 |
443
+ | `:manhattan` | L¹ | 比較不會被單一維度的偏差帶走 |
444
+ | `:chebyshev` | L∞ | 只看偏差最大的那一維 |
445
+ | `:cosine` | 1 − cos θ,範圍 [0, 2] | 不受大小影響,只比方向 |
446
+
447
+ ```ruby
448
+ DTW.distance(a, b, metric: :manhattan)
449
+ DTW.distance(a, b, metric: ->(x, y) { (x.first - y.first).abs })
450
+ ```
451
+
452
+ ### 全域限制
453
+
454
+ Sakoe–Chiba 帶(Sakoe 跟 Chiba,1978)把對齊限制在 `|i − j| ≤ r` 的格子裡。這樣可以限制扭曲的程度,
455
+ 成本矩陣也只要算對角線附近的一條帶子:
456
+
457
+ ```text
458
+ r = max( ⌈ratio · max(n, m)⌉, |n − m| + 1 )
459
+ ```
460
+
461
+ 第二項保證至少有一條路徑走得通。但這也代表兩條序列長度差很多的時候,帶子就限制不了什麼:
462
+ `n = 40, m = 140` 時,不管 ratio 給多少,半徑至少都是 101,因為帶子要從主對角線一路延伸到另一個角落。
463
+
464
+ 斜帶(slanted band)沿著整個矩形的對角線走,不是沿著主對角線,所以不管兩條序列長度比例多少,半徑的
465
+ 意思都不變:
466
+
467
+ ```text
468
+ center(i) = 1 + (i − 1) · (m − 1) / (n − 1), |j − center(i)| ≤ r
469
+ r = max( ⌈ratio · max(n, m)⌉, ⌈½ · (m − 1) / (n − 1)⌉, 1 )
470
+ ```
471
+
472
+ 第二項是對角線半步的寬度,比這個窄的話,相鄰兩列就接不起來,也就沒有路徑。同樣是 `40 × 140`,ratio
473
+ `0.25` 得到的是 `r = 35`,不是 `101`。
474
+
475
+ 斜帶是不對稱的:第一條序列當列,半徑沿著第二條序列量,所以 `n ≠ m` 時把兩個參數對調,允許的格子就不
476
+ 一樣。像 `[6, 6, 0]` 跟 `[9, 8, 4, 7, 0, 0, 7, 1]`,一個方向的距離是 `2.75`,反過來是 `2.0`;用這種帶子
477
+ 的時候,`DTW.medoid` 的結果也會跟輸入的順序有關。
478
+
479
+ | `band:` | 意思 |
480
+ | ------------------------- | ----------------------------------------------------------------------------------------------- |
481
+ | `0.25` | 預設的 ratio |
482
+ | 任何 `Numeric` | 用這個 ratio 的 Sakoe–Chiba 帶 |
483
+ | `:sakoe_chiba` | 預設 ratio 的 Sakoe–Chiba 帶 |
484
+ | `:slanted` | 預設 ratio 的斜帶 |
485
+ | `:unconstrained` 或 `nil` | 整個成本矩陣都算 |
486
+ | 自訂 | 任何有 `#radius(n, m) -> Integer` 的物件,也可以再加上 `#bounds(i, n, m) -> [Integer, Integer]` |
487
+
488
+ 帶子越窄,累積成本只會變高,不會變低。`#radius(n, m)` 收到的是第一條跟第二條序列的長度;半徑小於
489
+ `|n − m|` 的話會自動放寬到 `|n − m|`,這是走得到終點格的最小寬度。有定義 `#bounds(i, n, m)` 的話會
490
+ 優先用它,回傳第 `i` 列允許的第一欄跟最後一欄,全部從 1 開始算,包含兩端。如果自訂的範圍讓終點格走
491
+ 不到,或是累積成本不是有限值,`align` 會回傳 `DTW::Alignment::UNDEFINED`。
492
+
493
+ ```ruby
494
+ DTW::Bands::SakoeChiba.new(ratio: 0.25).radius(40, 140) # => 101
495
+ DTW::Bands::Slanted.new(ratio: 0.25).radius(40, 140) # => 35
496
+ ```
497
+
498
+ ### 統計跟重新取樣
499
+
500
+ ```ruby
501
+ DTW::Statistics.median([5.0, 1.0, 3.0]) # => 3.0
502
+ DTW::Statistics.robust_sigma([10.0, 11.0, 12.0, 13.0, 1000.0]) # => 1.4826
503
+ DTW::Statistics.standard_deviation([2.0, 4.0, 4.0, 4.0, 5.0]) # => 1.0954451150103321
504
+
505
+ DTW::Resampler.call([[0.0], [10.0]], 3) # => [[0.0], [5.0], [10.0]]
506
+ DTW::Resampler.call([0.0, 10.0], 3) # => [0.0, 5.0, 10.0]
507
+ ```
508
+
509
+ `median` 跟 `mean` 遇到空陣列回傳 `nil`;`robust_sigma` 跟 `standard_deviation`(除以 n − 1 的樣本
510
+ 標準差)在值不到兩個時回傳 `0.0`。需要估計量的地方(`aggregator:`、`dispersion:`)可以直接寫
511
+ `:median`、`:mean`、`:robust_sigma`、`:standard_deviation` 這幾個名稱。
512
+
513
+ `robust_sigma` 回傳的是 1.4826 × MAD,也就是標準差的穩健估計;要原本的中位數絕對偏差,就用
514
+ `robust_sigma / 1.4826`。`median_absolute_deviation` 跟估計量名稱 `:median_absolute_deviation`、
515
+ `:mad` 是已經棄用的別名,在整個 1.x 都回傳一樣、乘過 1.4826 的值。只有打開棄用警告
516
+ (`Warning[:deprecated] = true` 或 `ruby -W:deprecated`)的時候才會出現警告。
517
+
518
+ `DTW::Resampler.call(sequence, length)` 用線性內插把序列重新取樣成 `length` 個時間點,頭尾兩點不變;
519
+ 純量序列進去,出來也是純量序列。
520
+
521
+ ### 錯誤
522
+
523
+ | 錯誤 | 什麼時候會丟出 |
524
+ | ----------------------------- | ------------------------------------------------------------------------------------- |
525
+ | `DTW::InvalidSequenceError` | 序列不是陣列、裡面有不是有限數字的值,或是純量跟向量混在一起 |
526
+ | `DTW::DimensionMismatchError` | 拿來比較的兩個時間點維度不同 |
527
+ | `DTW::EmptyInputError` | `medoid` 或 `barycenter` 拿到的序列全是空的 |
528
+ | `DTW::UnknownStrategyError` | 不認得的距離、帶子或估計量名稱 |
529
+ | `ArgumentError` | band 的 ratio、`iterations` 或 `tolerance` 是負的;`length` 或 `sample_size` 不是正數 |
530
+
531
+ `DTW::` 開頭的錯誤都繼承 `DTW::Error`。
532
+
533
+ ### 實際應用
534
+
535
+ [taiwancards](https://github.com/taiwancards/taiwancards) 是教臺灣華語的網站,會拿學習者的錄音跟母語者
536
+ 的範本比對、打分數。這個函式庫用在兩個地方。
537
+
538
+ **離線建立範本。** 每一個「音節加聲調」,語料處理流程都會收集很多不同說話者的錄音,每段重新取樣成固定
539
+ 長度:12 個 MFCC 音框、每框 13 個係數,再加上 16 點的基頻(F0)曲線。`DTW.barycenter` 把每一組錄音
540
+ 對齊成這個長度的原型,同時回傳每個音框的離散程度,拿來當容許範圍。固定長度的重新取樣處理不掉音節內部
541
+ 的快慢差異,這部分就交給對齊路徑吸收。
542
+
543
+ **線上評分。** 學習者的發音也轉成一樣的 12 × 13 MFCC 矩陣。跟原型中心的 `DTW.distance` 就是音色分數,
544
+ 再用存下來的離散程度把距離換成 z 分數,這樣本來就比較多變的音節不會一直誤報。
545
+
546
+ 實際收來的錄音難免有破音、被截斷或標錯的片段。用中位數彙整,這些少數的壞資料就拉不走原型。
547
+
548
+ 語音只是其中一種情況。手勢軌跡、生理訊號、機器循環、筆跡這些快慢不一的數值序列,也都有一樣的對齊跟
549
+ 找原型的問題。
550
+
551
+ ### 複雜度
552
+
553
+ 時間跟記憶體的複雜度列在英文段落的[表格](#complexity)。要注意的是:有帶狀限制時,計算時間跟帶子的寬度
554
+ 成正比,但成本矩陣還是會整個配置出來,記憶體一樣是 O(n·m)。
555
+
556
+ ### 設計
557
+
558
+ 可以替換的部分都是用參數傳進去的,不寫死在程式裡:局部距離(`DTW::Metrics`)、全域限制(`DTW::Bands`)、
559
+ 彙整方式跟離散程度的估計量(`DTW::Statistics`)。`DTW::Aligner`、`DTW::Medoid` 跟
560
+ `DTW::BarycenterAveraging` 都是不可變的物件,可以重複使用;要對齊很多組序列時,建一次就好。
561
+
562
+ ```ruby
563
+ aligner = DTW::Aligner.new(metric: :cosine, band: 0.1)
564
+ averaging = DTW::BarycenterAveraging.new(aligner: aligner, aggregator: :mean, iterations: 10)
565
+
566
+ averaging.call(observations, length: 32)
567
+ ```
568
+
569
+ `DTW::Alignment`、`DTW::Barycenter` 跟 `DTW::Sample` 都是 `Data` 值物件:已經凍結、用值來比較,要改就用
570
+ `#with` 複製一份。
571
+
572
+ 由 Den Patin 丁丹旭(<hi@dpat.in>)在臺灣臺北開發與維護。獨立研究者,做語言學跟軟體工程。
573
+
574
+ ### 授權條款
230
575
 
231
- WTFPL — see [LICENSE](LICENSE).
576
+ MIT,詳見 [LICENSE](LICENSE)。
data/lib/dtwrb/aligner.rb CHANGED
@@ -16,10 +16,10 @@ module DTW
16
16
  return Alignment::UNDEFINED if frames_a.empty? || frames_b.empty?
17
17
 
18
18
  grid = accumulate(frames_a, frames_b)
19
- Alignment.new(
20
- path: backtrack(grid, frames_a.length, frames_b.length),
21
- cost: grid[frames_a.length][frames_b.length]
22
- )
19
+ cost = grid[frames_a.length][frames_b.length]
20
+ return Alignment::UNDEFINED unless cost.finite?
21
+
22
+ Alignment.new(path: backtrack(grid, frames_a.length, frames_b.length), cost: cost)
23
23
  end
24
24
 
25
25
  def distance(sequence_a, sequence_b) = align(sequence_a, sequence_b).distance
@@ -65,7 +65,7 @@ module DTW
65
65
  [[1, first].max, [columns, last].min]
66
66
  end
67
67
  else
68
- radius = @band.radius(rows, columns)
68
+ radius = [@band.radius(rows, columns), (rows - columns).abs].max
69
69
  Array.new(rows + 1) { |row| [[1, row - radius].max, [columns, row + radius].min] }
70
70
  end
71
71
  end
data/lib/dtwrb/bands.rb CHANGED
@@ -39,8 +39,8 @@ module DTW
39
39
  return [1, columns] if rows < 2 || columns < 2
40
40
 
41
41
  width = radius(rows, columns)
42
- centre = 1.0 + ((row - 1) * (columns - 1).fdiv(rows - 1))
43
- [(centre - width).ceil, (centre + width).floor]
42
+ center = 1.0 + ((row - 1) * (columns - 1).fdiv(rows - 1))
43
+ [(center - width).ceil, (center + width).floor]
44
44
  end
45
45
 
46
46
  # Half a step of the diagonal, below which consecutive rows no longer overlap.
@@ -57,7 +57,7 @@ module DTW
57
57
  def self.bounds(_row, _rows, columns) = [1, columns]
58
58
  end
59
59
 
60
- # Admits warping of up to a quarter of the longer sequence, the usual setting for speech.
60
+ # Admits warping of up to a quarter of the longer sequence.
61
61
  DEFAULT_RATIO = 0.25
62
62
 
63
63
  DEFAULT = SakoeChiba.new(ratio: DEFAULT_RATIO)
@@ -13,7 +13,7 @@ module DTW
13
13
  def initialize(
14
14
  aligner: Aligner.new,
15
15
  aggregator: :median,
16
- dispersion: :median_absolute_deviation,
16
+ dispersion: :robust_sigma,
17
17
  iterations: DEFAULT_ITERATIONS,
18
18
  tolerance: DEFAULT_TOLERANCE,
19
19
  sample_size: Medoid::DEFAULT_SAMPLE_SIZE
@@ -7,6 +7,7 @@ module DTW
7
7
  def call(frames, length)
8
8
  raise ArgumentError, "resample length must be positive, got #{length}" unless length.positive?
9
9
  return [] if frames.empty?
10
+ return Sequence.scalarize(call(Sequence.vectorize(frames), length)) if Sequence.scalar?(frames)
10
11
  return Array.new(length) { frames.first.map(&:to_f) } if frames.length == 1 || length == 1
11
12
 
12
13
  last = frames.length - 1
@@ -11,7 +11,31 @@ module DTW
11
11
  def vectorize(sequence)
12
12
  raise InvalidSequenceError, "expected an Array of frames, got #{sequence.class}" unless sequence.is_a?(Array)
13
13
 
14
- scalar?(sequence) ? sequence.map { |value| [value] } : sequence
14
+ if scalar?(sequence)
15
+ sequence.map do |value|
16
+ assert_finite!(value) unless value.is_a?(Float) && value.finite?
17
+ [value]
18
+ end
19
+ else
20
+ # A NaN or an infinity makes the sum non-finite; overflow and TypeError fall back to the exact check.
21
+ sequence.each { |frame| assert_frame!(frame) unless frame.is_a?(Array) && frame.sum(0.0).finite? }
22
+ end
23
+
24
+ rescue TypeError
25
+ sequence.each { |frame| assert_frame!(frame) }
26
+ end
27
+
28
+ def assert_frame!(frame)
29
+ raise InvalidSequenceError, "cannot mix scalar values and vector frames in one sequence" unless frame.is_a?(Array)
30
+
31
+ frame.each { |value| assert_finite!(value) }
32
+ end
33
+
34
+ def assert_finite!(value)
35
+ raise InvalidSequenceError, "cannot mix scalar values and vector frames in one sequence" if value.is_a?(Array)
36
+ return if value.is_a?(Numeric) && value.real? && value.finite?
37
+
38
+ raise InvalidSequenceError, "expected a finite number, got #{value.inspect}"
15
39
  end
16
40
 
17
41
  def scalarize(frames) = frames.map(&:first)
@@ -6,6 +6,16 @@ module DTW
6
6
  # statistic a consistent estimator of sigma for normally distributed data.
7
7
  NORMAL_CONSISTENCY_SCALE = 1.4826
8
8
 
9
+ MEDIAN_ABSOLUTE_DEVIATION_NOTICE = "DTW::Statistics.median_absolute_deviation is deprecated: it returns 1.4826 * MAD, " \
10
+ "the same value as DTW::Statistics.robust_sigma; the raw MAD is robust_sigma / 1.4826"
11
+
12
+ DEPRECATED_ESTIMATORS = {
13
+ median_absolute_deviation: "estimator :median_absolute_deviation is deprecated, use :robust_sigma (same value)",
14
+ mad: "estimator :mad is deprecated, use :robust_sigma (same value)"
15
+ }.freeze
16
+
17
+ private_constant :MEDIAN_ABSOLUTE_DEVIATION_NOTICE, :DEPRECATED_ESTIMATORS
18
+
9
19
  module_function
10
20
 
11
21
  def median(values)
@@ -22,13 +32,18 @@ module DTW
22
32
  values.sum(0.0) / values.length
23
33
  end
24
34
 
25
- def median_absolute_deviation(values)
35
+ def robust_sigma(values)
26
36
  return 0.0 if values.length < 2
27
37
 
28
38
  center = median(values)
29
39
  NORMAL_CONSISTENCY_SCALE * median(values.map { |value| (value - center).abs })
30
40
  end
31
41
 
42
+ def median_absolute_deviation(values)
43
+ warn(MEDIAN_ABSOLUTE_DEVIATION_NOTICE, category: :deprecated, uplevel: 1) if Warning[:deprecated]
44
+ robust_sigma(values)
45
+ end
46
+
32
47
  def standard_deviation(values)
33
48
  return 0.0 if values.length < 2
34
49
 
@@ -39,11 +54,16 @@ module DTW
39
54
  ESTIMATORS = {
40
55
  median: method(:median),
41
56
  mean: method(:mean),
42
- median_absolute_deviation: method(:median_absolute_deviation),
43
- mad: method(:median_absolute_deviation),
57
+ robust_sigma: method(:robust_sigma),
58
+ median_absolute_deviation: method(:robust_sigma),
59
+ mad: method(:robust_sigma),
44
60
  standard_deviation: method(:standard_deviation)
45
61
  }.freeze
46
62
 
47
- def resolve(estimator) = Resolver.call(estimator, ESTIMATORS, "estimator")
63
+ def resolve(estimator)
64
+ notice = DEPRECATED_ESTIMATORS[estimator]
65
+ warn(notice, category: :deprecated) if notice && Warning[:deprecated]
66
+ Resolver.call(estimator, ESTIMATORS, "estimator")
67
+ end
48
68
  end
49
69
  end
data/lib/dtwrb/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DTW
4
- VERSION = "1.1.0"
4
+ VERSION = "1.2.0"
5
5
  end
data/sig/dtwrb.rbs CHANGED
@@ -54,6 +54,8 @@ module DTW
54
54
  def self.compact: (untyped) -> ::Array[sequence]
55
55
  def self.dimension_of: (frames) -> ::Integer
56
56
  def self.assert_uniform_dimension!: (::Array[frames]) -> ::Integer
57
+ def self.assert_frame!: (untyped) -> void
58
+ def self.assert_finite!: (untyped) -> void
57
59
  end
58
60
 
59
61
  class Sample
@@ -76,6 +78,13 @@ module DTW
76
78
 
77
79
  def self.median: (::Array[::Numeric]) -> ::Float?
78
80
  def self.mean: (::Array[::Numeric]) -> ::Float?
81
+
82
+ # Robust estimate of the standard deviation: 1.4826 * median(|x - median(x)|).
83
+ # The raw median absolute deviation is robust_sigma / 1.4826.
84
+ def self.robust_sigma: (::Array[::Numeric]) -> ::Float
85
+
86
+ # Deprecated alias of robust_sigma; returns the same scaled value, not the raw MAD.
87
+ %a{deprecated: Use DTW::Statistics.robust_sigma}
79
88
  def self.median_absolute_deviation: (::Array[::Numeric]) -> ::Float
80
89
  def self.standard_deviation: (::Array[::Numeric]) -> ::Float
81
90
  def self.resolve: (estimator) -> _Estimator
@@ -165,6 +174,7 @@ module DTW
165
174
 
166
175
  module Resampler
167
176
  def self.call: (frames, ::Integer) -> frames
177
+ | (::Array[::Numeric], ::Integer) -> ::Array[::Float]
168
178
  def self.interpolate: (frame, frame, ::Float) -> frame
169
179
  end
170
180
 
metadata CHANGED
@@ -1,10 +1,10 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: dtwrb
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.1.0
4
+ version: 1.2.0
5
5
  platform: ruby
6
6
  authors:
7
- - Den Patin
7
+ - Den Patin 丁丹旭
8
8
  bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
@@ -52,17 +52,19 @@ dependencies:
52
52
  - !ruby/object:Gem::Version
53
53
  version: '3.13'
54
54
  description: Elastic alignment of numeric time series under Dynamic Time Warping with
55
- a Sakoe-Chiba band constraint, DTW Barycenter Averaging (DBA) for computing a prototype
56
- sequence from a set of variable-length observations, approximate medoid selection,
57
- linear resampling and robust dispersion estimation via the median absolute deviation.
58
- Pure Ruby, no dependencies. Pluggable local distance (Euclidean, Manhattan, Chebyshev,
59
- cosine) and central-tendency estimator (median, arithmetic mean).
55
+ a Sakoe-Chiba, slanted or custom band constraint, DTW Barycenter Averaging (DBA)
56
+ for computing a prototype sequence from a set of variable-length observations, approximate
57
+ medoid selection, linear resampling and robust dispersion estimation via the scaled
58
+ median absolute deviation. Pure Ruby, no dependencies. Pluggable local distance
59
+ (Euclidean, Manhattan, Chebyshev, cosine) and central-tendency estimator (median,
60
+ arithmetic mean).
60
61
  email: hi@dpat.in
61
62
  executables: []
62
63
  extensions: []
63
64
  extra_rdoc_files: []
64
65
  files:
65
66
  - CHANGELOG.md
67
+ - CITATION.cff
66
68
  - LICENSE
67
69
  - README.md
68
70
  - lib/dtwrb.rb
@@ -83,7 +85,7 @@ files:
83
85
  - sig/dtwrb.rbs
84
86
  homepage: https://github.com/taiwancards/dtwrb
85
87
  licenses:
86
- - WTFPL
88
+ - MIT
87
89
  metadata:
88
90
  source_code_uri: https://github.com/taiwancards/dtwrb
89
91
  changelog_uri: https://github.com/taiwancards/dtwrb/blob/main/CHANGELOG.md
@@ -96,14 +98,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
96
98
  requirements:
97
99
  - - ">="
98
100
  - !ruby/object:Gem::Version
99
- version: '3.2'
101
+ version: '3.4'
100
102
  required_rubygems_version: !ruby/object:Gem::Requirement
101
103
  requirements:
102
104
  - - ">="
103
105
  - !ruby/object:Gem::Version
104
106
  version: '0'
105
107
  requirements: []
106
- rubygems_version: 4.0.17
108
+ rubygems_version: 4.0.20
107
109
  specification_version: 4
108
110
  summary: Dynamic Time Warping, DBA barycenter averaging and robust dispersion for
109
111
  numeric sequences