-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathHMMProblem.cpp
More file actions
2140 lines (1970 loc) · 77 KB
/
HMMProblem.cpp
File metadata and controls
2140 lines (1970 loc) · 77 KB
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
/*
Copyright (c) 2012-2015, Michael (Mikhail) Yudelson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Michael (Mikhail) Yudelson nor the
names of other contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string>
#include "utils.h"
#include "FitBit.h"
#include <math.h>
#include "HMMProblem.h"
#include <map>
HMMProblem::HMMProblem() {
}
HMMProblem::HMMProblem(struct param *param) {
NPAR i;
switch (param->structure) {
case STRUCTURE_SKILL: // Expectation Maximization (Baum-Welch)
for(i=0; i<3; i++) this->sizes[i] = param->nK;
this->n_params = param->nK * 4;
break;
case STRUCTURE_GROUP: // Gradient Descent by group
for(i=0; i<3; i++) this->sizes[i] = param->nG;
this->n_params = param->nG * 4;
break;
default:
fprintf(stderr,"Structure specified is not supported and should have been caught earlier\n");
break;
}
init(param);
}
void HMMProblem::init(struct param *param) {
this->p = param;
this->non01constraints = true;
this->null_obs_ratio = Calloc(NUMBER, (size_t)this->p->nO);
this->neg_log_lik = 0;
this->null_skill_obs = 0;
this->null_skill_obs_prob = 0;
if( this->p->solver == METHOD_CGD && this->p->solver_setting == -1)
this->p->solver_setting = 1; // default Fletcher-Reeves
NPAR nS = this->p->nS, nO = this->p->nO;
NUMBER *a_PI, ** a_A, ** a_B;
init3Params(a_PI, a_A, a_B, nS, nO);
//
// setup params
//
this->pi = init2D<NUMBER>((NDAT)this->sizes[0], (NDAT)nS);
this->A = init3D<NUMBER>((NDAT)this->sizes[1], (NDAT)nS, (NDAT)nS);
this->B = init3D<NUMBER>((NDAT)this->sizes[2], (NDAT)nS, (NDAT)nO);
NPAR i, j;
int offset, idx;
if(param->initfile[0]==0) { // no setup file
NUMBER sumPI = 0;
NUMBER sumA[this->p->nS];
NUMBER sumB[this->p->nS];
for(i=0; i<this->p->nS; i++) {
sumA[i] = 0;
sumB[i] = 0;
}
// populate PI
for(i=0; i<((nS)-1); i++) {
a_PI[i] = this->p->init_params[i];
sumPI += this->p->init_params[i];
}
a_PI[nS-1] = 1 - sumPI;
// populate A
offset = (int)(nS-1);
for(i=0; i<nS; i++) {
for(j=0; j<((nS)-1); j++) {
idx = (int)(offset + i*((nS)-1) + j);
a_A[i][j] = this->p->init_params[idx];
sumA[i] += this->p->init_params[idx];
}
a_A[i][((nS)-1)] = 1 - sumA[i];
}
// populate B
offset = (int)((nS-1) + nS*(nS-1));
for(i=0; i<nS; i++) {
for(j=0; j<((nO)-1); j++) {
idx = (int)(offset + i*((nO)-1) + j);
a_B[i][j] = this->p->init_params[idx];
sumB[i] += this->p->init_params[idx];
}
a_B[i][((nO)-1)] = 1 - sumB[i];
}
// mass produce PI's, A's, B's
if( this->p->do_not_check_constraints==0 && !checkPIABConstraints(a_PI, a_A, a_B)) {
fprintf(stderr,"params do not meet constraints.\n");
exit(1);
}
NCAT x;
for(x=0; x<this->sizes[0]; x++)
cpy1D<NUMBER>(a_PI, this->pi[x], (NDAT)nS);
for(x=0; x<this->sizes[1]; x++)
cpy2D<NUMBER>(a_A, this->A[x], (NDAT)nS, (NDAT)nS);
for(x=0; x<this->sizes[2]; x++)
cpy2D<NUMBER>(a_B, this->B[x], (NDAT)nS, (NDAT)nO);
// destroy setup params
free(a_PI);
free2D<NUMBER>(a_A, (NDAT)nS);
free2D<NUMBER>(a_B, (NDAT)nS);
} else {
// if needs be -- read in init params from a file
this->readModel(param->initfile, false /* read and upload but not overwrite*/);
}
// populate boundaries
// populate lb*/ub*
// *PI
init3Params(this->lbPI, this->lbA, this->lbB, nS, nO);
init3Params(this->ubPI, this->ubA, this->ubB, nS, nO);
for(i=0; i<nS; i++) {
lbPI[i] = this->p->param_lo[i];
ubPI[i] = this->p->param_hi[i];
}
// *A
offset = nS;
for(i=0; i<nS; i++)
for(j=0; j<nS; j++) {
idx = (int)(offset + i*nS + j);
lbA[i][j] = this->p->param_lo[idx];
ubA[i][j] = this->p->param_hi[idx];
}
// *B
offset = (int)(nS + nS*nS);
for(i=0; i<nS; i++)
for(j=0; j<nO; j++) {
idx = (int)(offset + i*nO + j);
lbB[i][j] = this->p->param_lo[idx];
ubB[i][j] = this->p->param_hi[idx];
}
}
HMMProblem::~HMMProblem() {
destroy();
}
void HMMProblem::destroy() {
// destroy model data
if(this->null_obs_ratio != NULL) free(this->null_obs_ratio);
if(this->pi != NULL) free2D<NUMBER>(this->pi, this->sizes[0]);
if(this->A != NULL) free3D<NUMBER>(this->A, this->sizes[1], this->p->nS);
if(this->B != NULL) free3D<NUMBER>(this->B, this->sizes[2], this->p->nS);
if(this->lbPI!=NULL) free(this->lbPI);
if(this->ubPI!=NULL) free(this->ubPI);
if(this->lbA!=NULL) free2D<NUMBER>(this->lbA, this->p->nS);
if(this->ubA!=NULL) free2D<NUMBER>(this->ubA, this->p->nS);
if(this->lbB!=NULL) free2D<NUMBER>(this->lbB, this->p->nS);
if(this->ubB!=NULL) free2D<NUMBER>(this->ubB, this->p->nS);
}// ~HMMProblem
bool HMMProblem::hasNon01Constraints() {
return this->non01constraints;
}
NUMBER** HMMProblem::getPI() {
return this->pi;
}
NUMBER*** HMMProblem::getA() {
return this->A;
}
NUMBER*** HMMProblem::getB() {
return this->B;
}
NUMBER* HMMProblem::getPI(NCAT x) {
if( x > (this->sizes[0]-1) ) {
fprintf(stderr,"While accessing PI, skill index %d exceeded last index of the data %d.\n", x, this->sizes[0]-1);
exit(1);
}
return this->pi[x];
}
NUMBER** HMMProblem::getA(NCAT x) {
if( x > (this->sizes[1]-1) ) {
fprintf(stderr,"While accessing A, skill index %d exceeded last index of the data %d.\n", x, this->sizes[1]-1);
exit(1);
}
return this->A[x];
}
NUMBER** HMMProblem::getB(NCAT x) {
if( x > (this->sizes[2]-1) ) {
fprintf(stderr,"While accessing B, skill index %d exceeded last index of the data %d.\n", x, this->sizes[2]-1);
exit(1);
}
return this->B[x];
}
NUMBER* HMMProblem::getLbPI() {
if( !this->non01constraints ) return NULL;
return this->lbPI;
}
NUMBER** HMMProblem::getLbA() {
if( !this->non01constraints ) return NULL;
return this->lbA;
}
NUMBER** HMMProblem::getLbB() {
if( !this->non01constraints ) return NULL;
return this->lbB;
}
NUMBER* HMMProblem::getUbPI() {
if( !this->non01constraints ) return NULL;
return this->ubPI;
}
NUMBER** HMMProblem::getUbA() {
if( !this->non01constraints ) return NULL;
return this->ubA;
}
NUMBER** HMMProblem::getUbB() {
if( !this->non01constraints ) return NULL;
return this->ubB;
}
// getters for computing alpha, beta, gamma
NUMBER HMMProblem::getPI(struct data* dt, NPAR i) {
switch(this->p->structure)
{
case STRUCTURE_SKILL:
return this->pi[dt->k][i];
break;
case STRUCTURE_GROUP:
return this->pi[dt->g][i];
break;
default:
fprintf(stderr,"Solver specified is not supported.\n");
exit(1);
break;
}
}
// getters for computing alpha, beta, gamma
NUMBER HMMProblem::getA (struct data* dt, NPAR i, NPAR j) {
switch(this->p->structure)
{
case STRUCTURE_SKILL:
return this->A[dt->k][i][j];
break;
case STRUCTURE_GROUP:
return this->A[dt->g][i][j];
break;
default:
fprintf(stderr,"Solver specified is not supported.\n");
exit(1);
break;
}
}
// getters for computing alpha, beta, gamma
NUMBER HMMProblem::getB (struct data* dt, NPAR i, NPAR m) {
// special attention for "unknonw" observations, i.e. the observation was there but we do not know what it is
// in this case we simply return 1, effectively resulting in no change in \alpha or \beta vatiables
if(m<0)
return 1;
switch(this->p->structure)
{
case STRUCTURE_SKILL:
return this->B[dt->k][i][m];
break;
case STRUCTURE_GROUP:
return this->B[dt->g][i][m];
break;
default:
fprintf(stderr,"Solver specified is not supported.\n");
exit(1);
break;
}
}
bool HMMProblem::checkPIABConstraints(NUMBER* a_PI, NUMBER** a_A, NUMBER** a_B) {
NPAR i, j;
// check values
NUMBER sum_pi = 0.0;
NUMBER sum_a_row[this->p->nS];
NUMBER sum_b_row[this->p->nS];
for(i=0; i<this->p->nS; i++) {
sum_a_row[i] = 0.0;
sum_b_row[i] = 0.0;
}
for(i=0; i<this->p->nS; i++) {
if( a_PI[i]>1.0 || a_PI[i]<0.0)
return false;
sum_pi += a_PI[i];
for(j=0; j<this->p->nS; j++) {
if( a_A[i][j]>1.0 || a_A[i][j]<0.0)
return false;
sum_a_row[i] += a_A[i][j];
}// all states 2
for(int m=0; m<this->p->nO; m++) {
if( a_B[i][m]>1.0 || a_B[i][m]<0.0)
return false;
sum_b_row[i] += a_B[i][m];
}// all observations
}// all states
if(sum_pi!=1.0)
return false;
for(i=0; i<this->p->nS; i++)
if( sum_a_row[i]!=1.0 || sum_b_row[i]!=1.0)
return false;
return true;
}
NUMBER HMMProblem::getSumLogPOPara(NCAT xndat, struct data** x_data) {
NUMBER result = 0.0;
for(NCAT x=0; x<xndat; x++) result += (x_data[x]->cnt==0)?x_data[x]->loglik:0;
return result;
}
void HMMProblem::initAlpha(NCAT xndat, struct data** x_data) {
NPAR nS = this->p->nS;
// int parallel_now = this->p->parallel==2; //PAR
// #pragma omp parallel for schedule(dynamic) if(parallel_now) //PAR
for(NCAT x=0; x<xndat; x++) {
NDAT t;
NPAR i;
if( x_data[x]->cnt!=0 ) continue; // ... and the thing has not been computed yet (e.g. from group to skill)
// alpha
if( x_data[x]->alpha == NULL ) {
x_data[x]->alpha = Calloc(NUMBER*, (size_t)x_data[x]->n);
for(t=0; t<x_data[x]->n; t++)
x_data[x]->alpha[t] = Calloc(NUMBER, (size_t)nS);
} else {
for(t=0; t<x_data[x]->n; t++)
for(i=0; i<nS; i++)
x_data[x]->alpha[t][i] = 0.0;
}
// p_O_param
x_data[x]->p_O_param = 0.0;
x_data[x]->loglik = 0.0;
// c - scaling
if( x_data[x]->c == NULL ) {
x_data[x]->c = Calloc(NUMBER, (size_t)x_data[x]->n);
} else {
for(t=0; t<x_data[x]->n; t++)
x_data[x]->c[t] = 0.0;
}
} // for all groups in skill
}
void HMMProblem::initXiGamma(NCAT xndat, struct data** x_data) {
NPAR nS = this->p->nS;
// int parallel_now = this->p->parallel==2; //PAR
// #pragma omp parallel for schedule(dynamic) if(parallel_now) //PAR
for(NCAT x=0; x<xndat; x++) {
NDAT t;
NPAR i, j;
if( x_data[x]->cnt!=0 ) continue; // ... and the thing has not been computed yet (e.g. from group to skill)
// Xi
if( x_data[x]->gamma == NULL ) {
x_data[x]->gamma = Calloc(NUMBER*, (size_t)x_data[x]->n);
for(t=0; t<x_data[x]->n; t++)
x_data[x]->gamma[t] = Calloc(NUMBER, (size_t)nS);
} else {
for(t=0; t<x_data[x]->n; t++)
for(i=0; i<nS; i++)
x_data[x]->gamma[t][i] = 0.0;
}
// Gamma
if( x_data[x]->xi == NULL ) {
x_data[x]->xi = Calloc(NUMBER**, (size_t)x_data[x]->n);
for(t=0; t<x_data[x]->n; t++) {
x_data[x]->xi[t] = Calloc(NUMBER*, (size_t)nS);
for(i=0; i<nS; i++)
x_data[x]->xi[t][i] = Calloc(NUMBER, (size_t)nS);
}
} else {
for(t=0; t<x_data[x]->n; t++)
for(i=0; i<nS; i++)
for(j=0; j<nS; j++)
x_data[x]->xi[t][i][j] = 0.0;
}
} // for all groups in skill
}
void HMMProblem::initBeta(NCAT xndat, struct data** x_data) {
NPAR nS = this->p->nS;
// int parallel_now = this->p->parallel==2; //PAR
// #pragma omp parallel for schedule(dynamic) if(parallel_now) //PAR
for(NCAT x=0; x<xndat; x++) {
NDAT t;
NPAR i;
if( x_data[x]->cnt!=0 ) continue; // ... and the thing has not been computed yet (e.g. from group to skill)
// beta
if( x_data[x]->beta == NULL ) {
x_data[x]->beta = Calloc(NUMBER*, (size_t)x_data[x]->n);
for(t=0; t<x_data[x]->n; t++)
x_data[x]->beta[t] = Calloc(NUMBER, (size_t)nS);
} else {
for(t=0; t<x_data[x]->n; t++)
for(i=0; i<nS; i++)
x_data[x]->beta[t][i] = 0.0;
}
} // for all groups in skill
} // initBeta
NDAT HMMProblem::computeAlphaAndPOParam(NCAT xndat, struct data** x_data) {
// NUMBER mult_c, old_pOparam, neg_sum_log_c;
initAlpha(xndat, x_data);
NPAR nS = this->p->nS;
NDAT ndat = 0;
// int parallel_now = this->p->parallel==2; //PAR
// #pragma omp parallel for schedule(dynamic) if(parallel_now) reduction(+:ndat) //PAR
for(NCAT x=0; x<xndat; x++) {
NDAT t;
NPAR i, j, o;
if( x_data[x]->cnt!=0 ) continue; // ... and the thing has not been computed yet (e.g. from group to skill)
ndat += x_data[x]->n; // reduction'ed
for(t=0; t<x_data[x]->n; t++) {
// o = x_data[x]->obs[t];
o = this->p->dat_obs[ x_data[x]->ix[t] ];//->get( x_data[x]->ix[t] );
if(t==0) { // it's alpha(1,i)
// compute \alpha_1(i) = \pi_i b_i(o_1)
for(i=0; i<nS; i++) {
x_data[x]->alpha[t][i] = getPI(x_data[x],i) * ((o<0)?1:getB(x_data[x],i,o)); // if observatiob unknown use 1
if(this->p->scaled==1) x_data[x]->c[t] += x_data[x]->alpha[t][i];
}
} else { // it's alpha(t,i)
// compute \alpha_{t}(i) = b_j(o_{t})\sum_{j=1}^N{\alpha_{t-1}(j) a_{ji}}
for(i=0; i<nS; i++) {
for(j=0; j<nS; j++) {
x_data[x]->alpha[t][i] += x_data[x]->alpha[t-1][j] * getA(x_data[x],j,i);
}
x_data[x]->alpha[t][i] *= ((o<0)?1:getB(x_data[x],i,o)); // if observatiob unknown use 1
if(this->p->scaled==1) x_data[x]->c[t] += x_data[x]->alpha[t][i];
}
}
// scale \alpha_{t}(i) - same for t=1 or otherwise
if(this->p->scaled==1) {
x_data[x]->c[t] = 1/x_data[x]->c[t];//safe0num();
for(i=0; i<nS; i++) x_data[x]->alpha[t][i] *= x_data[x]->c[t];
}
if(this->p->scaled==1) x_data[x]->loglik += log(x_data[x]->c[t]);
} // for all observations within skill-group
if(this->p->scaled==1) x_data[x]->p_O_param = exp( -x_data[x]->loglik );
else {
x_data[x]->p_O_param = 0; // 0 for non-scaled
for(i=0; i<nS; i++) x_data[x]->p_O_param += x_data[x]->alpha[x_data[x]->n-1][i];
x_data[x]->loglik = -safelog(x_data[x]->p_O_param);
}
} // for all groups in skill
return ndat;
}
void HMMProblem::computeBeta(NCAT xndat, struct data** x_data) {
initBeta(xndat, x_data);
NPAR nS = this->p->nS;
// int parallel_now = this->p->parallel==2; //PAR
// #pragma omp parallel for schedule(dynamic) if(parallel_now) //PAR
for(NCAT x=0; x<xndat; x++) {
int t;
NPAR i, j, o;
if( x_data[x]->cnt!=0 ) continue; // ... and the thing has not been computed yet (e.g. from group to skill)
for(t=(NDAT)(x_data[x]->n)-1; t>=0; t--) {
if( t==(x_data[x]->n-1) ) { // last \beta
// \beta_T(i) = 1
for(i=0; i<nS; i++)
x_data[x]->beta[t][i] = (this->p->scaled==1)?x_data[x]->c[t]:1.0;;
} else {
// \beta_t(i) = \sum_{j=1}^N{beta_{t+1}(j) a_{ij} b_j(o_{t+1})}
// o = x_data[x]->obs[t+1]; // next observation
o = this->p->dat_obs[ x_data[x]->ix[t+1] ];//->get( x_data[x]->ix[t+1] );
for(i=0; i<nS; i++) {
for(j=0; j<nS; j++)
x_data[x]->beta[t][i] += x_data[x]->beta[t+1][j] * getA(x_data[x],i,j) * ((o<0)?1:getB(x_data[x],j,o)); // if observatiob unknown use 1
// scale
if(this->p->scaled==1) x_data[x]->beta[t][i] *= x_data[x]->c[t];
}
}
} // for all observations, starting with last one
} // for all groups within skill
}
void HMMProblem::computeXiGamma(NCAT xndat, struct data** x_data){
HMMProblem::initXiGamma(xndat, x_data);
NPAR nS = this->p->nS;
// int parallel_now = this->p->parallel==2; //PAR
// #pragma omp parallel for schedule(dynamic) if(parallel_now) //PAR
for(NCAT x=0; x<xndat; x++) {
NDAT t;
NPAR i, j, o_tp1;
NUMBER denom;
if( x_data[x]->cnt!=0 ) continue; // ... and the thing has not been computed yet (e.g. from group to skill)
for(t=0; t<(x_data[x]->n-1); t++) { // -1 is important
// o_tp1 = x_data[x]->obs[t+1];
o_tp1 = this->p->dat_obs[ x_data[x]->ix[t+1] ];//->get( x_data[x]->ix[t+1] );
denom = 0.0;
for(i=0; i<nS; i++) {
for(j=0; j<nS; j++) {
denom += x_data[x]->alpha[t][i] * getA(x_data[x],i,j) * x_data[x]->beta[t+1][j] * ((o_tp1<0)?1:getB(x_data[x],j,o_tp1));
}
}
for(i=0; i<nS; i++) {
for(j=0; j<nS; j++) {
x_data[x]->xi[t][i][j] = x_data[x]->alpha[t][i] * getA(x_data[x],i,j) * x_data[x]->beta[t+1][j] * ((o_tp1<0)?1:getB(x_data[x],j,o_tp1)) / ((denom>0)?denom:1); //
x_data[x]->gamma[t][i] += x_data[x]->xi[t][i][j];
}
}
} // for all observations within skill-group
} // for all groups in skill
}
void HMMProblem::setGradPI(FitBit *fb){
if(this->p->block_fitting[0]>0) return;
NDAT t = 0, ndat = 0;
NPAR i, o;
struct data* dt;
for(NCAT x=0; x<fb->xndat; x++) {
dt = fb->x_data[x];
if( dt->cnt!=0 ) continue;
ndat += dt->n;
o = this->p->dat_obs[ dt->ix[t] ];//->get( dt->ix[t] );
for(i=0; i<this->p->nS; i++) {
fb->gradPI[i] -= dt->beta[t][i] * ((o<0)?1:getB(dt,i,o)) / safe0num(dt->p_O_param);
}
}
if( this->p->Cslices>0 ) // penalty
fb->addL2Penalty(FBV_PI, this->p, (NUMBER)ndat);
}
void HMMProblem::setGradA (FitBit *fb){
if(this->p->block_fitting[1]>0) return;
NDAT t, ndat = 0;
NPAR o, i, j;
struct data* dt;
for(NCAT x=0; x<fb->xndat; x++) {
dt = fb->x_data[x];
if( dt->cnt!=0 ) continue;
ndat += dt->n;
for(t=1; t<dt->n; t++) {
o = this->p->dat_obs[ dt->ix[t] ];//->get( dt->ix[t] );
for(i=0; i<this->p->nS; i++)
for(j=0; j<this->p->nS; j++)
fb->gradA[i][j] -= dt->beta[t][j] * ((o<0)?1:getB(dt,j,o)) * dt->alpha[t-1][i] / safe0num(dt->p_O_param);
}
}
if( this->p->Cslices>0 ) // penalty
fb->addL2Penalty(FBV_A, this->p, (NUMBER)ndat);
}
void HMMProblem::setGradB (FitBit *fb){
if(this->p->block_fitting[2]>0) return;
NDAT t, ndat = 0;
NPAR o, o0, i, j;
struct data* dt;
for(NCAT x=0; x<fb->xndat; x++) {
dt = fb->x_data[x];
if( dt->cnt!=0 ) continue;
ndat += dt->n;
for(t=0; t<dt->n; t++) { // Levinson MMFST
o = this->p->dat_obs[ dt->ix[t] ];//->get( dt->ix[t] );
o0 = this->p->dat_obs[ dt->ix[0] ];//->get( dt->ix[t] );
if(o<0) // if no observation -- skip
continue;
for(j=0; j<this->p->nS; j++)
if(t==0) {
fb->gradB[j][o] -= (o0==o) * getPI(dt,j) * dt->beta[0][j];
} else {
for(i=0; i<this->p->nS; i++)
fb->gradB[j][o] -= ( dt->alpha[t-1][i] * getA(dt,i,j) * dt->beta[t][j] /*+ (o0==o) * getPI(dt,j) * dt->beta[0][j]*/ ) / safe0num(dt->p_O_param); // Levinson MMFST
}
}
}
if( this->p->Cslices>0 ) // penalty
fb->addL2Penalty(FBV_B, this->p, (NUMBER)ndat);
}
NDAT HMMProblem::computeGradients(FitBit *fb){
fb->toZero(FBS_GRAD);
NDAT ndat = computeAlphaAndPOParam(fb->xndat, fb->x_data);
computeBeta(fb->xndat, fb->x_data);
if(fb->pi != NULL && this->p->block_fitting[0]==0) setGradPI(fb);
if(fb->A != NULL && this->p->block_fitting[1]==0) setGradA(fb);
if(fb->B != NULL && this->p->block_fitting[2]==0) setGradB(fb);
return ndat;
} // computeGradients()
void HMMProblem::toFile(const char *filename) {
switch(this->p->structure)
{
case STRUCTURE_SKILL:
toFileSkill(filename);
break;
case STRUCTURE_GROUP:
toFileGroup(filename);
break;
default:
fprintf(stderr,"Solver specified is not supported.\n");
break;
}
}
void HMMProblem::toFileSkill(const char *filename) {
FILE *fid = fopen(filename,"w");
if(fid == NULL) {
fprintf(stderr,"Can't write output model file %s\n",filename);
exit(1);
}
// write solved id
writeSolverInfo(fid, this->p);
fprintf(fid,"Null skill ratios\t");
for(NPAR m=0; m<this->p->nO; m++)
fprintf(fid," %10.7f%s",this->null_obs_ratio[m],(m==(this->p->nO-1))?"\n":"\t");
NCAT k;
std::map<NCAT,std::string>::iterator it;
for(k=0;k<this->p->nK;k++) {
it = this->p->map_skill_bwd->find(k);
fprintf(fid,"%d\t%s\n",k,it->second.c_str());
NPAR i,j,m;
fprintf(fid,"PI\t");
for(i=0; i<this->p->nS; i++)
fprintf(fid,"%12.10f%s",this->pi[k][i],(i==(this->p->nS-1))?"\n":"\t");
fprintf(fid,"A\t");
for(i=0; i<this->p->nS; i++)
for(j=0; j<this->p->nS; j++)
fprintf(fid,"%12.10f%s",this->A[k][i][j],(i==(this->p->nS-1) && j==(this->p->nS-1))?"\n":"\t");
fprintf(fid,"B\t");
for(i=0; i<this->p->nS; i++)
for(m=0; m<this->p->nO; m++)
fprintf(fid,"%12.10f%s",this->B[k][i][m],(i==(this->p->nS-1) && m==(this->p->nO-1))?"\n":"\t");
}
fclose(fid);
}
void HMMProblem::toFileGroup(const char *filename) {
FILE *fid = fopen(filename,"w");
if(fid == NULL) {
fprintf(stderr,"Can't write output model file %s\n",filename);
exit(1);
}
// write solved id
writeSolverInfo(fid, this->p);
fprintf(fid,"Null skill ratios\t");
for(NPAR m=0; m<this->p->nO; m++)
fprintf(fid," %10.7f%s",this->null_obs_ratio[m],(m==(this->p->nO-1))?"\n":"\t");
NCAT g;
std::map<NCAT,std::string>::iterator it;
for(g=0;g<this->p->nG;g++) {
it = this->p->map_group_bwd->find(g);
fprintf(fid,"%d\t%s\n",g,it->second.c_str());
NPAR i,j,m;
fprintf(fid,"PI\t");
for(i=0; i<this->p->nS; i++)
fprintf(fid,"%12.10f%s",this->pi[g][i],(i==(this->p->nS-1))?"\n":"\t");
fprintf(fid,"A\t");
for(i=0; i<this->p->nS; i++)
for(j=0; j<this->p->nS; j++)
fprintf(fid,"%12.10f%s",this->A[g][i][j],(i==(this->p->nS-1) && j==(this->p->nS-1))?"\n":"\t");
fprintf(fid,"B\t");
for(i=0; i<this->p->nS; i++)
for(m=0; m<this->p->nO; m++)
fprintf(fid,"%12.10f%s",this->B[g][i][m],(i==(this->p->nS-1) && m==(this->p->nO-1))?"\n":"\t");
}
fclose(fid);
}
void HMMProblem::producePCorrect(NUMBER*** group_skill_map, NUMBER* local_pred, NCAT* ks, NCAT nks, struct data* dt) {
NPAR m, i;
NCAT k;
NUMBER *local_pred_inner = init1D<NUMBER>(this->p->nO);
for(m=0; m<this->p->nO; m++) local_pred[m] = 0.0;
for(int l=0; l<nks; l++) {
for(m=0; m<this->p->nO; m++) local_pred_inner[m] = 0.0;
k = ks[l];
dt->k = k;
for(m=0; m<this->p->nO; m++)
for(i=0; i<this->p->nS; i++)
local_pred_inner[m] += group_skill_map[dt->g][k][i] * getB(dt,i,m);
for(m=0; m<this->p->nO; m++)
local_pred[m] += local_pred_inner[m];
}
if(nks>1) {
for(m=0; m<this->p->nO; m++)
local_pred[m] /= nks;
}
free(local_pred_inner);
}
//void HMMProblem::predict(NUMBER* metrics, const char *filename, NPAR* dat_obs, NCAT *dat_group, NCAT *dat_skill, StripedArray<NCAT*> *dat_multiskill) {
void HMMProblem::predict(NUMBER* metrics, const char *filename, NPAR* dat_obs, NCAT *dat_group, NCAT *dat_skill, NCAT *dat_skill_stacked, NCAT *dat_skill_rcount, NDAT *dat_skill_rix, HMMProblem **hmms, NPAR nhmms, NPAR *hmm_idx) {
NDAT t;
NCAT g, k;
NPAR i, j, m, o, isTarget = 0;
NPAR nS = hmms[0]->p->nS, nO = hmms[0]->p->nO;
NCAT nK = hmms[0]->p->nK, nG = hmms[0]->p->nG;
NDAT N = hmms[0]->p->N;
NDAT N_null = hmms[0]->p->N_null;
char f_multiskill = hmms[0]->p->multiskill;
char f_update_known = hmms[0]->p->update_known;
char f_update_unknown = hmms[0]->p->update_unknown;
int f_predictions = hmms[0]->p->predictions;
char f_metrics_target_obs = hmms[0]->p->metrics_target_obs;
for(i=1; i<nhmms; i++) {
if( nS != hmms[i]->p->nS || nO != hmms[i]->p->nO || nK != hmms[i]->p->nK ||
nG != hmms[i]->p->nG || hmms[i]->p->N != hmms[i]->p->N || hmms[i]->p->N_null != hmms[i]->p->N_null ||
f_multiskill != hmms[i]->p->multiskill ||
f_update_known != hmms[i]->p->update_known ||
f_update_unknown != hmms[i]->p->update_unknown ||
f_predictions != hmms[i]->p->predictions ||
f_metrics_target_obs != hmms[i]->p->metrics_target_obs) {
fprintf(stderr,"Error! One of count variables (N, N_null, nS, nO, nK, nG) or flags (multiskill, predictions, metrics_target_obs, update_known, update_unknown) does not have the same value across multiple models\n");
exit(1);
}
}
NUMBER *local_pred = init1D<NUMBER>(nO); // local prediction
NUMBER *pLe = init1D<NUMBER>(nS);// p(L|evidence);
NUMBER pLe_denom; // p(L|evidence) denominator
NUMBER ***group_skill_map = init3D<NUMBER>(nG, nK, nS);
NUMBER ll = 0.0, ll_no_null = 0.0, rmse = 0.0, rmse_no_null = 0.0, accuracy = 0.0, accuracy_no_null = 0.0;
NUMBER p;
// NUMBER *dat_predict = Calloc(NUMBER, N * nO);
FILE *fid = NULL; // file for storing prediction should that be necessary
if(f_predictions>0) {
fid = fopen(filename,"w");
if(fid == NULL)
{
fprintf(stderr,"Can't write output model file %s\n",filename);
exit(1);
}
}
// initialize
struct data* dt = new data;
NDAT count = 0;
// NDAT d = 0;
HMMProblem *hmm;
for(t=0; t<N; t++) {
// output_this = true;
o = dat_obs[t];
g = dat_group[t];
dt->g = g;
hmm = (nhmms==1)?hmms[0]:hmms[hmm_idx[t]]; // if just one hmm, use 0's, otherwise take the index value
isTarget = hmm->p->metrics_target_obs == o;
NCAT *ar;
int n;
if(f_multiskill==0) {
k = dat_skill[t];
ar = &k;
n = 1;
} else {
k = dat_skill_stacked[ dat_skill_rix[t] ];
ar = &dat_skill_stacked[ dat_skill_rix[t] ];
n = dat_skill_rcount[t];
}
// deal with null skill
if(ar[0]<0) { // if no skill label
isTarget = hmm->null_skill_obs==o;
rmse += pow(isTarget - hmm->null_obs_ratio[f_metrics_target_obs],2);
accuracy += isTarget == (hmm->null_obs_ratio[f_metrics_target_obs]==maxn(hmm->null_obs_ratio,nO) && hmm->null_obs_ratio[f_metrics_target_obs] > 1/nO);
// rmse += pow(isTarget - hmm->null_skill_obs_prob,2);
// accuracy += isTarget == (hmm->null_skill_obs_prob>=0.5);
ll -= isTarget*safelog(hmm->null_skill_obs_prob) + (1-isTarget)*safelog(1 - hmm->null_skill_obs_prob);
// if(this->p->predictions>0 && output_this) // write predictions file if it was opened
for(m=0; m<nO; m++) {
fprintf(fid,"%12.10f%s",hmm->null_obs_ratio[m],(m<(nO-1))?"\t":"\n");//PRINTNOW
// d = (NDAT)m*N + t;
// dat_predict[ d ] = hmm->null_obs_ratio[m];
}
continue;
}
// check if {g,k}'s were initialized
for(int l=0; l<n; l++) {
k = ar[l];
if( group_skill_map[g][k][0]==0)
{
dt->k = k;
for(i=0; i<nS; i++) {
group_skill_map[g][k][i] = hmm->getPI(dt,i);
count++;
}
}// pLo/pL not set
}// for all skills at this transaction
// produce prediction and copy to result
hmm->producePCorrect(group_skill_map, local_pred, ar, n, dt);
projectsimplex(local_pred, nO); // addition to make sure there's not side effects
// if necessary guess the obsevaion using Pi and B
if(f_update_known=='g') {
NUMBER max_local_pred=0;
NPAR ix_local_pred=0;
for(m=0; m<nO; m++) {
if( local_pred[m]>max_local_pred ) {
max_local_pred = local_pred[m];
ix_local_pred = m;
}
}
o = ix_local_pred;
}
// update pL
for(int l=0; l<n; l++) {
k = ar[l];
dt->k = k;
if(o>-1) { // known observations //
// update p(L)
pLe_denom = 0.0;
// 1. pLe = (L .* B(:,o)) ./ ( L'*B(:,o)+1e-8 );
for(i=0; i<nS; i++)
pLe_denom += group_skill_map[g][k][i] * hmm->getB(dt,i,o); // TODO: this is local_pred[o]!!!
for(i=0; i<nS; i++)
pLe[i] = group_skill_map[g][k][i] * hmm->getB(dt,i,o) / safe0num(pLe_denom);
// 2. L = (pLe'*A)';
for(i=0; i<nS; i++)
group_skill_map[g][k][i]= 0.0;
for(j=0; j<nS; j++)
for(j=0; j<nS; j++)
for(i=0; i<nS; i++)
group_skill_map[g][k][j] += pLe[i] * hmm->getA(dt,i,j);//A[i][j];
} else { // unknown observation
// 2. L = (pL'*A)';
for(i=0; i<nS; i++)
pLe[i] = group_skill_map[g][k][i]; // copy first;
for(i=0; i<nS; i++)
group_skill_map[g][k][i] = 0.0; // erase old value
for(j=0; j<nS; j++)
for(i=0; i<nS; i++)
group_skill_map[g][k][j] += pLe[i] * hmm->getA(dt,i,j);
}// observations
projectsimplex(group_skill_map[g][k], nS); // addition to make sure there's not side effects
}
// write prediction out (after update)
// write prediction out (before pKnown update)
if(f_predictions>0 /*&& output_this*/) { // write predictions file if it was opened
for(m=0; m<nO; m++) {
fprintf(fid,"%12.10f%s",local_pred[m],(m<(nO-1))?"\t": ((f_predictions==1)?"\n":"\t") );// if we print states of KCs, continut
// d = (NDAT)m*N + t;
// dat_predict[ d ] = local_pred[m];
}
if(f_predictions==2) { // if we print out states of KC's as welll
for(int l=0; l<n; l++) { // all KC here
fprintf(fid,"%12.10f%s",group_skill_map[g][ ar[l] ][0], (l==(n-1) && l==(n-1))?"\n":"\t"); // nnon boost // if end of all states: end line//UNBOOST
// fprintf(fid,"%12.10f%s",gsm(g, ar[l] )[0], (l==(n-1) && l==(n-1))?"\n":"\t"); // if end of all states: end line //BOOST
}
}
}
rmse += pow(isTarget-local_pred[f_metrics_target_obs],2);
rmse_no_null += pow(isTarget-local_pred[f_metrics_target_obs],2);
accuracy += isTarget == (local_pred[f_metrics_target_obs]==maxn(local_pred,nO) && local_pred[f_metrics_target_obs]>1/nO);
accuracy_no_null += isTarget == (local_pred[f_metrics_target_obs]==maxn(local_pred,nO) && local_pred[f_metrics_target_obs]>1/nO);
p = safe01num(local_pred[f_metrics_target_obs]);
ll -= safelog( p)* isTarget + safelog(1-p)*(1-isTarget);
ll_no_null -= safelog( p)* isTarget + safelog(1-p)*(1-isTarget);
} // for all data
delete(dt);
free(local_pred);
free(pLe);
free3D<NUMBER>(group_skill_map, nG, nK);
rmse = sqrt(rmse / N);
rmse_no_null = sqrt(rmse_no_null / (N - N_null));
if(metrics != NULL) {
metrics[0] = ll;
metrics[1] = ll_no_null;
metrics[2] = rmse;
metrics[3] = rmse_no_null;
metrics[4] = accuracy/N;
metrics[5] = accuracy_no_null/(N-N_null);
}
// if(f_predictions>0) {
// ofstream fout(filename,ios::out);
// char str[1024];
// if(!fout)
// {
// fprintf(stderr,"WARNINT! Failed to open output prediction file %s for writing\n",filename);
// //exit(1); // do not exit with error
// }
//
// for(NDAT t=0; t<N; t++) {
// for(m=0; m<nO; m++) {
// d = (NDAT)m*N + t;
// sprintf(str,"%12.10f%s",dat_predict[d],(m<(nO-1))?"\t": ((f_predictions==1)?"\n":"\t") );
// fout << str;
// }
//// if(f_predictions==2) { // if we print out states of KC's as welll
//// if(f_multiskill==0) {
//// k = dat_skill[t];
//// ar = &k;
//// v = dat_known[t];
//// var = &v;
//// n = 1;
//// } else {
//// k = dat_skill_stacked[ dat_skill_rix[t] ];
//// ar = &dat_skill_stacked[ dat_skill_rix[t] ];
//// v = dat_known_stacked[ dat_skill_rix[t] ];
//// var = &dat_known_stacked[ dat_skill_rix[t] ];
//// n = dat_skill_rcount[t];
//// }
//// for(int l=0; l<n && ar[0]>-1; l++) { // all KC here
//// sprintf(str,"%12.10f%s",var[l], (l==(n-1) && l==(n-1))?"\n":"\t");
//// fout << str;
//// }
//// }
// }
// fout.close();
// }
// free(dat_predict);
if(f_predictions>0) // close predictions file if it was opened
fclose(fid);
}
NUMBER HMMProblem::getLogLik() { // get log likelihood of the fitted model
return neg_log_lik;
}
NCAT HMMProblem::getNparams() {
return this->n_params;
}
NUMBER HMMProblem::getNullSkillObs(NPAR m) {
return this->null_obs_ratio[m];
}
void HMMProblem::fit() {
NUMBER* loglik_rmse = init1D<NUMBER>(2);
FitNullSkill(loglik_rmse, false /*do RMSE*/);
switch(this->p->solver)
{
case METHOD_BW: // Conjugate Gradient Descent
loglik_rmse[0] += BaumWelch();
break;