-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeandm.cpp
1661 lines (1454 loc) · 45.1 KB
/
beandm.cpp
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
/*
* BEANDiscoMulti: main program
*
* Copyright 2013 Diane Oyen <doyen(at)cs.unm.edu>
*
* Modified from BEANDisco, originally:
* Copyright 2011 Teppo Niinimäki <teppo.niinimaki(at)helsinki.fi>
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <gsl/gsl_sf_hyperg.h>
#include <gsl/gsl_sf_result.h>
#include "common.hpp"
#include "logger.hpp"
#include "lognum.hpp"
#include "timer.hpp"
#include "data.hpp"
#include "stacksubset.hpp"
#include "scores.hpp"
#include "parentsetmap.hpp"
#include "bucketorder.hpp"
#include "parbucketorder.hpp"
//#define NDEBUG
#include <cassert>
#define BEAND_VERSION_STRING "1.0.1"
// type definitions
typedef Lognum<double> Real;
// create a logger
Logger logger;
struct Arc {
int tail;
int head;
void setFirst() {
head = 0;
tail = 1;
}
bool next(int nNodes) {
++tail;
if (head == tail)
++tail;
if (tail >= nNodes) {
tail = 0;
++head;
if (head >= nNodes) {
head = 0;
return false;
}
}
return true;
}
bool holds(int v, const StackSubset& pa) {
return (head != v || pa.contains(tail));
}
};
std::ostream& operator<<(std::ostream& os, const Arc& arc) {
return os << arc.tail << " -> " << arc.head;
}
const Arc NullArc = { -1, -1 };
/**
* A templated map data structure with Arc as index type.
*/
template <class T>
class ArcMap {
private:
int nNodes_;
T* data_;
ArcMap(const ArcMap&); // disable copy constructor
ArcMap& operator=(const ArcMap&); // disable copying
public:
ArcMap(int nNodes) {
nNodes_ = nNodes;
data_ = new T[nNodes * nNodes];
}
~ArcMap() {
delete[] data_;
}
void setAll(T value) {
for (int i = 0; i < nNodes_ * nNodes_; ++i)
data_[i] = value;
}
T& operator[] (Arc arc) {
return data_[arc.head + arc.tail * nNodes_];
}
T operator[] (Arc arc) const {
return data_[arc.head + arc.tail * nNodes_];
}
};
/**
* Computes single-task K2 scores for all node-parentset pairs for all tasks
*/
void computeScores(const Data* data, ParentsetMap<Real>** scores,
int nTasks) {
//computeLogGammas(2 * data[0].nSamples);
StackSubset parents(scores[0]->maxParents);
for (int node = 0; node < scores[0]->nNodes; ++node) {
parents.clear();
do {
if (parents.contains(node))
continue;
double *logScores = new double[nTasks];
computeScore(logScores, data, parents, node,
nTasks);
for (int t = 0; t < nTasks; t++)
{
Lognum<double> tmp;
tmp.setLog(logScores[t]);
(*scores[t])(node, parents) = to<Real>(tmp);
}
} while (parents.next(0, scores[0]->nNodes, scores[0]->maxParents));
}
freeLogGammas();
}
int calcDelta(StackSubset p1, StackSubset p2) {
int delta = 0;
for (int i = 0; i < p1.size(); i++) {
if (!p2.contains(p1[i]))
delta++;
}
return delta;
}
Real* preCalcPDeltas(int maxN) {
Real* pDeltas = new Real[maxN];
if (maxN == 1) {
pDeltas[0] = 1;
return pDeltas;
}
double logZ = maxN * log(4);
double loghyp;
for (int i = 0; i < maxN; i++) {
loghyp = log(gsl_sf_hyperg_2F1(1.0, maxN - 1.0, i + 2.0, 0.25));
pDeltas[i].setLog(loghyp - logZ - log(i+1));
}
return pDeltas;
}
/**
* Computes multitask scores for all node-parentset pairs for all tasks with parentset prior
**/
void computeMultiScores(ParentsetMap<Real>** multiScores, ParentsetMap<Real>** scores,
int nTasks, int maxParentSets) {
Real* pDeltas = preCalcPDeltas(scores[0]->nNodes);
StackSubset parents(scores[0]->maxParents);
StackSubset pa(scores[0]->maxParents);
size_t** topPa = new size_t*[nTasks];
int numParentSets = 0;
// Pre-compute product of all single-task scores
ParentsetMap<Real>* kscores;
kscores = new ParentsetMap<Real>(scores[0]->nNodes, scores[0]->maxParents);
parents.clear();
for (int node = 0; node < scores[0]->nNodes; ++node) {
do {
if (parents.contains(node))
continue;
(*kscores)(node, parents) = 1;
} while (parents.next(0, scores[0]->nNodes, scores[0]->maxParents));
for (int task = 0; task < nTasks; ++task) {
do {
if (parents.contains(node))
continue;
(*kscores)(node, parents) = (*scores[task])(node, parents);
} while (parents.next(0, scores[0]->nNodes, scores[0]->maxParents));
}
}
for (int node = 0; node < scores[0]->nNodes; ++node) {
// Sort top family scores for each node in each task
if (maxParentSets > 0) {
for (int task = 0; task < nTasks; ++task) {
topPa[task] = new size_t[maxParentSets];
numParentSets = 0;
pa.clear();
do {
if (pa.contains(node))
continue;
Real scoreTemp = (*kscores)(node, pa) / (*scores[task])(node, pa);
// topPa full, see if this score will be added
if ((numParentSets == maxParentSets) &&
((*kscores)(node, topPa[task][numParentSets-1]) / (*scores[task])(node, topPa[task][numParentSets-1]) > scoreTemp))
continue;
// otherwise, it will be added, just need to find where
if (numParentSets == 0) {
topPa[task][0] = scores[task]->getParentsetIndex(pa);
numParentSets++;
continue;
}
if (numParentSets < maxParentSets) {
numParentSets++;
}
int i = numParentSets - 1;
while ((i>0) && (scoreTemp > (*kscores)(node, topPa[task][i-1]) / (*scores[task])(node, topPa[task][i-1]))) {
topPa[task][i] = topPa[task][i-1];
i--;
}
topPa[task][i] = scores[task]->getParentsetIndex(pa);
} while(pa.next(0, scores[0]->nNodes, scores[0]->maxParents));
}
}
// calculate scores
parents.clear();
do {
if (parents.contains(node))
continue;
// Initialize prior, parent sets to loop through
//Real* prior = new Real[nTasks];
for (int task = 0; task < nTasks; ++task) {
//prior[task] = 0;
(*multiScores[task])(node, parents) = 0;
}
// approximate prior with just top scoring parent sets
if (maxParentSets > 0) {
for (int i = 0; i < numParentSets; i++) {
for (int task = 0; task < nTasks; ++task) {
int delta = calcDelta(parents, topPa[task][i]);
(*multiScores[task])(node, parents) += (*kscores)(node, topPa[task][i]) * pDeltas[delta] / (*scores[task])(node, topPa[task][i]);
}
}
}
else { // do full prior
pa.clear();
// loop through parent sets (to examine pairs of parent sets)
do {
if (pa.contains(node))
continue;
int delta = calcDelta(parents, pa);
//for (int task = 0; task < nTasks; ++task) {
// prior[task] += (*scores[task])(node, pa) * pDeltas[delta];
//}
// apply prior from kscores to each task
for (int task = 0; task < nTasks; ++task) {
(*multiScores[task])(node, parents) += (*kscores)(node, pa) * pDeltas[delta] / (*scores[task])(node, pa);
}
} while (pa.next(0, scores[0]->nNodes, scores[0]->maxParents));
}
// Multiply prior and score
for (int task = 0; task < nTasks; ++task) {
(*multiScores[task])(node, parents) *= (*scores[task])(node, parents);
}
// apply prior from all tasks to each task
//for (int task = 0; task < nTasks; ++task) {
//(*multiScores[task])(node, parents) = (*scores[task])(node, parents);
//for (int j = 0; j < nTasks; ++j) {
// if (j==task)
// continue;
//if (prior[j] == 0)
// prior[j] = 1;
// (*multiScores[task])(node, parents) *= prior[j];
//}
//}
} while (parents.next(0, scores[0]->nNodes, scores[0]->maxParents));
}
if (maxParentSets > 0) {
for (int t; t < nTasks; t++)
delete[] topPa[t];
}
delete[] topPa;
delete[] pDeltas;
delete kscores;
}
template <class T>
T binom(int n, int k) {
return round(exp(lgamma(n+1) - lgamma(k+1) - lgamma(n-k+1)));
}
template <>
Lognum<double> binom<Lognum<double> >(int n, int k) {
Lognum<double> res;
res.setLog(lgamma(n+1) - lgamma(k+1) - lgamma(n-k+1));
return res;
}
Real* preCalcInvBinoms(int n) {
Real* invBinoms = new Real[n];
for (int k = 0; k < n; ++k)
invBinoms[k] = Real(1.0) / binom<Real>(n, k);
return invBinoms;
}
/**
* Divides scores by the number of parent sets with same size.
*/
void weightScores(ParentsetMap<Real>& scores) {
Real* invBinoms = preCalcInvBinoms(scores.nNodes - 1);
StackSubset pa(scores.maxParents);
for (int v = 0; v < scores.nNodes; ++v) {
//pa.length = 0;
do {
scores(v, pa) *= invBinoms[pa.size()];
} while (pa.next(0, scores.nNodes, scores.maxParents));
}
delete[] invBinoms;
}
/*
template <class POF>
void translateParentsetMap(
const POF& pof,
const typename POF::Order& po,
ParentsetMap<Real>& values,
ParentsetMap<Real>& transValues
) {
for (int v = 0; v < values.nNodes; ++v) {
int vt = po.getOrder()[v];
StackSubset x(values.maxParents);
StackSubset xt(values.maxParents);
do {
translateSubset(po.getOrder(), x, xt);
transValues(v, xi) = values(vt, xt);
} while (x.next(0, values.nNodes, values.maxParents));
}
}/**/
/*template <class POF>
void calcTailSums(
const POF& pof,
const typename POF::Order& po,
ParentsetMap<Real>& scores,
int node,
Arc feature,
typename POF::template IdealMap<Real>& tailSums
) {
typename POF::Ideal y(pof);
do {
const StackSubset yHat = y.hat();
Real sum = 0;
if (yHat.size() <= scores.maxParents) {
int maxTailSubsetSize = min((size_t)y.tailSize(), scores.maxParents - yHat.size());
StackSubset tailPart(maxTailSubsetSize);
StackSubset x(max((size_t)scores.maxParents, yHat.size()));
StackSubset xTrans(scores.maxParents);
//tailPart.clear();
do {
x.clear();
x.copyToEnd(yHat);
x.copyToEnd(tailPart);
translateSubset(po.getOrder(), x, xTrans);
if (feature.holds(node, xTrans))
sum = sum + scores(node, xTrans);
//if (feature.holds(x))
// sum = sum + scores(node, x);
} while (tailPart.next(0, y.tailSize(), maxTailSubsetSize));
}
tailSums[y] = sum;
} while (y.next());
}/**/
/**
* Computes tail sums of scores in given partial order.
*/
template <class POF>
void calcTailSums(
const POF& pof,
const typename POF::Order& po,
ParentsetMap<Real>& scores,
int node,
Arc feature,
typename POF::template IdealMap<Real>& tailSums
) {
tailSums.setAll(0.0);
StackSubset x(scores.maxParents);
StackSubset xt(scores.maxParents); // translated x
typename POF::Ideal xId(pof);
do {
translateSubset(po.getOrder(), x, xt);
//size_t xti = scores.getParentsetIndex(xt);
xId.setSuperOf(x);
if (feature.holds(node, xt))
tailSums[xId] += scores(node, xt);
} while (x.next(0, scores.nNodes, scores.maxParents));
}/**/
/*template <class POF>
void updateTailSums(
const POF& pof,
const typename POF::Order& po,
ParentsetMap<Real>& scores,
int node,
typename POF::template IdealMap<Real>& tailSums,
int node1,
int node2
) {
if (node == node1 || node == node2) {
calcTailSums(pof, po, scores, po[node], NullArc, tailSums);
return;
}
StackSubset x(scores.maxParents);
StackSubset x1t(scores.maxParents); // translated x
StackSubset x2t(scores.maxParents); // translated x
typename POF::Ideal x1Id(pof);
typename POF::Ideal x2Id(pof);
typename POF::template IdealMap<Real> additions(pof);
typename POF::template IdealMap<Real> subtractions(pof);
additions.setAll(0.0);
subtractions.setAll(0.0);
int nodet = po[node];
do {
if (x.contains(node1) || x.contains(node2))
continue;
x.push(node1);
translateSubset(po.getOrder(), x, x1t);
x1Id.setSuperOf(x);
x.pop();
x.push(node2);
translateSubset(po.getOrder(), x, x2t);
x2Id.setSuperOf(x);
x.pop();
//tailSums[x1Id] = tailSums[x1Id] + scores(node, x1t) - scores(node, x2t);
//tailSums[x2Id] = tailSums[x2Id] + scores(node, x2t) - scores(node, x1t);
additions[x1Id] += scores(nodet, x1t);
subtractions[x1Id] += scores(nodet, x2t);
additions[x2Id] += scores(nodet, x2t);
subtractions[x2Id] += scores(nodet, x1t);
} while (x.next(0, scores.nNodes, scores.maxParents - 1));
{
printf(" sub: ");
typename POF::Ideal id(pof);
do {
printf("%8.6g ", to<double>(log(subtractions[id])));
} while (id.next());
printf("\n");
}
tailSums -= subtractions;
{
printf(" => ");
typename POF::Ideal id(pof);
do {
printf("%8.6g ", to<double>(log(tailSums[id])));
} while (id.next());
printf("\n");
}
{
printf(" add: ");
typename POF::Ideal id(pof);
do {
printf("%8.6g ", to<double>(log(additions[id])));
} while (id.next());
printf("\n");
}
tailSums += additions;
//{
// printf(" => ");
// typename POF::Ideal id(pof);
// do {
// printf("%8.6g ", to<double>(log(tailSums[id])));
// } while (id.next());
// printf("\n");
//}
}/**/
/**
* Computes alphas from scores.
*/
template <class POF>
void calcAlphas(
const POF& pof,
const typename POF::Order& po,
ParentsetMap<Real>& scores,
Arc arc,
std::vector<typename POF::template IdealMap<Real> >& alphas
) {
for (int v = 0; v < pof.n; ++v) {
//printf(" v = %d\n", v);
calcTailSums(pof, po, scores, po[v], arc, alphas[v]);
//calcTailSums(pof, po, scores, v, arc, alphas[v]);
//{
// printf(" ");
// typename POF::Ideal i(pof);
// do {
// printf("%g ", to<double>(log(alphas[v][i])));
// } while (i.next());
// printf("\n");
//}
alphas[v].fastSparseZetaTransform();
//{
// printf(" ");
// typename POF::Ideal i(pof);
// do {
// printf("%g ", to<double>(log(alphas[v][i])));
// } while (i.next());
// printf("\n");
//}
}
}
/*
template <class POF>
void fastSparseZetaTransform(
const POF& pof,
typename POF::template IdealMap<Real>& im
) {
// for each variable
for (int v = 0; v < pof.n; ++v) {
// iterate over all ideals y
typename POF::Ideal y(pof);
//y.setFirstExpandableWith(v);
//do {
// y.shrinkWith(v);
// Real tmp = im[y];
// y.expandWith(v);
// im[y] += tmp;
//} while(y.nextExpandableWith(v));
do {
if (y.isShrinkableWith(v)) {
y.shrinkWith(v);
Real tmp = im[y];
y.expandWith(v);
im[y] += tmp;
}
} while(y.next());
}
}/**/
/*template <class POF>
Real basicForwardBackwardSum(
const POF& pof,
typename POF::template IdealMap<Real>& fp,
typename POF::template IdealMap<Real>& bp,
std::vector<typename POF::template IdealMap<Real> >& alpha,
int v) {
int b = v / pof.maxBucketSize;
int i = v % pof.maxBucketSize;
int bucketSize = pof.bucketSize(b);
// index increment from bucket number
int bi = b * ((1 << pof.maxBucketSize) - 1);
// variable mask
int vm = 1 << i;
Real sum = 0.0;
for (int yHatI = 0; yHatI < (1 << bucketSize); ++yHatI)
if (!(vm & yHatI))
//sum += alpha[v][bi + yHatI] * fp[bi + yHatI] * bp[bi + yHatI + vm];
sum += alpha[v][b][yHatI] * fp[b][yHatI] * bp[b][yHatI + vm];
return sum;
}/**/
/*template <class POF>
void calcGammas(
const POF& pof,
typename POF::template IdealMap<Real>& fp,
typename POF::template IdealMap<Real>& bp,
std::vector<typename POF::template IdealMap<Real> >& gamma
) {
int v = 0;
// for each bucket
for (int b = 0; b < pof.nBuckets(); ++b) {
int bucketSize = pof.bucketSize(b);
// index increment from bucket number
int bi = b * ((1 << pof.maxBucketSize) - 1);
// for each variable in bucket
for (int i = 0; i < bucketSize; ++i) {
// variable mask
int vm = 1 << i;
// enumerate all Y̌:s in the bucket
for (int yHatI = 0; yHatI < (1 << bucketSize) - 1; ++yHatI)
if (!(vm & yHatI))
gamma[v][b][yHatI] = fp[b][yHatI] * bp[b][yHatI + vm];
gamma[v].fastSparseUpZetaTransform();
++v;
}
}
}/**/
/**
* Computes gammas from forward and backward sums.
*/
template <class POF>
void calcGammas(
const POF& pof,
typename POF::template IdealMap<Real>& fp,
typename POF::template IdealMap<Real>& bp,
std::vector<typename POF::template IdealMap<Real> >& gamma
) {
// for each variable
for (int v = 0; v < pof.n; ++v) {
// iterate over all ideals y
typename POF::Ideal y(pof);
//y.setFirstExpandableWith(v);
//do {
// y.expandWith(v);
// Real tmp = bp[y];
// y.shrinkWith(v);
// gamma[v][y] = fp[y] * tmp;
//} while(y.nextExpandableWith(v));
do {
if (y.isShrinkableWith(v)) {
Real tmp = bp[y];
y.shrinkWith(v);
gamma[v][y] = fp[y] * tmp;
y.expandWith(v);
}
} while(y.next());
gamma[v].fastSparseUpZetaTransform();
}
}/**/
/**
* Computes the final (unnormalized) probabilities for each arc from gammas and local scores.
*/
template <class POF>
void addParentsetSums(
const POF& pof,
ParentsetMap<Real>& scores,
std::vector<typename POF::template IdealMap<Real> >& gammas,
const typename POF::Order& po,
ArcMap<Real>& sums
) {
StackSubset pa(scores.maxParents);
StackSubset pat(scores.maxParents);
typename POF::Ideal paId(pof);
do {
translateSubset(po.getOrder(), pa, pat);
//size_t pai = scores.getParentsetIndex(pa);
size_t pati = scores.getParentsetIndex(pat);
paId.setSuperOf(pa);
Arc arc;
for (int i = 0; i < pat.size(); ++i) {
arc.tail = pat[i];
for (int headt = 0; headt < pof.n; ++headt) {
arc.head = po.getOrder()[headt];
if (arc.head == arc.tail)
continue;
sums[arc] += scores(arc.head, pati) * gammas[headt][paId];
}
}
} while (pa.next(0, scores.nNodes, scores.maxParents));
}/**/
/**
* Computes the (unnormalized) probability of given arc in given partial order.
*/
template <class POF>
Real calcUnnormProb(
const POF& pof,
ParentsetMap<Real>& scores,
const typename POF::Order& po,
Arc arc
) {
//po.print(); printf("\n");
// compute alphas
std::vector<typename POF::template IdealMap<Real> >
alphas(pof.n, typename POF::template IdealMap<Real>(pof));
calcAlphas(pof, po, scores, arc, alphas);
// compute the probability
typename POF::template IdealMap<Real> fp(pof);
fp.sparseForwardSum(alphas);
//{
// printf("sparse forward sum =>\n ");
// typename POF::Ideal i(pof);
// do {
// printf("%g ", to<double>(log(fp[i])));
// } while (i.next());
// printf("\n");
//}
Real p = fp.getFull();
//typename POF::template IdealMap<Real> fp(pof);
//bp.sparseBackwardSum(alphas);
//Real p = bp.getEmpty();
//Real p = basicForwardBackwardSum(pof, fp, bp, alphas, po.getIndex(arc.tail));
return p;
}
/**
* Computes the (unnormalized) probabilities of all arc simultaneously in given partial order.
*/
template <class POF>
void calcUnnormArcProbs(
const POF& pof,
ParentsetMap<Real>& scores,
const typename POF::Order& po,
ArcMap<Real>& probs
) {
// compute alphas for null feature
std::vector<typename POF::template IdealMap<Real> >
nullAlphas(pof.n, typename POF::template IdealMap<Real>(pof));
calcAlphas(pof, po, scores, NullArc, nullAlphas);
// compute forward and backward functions
typename POF::template IdealMap<Real> fp(pof);
fp.sparseForwardSum(nullAlphas);
typename POF::template IdealMap<Real> bp(pof);
bp.sparseBackwardSum(nullAlphas);
// compute gammas
std::vector<typename POF::template IdealMap<Real> >
gammas(pof.n, typename POF::template IdealMap<Real>(pof));
calcGammas(pof, fp, bp, gammas);
// compute all arc probs at once
probs.setAll(0.0);
addParentsetSums(pof, scores, gammas, po, probs);
}
/*
class MarginProbComputer {
private:
ParentsetMap<Real>& scores_;
MarginProbComputer(const MarginProbComputer&); // disable copying
MarginProbComputer& operator=(const MarginProbComputer&); // disable copying
public:
MarginProbComputer(ParentsetMap<Real>& scores) : scores_(scores) {}
template <class POF>
Real calcProb(const POF& pof, const typename POF::Order& po) {
return calcUnnormProb(pof, scores_, po, NullArc);
}
};/**/
/*template <class POF>
class ProbComputer {
private:
const POF& pof_;
ParentsetMap<Real>& scores_;
std::vector<typename POF::template IdealMap<Real> > marginTailSums_;
std::vector<typename POF::template IdealMap<Real> > marginAlphas_;
//const typename POF::Order& po;
ProbComputer(const ProbComputer&); // disable copying
ProbComputer& operator=(const ProbComputer&); // disable copying
public:
ProbComputer(ParentsetMap<Real>& scores, const POF& pof) :
scores_(scores),
marginTailSums_(pof.n, typename POF::template IdealMap<Real>(pof)),
marginAlphas_(pof.n, typename POF::template IdealMap<Real>(pof)),
pof_(pof)
{}
Real initMargin(const typename POF::Order& po) {
for (int v = 0; v < pof_.n; ++v) {
calcTailSums(pof_, po, scores_, po[v], NullArc, marginTailSums_[v]);
//calcTailSums(pof, po, scores, v, arc, alphas[v]);
marginAlphas_[v] = marginTailSums_[v];
marginAlphas_[v].fastSparseZetaTransform();
}
typename POF::template IdealMap<Real> fp(pof_);
fp.sparseForwardSum(marginAlphas_);
Real p = fp.getFull();
return p;
}
Real updateMargin(const typename POF::Order& po, int node1, int node2) {
std::vector<typename POF::template IdealMap<Real> > marginTailSums2(marginTailSums_);
std::vector<typename POF::template IdealMap<Real> > marginAlphas2(marginAlphas_);
printf("\nSWAP %d and %d\n", node1, node2);
for (int v = 0; v < pof_.n; ++v) {
printf(" v = %d\n", v);
{
printf("## origin: ");
typename POF::Ideal id(pof_);
do {
printf("%8.6g ", to<double>(log(marginTailSums_[v][id])));
} while (id.next());
printf("\n");
}
//updateTailSums(pof_, po, scores_, v, marginTailSums_[v], node1, node2);
updateTailSums(pof_, po, scores_, v, marginTailSums2[v], node1, node2);
{
printf("## update: ");
typename POF::Ideal id(pof_);
do {
//printf("%8.6g ", to<double>(log(marginTailSums_[v][id])));
printf("%8.6g ", to<double>(log(marginTailSums2[v][id])));
} while (id.next());
printf("\n");
}
calcTailSums(pof_, po, scores_, po[v], NullArc, marginTailSums_[v]);
{
printf("## recalc: ");
typename POF::Ideal id(pof_);
do {
printf("%8.6g ", to<double>(log(marginTailSums_[v][id])));
} while (id.next());
printf("\n");
}
printf("\n");
marginAlphas_[v] = marginTailSums_[v];
marginAlphas_[v].fastSparseZetaTransform();
marginAlphas2[v] = marginTailSums2[v];
marginAlphas2[v].fastSparseZetaTransform();
}
{
typename POF::template IdealMap<Real> fp(pof_);
fp.sparseForwardSum(marginAlphas2);
Real p = fp.getFull();
printf("log(p) = %g\n", to<double>(log(p)));
}
typename POF::template IdealMap<Real> fp(pof_);
fp.sparseForwardSum(marginAlphas_);
Real p = fp.getFull();
printf("log(p) = %g\n", to<double>(log(p)));
return p;
//return initMargin(po);
}
void calcUnnormArcProbs(
const typename POF::Order& po,
ArcMap<Real>& probs
) {
// compute forward and backward functions
typename POF::template IdealMap<Real> fp(pof_);
fp.sparseForwardSum(marginAlphas_);
typename POF::template IdealMap<Real> bp(pof_);
bp.sparseBackwardSum(marginAlphas_);
// compute gammas
std::vector<typename POF::template IdealMap<Real> >
gammas(pof_.n, typename POF::template IdealMap<Real>(pof_));
calcGammas(pof_, fp, bp, gammas);
// compute all arc probs at once
probs.setAll(0.0);
addParentsetSums(pof_, scores_, gammas, po, probs);
}
};/**/
template <class POF>
class ExactArcProbComputer {
private:
ParentsetMap<Real>& scores_;
const POF& pof_;
public:
ExactArcProbComputer(ParentsetMap<Real>& scores, const POF& pof) :
scores_(scores), pof_(pof)
{
}
~ExactArcProbComputer() {
}
double calcProb(Arc arc) {
//ParentsetMap<Real> transScores;
Real cumMarginalLikelihood = 0;
Real cumArcLikelihood = 0;
typename POF::OrderEnumerator poe(pof_);
do {
Real lhPO = calcUnnormProb(pof_, scores_, poe.getOrder(), NullArc);
Real lhFPO = calcUnnormProb(pof_, scores_, poe.getOrder(), arc);
//translateParentsetMap(pof_, subsetDirectory_, poe.getOrder(), scores_, transScores);
//Real lhPO = calcUnnormProb(pof_, subsetDirectory_, transScores, poe.getOrder(), NullArc);
//Arc arct;
//arct.head = poe.getOrder().getIndex(arc.head);
//arct.tail = poe.getOrder().getIndex(arc.tail);
//Real lhFPO = calcUnnormProb(pof_, subsetDirectory_, transScores, poe.getOrder(), arct);
cumMarginalLikelihood += lhPO;
cumArcLikelihood += lhFPO;
} while(poe.next());
return to<double>(cumArcLikelihood / cumMarginalLikelihood);
}
void printAllProbs(std::ostream& resStream) {
Arc arc; arc.setFirst();
do {
double p = calcProb(arc);
resStream << arc << " " << p << std::endl;
} while (arc.next(pof_.n));
}
void printArcProbs(std::ostream& resStream) {
Real cumMarginalProb = 0;
ArcMap<Real> cumArcProbs(pof_.n);
ArcMap<Real> probs(pof_.n);
cumArcProbs.setAll(0.0);
typename POF::OrderEnumerator poe(pof_);
do {
Real marginalProb = calcUnnormProb(pof_, scores_, poe.getOrder(), NullArc);
calcUnnormArcProbs(pof_, scores_, poe.getOrder(), probs);
cumMarginalProb += marginalProb;
Arc arc; arc.setFirst();
do {
cumArcProbs[arc] += probs[arc];
} while (arc.next(pof_.n));
} while(poe.next());
Arc arc; arc.setFirst();
do {
double p = to<double>(cumArcProbs[arc] / cumMarginalProb);
resStream << arc << " " << p << std::endl;
} while (arc.next(pof_.n));
}
};
template <class POF>
class MCMCArcProbComputer {
private:
ParentsetMap<Real>& scores_;
const POF& pof_;
Real marginUnnormProb_;
typename POF::Order po_;
//Real* burnInProbs_;
//MarginProbComputer marginProbComputer;
//ProbComputer<POF> probComputer;
int nAccepts_;
int nSteps_;