Debian Codegraph @

dwtools/HMM.cpp

raw
1 /* HMM.cpp
2 *
3 * Copyright (C) 2010-2023 David Weenink, 2015,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 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18 /*
19 djmw 20110304 Thing_new
20 */
21
22 #include "Distributions_and_Strings.h"
23 #include "HMM.h"
24 #include "Index.h"
25 #include "NUM2.h"
26 #include "Strings_extensions.h"
27
28 #include "oo_DESTROY.h"
29 #include "HMM_def.h"
30 #include "oo_COPY.h"
31 #include "HMM_def.h"
32 #include "oo_EQUAL.h"
33 #include "HMM_def.h"
34 #include "oo_CAN_WRITE_AS_ENCODING.h"
35 #include "HMM_def.h"
36 #include "oo_WRITE_TEXT.h"
37 #include "HMM_def.h"
38 #include "oo_WRITE_BINARY.h"
39 #include "HMM_def.h"
40 #include "oo_READ_TEXT.h"
41 #include "HMM_def.h"
42 #include "oo_READ_BINARY.h"
43 #include "HMM_def.h"
44 #include "oo_DESCRIPTION.h"
45 #include "HMM_def.h"
46
47
48 #include "enums_getText.h"
49 #include "HMM_enums.h"
50 #include "enums_getValue.h"
51 #include "HMM_enums.h"
52
53 Thing_implement (HMM, Daata, 2);
54 Thing_implement (HMMState, Daata, 0);
55 Thing_implement (HMMStateList, Ordered, 0);
56 Thing_implement (HMMObservation, Daata, 0);
57 Thing_implement (HMMObservationList, Ordered, 0);
58 Thing_implement (HMMBaumWelch, Daata, 0);
59 Thing_implement (HMMViterbi, Daata, 0);
60 Thing_implement (HMMObservationSequence, Table, 0);
61 Thing_implement (HMMObservationSequenceBag, Collection, 0);
62 Thing_implement (HMMStateSequence, Strings, 0);
63
64 /*
65 Whenever a routine returns ln(p), the result for p=0 is -INFINITY.
66 On IEEE floating point hardware this number behaves reasonably.
67 This means that when the variable q equals INFINITY, q + a -> INFINITY,
68 where a is a finite number.
69 */
70
71 // helpers
72 autoHMMObservation HMMObservation_create (conststring32 label, integer numberOfComponents, integer dimension, kHMMstorage storage);
73
74 integer HMM_HMMObservationSequence_getLongestSequence (HMM me, HMMObservationSequence thee, integer symbolNumber);
75 integer StringsIndex_getLongestSequence (StringsIndex me, integer index, integer *out_pos);
76 integer Strings_getLongestSequence (Strings me, char32 *string, integer *out_pos);
77 autoHMMState HMMState_create (conststring32 label);
78
79 autoHMMBaumWelch HMMBaumWelch_create (integer nstates, integer nsymbols, integer capacity);
80 void HMMBaumWelch_getGamma (HMMBaumWelch me);
81 autoHMMBaumWelch HMM_forward (HMM me, constINTVEC obs);
82 void HMMBaumWelch_reInit (HMMBaumWelch me);
83 void HMM_HMMBaumWelch_getXi (HMM me, HMMBaumWelch thee, constINTVEC obs);
84 void HMM_HMMBaumWelch_reestimate (HMM me, HMMBaumWelch thee);
85 void HMM_HMMBaumWelch_addEstimate (HMM me, HMMBaumWelch thee, constINTVEC obs);
86 void HMM_HMMBaumWelch_forward (HMM me, HMMBaumWelch thee, constINTVEC obs);
87 void HMM_HMMBaumWelch_backward (HMM me, HMMBaumWelch thee, constINTVEC obs);
88 void HMM_HMMViterbi_decode (HMM me, HMMViterbi thee, constINTVEC obs);
89 double HMM_getProbabilityOfObservations (HMM me, constINTVEC obs);
90 autoTableOfReal StringsIndex_to_TableOfReal_transitions (StringsIndex me, int probabilities);
91 autoStringsIndex HMM_HMMStateSequence_to_StringsIndex (HMM me, HMMStateSequence thee);
92
93
94 autoHMMViterbi HMMViterbi_create (integer nstates, integer ntimes);
95
96 #if 0
97 static integer NUMget_line_intersection_with_circle (double xc, double yc, double r, double a, double b, double *out_x1, double *out_y1, double *out_x2, double *out_y2) {
98 const double ca = a * a + 1.0, bmyc = (b - yc);
99 const double cb = 2.0 * (a * bmyc - xc);
100 const double cc = bmyc * bmyc + xc * xc - r * r;
101 double x1, x2, y1, y2;
102 const integer nroots = NUMsolveQuadraticEquation (ca, cb, cc, & x1, & x2);
103 if (nroots == 1) {
104 y1 = a * x1 + b;
105 x2 = x1;
106 y2 = y1;
107 } else if (nroots == 2) {
108 if (x1 > x2)
109 std::swap (x1, x2);
110 y1 = x1 * a + b;
111 y2 = x2 * a + b;
112 }
113 if (out_x1)
114 *out_x1 = x1;
115 if (out_x2)
116 *out_x2 = x2;
117 if (out_y1)
118 *out_y1 = y1;
119 if (out_y2)
120 *out_y2 = y2;
121 return nroots;
122 }
123 #endif
124
125 // D(l_1,l_2)=1/n( log p(O_2|l_1) - log p(O_2|l_2)
126 static double HMM_HMM_getCrossEntropy_asym (HMM me, HMM thee, integer observationLength) {
127 autoHMMObservationSequence os = HMM_to_HMMObservationSequence (thee, 0, observationLength);
128 const double ce = HMM_HMMObservationSequence_getCrossEntropy (me, os.get());
129 if (isundef (ce))
130 return ce;
131 const double ce2 = HMM_HMMObservationSequence_getCrossEntropy (thee, os.get());
132 if (isundef (ce2))
133 return ce2;
134 return ce - ce2;
135 }
136
137 /**************** HMMObservation ******************************/
138
139 static void HMMObservation_init (HMMObservation me, conststring32 label, integer numberOfComponents, integer dimension, kHMMstorage storage) {
140 my label = Melder_dup (label);
141 my gm = GaussianMixture_create (numberOfComponents, dimension, storage == kHMMstorage::DIAGONALS ?
142 kGaussianMixtureStorage::DIAGONALS : kGaussianMixtureStorage::COMPLETE);
143 }
144
145 autoHMMObservation HMMObservation_create (conststring32 label, integer numberOfComponents, integer dimension, kHMMstorage storage) {
146 try {
147 autoHMMObservation me = Thing_new (HMMObservation);
148 HMMObservation_init (me.get(), label, numberOfComponents, dimension, storage);
149 return me;
150 } catch (MelderError) {
151 Melder_throw (U"HMMObservation not created.");
152 }
153 }
154
155 integer Strings_getLongestSequence (Strings me, char32 *string, integer *out_pos) {
156 integer length = 0, longest = 0, lpos = 0, pos = 0;
157 for (integer i = 1; i <= my numberOfStrings; i ++) {
158 if (Melder_equ (my strings [i].get(), string)) {
159 if (length == 0) {
160 lpos = i;
161 }
162 length ++;
163 } else {
164 if (length > 0) {
165 if (length > longest) {
166 longest = length;
167 pos = lpos;
168 }
169 length = 0;
170 }
171 }
172 }
173 if (out_pos)
174 *out_pos = pos;
175 return length;
176 }
177
178 integer StringsIndex_getLongestSequence (StringsIndex me, integer index, integer *out_pos) {
179 integer length = 0, longest = 0, lpos = 0, pos = 0;
180 for (integer i = 1; i <= my numberOfItems; i ++) {
181 if (my classIndex [i] == index) {
182 if (length == 0)
183 lpos = i;
184 length ++;
185 } else {
186 if (length > 0) {
187 if (length > longest) {
188 longest = length;
189 pos = lpos;
190 }
191 length = 0;
192 }
193 }
194 }
195 if (out_pos)
196 *out_pos = pos;
197 return length;
198 }
199
200 /**************** HMMState ******************************/
201
202 static void HMMState_init (HMMState me, conststring32 label) {
203 my label = Melder_dup (label);
204 }
205
206 autoHMMState HMMState_create (conststring32 label) {
207 try {
208 autoHMMState me = Thing_new (HMMState);
209 HMMState_init (me.get(), label);
210 return me;
211 } catch (MelderError) {
212 Melder_throw (U"HMMState not created.");
213 }
214 }
215
216 void HMMState_setLabel (HMMState me, char32 *label) {
217 my label = Melder_dup (label);
218 }
219
220 /**************** HMMBaumWelch ******************************/
221
222 autoHMMBaumWelch HMMBaumWelch_create (integer nstates, integer nsymbols, integer capacity) {
223 try {
224 autoHMMBaumWelch me = Thing_new (HMMBaumWelch);
225 my numberOfTimes = my capacity = capacity;
226 my numberOfStates = nstates;
227 my numberOfSymbols = nsymbols;
228 my alpha = zero_MAT (nstates, capacity);
229 my beta = zero_MAT (nstates, capacity);
230 my scale = zero_VEC (capacity);
231 my xi = zero_TEN3 (capacity, nstates, nstates); // TEN3
232 my aij_num_p0 = zero_VEC (nstates + 1);
233 my aij_num = zero_MAT (nstates, nstates + 1);
234 my aij_denom_p0 = zero_VEC (nstates + 1);
235 my aij_denom = zero_MAT (nstates, nstates + 1);
236 my bik_num = zero_MAT (nstates, nsymbols);
237 my bik_denom = zero_MAT (nstates, nsymbols);
238 my gamma = zero_MAT (nstates, capacity);
239 return me;
240 } catch (MelderError) {
241 Melder_throw (U"HMMBaumWelch not created.");
242 }
243 }
244
245 void HMMBaumWelch_getGamma (HMMBaumWelch me) {
246 for (integer it = 1; it <= my numberOfTimes; it ++) {
247 my gamma.column (it) <<= my alpha.column (it) * my beta.column (it);
248 my gamma.column (it) /= NUMsum (my gamma.column (it));
249 }
250 }
251
252 /**************** HMMViterbi ******************************/
253
254 autoHMMViterbi HMMViterbi_create (integer nstates, integer ntimes) {
255 try {
256 autoHMMViterbi me = Thing_new (HMMViterbi);
257 my numberOfTimes = ntimes;
258 my numberOfStates = nstates;
259 my viterbi = zero_MAT (nstates, ntimes);
260 my bp = zero_INTMAT (nstates, ntimes);
261 my path = zero_INTVEC (ntimes);
262 return me;
263 } catch (MelderError) {
264 Melder_throw (U"HMMViterbi not created.");
265 }
266 }
267
268 /******************* HMMObservationSequence & HMMStateSequence ***/
269
270 autoHMMObservationSequence HMMObservationSequence_create (integer numberOfItems, integer dataLength) {
271 try {
272 autoHMMObservationSequence me = Thing_new (HMMObservationSequence);
273 Table_initWithoutColumnNames (me.get(), numberOfItems, dataLength + 1);
274 return me;
275 } catch (MelderError) {
276 Melder_throw (U"HMMObservationSequence not created.");
277 }
278 }
279
280 integer HMMObservationSequence_getNumberOfObservations (HMMObservationSequence me) {
281 return my rows.size;
282 }
283
284 void HMMObservationSequence_removeObservation (HMMObservationSequence me, integer index) {
285 Table_removeRow (me, index);
286 }
287
288 autoStrings HMMObservationSequence_to_Strings (HMMObservationSequence me) {
289 try {
290 const integer numberOfStrings = my rows.size;
291 autoStrings thee = Thing_new (Strings);
292 thy strings = autoSTRVEC (numberOfStrings);
293 for (integer i = 1; i <= numberOfStrings; i ++)
294 thy strings [i] = Melder_dup (Table_getStringValue_a (me, i, 1));
295 thy numberOfStrings = numberOfStrings;
296 return thee;
297 } catch (MelderError) {
298 Melder_throw (me, U": no Strings created.");
299 }
300 }
301
302 autoHMMObservationSequence Strings_to_HMMObservationSequence (Strings me) {
303 try {
304 autoHMMObservationSequence thee = HMMObservationSequence_create (my numberOfStrings, 0);
305 for (integer i = 1; i <= my numberOfStrings; i ++)
306 Table_setStringValue (thee.get(), i, 1, my strings [i].get());
307 return thee;
308 } catch (MelderError) {
309 Melder_throw (me, U": no HMMObservationSequence created.");
310 }
311 }
312
313 autoStringsIndex HMMObservationSequence_to_StringsIndex (HMMObservationSequence me) {
314 try {
315 autoStrings s = HMMObservationSequence_to_Strings (me);
316 autoStringsIndex thee = Strings_to_StringsIndex (s.get(), kStrings_sorting::NUMBER_AWARE);
317 return thee;
318 } catch (MelderError) {
319 Melder_throw (me, U": no StringsIndex created.");
320 }
321 }
322
323 integer HMM_HMMObservationSequence_getLongestSequence (HMM me, HMMObservationSequence thee, integer symbolNumber) {
324 autoStringsIndex si = HMM_HMMObservationSequence_to_StringsIndex (me, thee);
325 // TODO
326 (void) symbolNumber;
327 return 1;
328 }
329
330 integer HMMObservationSequenceBag_getLongestSequence (HMMObservationSequenceBag me) {
331 integer longest = 0;
332 for (integer i = 1; i <= my size; i ++) {
333 HMMObservationSequence thee = my at [i];
334 if (thy rows.size > longest)
335 longest = thy rows.size;
336 }
337 return longest;
338 }
339
340 autoHMMStateSequence HMMStateSequence_create (integer numberOfItems) {
341 try {
342 autoHMMStateSequence me = Thing_new (HMMStateSequence);
343 my strings = autoSTRVEC (numberOfItems);
344 return me;
345 } catch (MelderError) {
346 Melder_throw (U"HMMStateSequence not created.");
347 }
348 }
349
350 autoStrings HMMStateSequence_to_Strings (HMMStateSequence me) {
351 try {
352 autoStrings thee = Thing_new (Strings);
353 my structStrings :: v1_copy (thee.get());
354 return thee;
355 } catch (MelderError) {
356 Melder_throw (me, U": no Strings created.");
357 }
358 }
359
360
361 /**************** HMM ******************************/
362
363 void structHMM :: v1_info () {
364 structDaata :: v1_info ();
365 MelderInfo_writeLine (U"Number of states: ", numberOfStates);
366 for (integer i = 1; i <= numberOfStates; i ++) {
367 const HMMState hmms = our states->at [i];
368 MelderInfo_writeLine (U" ", hmms -> label.get());
369 }
370 MelderInfo_writeLine (U"Number of symbols: ", numberOfObservationSymbols);
371 for (integer i = 1; i <= numberOfObservationSymbols; i ++) {
372 const HMMObservation hmms = our observationSymbols->at [i];
373 MelderInfo_writeLine (U" ", hmms -> label.get());
374 }
375 }
376
377 static void HMM_init (HMM me, integer numberOfStates, integer numberOfObservationSymbols, int leftToRight) {
378 my numberOfStates = numberOfStates;
379 my numberOfObservationSymbols = numberOfObservationSymbols;
380 my componentStorage = kHMMstorage::DIAGONALS;
381 my leftToRight = leftToRight;
382 my states = HMMStateList_create ();
383 my observationSymbols = HMMObservationList_create ();
384 my initialStateProbs = zero_VEC (numberOfStates);
385 my transitionProbs = zero_MAT (numberOfStates, numberOfStates + 1);
386 my emissionProbs = zero_MAT (numberOfStates, numberOfObservationSymbols);
387 HMM_setDefaultInitialStateProbs (me);
388 HMM_setDefaultTransitionProbs (me);
389 HMM_setDefaultEmissionProbs (me);
390 }
391
392 autoHMM HMM_create (int leftToRight, integer numberOfStates, integer numberOfObservationSymbols) {
393 try {
394 autoHMM me = Thing_new (HMM);
395 HMM_init (me.get(), numberOfStates, numberOfObservationSymbols, leftToRight);
396 HMM_setDefaultStates (me.get());
397 HMM_setDefaultObservations (me.get());
398 return me;
399 } catch (MelderError) {
400 Melder_throw (U"HMM not created.");
401 }
402 }
403
404 void HMM_setDefaultStates (HMM me) {
405 for (integer i = 1; i <= my numberOfStates; i ++) {
406 autoHMMState hmms = HMMState_create (Melder_cat (U"S", i));
407 HMM_addState_move (me, hmms.move());
408 }
409 }
410
411 autoHMM HMM_createFullContinuousModel (int leftToRight, integer numberOfStates, integer numberOfObservationSymbols, integer numberOfFeatureStreams, integer *dimensionOfStream, integer *numberOfGaussiansforStream) {
412 (void) leftToRight;
413 (void) numberOfStates;
414 (void) numberOfObservationSymbols;
415 (void) numberOfFeatureStreams;
416 (void) dimensionOfStream;
417 (void) numberOfGaussiansforStream;
418 return autoHMM();
419 }
420
421 autoHMM HMM_createContinuousModel (int leftToRight, integer numberOfStates, integer numberOfObservationSymbols, integer numberOfMixtureComponentsPerSymbol, integer componentDimension, kHMMstorage componentStorage) {
422 try {
423 autoHMM me = Thing_new (HMM);
424 HMM_init (me.get(), numberOfStates, numberOfObservationSymbols, leftToRight);
425 my numberOfMixtureComponents = numberOfMixtureComponentsPerSymbol;
426 my componentDimension = componentDimension;
427 my componentStorage = componentStorage;
428 for (integer i = 1; i <= numberOfStates; i ++) {
429 autoHMMState state = HMMState_create (Melder_cat (U"S", i));
430 HMM_addState_move (me.get(), state.move());
431 }
432 for (integer j = 1; j <= numberOfObservationSymbols; j ++) {
433 autoHMMObservation obs = HMMObservation_create (Melder_cat (U"s", j), numberOfMixtureComponentsPerSymbol, componentDimension, componentStorage);
434 HMM_addObservation_move (me.get(), obs.move());
435 }
436 return me;
437 } catch (MelderError) {
438 Melder_throw (U"Continuous model HMM not created.");
439 }
440 }
441
442 // for a simple non-hidden model leave either states empty or symbols empty !!!
443 autoHMM HMM_createSimple (int leftToRight, conststring32 states_string, conststring32 symbols_string) {
444 try {
445 autoSTRVEC states = splitByWhitespace_STRVEC (states_string);
446 autoSTRVEC symbols = splitByWhitespace_STRVEC (symbols_string);
447 autoHMM me = Thing_new (HMM);
448
449 Melder_require (states.size > 0 || symbols.size > 0,
450 U"The states and symbols should not both be empty.");
451
452 if (symbols.size == 0) {
453 symbols = copy_STRVEC (states.get());
454 my notHidden = 1;
455 }
456 if (states.size == 0) {
457 states = copy_STRVEC (symbols.get());
458 my notHidden = 1;
459 }
460
461 HMM_init (me.get(), states.size, symbols.size, leftToRight);
462
463 for (integer istate = 1; istate <= states.size; istate ++) {
464 autoHMMState state = HMMState_create (states [istate].get());
465 HMM_addState_move (me.get(), state.move());
466 }
467 for (integer isymbol = 1; isymbol <= symbols.size; isymbol ++) {
468 autoHMMObservation symbol = HMMObservation_create (symbols [isymbol].get(), 0, 0, kHMMstorage::DIAGONALS);
469 HMM_addObservation_move (me.get(), symbol.move());
470 }
471 return me;
472 } catch (MelderError) {
473 Melder_throw (U"Simple HMM not created.");
474 }
475 }
476
477 void HMM_setDefaultObservations (HMM me) {
478 const conststring32 def = ( my notHidden ? U"S" : U"s" );
479 for (integer i = 1; i <= my numberOfObservationSymbols; i ++) {
480 autoHMMObservation hmms = HMMObservation_create (Melder_cat (def, i), 0, 0, kHMMstorage::DIAGONALS);
481 HMM_addObservation_move (me, hmms.move());
482 }
483 }
484
485 void HMM_setDefaultTransitionProbs (HMM me) {
486 if (my leftToRight) {
487 for (integer irow = 1; irow <= my numberOfStates; irow ++) {
488 const double p = 1.0 / (my numberOfStates - irow + 1.0);
489 my transitionProbs.row (irow).part (irow, my numberOfStates) <<= p;
490 }
491 // leftToRight must have end state!
492 my transitionProbs [my numberOfStates] [my numberOfStates] =
493 my transitionProbs [my numberOfStates] [my numberOfStates + 1] = 0.5;
494 } else {
495 my transitionProbs.part (1, my numberOfStates, 1, my numberOfStates) <<= 1.0 / my numberOfStates;
496 my transitionProbs.column (my numberOfStates + 1) <<= 0.0;
497 }
498 }
499
500 void HMM_setDefaultInitialStateProbs (HMM me) {
501 my initialStateProbs.get () <<= 1.0 / my numberOfStates;
502 }
503
504 void HMM_setDefaultEmissionProbs (HMM me) {
505 if (my notHidden) {
506 my emissionProbs.get() <<= 0.0;
507 my emissionProbs.diagonal() <<= 1.0;
508 } else
509 my emissionProbs.part (1, my numberOfStates, 1, my numberOfObservationSymbols) <<= 1.0 / my numberOfObservationSymbols;
510 }
511
512 void HMM_setDefaultMixingProbabilities (HMM me) {
513 const double mp = 1.0 / my numberOfMixtureComponents;
514 for (integer is = 1; is <= my numberOfObservationSymbols; is ++) {
515 HMMObservation hmmo = my observationSymbols->at [is];
516 hmmo -> gm -> mixingProbabilities.all() <<= mp;
517 }
518 }
519
520 // evaluate the numbers given to probabilities
521 static autoVEC normalizeProbabilities_VEC (constVECVU const& relativeProbabilities, integer nwanted) {
522 if (relativeProbabilities.size != nwanted)
523 Melder_throw (U"You supplied ", relativeProbabilities.size, U" numbers, whereas we need ", nwanted, U" numbers.");
524 for (integer i = 1; i <= relativeProbabilities.size; i ++)
525 Melder_require (relativeProbabilities [i] >= 0.0,
526 U"Relative probabilities have to be non-negative.");
527 const double sum = NUMsum (relativeProbabilities);
528 Melder_require (sum > 0.0,
529 U"All probabilities cannot be zero.");
530 autoVEC absoluteProbabilities = copy_VEC (relativeProbabilities);
531 absoluteProbabilities.all() /= sum;
532 return absoluteProbabilities;
533 }
534
535 void HMM_setStartProbabilities (HMM me, constVECVU const& relativeProbabilities) {
536 try {
537 autoVEC absoluteProbabilities = normalizeProbabilities_VEC (relativeProbabilities, my numberOfStates);
538 my initialStateProbs.all() <<= absoluteProbabilities.all();
539 } catch (MelderError) {
540 Melder_throw (me, U": no start probabilities set.");
541 }
542 }
543
544 void HMM_setTransitionProbabilities (HMM me, integer state_number, constVECVU const& relativeProbabilities) {
545 try {
546 Melder_require (state_number <= my states->size,
547 U"State number should not exceed ", my states->size, U".");
548 autoVEC absoluteProbabilities = normalizeProbabilities_VEC (relativeProbabilities, my numberOfStates);
549 my transitionProbs.row (state_number).part (1, my numberOfStates) <<= absoluteProbabilities.all();
550 } catch (MelderError) {
551 Melder_throw (me, U": no transition probabilities set.");
552 }
553 }
554
555 void HMM_setEmissionProbabilities (HMM me, integer state_number, constVECVU const& relativeProbabilities) {
556 try {
557 Melder_require (state_number <= my states->size,
558 U"State number should not exceed ", my states->size, U".");
559 Melder_require (! my notHidden,
560 U"The emission probabilities of this model are fixed.");
561 autoVEC absoluteProbabilities = normalizeProbabilities_VEC (relativeProbabilities, my numberOfObservationSymbols);
562 my emissionProbs.row (state_number).part (1, my numberOfObservationSymbols) <<= absoluteProbabilities.all();
563 } catch (MelderError) {
564 Melder_throw (me, U": no emission probabilities set.");
565 }
566 }
567
568 void HMM_addObservation_move (HMM me, autoHMMObservation thee) {
569 const integer ns = my observationSymbols->size + 1;
570 Melder_require (ns <= my numberOfObservationSymbols, U"Observation list is full.");
571 my observationSymbols -> addItemAtPosition_move (thee.move(), ns);
572 }
573
574 void HMM_addState_move (HMM me, autoHMMState thee) {
575 const integer ns = my states->size + 1;
576 Melder_require (ns <= my numberOfStates, U"States list is full.");
577 my states -> addItemAtPosition_move (thee.move(), ns);
578 }
579
580 autoTableOfReal HMM_extractTransitionProbabilities (HMM me) {
581 try {
582 autoTableOfReal thee = TableOfReal_create (my numberOfStates + 1, my numberOfStates + 1);
583 thy data.row (1).part (1, my numberOfStates) <<= my initialStateProbs.get();
584 for (integer is = 1; is <= my numberOfStates; is ++) {
585 const HMMState hmms = my states->at [is];
586 TableOfReal_setRowLabel (thee.get(), is + 1, hmms -> label.get());
587 TableOfReal_setColumnLabel (thee.get(), is, hmms -> label.get());
588 thy data.row (is + 1).part (1, my numberOfStates) <<= my transitionProbs.row (is).part (1, my numberOfStates);
589 }
590 TableOfReal_setRowLabel (thee.get(), 1, U"START");
591 TableOfReal_setColumnLabel (thee.get(), my numberOfStates + 1, U"END");
592 //thy data.column (my numberOfStates + 1).part (2, my numberOfStates) <<= my transitionProbs.column (my numberOfStates + 1 );
593 for (integer is = 1; is <= my numberOfStates; is ++) {
594 thy data [is + 1] [my numberOfStates + 1] = my transitionProbs [is] [my numberOfStates + 1];
595 }
596 return thee;
597 } catch (MelderError) {
598 Melder_throw (me, U": no transition probabilities extracted.");
599 }
600 }
601
602 autoTableOfReal HMM_extractEmissionProbabilities (HMM me) {
603 try {
604 autoTableOfReal thee = TableOfReal_create (my numberOfStates, my numberOfObservationSymbols);
605 for (integer js = 1; js <= my numberOfObservationSymbols; js ++) {
606 const HMMObservation hmms = my observationSymbols->at [js];
607 TableOfReal_setColumnLabel (thee.get(), js, hmms -> label.get());
608 }
609 for (integer is = 1; is <= my numberOfStates; is ++) {
610 const HMMState hmms = my states->at [is];
611 TableOfReal_setRowLabel (thee.get(), is, hmms -> label.get());
612 for (integer js = 1; js <= my numberOfObservationSymbols; js ++)
613 thy data [is] [js] = my emissionProbs [is] [js];
614 }
615 return thee;
616 } catch (MelderError) {
617 Melder_throw (me, U": no emission probabilities extracted.");
618 };
619 }
620
621 double HMM_getExpectedValueOfDurationInState (HMM me, integer istate) {
622 if (istate < 0 || istate > my numberOfStates)
623 return undefined;
624 return 1.0 / (1.0 - my transitionProbs [istate] [istate]);
625 }
626
627 double HMM_getProbabilityOfStayingInState (HMM me, integer istate, integer numberOfTimeUnits) {
628 if (istate < 0 || istate > my numberOfStates)
629 return undefined;
630 return pow (my transitionProbs [istate] [istate], numberOfTimeUnits - 1.0) * (1.0 - my transitionProbs [istate] [istate]);
631 }
632
633 double HMM_HMM_getCrossEntropy (HMM me, HMM thee, integer observationLength, int symmetric) {
634 const double ce1 = HMM_HMM_getCrossEntropy_asym (me, thee, observationLength);
635 if (! symmetric || isundef (ce1))
636 return ce1;
637 const double ce2 = HMM_HMM_getCrossEntropy_asym (thee, me, observationLength);
638 if (isundef (ce2))
639 return ce2;
640 return (ce1 + ce2) / 2.0;
641 }
642
643 double HMM_HMM_HMMObservationSequence_getCrossEntropy (HMM me, HMM thee, HMMObservationSequence him) {
644 const double ce1 = HMM_HMMObservationSequence_getCrossEntropy (me, him);
645 if (isundef (ce1))
646 return ce1;
647 const double ce2 = HMM_HMMObservationSequence_getCrossEntropy (thee, him);
648 if (isundef (ce2))
649 return ce2;
650 return (ce1 + ce2) / 2.0;
651 }
652
653 void HMM_draw (HMM me, Graphics g, bool garnish) {
654 const double xwidth = sqrt (my numberOfStates);
655 const double rstate = 0.3 / xwidth, r = xwidth / 3.0;
656 const double xmax = 1.2 * xwidth / 2.0, xmin = -xmax, ymin = xmin, ymax = xmax;
657
658 autoVEC xs = raw_VEC (my numberOfStates);
659 autoVEC ys = raw_VEC (my numberOfStates);
660
661 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
662 // heuristic: all states on a circle until we have a better graph drawing algorithm.
663 xs [1] = ys [1] = 0.0;
664 if (my numberOfStates > 1) {
665 for (integer is = 1; is <= my numberOfStates; is ++) {
666 const double alpha = - NUMpi + NUMpi * 2.0 * (is - 1) / my numberOfStates;
667 xs [is] = r * cos (alpha); ys [is] = r * sin (alpha);
668 }
669 }
670 // reorder the positions such that state number 1 is most left and last state number is right.
671 // if > 5 may be one in the middle with the most connections
672 // ...
673 // find fontsize
674 const double fontSize = Graphics_inqFontSize (g);
675 conststring32 widest_label = U"";
676 double max_width = 0.0;
677 for (integer is = 1; is <= my numberOfStates; is ++) {
678 const HMMState hmms = my states->at [is];
679 const double w = ( hmms -> label ? Graphics_textWidth (g, hmms -> label.get()) : 0.0 );
680 if (w > max_width) {
681 widest_label = hmms -> label.get();
682 max_width = w;
683 }
684 }
685 double new_fontSize = fontSize;
686 while (max_width > 2.0 * rstate && new_fontSize > 4) {
687 new_fontSize --;
688 Graphics_setFontSize (g, new_fontSize);
689 max_width = Graphics_textWidth (g, widest_label);
690 }
691 Graphics_setFontSize (g, new_fontSize);
692 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
693 for (integer is = 1; is <= my numberOfStates; is ++) {
694 const HMMState hmms = my states->at [is];
695 Graphics_circle (g, xs [is], ys [is], rstate);
696 Graphics_text (g, xs [is], ys [is], hmms -> label.get());
697 }
698
699 // draw connections from is to js
700 // 1 -> 2 / 2-> : increase / decrease angle between 1 and 2 with pi /10
701 // use cos(a+b) and cos(a -b) rules
702 const double cosb = cos (NUMpi / 10.0), sinb = sin (NUMpi / 10.0);
703 for (integer is = 1; is <= my numberOfStates; is ++) {
704 const double x1 = xs [is], y1 = ys [is];
705 for (integer js = 1; js <= my numberOfStates; js ++) {
706 if (my transitionProbs [is] [js] > 0.0 && is != js) {
707 const double x2 = xs [js], y2 = ys [js];
708 const double dx = x2 - x1, dy = y2 - y1, h = sqrt (dx * dx + dy * dy), cosa = dx / h, sina = dy / h;
709 const double cosabp = cosa * cosb - sina * sinb, cosabm = cosa * cosb + sina * sinb;
710 const double sinabp = cosa * sinb + sina * cosb, sinabm = -cosa * sinb + sina * cosb;
711 Graphics_arrow (g, x1 + rstate * cosabp, y1 + rstate * sinabp, x2 - rstate * cosabm, y2 - rstate * sinabm);
712 }
713 if (is == js) {
714 const double dx = - x1, dy = - y1, h = sqrt (dx * dx + dy * dy), cosa = dx / h, sina = dy / h;
715 Graphics_doubleArrow (g, x1 - rstate * cosa, y1 - rstate * sina, x1 - 1.4 * rstate * cosa, y1 - 1.4 * rstate * sina);
716 }
717 }
718 }
719 if (garnish) {
720 Graphics_drawInnerBox (g);
721 }
722 }
723
724 void HMM_unExpandPCA (HMM me) {
725 if (my componentDimension <= 0)
726 return; // nothing to do
727 for (integer is = 1; is <= my numberOfObservationSymbols; is ++) {
728 const HMMObservation s = my observationSymbols->at [is];
729 GaussianMixture_unExpandPCA (s -> gm.get());
730 }
731 }
732
733 autoHMMObservationSequence HMM_to_HMMObservationSequence (HMM me, integer startState, integer numberOfItems) {
734 try {
735 autoHMMObservationSequence thee = HMMObservationSequence_create (numberOfItems, my componentDimension);
736 integer istate = ( startState == 0 ? NUMgetIndexFromProbability (my initialStateProbs.get(), NUMrandomUniform (0.0, 1.0)) : startState );
737 if (my componentDimension > 0) {
738 autoVEC obs = raw_VEC (my componentDimension);
739 autoVEC buf = raw_VEC (my componentDimension);
740 for (integer i = 1; i <= numberOfItems; i ++) {
741 // Emit a symbol from istate
742
743 const integer isymbol = NUMgetIndexFromProbability (my emissionProbs.row (istate), NUMrandomUniform (0.0, 1.0));
744 const HMMObservation s = my observationSymbols->at [isymbol];
745 GaussianMixture_generateOneVector_inline (s -> gm.get(), obs.get(), nullptr, buf.get());
746 for (integer j = 1; j <= my componentDimension; j ++)
747 Table_setNumericValue (thee.get(), i, 1 + j, obs [j]);
748
749 Table_setStringValue (thee.get(), i, 1, s -> label.get());
750
751 // get next state
752
753 istate = NUMgetIndexFromProbability (my transitionProbs.row (istate).part (1, my numberOfStates), NUMrandomUniform (0.0, 1.0));
754 if (istate == my numberOfStates + 1) { // final state
755 for (integer j = numberOfItems; j > i; j --)
756 HMMObservationSequence_removeObservation (thee.get(), j);
757 break;
758 }
759 }
760 } else {
761 for (integer i = 1; i <= numberOfItems; i ++) {
762 // Emit a symbol from istate
763
764 const integer isymbol = NUMgetIndexFromProbability (my emissionProbs.row (istate), NUMrandomUniform (0.0, 1.0));
765 HMMObservation s = my observationSymbols->at [isymbol];
766
767 Table_setStringValue (thee.get(), i, 1, s -> label.get());
768
769 // get next state
770
771 istate = NUMgetIndexFromProbability (my transitionProbs.row (istate).part (1, my numberOfStates), NUMrandomUniform (0.0, 1.0));
772 if (istate == my numberOfStates + 1) { // final state
773 for (integer j = numberOfItems; j > i; j --)
774 HMMObservationSequence_removeObservation (thee.get(), j);
775 break;
776 }
777 }
778 }
779
780 HMM_unExpandPCA (me);
781 return thee;
782 } catch (MelderError) {
783 HMM_unExpandPCA (me);
784 Melder_throw (me, U":no HMMObservationSequence created.");
785 }
786 }
787
788 autoHMMBaumWelch HMM_forward (HMM me, constINTVEC obs) {
789 try {
790 autoHMMBaumWelch thee = HMMBaumWelch_create (my numberOfStates, my numberOfObservationSymbols, obs.size);
791 HMM_HMMBaumWelch_forward (me, thee.get(), obs);
792 return thee;
793 } catch (MelderError) {
794 Melder_throw (me, U": no HMMBaumWelch created.");
795 }
796 }
797
798 static autoHMMViterbi HMM_to_HMMViterbi (HMM me, constINTVEC obs) {
799 try {
800 autoHMMViterbi thee = HMMViterbi_create (my numberOfStates, obs.size);
801 HMM_HMMViterbi_decode (me, thee.get(), obs);
802 return thee;
803 } catch (MelderError) {
804 Melder_throw (me, U": no HMMViterbi created.");
805 }
806 }
807
808 void HMMBaumWelch_reInit (HMMBaumWelch me) {
809 my totalNumberOfSequences = 0;
810 my lnProb = 0.0;
811
812 /*
813 The _num and _denum matrices are assigned as += in the iteration loop and therefore need to be zeroed
814 at the start of each new iteration.
815 The elements of alpha, beta, scale, gamma & xi are always calculated directly and need not be
816 initialised.
817 */
818 my aij_num_p0.all() <<= 0.0;
819 my aij_num.all() <<= 0.0;
820 my aij_denom_p0.all() <<= 0.0;
821 my aij_denom.all() <<= 0.0;
822 my bik_num.all() <<= 0.0;
823 my bik_denom.all() <<= 0.0;
824 }
825
826 static integer HMM_getState_notHidden (HMM me, conststring32 stateLabel) {
827 for (integer istate = 1; istate <= my states->size; istate ++)
828 if (Melder_cmp (my states -> at [istate] -> label.get(), stateLabel) == 0)
829 return istate;
830 return 0;
831 }
832
833 /*
834 Translate the observation sequences to a number of state sequences for not continuous markov models.
835 A 0 state number signals the start of a new observation sequence.
836 */
837 static autoINTVEC HMM_HMMObservationSequenceBag_getStateSequences (HMM me, HMMObservationSequenceBag thee) {
838 /*
839 Calculate storage needed for state sequence numbers.
840 */
841 integer numberOfElements = 0;
842 for (integer iseq = 1; iseq <= thy size; iseq ++) {
843 const HMMObservationSequence hmm_os = thy at [iseq];
844 numberOfElements += hmm_os -> rows.size + 1; // 1 extra for 0 state
845 }
846 /*
847 Get state sequence numbers.
848 */
849 autoINTVEC stateSequenceNumbers = raw_INTVEC (numberOfElements);
850 integer numberOfElements2 = 0;
851 for (integer iseq = 1; iseq <= thy size; iseq ++) {
852 const HMMObservationSequence hmm_os = thy at [iseq];
853 for (integer islabel = 1; islabel <= hmm_os -> rows.size; islabel ++) {
854 const conststring32 label = Table_getStringValue_a (hmm_os, islabel, 1);
855 const integer stateNumber = HMM_getState_notHidden (me, label);
856 Melder_require (stateNumber > 0,
857 U"The ", islabel, U"th observation of sequence ", iseq, U" labeled", label, U" is not a valid state.");
858 stateSequenceNumbers [++ numberOfElements2] = stateNumber;
859 }
860 stateSequenceNumbers [++ numberOfElements2] = 0; // signal transition to another observation sequence
861 }
862 Melder_assert (numberOfElements == numberOfElements2);
863 return stateSequenceNumbers;
864 }
865 #if 0
866 static void HMM_smoothInitialStateProbs_naive (HMM me, double minProb) {
867 for (integer is = 1; is <= my numberOfStates; is ++)
868 my initialStateProbs [is] = std::max (my initialStateProbs [is], minProb );
869 /*
870 Normalize again as probabilities
871 */
872 VECnormalize_inplace (my initialStateProbs.get(), 1.0, 1.0);
873 }
874
875 static void HMM_smoothTransitionProbs_naive (HMM me, double minProb) {
876 for (integer irow = 1; irow <= my numberOfStates; irow ++)
877 for (integer icol = 1; icol <= my numberOfStates; icol ++)
878 my transitionProbs [irow] [icol] = std::max (my transitionProbs [irow] [icol], minProb);
879 /*
880 Normalize again as probabilities
881 */
882 for (integer irow = 1; irow <= my numberOfStates; irow ++)
883 VECnormalize_inplace (my transitionProbs.row (irow).part (1, my numberOfStates), 1.0, 1.0);
884 }
885
886 static void HMM_smoothEmissionProbs_naive (HMM me, double minProb) {
887 for (integer is = 1; is <= my numberOfStates; is ++)
888 for (integer k = 1; k <= my numberOfObservationSymbols; k ++)
889 my emissionProbs [is] [k] = std::max (my emissionProbs [is] [k], minProb);
890 for (integer irow = 1; irow <= my numberOfStates; irow ++)
891 VECnormalize_inplace (my emissionProbs.row (irow).part (1, my numberOfStates), 1.0, 1.0);
892 }
893 #endif
894 /*
895 For a not hidden markov model there is an analytical solution for the state transition probabilities
896 */
897
898 static void HMM_HMMObservationSequenceBag_learn_notHidden (HMM me, HMMObservationSequenceBag thee, double minProb) {
899 Melder_assert (my notHidden);
900 autoINTVEC stateSequenceNumbers = HMM_HMMObservationSequenceBag_getStateSequences (me, thee);
901 if (stateSequenceNumbers.size < 2)
902 return;
903 my transitionProbs.all() <<= 0.0;
904 integer inum = 2;
905 integer stateNumber = stateSequenceNumbers [1];
906 while (inum < stateSequenceNumbers.size) {
907 const integer stateNumberTo = stateSequenceNumbers [inum ++];
908 if (stateNumberTo != 0) {
909 my transitionProbs [stateNumber] [stateNumberTo] += 1.0;
910 stateNumber = stateNumberTo;
911 } else {
912 if (inum == stateSequenceNumbers.size)
913 break;
914 stateNumber = stateSequenceNumbers [inum ++];
915 }
916 }
917 /*
918 Normalize as probabilities
919 */
920 for (integer irow = 1; irow <= my numberOfStates; irow ++)
921 VECnormalize_inplace (my transitionProbs.row (irow).part (1, my numberOfStates), 1.0, 1.0);
922 /* No need to set minimum probabilities */
923 }
924
925
926 void HMM_HMMObservationSequenceBag_learn (HMM me, HMMObservationSequenceBag thee, double delta_lnp, double minProb, int info) {
927 try {
928 if (my notHidden) {
929 // For a not hidden markov model there is an analytical solution for the state transition probabilities
930 HMM_HMMObservationSequenceBag_learn_notHidden (me, thee, minProb);
931 return;
932 }
933 // act as if all observation sequences are in memory
934 const integer capacity = HMMObservationSequenceBag_getLongestSequence (thee);
935 autoHMMBaumWelch bw = HMMBaumWelch_create (my numberOfStates, my numberOfObservationSymbols, capacity);
936 bw -> minProb = minProb;
937 if (info)
938 MelderInfo_open ();
939 integer iter = 0;
940 double lnp;
941 do {
942 lnp = bw -> lnProb;
943 HMMBaumWelch_reInit (bw.get());
944 for (integer iseq = 1; iseq <= thy size; iseq ++) {
945 const HMMObservationSequence hmm_os = thy at [iseq];
946 autoStringsIndex si = HMM_HMMObservationSequence_to_StringsIndex (me, hmm_os); // TODO outside the loop or more efficiently
947 INTVEC obs = si -> classIndex.get();
948 const integer nobs = si -> numberOfItems; // convenience
949
950 // Interpretation of unknowns: end of sequence
951
952 integer istart = 1, iend = nobs;
953 while (istart <= nobs) {
954 while (istart <= nobs && obs [istart] == 0)
955 istart ++;
956 if (istart > nobs) break;
957
958 iend = istart + 1;
959 while (iend <= nobs && obs [iend] != 0)
960 iend ++;
961 iend --;
962 bw -> numberOfTimes = iend - istart + 1;
963 bw -> totalNumberOfSequences ++;
964 HMM_HMMBaumWelch_forward (me, bw.get(), obs.part (istart, nobs)); // get new alphas
965 HMM_HMMBaumWelch_backward (me, bw.get(), obs.part (istart, nobs)); // get new betas
966 HMMBaumWelch_getGamma (bw.get());
967 HMM_HMMBaumWelch_getXi (me, bw.get(), obs.part (istart, nobs));
968 HMM_HMMBaumWelch_addEstimate (me, bw.get(), obs.part (istart, nobs));
969 istart = iend + 1;
970 }
971 }
972 // we have processed all observation sequences, now it is time to estimate new probabilities.
973 iter ++;
974 HMM_HMMBaumWelch_reestimate (me, bw.get());
975 if (info)
976 MelderInfo_writeLine (U"Iteration: ", iter, U" ln(prob): ", bw -> lnProb);
977 } while (fabs (lnp - bw -> lnProb) > std::max (fabs (delta_lnp * bw -> lnProb), NUMeps));
978 if (info) {
979 MelderInfo_writeLine (U"******** Learning summary *********");
980 MelderInfo_writeLine (U" Processed ", thy size, U" sequence", ( thy size > 1 ? U"s," : U"," ));
981 MelderInfo_writeLine (U" consisting of ", bw -> totalNumberOfSequences, U" observation sequence",
982 ( bw -> totalNumberOfSequences > 1 ? U"s." : U"." ));
983 MelderInfo_writeLine (U" Longest observation sequence had ", capacity, U" items.");
984 MelderInfo_close();
985 }
986 } catch (MelderError) {
987 Melder_throw (me, U" & ", thee, U": not learned.");
988 }
989 }
990
991
992 // xc1 < xc2
993 void HMM_HMMStateSequence_drawTrellis (HMM me, HMMStateSequence thee, Graphics g, bool connect, bool garnish) {
994 const integer numberOfTimes = thy numberOfStrings;
995 autoStringsIndex si = HMM_HMMStateSequence_to_StringsIndex (me, thee);
996 const double xmin = 0.0, xmax = numberOfTimes + 1.0, ymin = 0.5, ymax = my numberOfStates + 0.5;
997
998 Graphics_setInner (g);
999 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1000
1001 const double r = 0.2 / ( numberOfTimes > my numberOfStates ? numberOfTimes : my numberOfStates );
1002
1003 for (integer it = 1; it <= numberOfTimes; it ++) {
1004 for (integer js = 1; js <= my numberOfStates; js ++) {
1005 const double xc = it, yc = js, x2 = it, y2 = js;
1006 Graphics_circle (g, xc, yc, r);
1007 if (it > 1) {
1008 for (integer is = 1; is <= my numberOfStates; is ++) {
1009 const bool indexedConnection = si -> classIndex [it - 1] == is && si -> classIndex [it] == js;
1010 Graphics_setLineWidth (g, ( indexedConnection ? 2.0 : 1.0 ));
1011 Graphics_setLineType (g, ( indexedConnection ? Graphics_DRAWN : Graphics_DOTTED ));
1012 const double x1 = it - 1, y1 = is;
1013 if (connect || indexedConnection) {
1014 const double a = (y1 - y2) / (x1 - x2), b = y1 - a * x1;
1015 // double xs11 = x1 - r / (a * a + 1), ys11 = a * xs11 + b;
1016 const double xs12 = x1 + r / (a * a + 1), ys12 = a * xs12 + b;
1017 const double xs21 = x2 - r / (a * a + 1), ys21 = a * xs21 + b;
1018 // double xs22 = x2 + r / (a * a + 1), ys22 = a * xs22 + b;
1019 Graphics_line (g, xs12, ys12, xs21, ys21);
1020 }
1021 }
1022 }
1023 }
1024 }
1025 Graphics_unsetInner (g);
1026 Graphics_setLineWidth (g, 1.0);
1027 Graphics_setLineType (g, Graphics_DRAWN);
1028 if (garnish) {
1029 Graphics_drawInnerBox (g);
1030 for (integer js = 1; js <= my numberOfStates; js ++) {
1031 const HMMState hmms = my states->at [js];
1032 Graphics_markLeft (g, js, false, false, false, hmms -> label.get());
1033 }
1034 Graphics_marksBottomEvery (g, 1.0, 1.0, true, true, false);
1035 Graphics_textBottom (g, true, U"Time index");
1036 }
1037 }
1038
1039 void HMM_drawBackwardProbabilitiesIllustration (Graphics g, bool garnish) {
1040 const double xmin = 0.0, xmax = 1.0, ymin = 0.0, ymax = 1.0;
1041 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1042 const double xleft = 0.1, xright = 0.9, r = 0.03;
1043 const integer np = 6;
1044 const double dy = (1.0 - 0.3) / (np - 1);
1045 const double x0 = xleft, y0 = 0.5;
1046 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1047 Graphics_circle (g, x0, y0, r);
1048 const double x = xright;
1049 double y = 0.9;
1050 for (integer i = 1; i <= np; i ++) {
1051 if (i < 4 or i == np) {
1052 Graphics_circle (g, x, y, r);
1053 const double xx = x0 - x, yy = y - y0;
1054 const double c = hypot (xx, yy);
1055 const double cosa = xx / c, sina = yy / c;
1056 Graphics_line (g, x0 - r * cosa, y0 + r * sina, x + r * cosa, y - r * sina);
1057 } else if (i == 4) {
1058 const double ddy = 3.0 * dy / 4.0;
1059 Graphics_fillCircle (g, x, y + dy - ddy, 0.5 * r);
1060 Graphics_fillCircle (g, x, y + dy - 2.0 * ddy, 0.5 * r);
1061 Graphics_fillCircle (g, x, y + dy - 3.0 * ddy, 0.5 * r);
1062 }
1063 y -= dy;
1064 }
1065 if (garnish) {
1066 const double x1 = xright + 1.5 * r, x2 = x1 - 0.2;
1067 double y1 = 0.9;
1068
1069 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_HALF);
1070 Graphics_text (g, x1, y1, U"%s__1_");
1071 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1072 Graphics_text (g, x2, y1, U"%a__%i1_");
1073
1074 y1 = 0.9 - dy;
1075 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_HALF);
1076 Graphics_text (g, x1, y1, U"%s__2_");
1077 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1078 Graphics_text (g, x2, y1, U"%a__%i2_");
1079
1080 y1 = 0.9 - (np - 1) * dy;
1081 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_HALF);
1082 Graphics_text (g, x1, y1, U"%s__%N_");
1083 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1084 Graphics_text (g, x2, y1, U"%a__%%iN%_");
1085
1086 Graphics_setTextAlignment (g, Graphics_RIGHT, Graphics_HALF);
1087 Graphics_text (g, x0 - 1.5 * r, y0, U"%s__%i_");
1088
1089 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_BOTTOM);
1090 Graphics_text (g, x0, 0.0, U"%t");
1091 Graphics_text (g, x, 0.0, U"%t+1");
1092
1093 const double y3 = 0.10;
1094 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1095 Graphics_text (g, x0, y3, U"%\\be__%t_(%i)%");
1096 Graphics_text (g, x, y3, U"%\\be__%t+1_(%j)");
1097 }
1098 }
1099
1100 void HMM_drawForwardProbabilitiesIllustration (Graphics g, bool garnish) {
1101 constexpr double xmin = 0.0, xmax = 1.0, ymin = 0.0, ymax = 1.0;
1102 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1103 const double xleft = 0.1, xright = 0.9, r = 0.03;
1104 constexpr integer np = 6;
1105 const double dy = (1.0 - 0.3) / (np - 1);
1106 const double x0 = xright, y0 = 0.5;
1107 Graphics_setWindow (g, xmin, xmax, ymin, ymax);
1108 Graphics_circle (g, x0, y0, r);
1109 const double x = xleft;
1110 double y = 0.9;
1111 for (integer i = 1; i <= np; i ++) {
1112 if (i < 4 or i == np) {
1113 Graphics_circle (g, x, y, r);
1114 const double xx = x0 - x, yy = y - y0;
1115 const double c = hypot (xx, yy);
1116 const double cosa = xx / c, sina = yy / c;
1117 Graphics_line (g, x0 - r * cosa, y0 + r * sina, x + r * cosa, y - r * sina);
1118 } else if (i == 4) {
1119 const double ddy = 3.0 * dy / 4.0;
1120 Graphics_fillCircle (g, x, y + dy - ddy, 0.5 * r);
1121 Graphics_fillCircle (g, x, y + dy - 2.0 * ddy, 0.5 * r);
1122 Graphics_fillCircle (g, x, y + dy - 3.0 * ddy, 0.5 * r);
1123 }
1124 y -= dy;
1125 }
1126 if (garnish) {
1127 const double x1 = xleft - 1.5 * r, x2 = x1 + 0.2, y1 = 0.9;
1128
1129 Graphics_setTextAlignment (g, Graphics_RIGHT, Graphics_HALF);
1130 Graphics_text (g, x1, y1, U"%s__1_");
1131 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1132 Graphics_text (g, x2, y1, U"%a__1%j_");
1133
1134 const double y2 = 0.9 - dy;
1135 Graphics_setTextAlignment (g, Graphics_RIGHT, Graphics_HALF);
1136 Graphics_text (g, x1, y2, U"%s__2_");
1137 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1138 Graphics_text (g, x2, y2, U"%a__2%j_");
1139
1140 const double y3 = 0.9 - (np - 1) * dy;
1141 Graphics_setTextAlignment (g, Graphics_RIGHT, Graphics_HALF);
1142 Graphics_text (g, x1, y3, U"%s__%N_");
1143 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1144 Graphics_text (g, x2, y3, U"%a__%%Nj%_");
1145
1146 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_HALF);
1147 Graphics_text (g, x0 + 1.5 * r, y0, U"%s__%j_");
1148
1149 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_BOTTOM);
1150 Graphics_text (g, x, 0.0, U"%t");
1151 Graphics_text (g, x0, 0.0, U"%t+1");
1152
1153 const double y4 = 0.10;
1154 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_HALF);
1155 Graphics_text (g, x, y4, U"%\\al__%t_(%i)%");
1156 Graphics_text (g, x0, y4, U"%\\al__%t+1_(%j)");
1157 }
1158 }
1159
1160 void HMM_drawForwardAndBackwardProbabilitiesIllustration (Graphics g, bool garnish) {
1161 const double xfrac = 0.1, xs = 1.0 / (0.5 - xfrac), r = 0.03;
1162 Graphics_Viewport vp = Graphics_insetViewport (g, 0.0, 0.5-xfrac, 0.0, 1.0);
1163 HMM_drawForwardProbabilitiesIllustration (g, false);
1164 Graphics_resetViewport (g, vp);
1165 Graphics_insetViewport (g, 0.5 + xfrac, 1.0, 0.0, 1.0);
1166 HMM_drawBackwardProbabilitiesIllustration (g, false);
1167 Graphics_resetViewport (g, vp);
1168 Graphics_setWindow (g, 0.0, xs, 0.0, 1.0);
1169 if (garnish) {
1170 const double rx1 = 1.0 + xs * 2.0 * xfrac + 0.1, rx2 = rx1 + 0.9 - 0.1, y1 = 0.1;
1171 Graphics_line (g, 0.9 + r, 0.5, rx1 - r, 0.5);
1172 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_BOTTOM);
1173 Graphics_text (g, 0.9, 0.5 + r, U"%s__%i_");
1174 Graphics_text (g, rx1, 0.5 + r, U"%s__%j_");
1175 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_TOP);
1176 Graphics_text (g, 1.0 + xfrac * xs, 0.5, U"%a__%%ij%_%b__%j_(O__%t+1_)");
1177 Graphics_setTextAlignment (g, kGraphics_horizontalAlignment::CENTRE, Graphics_BOTTOM);
1178 Graphics_text (g, 0.1, 0.0, U"%t-1");
1179 Graphics_text (g, 0.9, 0.0, U"%t");
1180 Graphics_text (g, rx1, 0.0, U"%t+1");
1181 Graphics_text (g, rx2, 0.0, U"%t+2");
1182 Graphics_setLineType (g, Graphics_DASHED);
1183 const double x4 = rx1 - 0.06, x3 = 0.9 + 0.06;
1184 Graphics_line (g, x3, 0.7, x3, 0.0);
1185 Graphics_line (g, x4, 0.7, x4, 0.0);
1186 Graphics_setLineType (g, Graphics_DRAWN);
1187 Graphics_arrow (g, x4, y1, x4 + 0.2, y1);
1188 Graphics_arrow (g, x3, y1, x3 - 0.2, y1);
1189 Graphics_setTextAlignment (g, Graphics_RIGHT, Graphics_BOTTOM);
1190 Graphics_text (g, x3 - 0.01, y1, U"\\al__%t_(i)");
1191 Graphics_setTextAlignment (g, Graphics_LEFT, Graphics_BOTTOM);
1192 Graphics_text (g, x4 + 0.01, y1, U"\\be__%t+1_(j)");
1193 }
1194 }
1195
1196 void HMM_HMMBaumWelch_getXi (HMM me, HMMBaumWelch thee, constINTVEC obs) {
1197 Melder_assert (obs.size == thy numberOfTimes);
1198 for (integer it = 1; it <= thy numberOfTimes - 1; it ++) {
1199 longdouble sum = 0.0;
1200 MATVU xi_it = thy xi [it];
1201 for (integer is = 1; is <= thy numberOfStates; is ++) {
1202 for (integer js = 1; js <= thy numberOfStates; js ++) {
1203 xi_it [is] [js] = thy alpha [is] [it] * thy beta [js] [it + 1] *
1204 my transitionProbs [is] [js] * my emissionProbs [js] [ obs [it + 1] ];
1205 sum += xi_it [is] [js];
1206 }
1207 }
1208 xi_it /= double (sum);
1209 }
1210 }
1211
1212 void HMM_HMMBaumWelch_addEstimate (HMM me, HMMBaumWelch thee, constINTVEC obs) {
1213 Melder_assert (obs.size == thy numberOfTimes);
1214 for (integer is = 1; is <= my numberOfStates; is ++) {
1215 // only for valid start states with p > 0
1216 if (my initialStateProbs [is] > 0.0) {
1217 thy aij_num_p0 [is] += thy gamma [is] [1];
1218 thy aij_denom_p0 [is] += 1.0;
1219 }
1220 }
1221
1222 for (integer is = 1; is <= my numberOfStates; is ++) {
1223 double gammasum = NUMsum (thy gamma.row (is).part (1, thy numberOfTimes - 1));
1224
1225 for (integer js = 1; js <= my numberOfStates; js ++) {
1226 longdouble xisum = 0.0;
1227 for (integer it = 1; it <= thy numberOfTimes - 1; it ++)
1228 xisum += thy xi [it] [is] [js];
1229 // zero probs signal invalid connections, don't reestimate
1230 if (my transitionProbs [is] [js] > 0.0) {
1231 thy aij_num [is] [js] += double (xisum);
1232 thy aij_denom [is] [js] += gammasum;
1233 }
1234 }
1235
1236 /*
1237 Only reestimate the emissionProbs for a hidden markov model.
1238 A not hidden model is emulated with fixed emissionProbs.
1239 */
1240 if (! my notHidden) {
1241 gammasum += thy gamma [is] [thy numberOfTimes]; // now sum all, add last term
1242 for (integer k = 1; k <= my numberOfObservationSymbols; k ++) {
1243 longdouble gammasum_k = 0.0;
1244 for (integer it = 1; it <= thy numberOfTimes; it ++)
1245 if (obs [it] == k)
1246 gammasum_k += thy gamma [is] [it];
1247 // only reestimate probs > 0 !
1248 if (my emissionProbs [is] [k] > 0.0) {
1249 thy bik_num [is] [k] += double (gammasum_k);
1250 thy bik_denom [is] [k] += gammasum;
1251 }
1252 }
1253 }
1254 // For a left-to-right model the final state determines the transition prob to go to the END state
1255 if (my leftToRight) {
1256 thy aij_num [is] [my numberOfStates + 1] += thy gamma [is] [thy numberOfTimes];
1257 thy aij_denom [is] [my numberOfStates + 1] += 1.0;
1258 }
1259 }
1260 }
1261
1262 void HMM_HMMBaumWelch_reestimate (HMM me, HMMBaumWelch thee) {
1263 double p;
1264 /*
1265 If we only have a couple of training sequences and they all happen to start with the same symbol,
1266 one or more starting probabilities can be zero.
1267
1268 What to do with the P_k (see Rabiner formulas 109-110)?
1269 */
1270 for (integer is = 1; is <= my numberOfStates; is ++) {
1271 /*
1272 If we have not enough observation sequences it can happen that some probabilities
1273 become zero. This means that for some future observation sequences the probability evaluation
1274 returns p=0 for sequences where these transitions turn up. This makes recognition impossible and
1275 also comparisons between models are difficult.
1276 We can prevent this from happening by asumimg a minimal probability for valid transitions
1277 i.e. which have initially p > 0.
1278 */
1279 if (my initialStateProbs [is] > 0.0) {
1280 p = thy aij_num_p0 [is] / thy aij_denom_p0 [is];
1281 my initialStateProbs [is] = ( p > 0.0 ? p : thy minProb );
1282 }
1283 for (integer js = 1; js <= my numberOfStates; js ++) {
1284 if (my transitionProbs [is] [js] > 0.0) {
1285 p = thy aij_num [is] [js] / thy aij_denom [is] [js];
1286 my transitionProbs [is] [js] = ( p > 0.0 ? p : thy minProb );
1287 }
1288 }
1289 if (! my notHidden) {
1290 for (integer k = 1; k <= my numberOfObservationSymbols; k ++) {
1291 if (my emissionProbs [is] [k] > 0.0) {
1292 p = thy bik_num [is] [k] / thy bik_denom [is] [k];
1293 my emissionProbs [is] [k] = ( p > 0.0 ? p : thy minProb );
1294 }
1295 }
1296 }
1297 if (my leftToRight && my transitionProbs [is] [my numberOfStates + 1] > 0.0) {
1298 p = thy aij_num [is] [my numberOfStates + 1] / thy aij_denom [is] [my numberOfStates + 1];
1299 my transitionProbs [is] [my numberOfStates + 1] = ( p > 0.0 ? p : thy minProb );
1300 }
1301 }
1302 }
1303
1304 void HMM_HMMBaumWelch_forward (HMM me, HMMBaumWelch thee, constINTVEC obs) {
1305 // initialise at t = 1 & scale
1306 for (integer js = 1; js <= my numberOfStates; js ++)
1307 thy alpha [js] [1] = my initialStateProbs [js] * my emissionProbs [js] [obs [1]];
1308 thy scale [1] = NUMsum (thy alpha.column (1));
1309 thy alpha.column (1) /= thy scale [1];
1310 // recursion
1311 for (integer it = 2; it <= thy numberOfTimes; it ++) {
1312 thy scale [it] = 0.0;
1313 for (integer js = 1; js <= my numberOfStates; js ++) {
1314 double sum = 0.0;
1315 for (integer is = 1; is <= my numberOfStates; is ++) {
1316 sum += thy alpha [is] [it - 1] * my transitionProbs [is] [js];
1317 }
1318
1319 thy alpha [js] [it] = sum * my emissionProbs [js] [obs [it]];
1320 thy scale [it] += thy alpha [js] [it];
1321 }
1322
1323 for (integer js = 1; js <= my numberOfStates; js ++) {
1324 thy alpha [js] [it] /= thy scale [it];
1325 }
1326 }
1327
1328 for (integer it = 1; it <= thy numberOfTimes; it ++) {
1329 thy lnProb += log (thy scale [it]);
1330 }
1331 }
1332
1333 void HMM_HMMBaumWelch_backward (HMM me, HMMBaumWelch thee, constINTVEC obs) {
1334 Melder_assert (obs.size == thy numberOfTimes);
1335 for (integer is = 1; is <= my numberOfStates; is ++) {
1336 thy beta [is] [thy numberOfTimes] = 1.0 / thy scale [thy numberOfTimes];
1337 }
1338 for (integer it = thy numberOfTimes - 1; it >= 1; it --) {
1339 for (integer is = 1; is <= my numberOfStates; is ++) {
1340 longdouble sum = 0.0;
1341 for (integer js = 1; js <= my numberOfStates; js ++) {
1342 sum += thy beta [js] [it + 1] * my transitionProbs [is] [js] * my emissionProbs [js] [obs [it + 1]];
1343 }
1344 thy beta [is] [it] = double (sum) / thy scale [it];
1345 }
1346 }
1347 }
1348
1349 /*************************** HMM decoding ***********************************/
1350
1351 // precondition: valid symbols, i.e. 1 <= o [i] <= my numberOfSymbols for i=1..nt
1352 void HMM_HMMViterbi_decode (HMM me, HMMViterbi thee, constINTVEC obs) {
1353 Melder_assert (obs.size == thy numberOfTimes);
1354 const integer numberOfTimes = thy numberOfTimes;
1355 // initialisation
1356 for (integer is = 1; is <= my numberOfStates; is ++) {
1357 thy viterbi [is] [1] = my initialStateProbs [is] * my emissionProbs [is] [obs [1]];
1358 thy bp [is] [1] = 0;
1359 }
1360 // recursion
1361 for (integer it = 2; it <= numberOfTimes; it ++) {
1362 for (integer is = 1; is <= my numberOfStates; is ++) {
1363 // all transitions isp -> is from previous time to current
1364 double max_score = -1; // any negative number is ok
1365 for (integer isp = 1; isp <= my numberOfStates; isp ++) {
1366 const double score = thy viterbi [isp] [it - 1] * my transitionProbs [isp] [is]; // * my emissionProbs [is] [obs [it]]
1367 if (score > max_score) {
1368 max_score = score;
1369 thy bp [is] [it] = isp;
1370 }
1371 }
1372 thy viterbi [is] [it] = max_score * my emissionProbs [is] [ obs [it] ];
1373 }
1374 }
1375 // path starts at state with best end probability
1376 thy path [numberOfTimes] = 1;
1377 thy prob = thy viterbi [1] [numberOfTimes];
1378 for (integer is = 2; is <= my numberOfStates; is ++) {
1379 if (thy viterbi [is] [numberOfTimes] > thy prob)
1380 thy prob = thy viterbi [thy path [numberOfTimes] = is] [numberOfTimes];
1381 }
1382 // trace back and get path
1383 for (integer it = numberOfTimes; it > 1; it --)
1384 thy path [it - 1] = thy bp [thy path [it]] [it];
1385 }
1386
1387 autoHMMStateSequence HMM_HMMObservationSequence_to_HMMStateSequence (HMM me, HMMObservationSequence thee) {
1388 try {
1389 autoStringsIndex si = HMM_HMMObservationSequence_to_StringsIndex (me, thee);
1390 INTVEC obs = si -> classIndex.get(); // convenience
1391 const integer numberOfUnknowns = StringsIndex_countItems (si.get(), 0);
1392
1393 Melder_require (numberOfUnknowns == 0, U"Unknown observation symbol(s) (# = ", numberOfUnknowns, U").");
1394
1395 const integer numberOfTimes = thy rows.size;
1396 autoHMMViterbi v = HMM_to_HMMViterbi (me, obs);
1397 autoHMMStateSequence him = HMMStateSequence_create (numberOfTimes);
1398 // trace the path and get states
1399 for (integer it = 1; it <= numberOfTimes; it ++) {
1400 const HMMState hmms = my states->at [v -> path [it]];
1401 his strings [it] = Melder_dup (hmms -> label.get());
1402 his numberOfStrings ++;
1403 }
1404 return him;
1405 } catch (MelderError) {
1406 Melder_throw (me, U": no HMMStateSequence created.");
1407 }
1408 }
1409
1410 double HMM_HMMStateSequence_getProbability (HMM me, HMMStateSequence thee) {
1411 autoStringsIndex si = HMM_HMMStateSequence_to_StringsIndex (me, thee);
1412 const integer numberOfUnknowns = StringsIndex_countItems (si.get(), 0);
1413 constINTVEC index = si -> classIndex.get();
1414
1415 if (NUMisEmpty (index))
1416 return undefined;
1417 if (numberOfUnknowns > 0) {
1418 Melder_warning (U"Unknown states (# = ", numberOfUnknowns, U").");
1419 return undefined;
1420 }
1421 const double p0 = my initialStateProbs [index [1]];
1422 Melder_require (p0 > 0.0,
1423 U"You should not start with a zero probability state.");
1424
1425 double lnp = log (p0);
1426 for (integer it = 2; it <= thy numberOfStrings; it ++)
1427 lnp += log (my transitionProbs [index [it - 1]] [index [it]]);
1428 return lnp;
1429 }
1430
1431 double HMM_getProbabilityAtTimeBeingInState (HMM me, integer itime, integer istate) {
1432 if (istate < 1 || istate > my numberOfStates)
1433 return undefined;
1434
1435 autoVEC scale = zero_VEC (itime);
1436 autoVEC alpha_t = raw_VEC (my numberOfStates);
1437 autoVEC alpha_tm1 = zero_VEC (my numberOfStates);
1438
1439 alpha_t.all() <<= my initialStateProbs.all();
1440 scale [1] = NUMsum (alpha_t.all());
1441
1442 alpha_t.all() /= scale [1];
1443
1444 // recursion
1445 for (integer it = 2; it <= itime; it ++) {
1446 alpha_tm1.all() <<= alpha_t.all();
1447
1448 for (integer js = 1; js <= my numberOfStates; js ++) {
1449 longdouble sum = 0.0; // NUMinner (alpha_tm1.get(), my transitionProbs.column (js));
1450 for (integer is = 1; is <= my numberOfStates; is ++)
1451 sum += alpha_tm1 [is] * my transitionProbs [is] [js];
1452 alpha_t [js] = double (sum);
1453 scale [it] += alpha_t [js];
1454 }
1455 alpha_t.all() /= scale [it];
1456 }
1457
1458 longdouble lnp = 0.0;
1459 for (integer it = 1; it <= itime; it ++)
1460 lnp += log (scale [it]);
1461
1462 lnp = ( alpha_t [istate] > 0 ? lnp + log (alpha_t [istate]) : -INFINITY ); // p = 0 -> ln(p)=-infinity // ppgb INFINITY is a small number
1463 return double (lnp);
1464 }
1465
1466 double HMM_getProbabilityAtTimeBeingInStateEmittingSymbol (HMM me, integer itime, integer istate, integer isymbol) {
1467 // for a notHidden model emissionProbs may be zero!
1468 if (isymbol < 1 || isymbol > my numberOfObservationSymbols || my emissionProbs [istate] [isymbol] == 0.0)
1469 return undefined;
1470 const double lnp = HMM_getProbabilityAtTimeBeingInState (me, itime, istate);
1471 return ( isundef (lnp) ? undefined : lnp + log (my emissionProbs [istate] [isymbol]) );
1472 }
1473
1474 double HMM_getProbabilityOfObservations (HMM me, constINTVEC obs) {
1475 Melder_assert (obs.size > 0);
1476 const integer numberOfTimes = obs.size;
1477 autoVEC scale = zero_VEC (numberOfTimes);
1478 autoVEC alpha_t = zero_VEC (my numberOfStates);
1479 autoVEC alpha_tm1 = zero_VEC (my numberOfStates);
1480
1481 // initialise
1482 for (integer js = 1; js <= my numberOfStates; js ++) {
1483 alpha_t [js] = my initialStateProbs [js] * my emissionProbs [js] [obs [1]];
1484 scale [1] += alpha_t [js];
1485 }
1486 Melder_require (scale [1] > 0.0,
1487 U"The observation sequence should not start with a symbol whose state has zero starting probability.");
1488
1489 alpha_t.all() /= scale [1];
1490
1491 // recursion
1492 for (integer it = 2; it <= numberOfTimes; it ++) {
1493 alpha_tm1.all() <<= alpha_t.all();
1494
1495 for (integer js = 1; js <= my numberOfStates; js ++) {
1496 longdouble sum = 0.0;
1497 for (integer is = 1; is <= my numberOfStates; is ++) {
1498 sum += alpha_tm1 [is] * my transitionProbs [is] [js];
1499 }
1500 alpha_t [js] = sum * my emissionProbs [js] [obs [it]];
1501 scale [it] += alpha_t [js];
1502 }
1503 if (scale [it] <= 0.0)
1504 return -INFINITY;
1505 for (integer js = 1; js <= my numberOfStates; js ++)
1506 alpha_t [js] /= scale [it];
1507 }
1508
1509 double lnp = 0.0;
1510 for (integer it = 1; it <= numberOfTimes; it ++)
1511 lnp += log (scale [it]);
1512 return lnp;
1513 }
1514
1515 double HMM_HMMObservationSequence_getProbability (HMM me, HMMObservationSequence thee) {
1516 autoStringsIndex si = HMM_HMMObservationSequence_to_StringsIndex (me, thee);
1517 const integer numberOfUnknowns = StringsIndex_countItems (si.get(), 0);
1518 Melder_require (numberOfUnknowns == 0, U"Unknown observations (# = ", numberOfUnknowns, U").");
1519
1520 return HMM_getProbabilityOfObservations (me, si -> classIndex.get());
1521 }
1522
1523 double HMM_HMMObservationSequence_getCrossEntropy (HMM me, HMMObservationSequence thee) {
1524 const double lnp = HMM_HMMObservationSequence_getProbability (me, thee);
1525 return ( isundef (lnp) ? undefined :
1526 -lnp / (NUMln10 * HMMObservationSequence_getNumberOfObservations (thee)) );
1527 }
1528
1529 double HMM_HMMObservationSequence_getPerplexity (HMM me, HMMObservationSequence thee) {
1530 const double ce = HMM_HMMObservationSequence_getCrossEntropy (me, thee);
1531 return ( isundef (ce) ? undefined : pow (2.0, ce) );
1532 }
1533
1534 autoHMM HMM_createFromHMMObservationSequence (HMMObservationSequence me, integer numberOfStates, int leftToRight) {
1535 try {
1536 autoHMM thee = Thing_new (HMM);
1537 autoStrings s = HMMObservationSequence_to_Strings (me);
1538 autoDistributions d = Strings_to_Distributions (s.get());
1539
1540 const integer numberOfObservationSymbols = d -> numberOfRows;
1541 thy notHidden = numberOfStates < 1;
1542 numberOfStates = ( numberOfStates > 0 ? numberOfStates : numberOfObservationSymbols );
1543
1544 HMM_init (thee.get(), numberOfStates, numberOfObservationSymbols, leftToRight);
1545
1546 for (integer i = 1; i <= numberOfObservationSymbols; i ++) {
1547 const conststring32 label = d -> rowLabels [i].get();
1548 autoHMMObservation hmmo = HMMObservation_create (label, 0, 0, kHMMstorage::DIAGONALS);
1549 HMM_addObservation_move (thee.get(), hmmo.move());
1550 if (thy notHidden) {
1551 autoHMMState hmms = HMMState_create (label);
1552 HMM_addState_move (thee.get(), hmms.move());
1553 }
1554 }
1555 if (! thy notHidden)
1556 HMM_setDefaultStates (thee.get());
1557
1558 //HMM_setDefaultTransitionProbs (thee.get());
1559 //HMM_setDefaultInitialStateProbs (thee.get());
1560 //HMM_setDefaultEmissionProbs (thee.get());
1561 return thee;
1562 } catch (MelderError) {
1563 Melder_throw (me, U": no HMM created.");
1564 }
1565 }
1566
1567 autoTableOfReal HMMObservationSequence_to_TableOfReal_transitions (HMMObservationSequence me, int probabilities) {
1568 try {
1569 autoStrings thee = HMMObservationSequence_to_Strings (me);
1570 autoTableOfReal him = Strings_to_TableOfReal_transitions (thee.get(), probabilities);
1571 return him;
1572 } catch (MelderError) {
1573 Melder_throw (me, U": no transitions created.");
1574 }
1575 }
1576
1577 autoStringsIndex HMM_HMMObservationSequence_to_StringsIndex (HMM me, HMMObservationSequence thee) {
1578 try {
1579 autoStrings classes = Thing_new (Strings);
1580 classes -> strings = autoSTRVEC (my numberOfObservationSymbols);
1581 for (integer is = 1; is <= my numberOfObservationSymbols; is ++) {
1582 const HMMObservation hmmo = my observationSymbols->at [is];
1583 classes -> strings [is] = Melder_dup (hmmo -> label.get());
1584 classes -> numberOfStrings ++;
1585 }
1586 autoStrings obs = HMMObservationSequence_to_Strings (thee);
1587 autoStringsIndex him = Stringses_to_StringsIndex (obs.get(), classes.get());
1588 return him;
1589 } catch (MelderError) {
1590 Melder_throw (me, U": no StringsIndex created.");
1591 }
1592 }
1593
1594 autoStringsIndex HMM_HMMStateSequence_to_StringsIndex (HMM me, HMMStateSequence thee) {
1595 try {
1596 autoStrings classes = Thing_new (Strings);
1597 classes -> strings = autoSTRVEC (my numberOfObservationSymbols);
1598 for (integer is = 1; is <= my numberOfStates; is ++) {
1599 const HMMState hmms = my states->at [is];
1600 classes -> strings [is] = Melder_dup (hmms -> label.get());
1601 classes -> numberOfStrings ++;
1602 }
1603 autoStrings sts = HMMStateSequence_to_Strings (thee);
1604 autoStringsIndex him = Stringses_to_StringsIndex (sts.get(), classes.get());
1605 return him;
1606 } catch (MelderError) {
1607 Melder_throw (me, U": no StringsIndex created.");
1608 }
1609 }
1610
1611 autoTableOfReal HMM_HMMObservationSequence_to_TableOfReal_transitions (HMM me, HMMObservationSequence thee, int probabilities) {
1612 try {
1613 autoStringsIndex si = HMM_HMMObservationSequence_to_StringsIndex (me, thee);
1614 autoTableOfReal him = StringsIndex_to_TableOfReal_transitions (si.get(), probabilities);
1615 return him;
1616 } catch (MelderError) {
1617 Melder_throw (me, U": no transition table created for HMMObservationSequence.");
1618 }
1619 }
1620
1621 autoTableOfReal HMM_HMMStateSequence_to_TableOfReal_transitions (HMM me, HMMStateSequence thee, int probabilities) {
1622 try {
1623 autoStringsIndex si = HMM_HMMStateSequence_to_StringsIndex (me, thee);
1624 autoTableOfReal him = StringsIndex_to_TableOfReal_transitions (si.get(), probabilities);
1625 return him;
1626 } catch (MelderError) {
1627 Melder_throw (me, U": no transition table created for HMMStateSequence.");
1628 }
1629 }
1630
1631 autoTableOfReal StringsIndex_to_TableOfReal_transitions (StringsIndex me, int probabilities) {
1632 try {
1633 const integer numberOfTypes = my classes->size;
1634
1635 autoTableOfReal thee = TableOfReal_create (numberOfTypes + 1, numberOfTypes + 1);
1636 for (integer i = 1; i <= numberOfTypes; i ++) {
1637 const SimpleString s = (SimpleString) my classes->at [i];
1638 TableOfReal_setRowLabel (thee.get(), i, s -> string.get());
1639 TableOfReal_setColumnLabel (thee.get(), i, s -> string.get());
1640 }
1641 for (integer i = 2; i <= my numberOfItems; i ++)
1642 if (my classIndex [i - 1] > 0 && my classIndex [i] > 0) // a zero is a restart!
1643 thy data [my classIndex [i-1]] [my classIndex [i]] ++;
1644
1645 longdouble sum = 0.0;
1646 for (integer i = 1; i <= numberOfTypes; i ++) {
1647 const double rowSum = NUMsum (thy data.row (i));
1648 const double colSum = NUMsum (thy data.column (i));
1649 thy data [i] [numberOfTypes + 1] = rowSum;
1650 thy data [numberOfTypes + 1] [i] = colSum;
1651 sum += colSum;
1652 }
1653 thy data [numberOfTypes + 1] [numberOfTypes + 1] = sum;
1654 if (probabilities && sum > 0.0) {
1655 for (integer i = 1; i <= numberOfTypes; i ++)
1656 if (thy data [i] [numberOfTypes + 1] > 0.0)
1657 for (integer j = 1; j <= numberOfTypes; j ++)
1658 thy data [i] [j] /= thy data [i] [numberOfTypes + 1];
1659 for (integer i = 1; i <= numberOfTypes; i ++) {
1660 thy data [i] [numberOfTypes + 1] /= sum;
1661 thy data [numberOfTypes + 1] [i] /= sum;
1662 }
1663 }
1664 return thee;
1665 } catch (MelderError) {
1666 Melder_throw (me, U": no transition table created.");
1667 }
1668 }
1669
1670 autoTableOfReal Strings_to_TableOfReal_transitions (Strings me, int probabilities) {
1671 try {
1672 autoStringsIndex him = Strings_to_StringsIndex (me, kStrings_sorting::ALPHABETICAL);
1673 autoTableOfReal thee = StringsIndex_to_TableOfReal_transitions (him.get(), probabilities);
1674 return thee;
1675 } catch (MelderError) {
1676 Melder_throw (me, U": no transition table created.");
1677 }
1678 }
1679
1680 /* End of file HMM.cpp */