Debian Codegraph @

dwtools/DTW.cpp

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