Debian Codegraph @

dwtools/DTW.cpp

raw symbols SCIP
1 /* DTW.cpp
2 *
3 * Copyright (C) 1993-2023 David Weenink, 2017 Paul Boersma
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * ilong with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /*
20 djmw 20020813 GPL header
21 djmw 20050302 Path finder modified with sakoe-chiba band
22 djmw 20050305 DTW_to_Polygon
23 djmw 20050306 DTW_swapAxes
24 djmw 20050530 Added Matrices_to_DTW
25 djmw 20060909 DTW_getPathY linear behaviour outside domains.
26 djmw 20061205 Pitches_to_DTW
27 djmw 20061214 Changed info to Melder_writeLine<x> format.
28 djmw 20071012 Added: o_CAN_WRITE_AS_ENCODING.h
29 djmw 20071016 To Melder_error<n>
30 djmw 20071022 Extra comments + possible bug correction in DTW_Path_recode.
31 djmw 20071201 Melder_warning<n>.
32 djmw 20071204 DTW_and_Sounds_draw.
33 djmw 20080122 float -> double
34 djmw 20081123 DTW_and_Sounds_checkDomains did not swap sounds correctly.
35 djmw 20091009 Removed a bug in DTW_Path_recode that could cause two identical x and y times in succession at the end.
36 djmw 20100504 extra check in DTW_Path_makeIndex
37 djmw 20110304 Thing_new
38 */
39
40 #include "DTW.h"
41 #include "Sound_extensions.h"
42 #include "NUM2.h"
43 #include "NUMmachar.h"
44
45 #include "oo_DESTROY.h"
46 #include "DTW_def.h"
47 #include "oo_COPY.h"
48 #include "DTW_def.h"
49 #include "oo_EQUAL.h"
50 #include "DTW_def.h"
51 #include "oo_CAN_WRITE_AS_ENCODING.h"
52 #include "DTW_def.h"
53 #include "oo_WRITE_TEXT.h"
54 #include "DTW_def.h"
55 #include "oo_WRITE_BINARY.h"
56 #include "DTW_def.h"
57 #include "oo_READ_TEXT.h"
58 #include "DTW_def.h"
59 #include "oo_READ_BINARY.h"
60 #include "DTW_def.h"
61 #include "oo_DESCRIPTION.h"
62 #include "DTW_def.h"
63
64 Thing_implement (DTW, Matrix, 2);
65
66 #define DTW_BIG 1e308
67
68 void structDTW :: v1_info () {
69 structDaata :: v1_info ();
70 MelderInfo_writeLine (U"Domain of prototype: ", ymin, U" to ", ymax, U" (s)."); // ppgb: Wat is een domain prototype?
71 MelderInfo_writeLine (U"Domain of candidate: ", xmin, U" to ", xmax, U" (s)."); // ppgb: Wat is een domain candidate?
72 MelderInfo_writeLine (U"Number of frames in prototype: ", ny);
73 MelderInfo_writeLine (U"Number of frames in candidate: ", nx);
74 MelderInfo_writeLine (U"Path length (frames): ", pathLength);
75 MelderInfo_writeLine (U"Global warped distance: ", weightedDistance);
76 if (nx == ny) {
77 double dd = 0;
78 for (integer i = 1; i <= nx; i ++) {
79 dd += z [i] [i];
80 }
81 MelderInfo_writeLine (U"Distance along diagonal: ", dd / nx);
82 }
83 }
84
85 static void DTW_drawPath_raw (DTW me, Graphics g, double xmin, double xmax, double ymin, double ymax, bool garnish, bool inset);
86 static void DTW_paintDistances_raw (DTW me, Graphics g, double xmin, double xmax, double ymin, double ymax, double minimum, double maximum, bool garnish, bool inset);
87 static double _DTW_Sounds_getPartY (Graphics g, double dtw_part_x);
88 static void DTW_findPath_special (DTW me, bool matchStart, bool matchEnd, int slope, autoMatrix *cumulativeDists);
89 /*
90 Two 'slope lines, lh and ll, start in the lower left corner, the upper/lower has the maximum/minimum allowed slope.
91 Two other lines, ru and rl, end in the upper-right corner. The upper/lower line have minimum/maximum slope.
92 1. the four lines with the two intersections determine a diamond
93 For vertical line at x we return the upper and lower y of the two intersections
94 1. When we don't have a diamond, we return an error and the vertical distance between the slopelines in ylow.
95 */
96
97
98 /*
99 The actual path will be interpolated as follows:
100 The distance matrix has cells of dimensions dx by dy.
101 The optimal path connects these cells with one another in the following way:
102
103 In a diagonal ''path'' segment, i.e. when cells have no side in common,
104 the interpolated path runs from the lowerleft corner to the upperright corner.
105 If a path segment is horizontal or vertical the path also runs from lowerleft to upperright.
106 It is only when a horizontal and a vertical segment have a cell in common that we have to make
107 some adjustments to the path in the common cell.
108 This will be done as follows:
109 Let nx and ny be the number of horizontal and vertical cells in this path segment.
110 The path will always start at the lowerleft of the leftmost block and end
111 at the upperright of the rightmost block.
112 In the common cell we have to introduce an extra point in the path at (x1,y1)
113 where the line from the horizontal segment and the line from the vertical segment intersect.
114 Let the lowerleft and upperright point of the common cell be (0,0) and (dx,dy),
115 then the coordinates (x,y) of the intersection can be calculated as follows:
116 If we have two lines y = a1*x+b1 and y = a2*x+b2 they intersect at
117 (x,y) = (b2-b1, a1*b2-a2*b1)/(a1-a2)
118 For horizontal-vertical (hv) cells:
119 a1 = dy/(nx*dx), a2 = ny*dy/dx
120 b1 = dy*(nx-1)/nx, b2 = 0
121 Then:
122 (x,y) = (dx, dy*ny ) * (nx-1)/(nx*ny-1)
123
124 For vertical-horizontal (vh) cells:
125 a1 = ny*dy/dx, a2 = dy/(nx*dx)
126 b1 = -(ny-1)*dy b2 = 0
127 Then:
128 (x,y) = (nx*dx, dy) * (ny-1)/(nx*ny-1)
129 */
130
131 /* DTW_getXTime (DTW me, (DTW_getYTime (DTW me, double tx)) == tx */
132 double DTW_getYTimeFromXTime (DTW me, double tx) {
133 double time = tx; // Catch cases where tier would give constant extrapolation
134 /*
135 If `eps` were zero, then the condition would rely on floating-point equality,
136 which is a bad idea (e.g. the result would be platform-dependent).
137 (fix ppgb 20240420, after this crashed on Windows only)
138 (rewind 20240501, because of retries in SpeechSynthesizer & Sound & TextGrid alignment)
139 */
140 const double eps = 0.0 * (my xmax - my xmin);
141 if (tx > my xmin + eps && tx < my xmax - eps) {
142 DTW_Path_Query thee = & my pathQuery;
143 time = RealTier_getValueAtTime (thy yfromx.get(), tx);
144 } else {
145 //TRACE
146 trace (U"Time set to ", tx, U" instead of between ", my xmin, U" and ", my xmax, U".");
147 }
148 return time;
149 }
150
151 double DTW_getXTimeFromYTime (DTW me, double ty) {
152 double time = ty; // Catch cases where tier would give constant extrapolation
153 /*
154 If `eps` were zero, then the condition would rely on floating-point equality,
155 which is a bad idea (e.g. the result would be platform-dependent).
156 (fix ppgb 20240420, after this crashed on Windows only)
157 (rewind 20240501, because of retries in SpeechSynthesizer & Sound & TextGrid alignment)
158 */
159 const double eps = 0.0 * (my ymax - my ymin);
160 if (ty > my ymin + eps && ty < my ymax - eps) {
161 DTW_Path_Query thee = & my pathQuery;
162 time = RealTier_getValueAtTime (thy xfromy.get(), ty);
163 }
164 return time;
165 }
166
167 void DTW_Path_Query_init (DTW_Path_Query me, integer ny, integer nx) {
168 Melder_assert (ny > 0 && nx > 0);
169 my ny = ny;
170 my nx = nx;
171 my nxy = 2 * std::max (ny, nx) + 2; // maximum number of points
172 my xfromy = Thing_new (RealTier);
173 my yfromx = Thing_new (RealTier);
174 }
175
176 /* Recode the path from a chain of cells to a piecewise linear path. */
177 void DTW_Path_recode (DTW me) {
178 try {
179 DTW_Path_Query thee = & my pathQuery;
180 integer nxy; // current number of elements in recoded path
181 integer nsc_x = 1; // current number of successive horizontal cells in the cells chain
182 integer nsc_y = 1; // current number of successive vertical cells in the cells chain
183 integer nd = 0; // current number of successive diagonal cells in the cells chain
184 bool yDirection = false; // previous segment in the original path was vertical
185 bool xDirection = false; // previous segment in the original path was horizontal
186 integer ixp = 0, iyp = 0; // previous cell
187 struct structPoint {
188 double x,y;
189 };
190
191 // 1. Starting point always at origin
192
193 const integer nxymax = thy nx + thy ny + 2;
194 autovector <structPoint> xytimes = newvectorzero <structPoint> (nxymax);
195 xytimes [1]. x = my xmin;
196 xytimes [1]. y = my ymin;
197
198 // 2. next point lower left of first cell
199
200 nsc_x = my path [1]. x;
201 ixp = nsc_x - 1;
202 xytimes [2]. x = my x1 + (nsc_x - 1 - 0.5) * my dx;
203 nsc_y = my path [1]. y;
204 iyp = nsc_y - 1;
205 xytimes [2]. y = my y1 + (nsc_y - 1 - 0.5) * my dy;
206
207 // 3. follow all cells. implicit: my x1 - 0.5 * my dx > my xmin && my y1 - 0.5 * my dy > my ymin */
208
209 nxy = 2;
210 for (integer j = 1; j <= my pathLength; j ++) {
211 const integer ix = my path [j]. x, iy = my path [j]. y;
212 const double xright = my x1 + (ix - 1 + 0.5) * my dx;
213 const double ytop = my y1 + (iy - 1 + 0.5) * my dy;
214 double x, y, f;
215 integer index; // where are we in the new path?
216
217 if (iy == iyp) { // horizontal path?
218 xDirection = true;
219 if (yDirection) {
220 // We came from a vertical direction so this is the second horizontal cell in a row.
221 // The statement after this "if" updates nsc_x to 2.
222 nsc_x = 1;
223 yDirection = false;
224 }
225 nsc_x ++;
226
227 if (nsc_y > 1 || nd > 1) {
228 // Previous segment was diagonal or vertical: modify intersection
229 // The vh intersection (x,y) = (nsc_x*dx, dy) * (nsc_y-1)/(nsc_x*nsc_y-1)
230 // A diagonal segment has nsc_y = 1.
231 f = (nsc_y - 1.0) / (nsc_x * nsc_y - 1);
232 x = xright - nsc_x * my dx + nsc_x * my dx * f;
233 y = ytop - my dy + my dy * f;
234 index = nxy - 1;
235 if (nsc_x == 2)
236 index = nxy ++;
237
238 xytimes [index]. x = x;
239 xytimes [index]. y = y;
240 }
241 nd = 0;
242 } else if (ix == ixp) { // vertical
243 yDirection = true;
244 if (xDirection) {
245 nsc_y = 1;
246 xDirection = false;
247 }
248 nsc_y ++;
249
250 if (nsc_x > 1 || nd > 1) {
251 // The hv intersection (x,y) = (dx, dy*nsc_y ) * (nsc_x-1)/(nsc_x*nsc_y-1)
252 f = (nsc_x - 1.0) / (nsc_x * nsc_y - 1);
253 x = xright - my dx + my dx * f;
254 y = ytop - nsc_y * my dy + nsc_y * my dy * f;
255 index = nxy - 1;
256 if (nsc_y == 2)
257 index = nxy ++;
258 xytimes [index]. x = x;
259 xytimes [index]. y = y;
260 }
261 nd = 0;
262 } else if (ix == ixp + 1 && iy == iyp + 1) { // diagonal
263 nd ++;
264 if (nd == 1)
265 nxy ++;
266 nsc_x = nsc_y = 1;
267 } else {
268 Melder_throw (U"The path goes back in time.");
269 }
270 // update
271 xytimes [nxy]. x = xright;
272 xytimes [nxy]. y = ytop;
273 ixp = ix;
274 iyp = iy;
275 }
276
277 if (my xmax > xytimes [nxy].x || my ymax > xytimes [nxy].y) {
278 xytimes [++ nxy]. x = my xmax;
279 xytimes [nxy]. y = my ymax;
280 }
281 Melder_assert (nxy <= 2 * std::max (my ny, my nx) + 2);
282
283 thy nxy = nxy;
284 thy yfromx = RealTier_create (my xmin, my xmax);
285 thy xfromy = RealTier_create (my ymin, my ymax);
286 for (integer i = 1; i <= nxy; i ++) {
287 RealTier_addPoint (thy yfromx.get(), xytimes [i]. x, xytimes [i]. y);
288 RealTier_addPoint (thy xfromy.get(), xytimes [i]. y, xytimes [i]. x);
289 }
290 } catch (MelderError) {
291 Melder_throw (me, U": not recoded.");
292 }
293 }
294
295 void DTW_pathRemoveRedundantNodes (DTW me) {
296 integer i = 1, skip = 0;
297
298 for (integer j = 2; j <= my pathLength; j ++) {
299 if (my path [j]. y == my path [i]. y || my path [j]. x == my path [i]. x)
300 skip ++;
301 else {
302 /* if (j-1)^th was the last of a series: store it */
303 if (skip > 0)
304 my path [++ i] = my path [j - 1];
305 /* same check again */
306 skip = 0;
307 if (my path [j]. y == my path [i]. y || my path [j]. x == my path [i]. x)
308 skip ++;
309 else
310 my path [++ i] = my path [j];
311 }
312 }
313 if (skip > 0)
314 my path [++ i] = my path [my pathLength];
315 my pathLength = i;
316 my path.resize (my pathLength); // maintain invariant
317 }
318
319 /* Prototype must be on y-axis and test on x-axis */
320
321 autoDTW DTW_create (double tminp, double tmaxp, integer ntp, double dtp, double t1p, double tminc, double tmaxc, integer ntc, double dtc, double t1c) {
322 try {
323 autoDTW me = Thing_new (DTW);
324 Matrix_init (me.get(), tminc, tmaxc, ntc, dtc, t1c, tminp, tmaxp, ntp, dtp, t1p);
325 my path = newvectorzero <structDTW_Path> (ntc + ntp - 1);
326 DTW_Path_Query_init (& my pathQuery, ntp, ntc);
327 my wx = 1;
328 my wy = 1;
329 my wd = 2;
330 return me;
331 } catch (MelderError) {
332 Melder_throw (U"DTW not created.");
333 }
334 }
335
336 void DTW_setWeights (DTW me, double wx, double wy, double wd) {
337 my wx = wx;
338 my wy = wy;
339 my wd = wd;
340 }
341
342 autoDTW DTW_swapAxes (DTW me) {
343 try {
344 autoDTW thee = DTW_create (my xmin, my xmax, my nx, my dx, my x1, my ymin, my ymax, my ny, my dy, my y1);
345
346 transpose_MAT_out (thy z.get(), my z.get());
347
348 thy pathLength = my pathLength;
349 for (integer i = 1; i <= my pathLength; i ++) {
350 thy path [i]. x = my path [i]. y;
351 thy path [i]. y = my path [i]. x;
352 }
353 thy path.resize (thy pathLength); // maintain invariant
354 return thee;
355 } catch (MelderError) {
356 Melder_throw (me, U": axes not swapped.");
357 }
358 }
359
360 double DTW_getPathY (DTW me, double tx) {
361 // Assume linear behaviour outside domains
362 // Other option: scale with x_domain/y_domain
363
364 if (tx < my xmin)
365 return my ymin - (my xmin - tx);
366 if (tx > my xmax)
367 return my ymax + (tx - my xmax);
368
369
370 // Find column in DTW matrix
371
372 integer ix = Melder_ifloor ((tx - my x1) / my dx) + 1;
373 if (ix < 1)
374 ix = 1;
375 if (ix > my nx)
376 ix = my nx;
377
378 // Find index in the path and the row number (iy)
379
380 integer i = ix + my path [1]. x - 1;
381 while (i <= my pathLength && my path [i]. x != ix)
382 i ++;
383
384 if (i > my pathLength)
385 return undefined;
386
387 const integer iy = my path [i]. y; /* row */
388
389 /*
390 We like to have a "continuous" interpretation of time for the quantized x and y times.
391 A time block is specified by lower left (x,y) and upper right (x+dx,y+dy).
392 The path is interpreted as piecewise linear.
393 Two special cases:
394 1. the local path is horizontal, i.e. two or more path elements with the same path.y value.
395 We calculate the y-time from the line that connects the lower-left position of the leftmost
396 horizontal time block to the upper-right position of the rightmost time horizontal block.
397 (lowest column number to highest column number)
398 For the first column and the last column we need to do something special if
399 2. the local path is vertical, i.e. two or path elements with the same path.x value.
400 We calculate the y-time from the line that connects the lower-left position of the bottommost
401 vertical time block to the upper-right position of the topmost time horizontal block.
402 (lowest row number to highest row number)
403 */
404
405 // Horizontal path? Find left and right positions.
406
407 integer ileft = i - 1;
408 while (ileft >= 1 && my path [ileft]. y == iy)
409 ileft --;
410
411 ileft ++;
412 if (ileft == 1 && ix > 1 && my path [ileft]. y > 1)
413 ileft ++;
414
415 integer iright = i + 1;
416 while (iright <= my pathLength && my path [iright]. y == iy)
417 iright ++;
418
419 iright --;
420 if (iright == my pathLength && ix < my nx && my path [iright]. y < my ny)
421 iright --;
422
423 integer nxx = iright - ileft + 1;
424
425 // Vertical path? Only if not already horizontal.
426
427 integer ibottom = i, itop = i;
428
429 if (nxx == 1) {
430 ibottom --;
431 while (ibottom >= 1 && my path [ibottom]. x == ix)
432 ibottom --;
433
434 ibottom ++;
435
436 itop ++;
437 while (itop <= 1 && my path [itop]. x == ix)
438 itop --;
439
440 itop ++;
441 }
442
443 const integer nyy = itop - ibottom + 1;
444 double boxx = nxx * my dx;
445 double boxy = nyy * my dy;
446 double ty;
447
448 // Corrections at extreme left and right if path [1].x=1 && path [1].y>1
449
450 if (ix == my nx) {
451 boxx = my xmax - (my x1 + (ix - 1) * my dx - my dx / 2.0);
452 boxy = my ymax - (my y1 + (iy - 1) * my dy - my dy / 2.0);
453 ty = my ymax - (boxy - (boxx - (my xmax - tx)) * boxy / boxx);
454 } else if (ix == 1) {
455 boxx = my x1 + my dx / 2.0 - my xmin;
456 boxy = my y1 + (itop - 1) * my dy + my dy / 2.0 - my ymin;
457 ty = (tx - my xmin) * boxy / boxx + my ymin;
458 } else {
459 // Diagonal interpolation in a box with lower left (0,0) and upper right (nxx*dx, nyy*dy).
460 const double ty0 = (tx - (my x1 + (my path [ileft]. x - 1.0) * my dx - my dx / 2.0)) * boxy / boxx;
461 ty = my y1 + (my path [ibottom]. y - 1.0) * my dy - my dy / 2.0 + ty0;
462 }
463 return ty;
464 }
465
466 integer DTW_getMaximumConsecutiveSteps (DTW me, int direction) {
467 integer nglobal = 1, nlocal = 1;
468 for (integer i = 2; i <= my pathLength; i ++) {
469 int localdirection;
470 if (my path [i]. y == my path [i - 1]. y)
471 localdirection = DTW_X;
472 else if (my path [i]. x == my path [i - 1]. x)
473 localdirection = DTW_Y;
474 else
475 localdirection = DTW_XANDY;
476 if (localdirection == direction)
477 nlocal += 1;
478 if (direction != localdirection || i == my pathLength) {
479 if (nlocal > nglobal)
480 nglobal = nlocal;
481 nlocal = 1;
482 }
483 }
484 return nglobal;
485 }
486
487 static void DTW_paintDistances_raw (DTW me, Graphics g, double xmin, double xmax, double ymin, double ymax, double minimum, double maximum, bool garnish, bool inset) {
488 integer ixmin, ixmax, iymin, iymax;
489 Function_unidirectionalAutowindow (me, & xmin, & xmax);
490 SampledXY_unidirectionalAutowindowY (me, & ymin, & ymax);
491 (void) Matrix_getWindowSamplesX (me, xmin - 0.49999 * my dx, xmax + 0.49999 * my dx, & ixmin, & ixmax);
492 (void) Matrix_getWindowSamplesY (me, ymin - 0.49999 * my dy, ymax + 0.49999 * my dy, & iymin, & iymax);
493 if (maximum <= minimum)
494 (void) Matrix_getWindowExtrema (me, ixmin, ixmax, iymin, iymax, & minimum, & maximum);
495
496 if (maximum <= minimum) {
497 minimum -= 1.0;
498 maximum += 1.0;
499 }
500 if (xmin >= xmax || ymin >= ymax)
501 return;
502 if (inset)
503 Graphics_setInner (g);
504 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
505 Graphics_cellArray (g, my z.part (iymin, iymax, ixmin, ixmax),
506 Matrix_columnToX (me, ixmin - 0.5), Matrix_columnToX (me, ixmax + 0.5),
507 Matrix_rowToY (me, iymin - 0.5), Matrix_rowToY (me, iymax + 0.5),
508 minimum, maximum);
509 Graphics_rectangle (g, xmin, xmax, ymin, ymax);
510 if (inset)
511 Graphics_unsetInner (g);
512 if (garnish) {
513 Graphics_marksBottom (g, 2, true, true, false);
514 Graphics_marksLeft (g, 2, true, true, false);
515 }
516 }
517
518 void DTW_paintDistances (DTW me, Graphics g, double xmin, double xmax, double ymin, double ymax, double minimum, double maximum, bool garnish) {
519 DTW_paintDistances_raw (me, g, xmin, xmax, ymin, ymax, minimum, maximum, garnish, true);
520 }
521
522 static double RealTier_getXAtIndex (RealTier me, integer ipoint) {
523 return ( ipoint > 0 && ipoint <= my points.size ? my points.at [ipoint] -> number : undefined );
524 }
525
526 static void DTW_drawPath_raw (DTW me, Graphics g, double xmin, double xmax, double ymin, double ymax, bool garnish, bool inset) {
527 DTW_Path_Query thee = & my pathQuery;
528
529 if (xmin >= xmax) {
530 xmin = my xmin;
531 xmax = my xmax;
532 }
533 if (ymin >= ymax) {
534 ymin = my ymin;
535 ymax = my ymax;
536 }
537
538 if (inset)
539 Graphics_setInner (g);
540
541 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
542 double x1 = RealTier_getXAtIndex (thy yfromx.get(), 1);
543 double y1 = RealTier_getValueAtIndex (thy yfromx.get(), 1);
544 for (integer i = 2; i <= thy yfromx -> points.size; i ++) {
545 const double x2 = RealTier_getXAtIndex (thy yfromx.get(), i);
546 const double y2 = RealTier_getValueAtIndex (thy yfromx.get(), i);
547 double xc1, yc1, xc2, yc2;
548 if (NUMclipLineWithinRectangle (x1, y1, x2, y2, xmin, ymin, xmax, ymax, & xc1, & yc1, & xc2, & yc2))
549 Graphics_line (g, xc1, yc1, xc2, yc2);
550
551 x1 = x2;
552 y1 = y2;
553 }
554
555 if (inset)
556 Graphics_unsetInner (g);
557
558 if (garnish) {
559 Graphics_drawInnerBox (g);
560 Graphics_marksBottom (g, 2, true, true, false);
561 Graphics_marksLeft (g, 2, true, true, false);
562 }
563 }
564
565 void DTW_drawPath (DTW me, Graphics g, double xmin, double xmax, double ymin, double ymax, bool garnish) {
566 DTW_drawPath_raw (me, g, xmin, xmax, ymin, ymax, garnish, true);
567 }
568
569 static void DTW_drawWarp_raw (DTW me, Graphics g, double xmin, double xmax, double ymin, double ymax, double t, bool garnish, bool inset, bool warpX) {
570 const double tx = ( warpX ? t : DTW_getXTimeFromYTime (me, t) );
571 const double ty = ( warpX ? DTW_getYTimeFromXTime (me, t) : t );
572 const int lineType = Graphics_inqLineType (g);
573
574 if (xmin >= xmax) {
575 xmin = my xmin;
576 xmax = my xmax;
577 }
578 if (ymin >= ymax) {
579 ymin = my ymin;
580 ymax = my ymax;
581 }
582
583 if (inset)
584 Graphics_setInner (g);
585
586 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
587
588 Graphics_setLineType (g, Graphics_DOTTED);
589 if (ty <= ymax) {
590 Graphics_line (g, tx, ymin, tx, ty);
591 Graphics_line (g, tx, ty, xmin, ty);
592 } else {
593 Graphics_line (g, tx, ymin, tx, ymax);
594 }
595
596 Graphics_setLineType (g, lineType);
597
598 if (inset)
599 Graphics_unsetInner (g);
600
601 if (garnish) {
602 Graphics_markBottom (g, tx, true, true, false, nullptr);
603 if (ty <= ymax)
604 Graphics_markLeft (g, ty, true, true, false, nullptr);
605 }
606 }
607
608 void DTW_drawWarpX (DTW me, Graphics g, double xmin, double xmax, double ymin, double ymax, double tx, bool garnish) {
609 DTW_drawWarp_raw (me, g, xmin, xmax, ymin, ymax, tx, garnish, true, true);
610 }
611
612 void DTW_drawWarpY (DTW me, Graphics g, double xmin, double xmax, double ymin, double ymax, double ty, bool garnish) {
613 DTW_drawWarp_raw (me, g, xmin, xmax, ymin, ymax, ty, garnish, true, false);
614 }
615
616 static void DTW_Sounds_checkDomains (DTW me, Sound *y, Sound *x, double *xmin, double *xmax, double *ymin, double *ymax) {
617 Melder_require ((my ymin == (*y) -> xmin && my ymax == (*y) -> xmax &&
618 my xmin == (*x) -> xmin && my xmax == (*x) -> xmax) ||
619 (my ymin == (*x) -> xmin && my ymax == (*x) -> xmax &&
620 my xmin == (*y) -> xmin && my xmax == (*y) -> xmax),
621 U"The domains of the DTW and the sound(s) should be equal.");
622
623 if (*xmin >= *xmax) {
624 *xmin = my xmin;
625 *xmax = my xmax;
626 }
627 if (*ymin >= *ymax) {
628 *ymin = my ymin;
629 *ymax = my ymax;
630 }
631 }
632
633 static void drawBox (Graphics g) {
634 double x1WC, x2WC, y1WC, y2WC;
635 const double lineWidth = Graphics_inqLineWidth (g);
636 Graphics_inqWindow (g, & x1WC, & x2WC, & y1WC, & y2WC);
637 Graphics_setLineWidth (g, 2.0 * lineWidth);
638 Graphics_rectangle (g, x1WC, x2WC, y1WC, y2WC);
639 Graphics_setLineWidth (g, lineWidth);
640 }
641
642 /*
643 In a picture with a DTW and a left and bottom Sound, we want "width" of the vertical sound
644 and the "height" of the horizontal Sound to be equal.
645 Given the horizontal fraction of the DTW-part, this routine returns the vertical part.
646 */
647 static double _DTW_Sounds_getPartY (Graphics g, double dtw_part_x) {
648 double x1NDC, x2NDC, y1NDC, y2NDC;
649 Graphics_inqViewport (g, & x1NDC, & x2NDC, & y1NDC, & y2NDC);
650 return 1.0 - (1.0 - dtw_part_x) * (x2NDC - x1NDC) / (y2NDC - y1NDC);
651 }
652
653 void DTW_Sounds_draw (DTW me, Sound y, Sound x, Graphics g, double xmin, double xmax, double ymin, double ymax, bool garnish) {
654 DTW_Sounds_checkDomains (me, & y, & x, & xmin, & xmax, & ymin, & ymax);
655
656 Graphics_setInner (g);
657 Graphics_Viewport ovp = g -> outerViewport; // save for unsetInner
658
659 const double dtw_part_x = 0.85;
660 const double dtw_part_y = _DTW_Sounds_getPartY (g, dtw_part_x);
661
662 // DTW
663
664 Graphics_Viewport vp = Graphics_insetViewport (g, 1.0 - dtw_part_x, 1.0, 1.0 - dtw_part_y, 1.0);
665 DTW_paintDistances_raw (me, g, xmin, xmax, ymin, ymax, 0.0, 0.0, false, false);
666 DTW_drawPath_raw (me, g, xmin, xmax, ymin, ymax, false, false);
667 drawBox (g);
668 Graphics_resetViewport (g, vp);
669
670 // Sound y
671
672 vp = Graphics_insetViewport (g, 0.0, 1.0 - dtw_part_x, 1.0 - dtw_part_y, 1.0);
673 Sound_draw_btlr (y, g, ymin, ymax, -1.0, 1.0, kSoundDrawingDirection::BOTTOM_TO_TOP, false);
674 if (garnish)
675 drawBox (g);
676 Graphics_resetViewport (g, vp);
677
678 // Sound x
679
680 vp = Graphics_insetViewport (g, 1 - dtw_part_x, 1, 0, 1 - dtw_part_y);
681 Sound_draw_btlr (x, g, xmin, xmax, -1.0, 1.0, kSoundDrawingDirection::LEFT_TO_RIGHT, false);
682 if (garnish)
683 drawBox (g);
684 Graphics_resetViewport (g, vp);
685
686
687 // Set window coordinates so that margins will work, i.e. extend time domains
688
689 const double xmin3 = xmax - (xmax - xmin) / dtw_part_x;
690 const double ymin3 = ymax - (ymax - ymin) / dtw_part_y;
691 Graphics_setWindow (g, xmin3, xmax, ymin3, ymax);
692
693 g -> outerViewport = ovp; // restore from _setInner
694 Graphics_unsetInner (g);
695
696 if (garnish) {
697 Graphics_markLeft (g, ymin, true, true, false, nullptr);
698 Graphics_markLeft (g, ymax, true, true, false, nullptr);
699 Graphics_markBottom (g, xmin, true, true, false, nullptr);
700 Graphics_markBottom (g, xmax, true, true, false, nullptr);
701 }
702 }
703
704 void DTW_Sounds_drawWarpX (DTW me, Sound yy, Sound xx, Graphics g, double xmin, double xmax, double ymin, double ymax, double tx, bool garnish)
705 {
706 Sound y = yy, x = xx;
707 const int lineType = Graphics_inqLineType (g);
708
709 DTW_Sounds_checkDomains (me, & y, & x, & xmin, & xmax, & ymin, & ymax);
710
711 Graphics_setInner (g);
712 const double dtw_part_x = 0.85;
713 const double dtw_part_y = _DTW_Sounds_getPartY (g, dtw_part_x);
714
715 xmin = xmax - (xmax - xmin) / dtw_part_x;
716 ymin = ymax - (ymax - ymin) / dtw_part_y;
717 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
718
719 const double ty = DTW_getYTimeFromXTime (me, tx);
720 Graphics_setLineType (g, Graphics_DOTTED);
721
722 Graphics_line (g, tx, ymin, tx, ty);
723 Graphics_line (g, tx, ty, xmin, ty);
724
725 Graphics_setLineType (g, lineType);
726
727 Graphics_unsetInner (g);
728
729 if (garnish) {
730 Graphics_markBottom (g, tx, true, true, false, nullptr);
731 Graphics_markLeft (g, ty, true, true, false, nullptr);
732 }
733 }
734
735 autoMatrix DTW_to_Matrix_distances (DTW me) {
736 try {
737 autoMatrix thee = Matrix_create (my xmin, my xmax, my nx, my dx, my x1, my ymin, my ymax, my ny, my dy, my y1);
738 thy z.all() <<= my z.all();
739 return thee;
740 } catch (MelderError) {
741 Melder_throw (me, U": distances not converted to Matrix.");
742 }
743 }
744
745 /* nog aanpassen, dl = sqrt (dx^2 + dy^2) */
746 void DTW_drawDistancesAlongPath (DTW me, Graphics g, double xmin, double xmax, double dmin, double dmax, bool garnish) {
747 Function_unidirectionalAutowindow (me, & xmin, & xmax);
748 integer ixmax, ixmin;
749 if (Matrix_getWindowSamplesX (me, xmin, xmax, & ixmin, & ixmax) == 0)
750 return;
751
752 integer ii = 1;
753 while (ii < my pathLength && my path [ii]. x < ixmin)
754 ii ++;
755 ixmin = ii;
756
757 while (ii <= my pathLength && my path [ii]. x < ixmax)
758 ii ++;
759 ixmax = ii;
760
761 const integer numberOfSelected = ixmax - ixmin + 1;
762 autoVEC d = raw_VEC (numberOfSelected);
763
764 for (integer i = ixmin; i <= ixmax; i ++)
765 d [i - ixmin + 1] = my z [my path [i]. y] [i];
766
767 if (dmin >= dmax) {
768 NUMextrema_u (d.get(), & dmin, & dmax);
769 if (isundef (dmin) || isundef (dmax))
770 return;
771 } else
772 VECclip_inplace (dmin, d.get(), dmax);
773
774 Graphics_setInner (g);
775 Graphics_setWindow (g, xmin, xmax, dmin, dmax);
776 Graphics_function (g, d.asArgumentToFunctionThatExpectsOneBasedArray(), 1, numberOfSelected, xmin, xmax);
777 Graphics_unsetInner (g);
778
779 if (garnish) {
780 Graphics_drawInnerBox (g);
781 Graphics_textLeft (g, true, U"distance");
782 Graphics_marksBottom (g, 2, true, true, false);
783 Graphics_marksLeft (g, 2, true, true, false);
784 }
785 }
786
787 /*
788 metric = 1...n (sum (a_i^n))^(1/n)
789 */
790 autoDTW Matrices_to_DTW (Matrix me, Matrix thee, bool matchStart, bool matchEnd, int slope, double metric) {
791 try {
792 Melder_require (thy ny == my ny,
793 U"Column sizes should be equal.");
794
795 autoDTW him = DTW_create (my xmin, my xmax, my nx, my dx, my x1, thy xmin, thy xmax, thy nx, thy dx, thy x1);
796 autoMelderProgress progess (U"Matrices to DTW: Calculate distances...");
797 for (integer i = 1; i <= my nx; i ++) {
798 for (integer j = 1; j <= thy nx; j ++) {
799 /*
800 First divide distance by maximum to prevent overflow when metric
801 is a large number.
802 d = (x^n)^(1/n) may overflow if x>1 & n >>1 even if d would not overflow!
803 */
804 double dmax = 0.0, d = 0.0;
805 for (integer k = 1; k <= my ny; k ++) {
806 const double dtmp = fabs (my z [k] [i] - thy z [k] [j]);
807 if (dtmp > dmax)
808 dmax = dtmp;
809 }
810 if (dmax > 0) {
811 for (integer k = 1; k <= my ny; k ++) {
812 const double dtmp = fabs (my z [k] [i] - thy z [k] [j]) / dmax;
813 d += pow (dtmp, metric);
814 }
815 }
816 d = dmax * pow (d, 1.0 / metric);
817 his z [i] [j] = d / my ny; // == d * dy / ymax
818 }
819 if ((i % 10) == 1) {
820 Melder_progress (0.999 * i / my nx, U"Calculate distances: column ", i, U" from ", my nx, U".");
821 }
822 }
823 DTW_findPath (him.get(), matchStart, matchEnd, slope);
824 return him;
825 } catch (MelderError) {
826 Melder_throw (U"DTW not created from matrices.");
827 }
828 }
829
830 autoDTW Spectrograms_to_DTW (Spectrogram me, Spectrogram thee, bool matchStart, bool matchEnd, int slope, double metric) {
831 try {
832 Melder_require (my xmin == thy xmin && my ymax == thy ymax && my ny == thy ny,
833 U"The number of frequencies and/or frequency ranges should be equal.");
834
835 autoMatrix m1 = Spectrogram_to_Matrix (me);
836 autoMatrix m2 = Spectrogram_to_Matrix (thee);
837
838 /*
839 Take log10 for dB's (4e-10 scaling not necessary)
840 */
841 for (integer i = 1; i <= my ny; i ++) {
842 for (integer j = 1; j <= my nx; j ++)
843 m1 -> z [i] [j] = 10.0 * log10 (m1 -> z [i] [j]);
844 }
845 for (integer i = 1; i <= thy ny; i ++) {
846 for (integer j = 1; j <= thy nx; j ++)
847 m2 -> z [i] [j] = 10.0 * log10 (m2 -> z [i] [j]);
848 }
849
850 autoDTW him = Matrices_to_DTW (m1.get(), m2.get(), matchStart, matchEnd, slope, metric);
851 return him;
852 } catch (MelderError) {
853 Melder_throw (U"DTW not created from Spectrograms.");
854 }
855 }
856
857 static int Pitch_findFirstAndLastVoicedFrame (Pitch me, integer *first, integer *last) {
858 *first = 1;
859 while (*first <= my nx && ! Pitch_isVoiced_i (me, *first))
860 (*first) ++;
861
862 *last = my nx;
863 while (*last >= *first && ! Pitch_isVoiced_i (me, *last))
864 (*last) --;
865
866 return *first <= my nx && *last >= 1;
867 }
868
869 autoDTW Pitches_to_DTW_sgc (Pitch me, Pitch thee, double vuv_costs, double time_weight, bool matchStart, bool matchEnd, int slope);
870 autoDTW Pitches_to_DTW_sgc (Pitch me, Pitch thee, double vuv_costs, double time_weight, bool matchStart, bool matchEnd, int slope) { // vuv_costs=24, time_weight=10 ?
871 try {
872 Melder_require (vuv_costs >= 0.0,
873 U"Voiced-unvoiced costs should not be negative.");
874 Melder_require (time_weight >= 0.0,
875 U"Time costs weight should not be negative.");
876
877 integer myfirst, mylast, thyfirst, thylast;
878 Melder_require (Pitch_findFirstAndLastVoicedFrame (me, & myfirst, & mylast) && Pitch_findFirstAndLastVoicedFrame (thee, & thyfirst, & thylast),
879 U"No voiced frames.");
880
881 /*
882 We do not want the silences before the first voiced frame and after the last voiced frame
883 to determine the distances.
884 We create paths from (1,1)...(thyfirst,myfirst) and (thylast,mylast)...(thy nx,my nx)
885 by making the other cell's distances very large.
886 */
887 autoDTW him = DTW_create (my xmin, my xmax, my nx, my dx, my x1, thy xmin, thy xmax, thy nx, thy dx, thy x1);
888 autoVEC pitchx = raw_VEC (thy nx);
889 kPitch_unit unit = kPitch_unit::SEMITONES_100;
890 for (integer j = 1; j <= thy nx; j ++)
891 pitchx [j] = Sampled_getValueAtSample (thee, j, Pitch_LEVEL_FREQUENCY, (int) unit);
892
893 for (integer i = 1; i <= my nx; i ++) {
894 const double pitchy = Sampled_getValueAtSample (me, i, Pitch_LEVEL_FREQUENCY, (int) unit);
895 const double t1 = my x1 + (i - 1) * my dx;
896 for (integer j = 1; j <= thy nx; j ++) {
897 const double t2 = thy x1 + (j - 1) * thy dx;
898 const double dist_t = fabs (t1 - t2);
899 double dist_f = 0.0; // based on pitch difference
900 if (isundef (pitchy)) {
901 if (isdefined (pitchx [j]))
902 dist_f = vuv_costs;
903 } else if (isundef (pitchx [j])) {
904 dist_f = vuv_costs;
905 } else {
906 dist_f = fabs (pitchy - pitchx [j]);
907 }
908 his z [i] [j] = sqrt (dist_f * dist_f + time_weight * dist_t * dist_t);
909 }
910 }
911 DTW_findPath (him.get(), matchStart, matchEnd, slope);
912 return him;
913 } catch (MelderError) {
914 Melder_throw (U"DTW not created from Pitches.");
915 }
916 }
917
918 autoDTW Pitches_to_DTW (Pitch me, Pitch thee, double vuv_costs, double time_weight, bool matchStart, bool matchEnd, int slope) { // vuv_costs=24, time_weight=10 ?
919 try {
920 Melder_require (vuv_costs >= 0.0,
921 U"Voiced-unvoiced costs should not be negative.");
922 Melder_require (time_weight >= 0.0,
923 U"Time costs weight should not be negative.");
924
925 autoDTW him = DTW_create (my xmin, my xmax, my nx, my dx, my x1, thy xmin, thy xmax, thy nx, thy dx, thy x1);
926 autoVEC pitchx = raw_VEC (thy nx);
927 kPitch_unit unit = kPitch_unit::SEMITONES_100;
928 for (integer j = 1; j <= thy nx; j ++)
929 pitchx [j] = Sampled_getValueAtSample (thee, j, Pitch_LEVEL_FREQUENCY, (int) unit);
930
931 for (integer i = 1; i <= my nx; i ++) {
932 const double pitchy = Sampled_getValueAtSample (me, i, Pitch_LEVEL_FREQUENCY, (int) unit);
933 const double t1 = my x1 + (i - 1) * my dx;
934 for (integer j = 1; j <= thy nx; j ++) {
935 const double t2 = thy x1 + (j - 1) * thy dx;
936 const double dist_t = fabs (t1 - t2);
937 double dist_f = 0; // based on pitch difference
938 if (isundef (pitchy)) {
939 if (isdefined (pitchx [j]))
940 dist_f = vuv_costs;
941 } else if (isundef (pitchx [j])) {
942 dist_f = vuv_costs;
943 } else {
944 dist_f = fabs (pitchy - pitchx [j]);
945 }
946 his z [i] [j] = sqrt (dist_f * dist_f + time_weight * dist_t * dist_t);
947 }
948 }
949
950 DTW_findPath (him.get(), matchStart, matchEnd, slope);
951 return him;
952 } catch (MelderError) {
953 Melder_throw (U"DTW not created from Pitches.");
954 }
955 }
956
957 autoDurationTier DTW_to_DurationTier (DTW /* me */) {
958 return autoDurationTier();
959 }
960
961 void DTW_Matrix_replace (DTW me, Matrix thee) {
962 try {
963 Melder_require (my xmin == thy xmin && my xmax == thy xmax && my ymin == thy ymin && my ymax == thy ymax,
964 U"The X and Y domains of the matrix and the DTW must be equal.");
965 Melder_require (my nx == thy nx && my dx == thy dx && my ny == thy ny && my dy == thy dy,
966 U"The sampling of the matrix and the DTW should be equal.");
967 double minimum, maximum;
968 Matrix_getWindowExtrema (me, 0, 0, 0, 0, & minimum, & maximum);
969 Melder_require (minimum >= 0.0,
970 U"Distances should not be negative.");
971 my z.all() <<= thy z.all();
972 } catch (MelderError) {
973 Melder_throw (me, U": distances not replaced.");
974 }
975 }
976
977 /****************** new implementation ********/
978
979 void DTW_findPath (DTW me, bool matchStart, bool matchEnd, int slope) {
980 DTW_findPath_special (me, matchStart, matchEnd, slope, nullptr);
981 }
982
983 autoMatrix DTW_to_Matrix_cumulativeDistances (DTW me, double sakoeChibaBand, int slope) {
984 try {
985 autoMatrix cumulativeDistances;
986 DTW_findPath_bandAndSlope (me, sakoeChibaBand, slope, & cumulativeDistances);
987 return cumulativeDistances;
988 } catch (MelderError) {
989 Melder_throw (me, U": cumulative costs matrix not created.");
990 }
991 }
992
993 static void DTW_relaxConstraints (DTW me, double band, int /* slope */, double *relaxedBand, int *relaxedSlope) {
994
995 //double dtw_slope = (my ymax - my ymin - band) / (my xmax - my xmin - band);
996 //dtw_slope = dtw_slope+1.0; // fake instruction to avoid compiler warning
997 *relaxedBand = 0.0;
998 *relaxedSlope = 1;
999 }
1000
1001 static void DTW_checkSlopeConstraints (DTW me, double band, int slope) {
1002 try {
1003 const double slopes [5] = { DTW_BIG, DTW_BIG, 3.0, 2.0, 1.5 } ;
1004 double dtw_slope = (my ymax - my ymin - band) / (my xmax - my xmin - band);
1005 Melder_require (slope > 0 && slope < 5,
1006 U"Invalid slope constraint.");
1007 Melder_require (! (dtw_slope == 0.0 && slope != 1),
1008 U"Band too wide.");
1009
1010 if (dtw_slope < 1.0)
1011 dtw_slope = 1.0 / dtw_slope;
1012
1013 Melder_require (dtw_slope <= slopes [slope],
1014 U"There is a conflict between the chosen slope constraint and the relative duration. "
1015 U"The duration ratio of the longest and the shortest object is ", dtw_slope,
1016 U". This implies that the largest slope in the constraint must have a value greater than or equal to this ratio."
1017 );
1018 } catch (MelderError) {
1019 Melder_throw (U"Slope constraints cannot be met.");
1020 }
1021 }
1022
1023 static void DTW_Polygon_setUnreachableParts (DTW me, Polygon thee, INTMAT const& psi) {
1024 try {
1025 const double eps = my dx / 100.0; // safe enough
1026 const double dtw_slope = (my ymax - my ymin) / (my xmax - my xmin);
1027
1028 double xmin, xmax, ymin, ymax;
1029 Polygon_getExtrema (thee, & xmin, & xmax, & ymin, & ymax);
1030 // if the Polygon and the DTW don't overlap everything is unreachable!
1031 Melder_require (! (xmax <= my xmin || xmin >= my xmax || ymax <= my ymin || ymin >= my ymax),
1032 U"DTW and Polygon don't overlap.");
1033
1034 // find border "above" polygon
1035 for (integer ix = 1; ix <= my nx; ix ++) {
1036 const double x = my x1 + (ix - 1) * my dx;
1037 const integer iystart = Melder_ifloor (dtw_slope * ix * (my dx / my dy)) + 1;
1038 for (integer iy = iystart + 1; iy <= my ny; iy ++) {
1039 const double y = my y1 + (iy - 1) * my dy;
1040 if (Polygon_getLocationOfPoint (thee, x, y, eps) == Polygon_OUTSIDE) {
1041 for (integer k = iy; k <= my ny; k ++)
1042 psi [k] [ix] = DTW_UNREACHABLE;
1043 break;
1044 }
1045 }
1046 }
1047 // find border "below" polygon
1048 for (integer ix = 2; ix <= my nx; ix ++) {
1049 const double x = my x1 + (ix - 1) * my dx;
1050 integer iystart = Melder_ifloor (dtw_slope * ix * (my dx / my dy)); // start 1 lower
1051 if (iystart > my ny)
1052 iystart = my ny;
1053 for (integer iy = iystart - 1; iy >= 1; iy --) {
1054 const double y = my y1 + (iy - 1) * my dy;
1055 if (Polygon_getLocationOfPoint (thee, x, y, eps) == Polygon_OUTSIDE) {
1056 for (integer k = iy; k >= 1; k --)
1057 psi [k] [ix] = DTW_UNREACHABLE;
1058 break;
1059 }
1060 }
1061 }
1062 } catch (MelderError) {
1063 Melder_throw (me, U" cannot set unreachable parts.");
1064 }
1065 }
1066
1067 #define DTW_ISREACHABLE(y,x) ((psi [y] [x] != DTW_UNREACHABLE) && (psi [y] [x] != DTW_FORBIDDEN))
1068 static void DTW_findPath_special (DTW me, bool /* matchStart */, bool /* matchEnd */, int slope, autoMatrix *cumulativeDists) {
1069 try {
1070 autoPolygon thee = DTW_to_Polygon (me, 0.0, slope);
1071 DTW_Polygon_findPathInside (me, thee.get(), slope, cumulativeDists);
1072 } catch (MelderError) {
1073 Melder_throw (me, U": cannot find path.");
1074 }
1075 }
1076
1077 /*
1078 Intersection of two straight lines y = a [i]*x+b [i], where a [2] = 1 / a [1]. Point (x1,y1) is on first line,
1079 point (x2,y2) is on second line.
1080 */
1081 static void getIntersectionPoint (double x1, double y1, double x2, double y2, double a, double *x3, double *y3) {
1082 *x3 = (y2 - y1 + a * x1 - x2 / a) / (a - 1.0 / a);
1083 *y3 = a * *x3 + y1 - a * x1;
1084 }
1085
1086 autoPolygon DTW_to_Polygon (DTW me, double band, int slope) {
1087 try {
1088 try {
1089 DTW_checkSlopeConstraints (me, band, slope);
1090 } catch (MelderError) {
1091 DTW_relaxConstraints (me, band, slope, & band, & slope);
1092 Melder_flushError ();
1093 }
1094
1095 double slopes [5] = { DTW_BIG, DTW_BIG, 3.0, 2.0, 1.5 } ;
1096 if (band <= 0) {
1097 if (slope == 1) {
1098 autoPolygon thee = Polygon_create (4);
1099 thy x [1] = my xmin;
1100 thy y [1] = my ymin;
1101 thy x [2] = my xmin;
1102 thy y [2] = my ymax;
1103 thy x [3] = my xmax;
1104 thy y [3] = my ymax;
1105 thy x [4] = my xmax;
1106 thy y [4] = my ymin;
1107 return thee;
1108 } else {
1109 autoPolygon thee = Polygon_create (4);
1110 thy x [1] = my xmin;
1111 thy y [1] = my ymin;
1112 thy x [3] = my xmax;
1113 thy y [3] = my ymax;
1114 double x, y;
1115 getIntersectionPoint (my xmin, my ymin, my xmax, my ymax, slopes [slope], & x, & y);
1116 if (x < my xmin)
1117 x = my xmin;
1118 if (x > my xmax)
1119 x = my xmax;
1120 if (y < my ymin)
1121 y = my ymin;
1122 if (y > my ymax)
1123 y = my ymax;
1124 thy x [2] = x;
1125 thy y [2] = y;
1126 getIntersectionPoint (my xmin, my ymin, my xmax, my ymax, 1.0 / slopes [slope], & x, & y);
1127 if (x < my xmin)
1128 x = my xmin;
1129 if (x > my xmax)
1130 x = my xmax;
1131 if (y < my ymin)
1132 y = my ymin;
1133 if (y > my ymax)
1134 y = my ymax;
1135 thy x [4] = x;
1136 thy y [4] = y;
1137 return thee;
1138 }
1139 } else {
1140 if (slope == 1) {
1141 autoPolygon thee = Polygon_create (6);
1142 thy x [1] = my xmin;
1143 thy y [1] = my ymin;
1144 thy x [2] = my xmin;
1145 thy y [2] = my ymin + band;
1146 thy x [3] = my xmax - band;
1147 thy y [3] = my ymax;
1148 thy x [4] = my xmax;
1149 thy y [4] = my ymax;
1150 thy x [5] = my xmax;
1151 thy y [5] = my ymax - band;
1152 thy x [6] = my xmin + band;
1153 thy y [6] = my ymin;
1154 return thee;
1155 } else {
1156 autoPolygon thee = Polygon_create (8);
1157 double x, y;
1158 thy x [1] = my xmin;
1159 thy y [1] = my ymin;
1160 thy x [2] = my xmin;
1161 thy y [2] = my ymin + band;
1162 getIntersectionPoint (my xmin, my ymin + band, my xmax - band, my ymax, slopes [slope], & x, & y);
1163 if (x < my xmin)
1164 x = my xmin;
1165 if (x > my xmax)
1166 x = my xmax;
1167 if (y < my ymin)
1168 y = my ymin;
1169 if (y > my ymax)
1170 y = my ymax;
1171 thy x [3] = x;
1172 thy y [3] = y;
1173 thy x [4] = my xmax - band;
1174 thy y [4] = my ymax;
1175 thy x [5] = my xmax;
1176 thy y [5]= my ymax;
1177 thy x [6] = my xmax;
1178 thy y [6] = my ymax - band;
1179 getIntersectionPoint (my xmin + band, my ymin, my xmax, my ymax - band, 1.0 / slopes [slope], & x, & y);
1180 if (x < my xmin)
1181 x = my xmin;
1182 if (x > my xmax)
1183 x = my xmax;
1184 if (y < my ymin)
1185 y = my ymin;
1186 if (y > my ymax)
1187 y = my ymax;
1188 thy x [7] = x;
1189 thy y [7] = y;
1190 thy x [8] = my xmin + band;
1191 thy y [8] = my ymin;
1192 return thee;
1193 }
1194 }
1195 } catch (MelderError) {
1196 Melder_throw (me, U" no Polygon created.");
1197 }
1198 }
1199
1200 autoMatrix DTW_Polygon_to_Matrix_cumulativeDistances (DTW me, Polygon thee, int localSlope) {
1201 try {
1202 autoMatrix cumulativeDistances;
1203 DTW_Polygon_findPathInside (me, thee, localSlope, & cumulativeDistances);
1204 return cumulativeDistances;
1205 } catch (MelderError) {
1206 Melder_throw (me, U": cumulative costs matrix not created from DTW and Polygon.");
1207 }
1208 }
1209
1210 void DTW_findPath_bandAndSlope (DTW me, double sakoeChibaBand, int localSlope, autoMatrix *cumulativeDists) {
1211 try {
1212 autoPolygon thee = DTW_to_Polygon (me, sakoeChibaBand, localSlope);
1213 DTW_Polygon_findPathInside (me, thee.get(), localSlope, cumulativeDists);
1214 } catch (MelderError) {
1215 Melder_throw (me, U" cannot determine the path.");
1216 }
1217 }
1218
1219 void DTW_Polygon_findPathInside (DTW me, Polygon thee, int localSlope, autoMatrix *cumulativeDists) {
1220 try {
1221 const double slopes [5] = { DTW_BIG, DTW_BIG, 3.0, 2.0, 1.5 };
1222 // if localSlope == 1 start of path is within 10% of minimum duration. Starts farther away
1223 integer delta_xy = std::min (my nx, my ny) / 10; // if localSlope == 1 start within 10% of
1224
1225 Melder_require (localSlope > 0 && localSlope < 5,
1226 U"Local slope parameter ", localSlope, U" not supported.");
1227
1228 autoMAT delta = copy_MAT (my z.get());
1229 autoINTMAT psi = zero_INTMAT (my ny, my nx);
1230 /*
1231 Start by making the outside unreachable.
1232 */
1233 for (integer j = 1; j <= my nx; j ++)
1234 psi [1] [j] = DTW_UNREACHABLE;
1235 for (integer i = 1; i <= my ny; i ++)
1236 psi [i] [1] = DTW_UNREACHABLE;
1237
1238 /*
1239 Make begin part of first column reachable.
1240 */
1241 const integer rowto = ( localSlope != 1 ? Melder_ifloor (slopes [localSlope]) + 1 : delta_xy );
1242 for (integer iy = 2; iy <= rowto; iy ++) {
1243 if (localSlope != 1) {
1244 delta [iy] [1] = delta [iy - 1] [1] + my z [iy] [1];
1245 psi [iy] [1] = DTW_Y;
1246 } else {
1247 psi [iy] [1] = DTW_START; // will be adapted by DTW_Polygon_setUnreachableParts
1248 }
1249 }
1250 /*
1251 Make begin part of first row reachable.
1252 */
1253 const integer colto = ( localSlope != 1 ? Melder_ifloor (slopes [localSlope]) + 1 : delta_xy );
1254 for (integer ix = 2; ix <= colto; ix ++) {
1255 if (localSlope != 1) {
1256 delta [1] [ix] = delta [1] [ix -1] + my z [1] [ix];
1257 psi [1] [ix] = DTW_X;
1258 } else {
1259 psi [1] [ix] = DTW_START; // will be adapted by DTW_Polygon_setUnreachableParts
1260 }
1261 }
1262
1263 /*
1264 Now we can set the unreachable parts from the Polygon.
1265 */
1266 DTW_Polygon_setUnreachableParts (me, thee, psi.get());
1267
1268 /*
1269 Forward pass.
1270 */
1271 integer numberOfIsolatedPoints = 0;
1272 autoMelderProgress progress (U"DTW & Polygon: Find path...");
1273 for (integer j = 2; j <= my nx; j ++) {
1274 for (integer i = 2; i <= my ny; i ++) {
1275 if (! DTW_ISREACHABLE (i, j))
1276 continue;
1277 double g, gmin = DTW_BIG;
1278 integer direction = 0;
1279 if (DTW_ISREACHABLE (i - 1, j - 1)) {
1280 gmin = delta [i - 1] [j - 1] + 2.0 * my z [i] [j];
1281 direction = DTW_XANDY;
1282 } else if (DTW_ISREACHABLE (i, j - 1)) {
1283 gmin = delta [i] [j - 1] + my z [i] [j];
1284 direction = DTW_X;
1285 } else if (DTW_ISREACHABLE (i - 1, j)) {
1286 gmin = delta [i - 1] [j] + my z [i] [j];
1287 direction = DTW_Y;
1288 } else {
1289 numberOfIsolatedPoints ++;
1290 continue;
1291 }
1292
1293 switch (localSlope) {
1294 case 1: { // no restriction
1295 if (DTW_ISREACHABLE (i, j - 1) && ((g = delta [i] [j - 1] + my z [i] [j]) < gmin)) {
1296 gmin = g;
1297 direction = DTW_X;
1298 }
1299 if (DTW_ISREACHABLE (i - 1, j) && ((g = delta [i - 1] [j] + my z [i] [j]) < gmin)) {
1300 gmin = g;
1301 direction = DTW_Y;
1302 }
1303 }
1304 break;
1305
1306 /*
1307 Sakoe & Chiba (1978) define the slope constraint measure as P = n / m,
1308 where n is the number of steps in the diagonal and
1309 m the number of steps in one of the other directions.
1310
1311 P = 1/2
1312 */
1313 case 2: { // P = 1/2
1314 if (j >= 4 && DTW_ISREACHABLE (i - 1, j - 3) && psi [i] [j - 1] == DTW_X && psi [i] [j - 2] == DTW_XANDY &&
1315 (g = delta [i-1] [j-3] + 2.0 * my z [i] [j-2] + my z [i] [j-1] + my z [i] [j]) < gmin) {
1316 gmin = g;
1317 direction = DTW_X;
1318 }
1319 if (j >= 3 && DTW_ISREACHABLE (i - 1, j - 2) && psi [i] [j - 1] == DTW_XANDY &&
1320 (g = delta [i - 1] [j - 2] + 2.0 * my z [i] [j - 1] + my z [i] [j]) < gmin) {
1321 gmin = g;
1322 direction = DTW_X;
1323 }
1324 if (i >= 3 && DTW_ISREACHABLE (i - 2, j - 1) && psi [i - 1] [j] == DTW_XANDY &&
1325 (g = delta [i - 2] [j - 1] + 2.0 * my z [i - 1] [j] + my z [i] [j]) < gmin) {
1326 gmin = g;
1327 direction = DTW_Y;
1328 }
1329 if (i >= 4 && DTW_ISREACHABLE (i - 3, j - 1) && psi [i - 1] [j] == DTW_Y && psi [i - 2] [j] == DTW_XANDY &&
1330 (g = delta [i-3] [j-1] + 2.0 * my z [i-2] [j] + my z [i-1] [j] + my z [i] [j]) < gmin) {
1331 gmin = g;
1332 direction = DTW_Y;
1333 }
1334 }
1335 break;
1336
1337 // P = 1
1338
1339 case 3: {
1340 if (j >= 3 && DTW_ISREACHABLE (i - 1, j - 2) && psi [i] [j - 1] == DTW_XANDY &&
1341 (g = delta [i - 1] [j - 2] + 2.0 * my z [i] [j - 1] + my z [i] [j]) < gmin)
1342 {
1343 gmin = g;
1344 direction = DTW_X;
1345 }
1346 if (i >= 3 && DTW_ISREACHABLE (i - 2, j - 1) && psi [i - 1] [j] == DTW_XANDY &&
1347 (g = delta [i - 2] [j - 1] + 2.0 * my z [i - 1] [j] + my z [i] [j]) < gmin)
1348 {
1349 gmin = g;
1350 direction = DTW_Y;
1351 }
1352 }
1353 break;
1354
1355 // P = 2
1356
1357 case 4: {
1358 if (i >= 3 && j >= 4 && DTW_ISREACHABLE (i - 2, j - 3) && psi [i] [j - 1] == DTW_XANDY && psi [i - 1] [j - 2] == DTW_XANDY &&
1359 (g = delta [i-2] [j-3] + 2.0 * my z [i-1] [j-2] + 2.0 * my z [i] [j-1] + my z [i] [j]) < gmin)
1360 {
1361 gmin = g;
1362 direction = DTW_X;
1363 }
1364 if (i >= 4 && j >= 3 && DTW_ISREACHABLE (i - 3, j - 2) && psi [i - 1] [j] == DTW_XANDY && psi [i - 2] [j - 1] == DTW_XANDY &&
1365 (g = delta [i-3] [j-2] + 2.0 * my z [i-2] [j-1] + 2.0 * my z [i-1] [j] + my z [i] [j]) < gmin)
1366 {
1367 gmin = g;
1368 direction = DTW_Y;
1369 }
1370 }
1371 break;
1372 default:
1373 break;
1374 }
1375 Melder_assert (direction != 0);
1376 psi [i] [j] = direction;
1377 delta [i] [j] = gmin;
1378 }
1379 if (j % 10 == 2)
1380 Melder_progress (0.999 * j / my nx, U"Calculate time warp: frame ", j, U" from ", my nx, U".");
1381 }
1382
1383 /*
1384 Find minimum at end of path and trace back.
1385 */
1386 integer iy = my ny;
1387 double minimum = delta [iy] [my nx];
1388 for (integer i = my ny - 1; i > 0; i --) {
1389 if (! DTW_ISREACHABLE (i, my nx)) {
1390 break; // we're in unreachable places
1391 } else if (delta [i] [my nx] < minimum) {
1392 minimum = delta [iy = i] [my nx];
1393 }
1394 }
1395
1396 integer pathIndex = my nx + my ny - 1; // maximum path length
1397 my weightedDistance = minimum / (my nx + my ny);
1398 my path [pathIndex]. y = iy;
1399 integer ix = my path [pathIndex]. x = my nx;
1400
1401 /*
1402 Fill path backwards.
1403 */
1404 while (ix > 1) {
1405 if (psi [iy] [ix] == DTW_XANDY) {
1406 ix --;
1407 iy --;
1408 } else if (psi [iy] [ix] == DTW_X) {
1409 ix --;
1410 } else if (psi [iy] [ix] == DTW_Y) {
1411 iy --;
1412 } else if (psi [iy] [ix] == DTW_START) {
1413 break;
1414 }
1415 if (pathIndex < 2 || iy < 1)
1416 break;
1417 //Melder_assert (pathIndex > 1 && iy > 0);
1418 my path [-- pathIndex]. x = ix;
1419 my path [pathIndex]. y = iy;
1420 }
1421
1422 my pathLength = my nx + my ny - 1 - pathIndex + 1;
1423 if (pathIndex > 1)
1424 for (integer j = 1; j <= my pathLength; j ++)
1425 my path [j] = my path [pathIndex ++];
1426 my path.resize (my pathLength); // maintain invariant
1427 DTW_Path_recode (me);
1428 if (cumulativeDists) {
1429 autoMatrix him = Matrix_create (my xmin, my xmax, my nx, my dx, my x1,
1430 my ymin, my ymax, my ny, my dy, my y1);
1431 his z.all() <<= delta.all();
1432 *cumulativeDists = him.move();
1433 }
1434 } catch (MelderError) {
1435 Melder_throw (me, U": cannot find path.");
1436 }
1437 }
1438
1439 /* End of file DTW.cpp */