/
HMM.h
1579 lines (1337 loc) · 44.1 KB
/
HMM.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2009 Soeren Sonnenburg
* Written (W) 1999-2008 Gunnar Raetsch
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#ifndef __CHMM_H__
#define __CHMM_H__
#include <shogun/mathematics/Math.h>
#include <shogun/lib/common.h>
#include <shogun/io/SGIO.h>
#include <shogun/lib/config.h>
#include <shogun/features/Features.h>
#include <shogun/features/StringFeatures.h>
#include <shogun/distributions/Distribution.h>
#include <stdio.h>
#ifdef USE_HMMPARALLEL
#define USE_HMMPARALLEL_STRUCTURES 1
#endif
namespace shogun
{
class CFeatures;
template <class ST> class CStringFeatures;
/**@name HMM specific types*/
//@{
/// type for alpha/beta caching table
typedef float64_t T_ALPHA_BETA_TABLE;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/// type for alpha/beta table
struct T_ALPHA_BETA
{
/// dimension for that alpha/beta table was generated
int32_t dimension;
/// perversely huge alpha/beta cache table
T_ALPHA_BETA_TABLE* table;
/// true if table is valid
bool updated;
/// sum over all paths == model_probability for this dimension
float64_t sum;
};
#endif // DOXYGEN_SHOULD_SKIP_THIS
/** type that is used for states.
* Probably uint8_t is enough if you have at most 256 states,
* however uint16_t/long/... is also possible although you might quickly run into memory problems
*/
#ifdef USE_BIGSTATES
typedef uint16_t T_STATES ;
#else
typedef uint8_t T_STATES ;
#endif
typedef T_STATES* P_STATES ;
//@}
/** Training type */
enum BaumWelchViterbiType
{
/// standard baum welch
BW_NORMAL,
/// baum welch only for specified transitions
BW_TRANS,
/// baum welch only for defined transitions/observations
BW_DEFINED,
/// standard viterbi
VIT_NORMAL,
/// viterbi only for defined transitions/observations
VIT_DEFINED
};
/** @brief class Model */
class Model
{
public:
/// Constructor - initializes all variables/structures
Model();
/// Destructor - cleans up
virtual ~Model();
/// sorts learn_a matrix
inline void sort_learn_a()
{
CMath::sort(learn_a,2) ;
}
/// sorts learn_b matrix
inline void sort_learn_b()
{
CMath::sort(learn_b,2) ;
}
/**@name read access functions.
* For learn arrays and const arrays
*/
//@{
/// get entry out of learn_a matrix
inline int32_t get_learn_a(int32_t line, int32_t column) const
{
return learn_a[line*2 + column];
}
/// get entry out of learn_b matrix
inline int32_t get_learn_b(int32_t line, int32_t column) const
{
return learn_b[line*2 + column];
}
/// get entry out of learn_p vector
inline int32_t get_learn_p(int32_t offset) const
{
return learn_p[offset];
}
/// get entry out of learn_q vector
inline int32_t get_learn_q(int32_t offset) const
{
return learn_q[offset];
}
/// get entry out of const_a matrix
inline int32_t get_const_a(int32_t line, int32_t column) const
{
return const_a[line*2 + column];
}
/// get entry out of const_b matrix
inline int32_t get_const_b(int32_t line, int32_t column) const
{
return const_b[line*2 + column];
}
/// get entry out of const_p vector
inline int32_t get_const_p(int32_t offset) const
{
return const_p[offset];
}
/// get entry out of const_q vector
inline int32_t get_const_q(int32_t offset) const
{
return const_q[offset];
}
/// get value out of const_a_val vector
inline float64_t get_const_a_val(int32_t line) const
{
return const_a_val[line];
}
/// get value out of const_b_val vector
inline float64_t get_const_b_val(int32_t line) const
{
return const_b_val[line];
}
/// get value out of const_p_val vector
inline float64_t get_const_p_val(int32_t offset) const
{
return const_p_val[offset];
}
/// get value out of const_q_val vector
inline float64_t get_const_q_val(int32_t offset) const
{
return const_q_val[offset];
}
#ifdef FIX_POS
/// get value out of fix_pos_state array
inline char get_fix_pos_state(int32_t pos, T_STATES state, T_STATES num_states)
{
#ifdef HMM_DEBUG
if ((pos<0)||(pos*num_states+state>65336))
SG_DEBUG("index out of range in get_fix_pos_state(%i,%i,%i) \n", pos,state,num_states) ;
#endif
return fix_pos_state[pos*num_states+state] ;
}
#endif
//@}
/**@name write access functions
* For learn and const arrays
*/
//@{
/// set value in learn_a matrix
inline void set_learn_a(int32_t offset, int32_t value)
{
learn_a[offset]=value;
}
/// set value in learn_b matrix
inline void set_learn_b(int32_t offset, int32_t value)
{
learn_b[offset]=value;
}
/// set value in learn_p vector
inline void set_learn_p(int32_t offset, int32_t value)
{
learn_p[offset]=value;
}
/// set value in learn_q vector
inline void set_learn_q(int32_t offset, int32_t value)
{
learn_q[offset]=value;
}
/// set value in const_a matrix
inline void set_const_a(int32_t offset, int32_t value)
{
const_a[offset]=value;
}
/// set value in const_b matrix
inline void set_const_b(int32_t offset, int32_t value)
{
const_b[offset]=value;
}
/// set value in const_p vector
inline void set_const_p(int32_t offset, int32_t value)
{
const_p[offset]=value;
}
/// set value in const_q vector
inline void set_const_q(int32_t offset, int32_t value)
{
const_q[offset]=value;
}
/// set value in const_a_val vector
inline void set_const_a_val(int32_t offset, float64_t value)
{
const_a_val[offset]=value;
}
/// set value in const_b_val vector
inline void set_const_b_val(int32_t offset, float64_t value)
{
const_b_val[offset]=value;
}
/// set value in const_p_val vector
inline void set_const_p_val(int32_t offset, float64_t value)
{
const_p_val[offset]=value;
}
/// set value in const_q_val vector
inline void set_const_q_val(int32_t offset, float64_t value)
{
const_q_val[offset]=value;
}
#ifdef FIX_POS
/// set value in fix_pos_state vector
inline void set_fix_pos_state(
int32_t pos, T_STATES state, T_STATES num_states, char value)
{
#ifdef HMM_DEBUG
if ((pos<0)||(pos*num_states+state>65336))
SG_DEBUG("index out of range in set_fix_pos_state(%i,%i,%i,%i) [%i]\n", pos,state,num_states,(int)value, pos*num_states+state) ;
#endif
fix_pos_state[pos*num_states+state]=value;
if (value==FIX_ALLOWED)
for (int32_t i=0; i<num_states; i++)
if (get_fix_pos_state(pos,i,num_states)==FIX_DEFAULT)
set_fix_pos_state(pos,i,num_states,FIX_DISALLOWED) ;
}
//@}
/// FIX_DISALLOWED - state is forbidden and will be penalized with DISALLOWED_PENALTY
const static char FIX_DISALLOWED ;
/// FIX_ALLOWED - state is allowed
const static char FIX_ALLOWED ;
/// FIX_DEFAULT - default value
const static char FIX_DEFAULT ;
/// DISALLOWED_PENALTY - states in FIX_DISALLOWED will be penalized with this value
const static float64_t DISALLOWED_PENALTY ;
#endif
protected:
/**@name learn arrays.
* Everything that is to be learned is enumerated here.
* All values will be inititialized with random values
* and normalized to satisfy stochasticity.
*/
//@{
/// transitions to be learned
int32_t* learn_a;
/// emissions to be learned
int32_t* learn_b;
/// start states to be learned
int32_t* learn_p;
/// end states to be learned
int32_t* learn_q;
//@}
/**@name constant arrays.
* These arrays hold constant fields. All values that
* are not constant and will not be learned are initialized
* with 0.
*/
//@{
/// transitions that have constant probability
int32_t* const_a;
/// emissions that have constant probability
int32_t* const_b;
/// start states that have constant probability
int32_t* const_p;
/// end states that have constant probability
int32_t* const_q;
/// values for transitions that have constant probability
float64_t* const_a_val;
/// values for emissions that have constant probability
float64_t* const_b_val;
/// values for start states that have constant probability
float64_t* const_p_val;
/// values for end states that have constant probability
float64_t* const_q_val;
#ifdef FIX_POS
/** states in whose the model has to be at specific times/states which the model has to avoid.
* only used in viterbi
*/
char* fix_pos_state;
#endif
//@}
};
/** @brief Hidden Markov Model.
*
* Structure and Function collection.
* This Class implements a Hidden Markov Model.
* For a tutorial on HMMs see Rabiner et.al A Tutorial on Hidden Markov Models
* and Selected Applications in Speech Recognition, 1989
*
* Several functions for tasks such as training,reading/writing models, reading observations,
* calculation of derivatives are supplied.
*/
class CHMM : public CDistribution
{
private:
T_STATES trans_list_len ;
T_STATES **trans_list_forward ;
T_STATES *trans_list_forward_cnt ;
float64_t **trans_list_forward_val ;
T_STATES **trans_list_backward ;
T_STATES *trans_list_backward_cnt ;
bool mem_initialized ;
#ifdef USE_HMMPARALLEL_STRUCTURES
/// Datatype that is used in parrallel computation of viterbi
struct S_DIM_THREAD_PARAM
{
CHMM* hmm;
int32_t dim;
float64_t prob_sum;
};
/// Datatype that is used in parrallel baum welch model estimation
struct S_BW_THREAD_PARAM
{
CHMM* hmm;
int32_t dim_start;
int32_t dim_stop;
float64_t ret;
float64_t* p_buf;
float64_t* q_buf;
float64_t* a_buf;
float64_t* b_buf;
};
inline T_ALPHA_BETA & ALPHA_CACHE(int32_t dim) {
return alpha_cache[dim%parallel->get_num_threads()] ; } ;
inline T_ALPHA_BETA & BETA_CACHE(int32_t dim) {
return beta_cache[dim%parallel->get_num_threads()] ; } ;
#ifdef USE_LOGSUMARRAY
inline float64_t* ARRAYS(int32_t dim) {
return arrayS[dim%parallel->get_num_threads()] ; } ;
#endif
inline float64_t* ARRAYN1(int32_t dim) {
return arrayN1[dim%parallel->get_num_threads()] ; } ;
inline float64_t* ARRAYN2(int32_t dim) {
return arrayN2[dim%parallel->get_num_threads()] ; } ;
inline T_STATES* STATES_PER_OBSERVATION_PSI(int32_t dim) {
return states_per_observation_psi[dim%parallel->get_num_threads()] ; } ;
inline const T_STATES* STATES_PER_OBSERVATION_PSI(int32_t dim) const {
return states_per_observation_psi[dim%parallel->get_num_threads()] ; } ;
inline T_STATES* PATH(int32_t dim) {
return path[dim%parallel->get_num_threads()] ; } ;
inline bool & PATH_PROB_UPDATED(int32_t dim) {
return path_prob_updated[dim%parallel->get_num_threads()] ; } ;
inline int32_t & PATH_PROB_DIMENSION(int32_t dim) {
return path_prob_dimension[dim%parallel->get_num_threads()] ; } ;
#else
inline T_ALPHA_BETA & ALPHA_CACHE(int32_t /*dim*/) {
return alpha_cache ; } ;
inline T_ALPHA_BETA & BETA_CACHE(int32_t /*dim*/) {
return beta_cache ; } ;
#ifdef USE_LOGSUMARRAY
inline float64_t* ARRAYS(int32_t dim) {
return arrayS ; } ;
#endif
inline float64_t* ARRAYN1(int32_t /*dim*/) {
return arrayN1 ; } ;
inline float64_t* ARRAYN2(int32_t /*dim*/) {
return arrayN2 ; } ;
inline T_STATES* STATES_PER_OBSERVATION_PSI(int32_t /*dim*/) {
return states_per_observation_psi ; } ;
inline const T_STATES* STATES_PER_OBSERVATION_PSI(int32_t /*dim*/) const {
return states_per_observation_psi ; } ;
inline T_STATES* PATH(int32_t /*dim*/) {
return path ; } ;
inline bool & PATH_PROB_UPDATED(int32_t /*dim*/) {
return path_prob_updated ; } ;
inline int32_t & PATH_PROB_DIMENSION(int32_t /*dim*/) {
return path_prob_dimension ; } ;
#endif
/** Determines if algorithm has converged
* @param x value to check against y
* @param y value to check against x
*/
bool converged(float64_t x, float64_t y);
/** Train definitions.
* Encapsulates Modelparameters that are constant/shall be learned.
* Consists of structures and access functions for learning only defined transitions and constants.
*/
public:
/** default constructor */
CHMM();
/**@name Constructor/Destructor and helper function
*/
//@{
/** Constructor
* @param N number of states
* @param M number of emissions
* @param model model which holds definitions of states to be learned + consts
* @param PSEUDO Pseudo Value
*/
CHMM(
int32_t N, int32_t M, Model* model, float64_t PSEUDO);
CHMM(
CStringFeatures<uint16_t>* obs, int32_t N, int32_t M,
float64_t PSEUDO);
CHMM(
int32_t N, float64_t* p, float64_t* q, float64_t* a);
CHMM(
int32_t N, float64_t* p, float64_t* q, int32_t num_trans,
float64_t* a_trans);
/** Constructor - Initialization from model file.
* @param model_file Filehandle to a hmm model file (*.mod)
* @param PSEUDO Pseudo Value
*/
CHMM(FILE* model_file, float64_t PSEUDO);
/// Constructor - Clone model h
CHMM(CHMM* h);
/// Destructor - Cleanup
virtual ~CHMM();
/** learn distribution
*
* @param data training data (parameter can be avoided if distance or
* kernel-based classifiers are used and distance/kernels are
* initialized with train data)
*
* @return whether training was successful
*/
virtual bool train(CFeatures* data=NULL);
virtual inline int32_t get_num_model_parameters() { return N*(N+M+2); }
virtual float64_t get_log_model_parameter(int32_t num_param);
virtual float64_t get_log_derivative(int32_t num_param, int32_t num_example);
virtual float64_t get_log_likelihood_example(int32_t num_example)
{
return model_probability(num_example);
}
/** initialization function - gets called by constructors.
* @param model model which holds definitions of states to be learned + consts
* @param PSEUDO Pseudo Value
* @param model_file Filehandle to a hmm model file (*.mod)
*/
bool initialize(Model* model, float64_t PSEUDO, FILE* model_file=NULL);
//@}
/// allocates memory that depends on N
bool alloc_state_dependend_arrays();
/// free memory that depends on N
void free_state_dependend_arrays();
/**@name probability functions.
* forward/backward/viterbi algorithm
*/
//@{
/** forward algorithm.
* calculates Pr[O_0,O_1, ..., O_t, q_time=S_i| lambda] for 0<= time <= T-1
* Pr[O|lambda] for time > T
* @param time t
* @param state i
* @param dimension dimension of observation (observations are a matrix, where a row stands for one dimension i.e. 0_0,O_1,...,O_{T-1}
*/
float64_t forward_comp(int32_t time, int32_t state, int32_t dimension);
float64_t forward_comp_old(
int32_t time, int32_t state, int32_t dimension);
/** backward algorithm.
* calculates Pr[O_t+1,O_t+2, ..., O_T-1| q_time=S_i, lambda] for 0<= time <= T-1
* Pr[O|lambda] for time >= T
* @param time t
* @param state i
* @param dimension dimension of observation (observations are a matrix, where a row stands for one dimension i.e. 0_0,O_1,...,O_{T-1}
*/
float64_t backward_comp(int32_t time, int32_t state, int32_t dimension);
float64_t backward_comp_old(
int32_t time, int32_t state, int32_t dimension);
/** calculates probability of best state sequence s_0,...,s_T-1 AND path itself using viterbi algorithm.
* The path can be found in the array PATH(dimension)[0..T-1] afterwards
* @param dimension dimension of observation for which the most probable path is calculated (observations are a matrix, where a row stands for one dimension i.e. 0_0,O_1,...,O_{T-1}
*/
float64_t best_path(int32_t dimension);
inline uint16_t get_best_path_state(int32_t dim, int32_t t)
{
ASSERT(PATH(dim));
return PATH(dim)[t];
}
/// calculates probability that observations were generated
/// by the model using forward algorithm.
float64_t model_probability_comp() ;
/// inline proxy for model probability.
inline float64_t model_probability(int32_t dimension=-1)
{
//for faster calculation cache model probability
if (dimension==-1)
{
if (mod_prob_updated)
return mod_prob/p_observations->get_num_vectors();
else
return model_probability_comp()/p_observations->get_num_vectors();
}
else
return forward(p_observations->get_vector_length(dimension), 0, dimension);
}
/** calculates likelihood for linear model
* on observations in MEMORY
* @param dimension dimension for which probability is calculated
* @return model probability
*/
inline float64_t linear_model_probability(int32_t dimension)
{
float64_t lik=0;
int32_t len=0;
bool free_vec;
uint16_t* o=p_observations->get_feature_vector(dimension, len, free_vec);
float64_t* obs_b=observation_matrix_b;
ASSERT(N==len);
for (int32_t i=0; i<N; i++)
{
lik+=obs_b[*o++];
obs_b+=M;
}
p_observations->free_feature_vector(o, dimension, free_vec);
return lik;
// sorry, the above code is the speed optimized version of :
/* float64_t lik=0;
for (int32_t i=0; i<N; i++)
lik+=get_b(i, p_observations->get_feature(dimension, i));
return lik;
*/
// : that
}
//@}
/**@name convergence criteria
*/
inline bool set_iterations(int32_t num) { iterations=num; return true; }
inline int32_t get_iterations() { return iterations; }
inline bool set_epsilon (float64_t eps) { epsilon=eps; return true; }
inline float64_t get_epsilon() { return epsilon; }
/** interface for e.g. GUIHMM to run BaumWelch or Viterbi training
* @param type type of BaumWelch/Viterbi training
*/
bool baum_welch_viterbi_train(BaumWelchViterbiType type);
/**@name model training
*/
//@{
/** uses baum-welch-algorithm to train a fully connected HMM.
* @param train model from which the new model is estimated
*/
void estimate_model_baum_welch(CHMM* train);
void estimate_model_baum_welch_trans(CHMM* train);
#ifdef USE_HMMPARALLEL_STRUCTURES
void ab_buf_comp(
float64_t* p_buf, float64_t* q_buf, float64_t* a_buf,
float64_t* b_buf, int32_t dim) ;
#else
void estimate_model_baum_welch_old(CHMM* train);
#endif
/** uses baum-welch-algorithm to train the defined transitions etc.
* @param train model from which the new model is estimated
*/
void estimate_model_baum_welch_defined(CHMM* train);
/** uses viterbi training to train a fully connected HMM
* @param train model from which the new model is estimated
*/
void estimate_model_viterbi(CHMM* train);
/** uses viterbi training to train the defined transitions etc.
* @param train model from which the new model is estimated
*/
void estimate_model_viterbi_defined(CHMM* train);
//@}
/// estimates linear model from observations.
bool linear_train(bool right_align=false);
/// compute permutation entropy
bool permutation_entropy(int32_t window_width, int32_t sequence_number);
/**@name output functions.*/
//@{
/** prints the model parameters on screen.
* @param verbose when false only the model probability will be printed
* when true the whole model will be printed additionally
*/
void output_model(bool verbose=false);
/// performs output_model only for the defined transitions etc
void output_model_defined(bool verbose=false);
//@}
/**@name model helper functions.*/
//@{
/// normalize the model to satisfy stochasticity
void normalize(bool keep_dead_states=false);
/// increases the number of states by num_states
/// the new a/b/p/q values are given the value default_val
/// where 0<=default_val<=1
void add_states(int32_t num_states, float64_t default_val=0);
/// appends the append_model to the current hmm, i.e.
/// two extra states are created. one is the end state of
/// the current hmm with outputs cur_out (of size M) and
/// the other state is the start state of the append_model.
/// transition probability from state 1 to states 1 is 1
bool append_model(
CHMM* append_model, float64_t* cur_out, float64_t* app_out);
/// appends the append_model to the current hmm, here
/// no extra states are created. former q_i are multiplied by q_ji
/// to give the a_ij from the current hmm to the append_model
bool append_model(CHMM* append_model);
/// set any model parameter with probability smaller than value to ZERO
void chop(float64_t value);
/// convert model to log probabilities
void convert_to_log();
/// init model with random values
void init_model_random();
/** init model according to const_x, learn_x.
* first model is initialized with 0 for all parameters
* then parameters in learn_x are initialized with random values
* finally const_x parameters are set and model is normalized.
*/
void init_model_defined();
/// initializes model with log(PSEUDO)
void clear_model();
/// initializes only parameters in learn_x with log(PSEUDO)
void clear_model_defined();
/// copies the the modelparameters from l
void copy_model(CHMM* l);
/** invalidates all caches.
* this function has to be called when direct changes to the model have been made.
* this is necessary for the forward/backward/viterbi algorithms to not work with old tables
*/
void invalidate_model();
/** get status
* @return true if everything is ok, else false
*/
inline bool get_status() const
{
return status;
}
/// returns current pseudo value
inline float64_t get_pseudo() const
{
return PSEUDO ;
}
/// sets current pseudo value
inline void set_pseudo(float64_t pseudo)
{
PSEUDO=pseudo ;
}
#ifdef USE_HMMPARALLEL_STRUCTURES
static void* bw_dim_prefetch(void * params);
static void* bw_single_dim_prefetch(void * params);
static void* vit_dim_prefetch(void * params);
#endif
#ifdef FIX_POS
/** access function to set value in fix_pos_state vector in underlying model
* @see Model
*/
inline bool set_fix_pos_state(int32_t pos, T_STATES state, char value)
{
if (!model)
return false ;
model->set_fix_pos_state(pos, state, N, value) ;
return true ;
} ;
#endif
//@}
/** observation functions
* set/get observation matrix
*/
//@{
/** set new observations
* sets the observation pointer and initializes observation-dependent caches
* if hmm is given, then the caches of the model hmm are used
*/
void set_observations(CStringFeatures<uint16_t>* obs, CHMM* hmm=NULL);
/** set new observations
* only set the observation pointer and drop caches if there were any
*/
void set_observation_nocache(CStringFeatures<uint16_t>* obs);
/// return observation pointer
inline CStringFeatures<uint16_t>* get_observations()
{
SG_REF(p_observations);
return p_observations;
}
//@}
/**@name load/save functions.
* for observations/model/traindefinitions
*/
//@{
/** read definitions file (learn_x,const_x) used for training.
* -format specs: definition_file (train.def)
% HMM-TRAIN - specification
% learn_a - elements in state_transition_matrix to be learned
% learn_b - elements in oberservation_per_state_matrix to be learned
% note: each line stands for
% state, observation(0), observation(1)...observation(NOW)
% learn_p - elements in initial distribution to be learned
% learn_q - elements in the end-state distribution to be learned
%
% const_x - specifies initial values of elements
% rest is assumed to be 0.0
%
% NOTE: IMPLICIT DEFINES:
% define A 0
% define C 1
% define G 2
% define T 3
learn_a=[ [int32_t,int32_t];
[int32_t,int32_t];
[int32_t,int32_t];
........
[int32_t,int32_t];
[-1,-1];
];
learn_b=[ [int32_t,int32_t,int32_t,...,int32_t];
[int32_t,int32_t,int32_t,...,int32_t];
[int32_t,int32_t,int32_t,...,int32_t];
........
[int32_t,int32_t,int32_t,...,int32_t];
[-1,-1];
];
learn_p= [ int32_t, ... , int32_t, -1 ];
learn_q= [ int32_t, ... , int32_t, -1 ];
const_a=[ [int32_t,int32_t,float64_t];
[int32_t,int32_t,float64_t];
[int32_t,int32_t,float64_t];
........
[int32_t,int32_t,float64_t];
[-1,-1,-1];
];
const_b=[ [int32_t,int32_t,int32_t,...,int32_t,float64_t];
[int32_t,int32_t,int32_t,...,int32_t,float64_t];
[int32_t,int32_t,int32_t,...,int32_t,<DOUBLE];
........
[int32_t,int32_t,int32_t,...,int32_t,float64_t];
[-1,-1,-1];
];
const_p[]=[ [int32_t, float64_t], ... , [int32_t,float64_t], [-1,-1] ];
const_q[]=[ [int32_t, float64_t], ... , [int32_t,float64_t], [-1,-1] ];
* @param file filehandle to definitions file
* @param verbose true for verbose messages
* @param initialize true to initialize to underlying HMM
*/
bool load_definitions(FILE* file, bool verbose, bool initialize=true);
/** read model from file.
-format specs: model_file (model.hmm)
% HMM - specification
% N - number of states
% M - number of observation_tokens
% a is state_transition_matrix
% size(a)= [N,N]
%
% b is observation_per_state_matrix
% size(b)= [N,M]
%
% p is initial distribution
% size(p)= [1, N]
N=int32_t;
M=int32_t;
p=[float64_t,float64_t...float64_t];
q=[float64_t,float64_t...float64_t];
a=[ [float64_t,float64_t...float64_t];
[float64_t,float64_t...float64_t];
[float64_t,float64_t...float64_t];
[float64_t,float64_t...float64_t];
[float64_t,float64_t...float64_t];
];
b=[ [float64_t,float64_t...float64_t];
[float64_t,float64_t...float64_t];
[float64_t,float64_t...float64_t];
[float64_t,float64_t...float64_t];
[float64_t,float64_t...float64_t];
];
* @param file filehandle to model file
*/
bool load_model(FILE* file);
/** save model to file.
* @param file filehandle to model file
*/
bool save_model(FILE* file);
/** save model derivatives to file in ascii format.
* @param file filehandle
*/
bool save_model_derivatives(FILE* file);
/** save model derivatives to file in binary format.
* @param file filehandle
*/
bool save_model_derivatives_bin(FILE* file);
/** save model in binary format.
* @param file filehandle
*/
bool save_model_bin(FILE* file);
/// numerically check whether derivates were calculated right
bool check_model_derivatives() ;
bool check_model_derivatives_combined() ;
/** get viterbi path and path probability
* @param dim dimension for which to obtain best path
* @param prob likelihood of path
* @return viterbi path
*/
T_STATES* get_path(int32_t dim, float64_t& prob);
/** save viterbi path in ascii format
* @param file filehandle
*/
bool save_path(FILE* file);
/** save viterbi path in ascii format
* @param file filehandle
*/
bool save_path_derivatives(FILE* file);
/** save viterbi path in binary format
* @param file filehandle
*/
bool save_path_derivatives_bin(FILE* file);
#ifdef USE_HMMDEBUG
/// numerically check whether derivates were calculated right
bool check_path_derivatives() ;
#endif //USE_HMMDEBUG
/** save model probability in binary format
* @param file filehandle
*/
bool save_likelihood_bin(FILE* file);
/** save model probability in ascii format
* @param file filehandle
*/
bool save_likelihood(FILE* file);
//@}
/**@name access functions for model parameters
* for all the arrays a,b,p,q,A,B,psi
* and scalar model parameters like N,M
*/
//@{
/// access function for number of states N
inline T_STATES get_N() const { return N ; }
/// access function for number of observations M
inline int32_t get_M() const { return M ; }
/** access function for probability of end states
* @param offset index 0...N-1
* @param value value to be set
*/
inline void set_q(T_STATES offset, float64_t value)
{
#ifdef HMM_DEBUG
if (offset>=N)
SG_DEBUG("index out of range in set_q(%i,%e) [%i]\n", offset,value,N) ;
#endif
end_state_distribution_q[offset]=value;
}