-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdatastructs.h
1276 lines (1090 loc) · 36.4 KB
/
datastructs.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
// Hierarchy, Data, and Hyperparams classes
//
#ifndef DATA_STRUCTS_H
#define DATA_STRUCTS_H
#include <string>
#include <memory>
#include <random>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <boost/math/distributions.hpp>
#include "helpermex.h"
#include "printmex.h"
// TODO separate into .h and .cpp
// see https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution
// for random number generation
std::random_device rd; //Will be used to obtain a seed for the random number engine
//std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::mt19937 gen(0); // for reproducibility
const double EPS = 1e-9;
// random draw U ~ Unif(a, b)
// see https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution
//
double UnifRnd(double a = 0, double b = 1)
{
std::uniform_real_distribution<double> dis(a, b);
double U = dis(gen);
return U;
}
// random draw X ~ Beta(alpha, beta)
// Uses universality of the normal, i.e. F(X) ~ Unif(0,1), where X ~ CDF F
// see https://stackoverflow.com/questions/4181403/generate-random-number-based-on-beta-distribution-using-boost
//
double BetaRnd(double alpha = 1, double beta = 1)
{
boost::math::beta_distribution<double> dist(alpha, beta);
double U = UnifRnd();
double X = quantile(dist, U);
return X;
}
double BetaPDF(double x, double alpha = 1, double beta = 1)
{
boost::math::beta_distribution<double> dist(alpha, beta);
return boost::math::pdf(dist, x);
}
// random draw X ~ N(mu, sigma)
// see http://www.cplusplus.com/reference/random/normal_distribution/
//
double NormRnd(double mu, double sigma)
{
std::normal_distribution<double> dist(mu, sigma);
double X = dist(gen);
return X;
}
double NormPDF(double x, double mu, double sigma)
{
boost::math::normal_distribution<double> dist(mu, sigma);
return boost::math::pdf(dist, x);
}
double NormCDF(double x, double mu, double sigma)
{
boost::math::normal_distribution<double> dist(mu, sigma);
return boost::math::cdf(dist, x);
}
// random draw X ~ Cat(p), where p is a vector of (unnormalized) categorical probabilities
// see http://www.cplusplus.com/reference/random/discrete_distribution/
//
int CatRnd(const std::vector<double> &p)
{
std::discrete_distribution<int> dist(p.begin(), p.end());
int X = dist(gen);
return X;
}
using namespace matlab::mex;
using namespace matlab::data;
class Data
{
public:
// types -- see https://www.mathworks.com/help/matlab/apiref/matlab.data.arraytype.html
static const std::vector<std::string> fieldNames;
static const std::vector<ArrayType> fieldTypes;
static void check(StructArray const &matlabStructArrayD, std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr);
Data(StructArray const matlabStructArrayD);
~Data();
struct Edge
{
int u, v;
Edge(int _u, int _v) : u(_u), v(_v) {}
};
struct Task
{
int s, g;
Task(int _s, int _g) : s(_s), g(_g) {}
};
struct Graph
{
static const std::vector<std::string> fieldNames; // D.G
static const std::vector<ArrayType> fieldTypes;
int **E;
int **hidden_E;
int N;
std::vector<Edge> edges;
std::vector<Edge> hidden_edges;
std::vector<int> *adj;
};
//std::string name;
Graph G;
std::vector<Task> tasks;
std::vector<double> *rewards;
};
const std::vector<std::string> Data::fieldNames = {"name", "G", "tasks", "r"};
const std::vector<ArrayType> Data::fieldTypes = {ArrayType::CHAR, ArrayType::STRUCT, ArrayType::STRUCT, ArrayType::CELL};
const std::vector<std::string> Data::Graph::fieldNames = {"N", "E", "edges", "hidden_E", "hidden_edges"}; // D.G
const std::vector<ArrayType> Data::Graph::fieldTypes = {ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE};
void Data::check(StructArray const &matlabStructArrayD, std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr)
{
checkStructureElements(matlabStructArrayD, "D", Data::fieldNames, Data::fieldTypes, matlabPtr);
size_t total_num_of_elements = matlabStructArrayD.getNumberOfElements();
for (size_t i=0; i<total_num_of_elements; i++)
{
// check D.G
const StructArray structFieldG = matlabStructArrayD[i]["G"];
checkStructureElements(structFieldG, "D.G", Data::Graph::fieldNames, Data::Graph::fieldTypes, matlabPtr);
const TypedArray<double> _N = structFieldG[0]["N"];
const TypedArray<double> _E = structFieldG[0]["E"];
int N = (int)_N[0];
if (_E.getNumberOfElements() != N * N)
{
displayError("D.G.E must have D.G.N^2 elements.", matlabPtr);
}
// check D.tasks
const StructArray matlabStructArrayTasks = matlabStructArrayD[i]["tasks"];
const TypedArray<double> _s = matlabStructArrayTasks[0]["s"];
const TypedArray<double> _g = matlabStructArrayTasks[0]["g"];
if (_s.getNumberOfElements() != _g.getNumberOfElements())
{
displayError("D.tasks.s and D.tasks.g must have the same number of elements.", matlabPtr);
}
// check D.r
const CellArray matlabStructArrayRewards = matlabStructArrayD[i]["r"];
if (matlabStructArrayRewards.getNumberOfElements() != N)
{
displayError("D.r should have D.N elements", matlabPtr);
}
}
}
// TODO pass entryIndex and use instead of [0]
Data::Data(StructArray const matlabStructArrayD)
{
// const TypedArray<char*> _name = matlabStructArrayD[0]["name"];
// convert G
//
const StructArray matlabStructArrayG = matlabStructArrayD[0]["G"];
const TypedArray<double> _N = matlabStructArrayG[0]["N"];
const TypedArray<double> _E = matlabStructArrayG[0]["E"];
const TypedArray<double> _edges = matlabStructArrayG[0]["edges"];
const TypedArray<double> _hidden_E = matlabStructArrayG[0]["hidden_E"];
const TypedArray<double> _hidden_edges = matlabStructArrayG[0]["hidden_edges"];
G.N = (int)_N[0];
DEBUG_PRINT("G.N = %d\n", G.N);
DEBUG_PRINT("G.E = \n");
G.E = new int*[G.N];
G.adj = new std::vector<int>[G.N];
for (int i = 0; i < G.N; i++)
{
G.E[i] = new int[G.N];
for (int j = 0; j < G.N; j++)
{
G.E[i][j] = (int)_E[i][j];
G.adj[i].push_back(j);
DEBUG_PRINT("%d ", G.E[i][j]);
}
DEBUG_PRINT("\n");
}
for (int i = 0; i < _edges.getDimensions()[0]; i++)
{
int u = _edges[i][0];
int v = _edges[i][1];
G.edges.push_back(Edge(u, v));
DEBUG_PRINT("G.edge %d %d\n", u, v);
}
DEBUG_PRINT("G.hidden_E = \n");
G.hidden_E = new int*[G.N];
G.adj = new std::vector<int>[G.N];
for (int i = 0; i < G.N; i++)
{
G.hidden_E[i] = new int[G.N];
for (int j = 0; j < G.N; j++)
{
G.hidden_E[i][j] = (int)_hidden_E[i][j];
// important for connectivity that hidden edges are not present in E
ASSERT(!G.hidden_E[i][j] || !G.E[i][j], "!G.hidden_E[i][j] || !G.E[i][j]");
DEBUG_PRINT("%d ", G.hidden_E[i][j]);
}
DEBUG_PRINT("\n");
}
for (int i = 0; i < _hidden_edges.getDimensions()[0]; i++)
{
int u = _hidden_edges[i][0];
int v = _hidden_edges[i][1];
G.hidden_edges.push_back(Edge(u, v));
DEBUG_PRINT("G.hidden_edge %d %d\n", u, v);
}
// convert tasks
//
const StructArray matlabStructArrayTasks = matlabStructArrayD[0]["tasks"];
const TypedArray<double> _s = matlabStructArrayTasks[0]["s"];
const TypedArray<double> _g = matlabStructArrayTasks[0]["g"];
for (int i = 0; i < _s.getNumberOfElements(); i++)
{
int s = _s[i];
int g = _g[i];
tasks.push_back(Task(s, g));
DEBUG_PRINT("task %d %d\n", s, g);
}
// convert rewards
//
const CellArray matlabStructArrayRewards = matlabStructArrayD[0]["r"];
rewards = new std::vector<double>[G.N];
for (int i = 0; i < G.N; i++)
{
const TypedArray<double> _r = matlabStructArrayRewards[i];
DEBUG_PRINT("r{%d} = [", i);
for (int j = 0; j < _r.getNumberOfElements(); j++)
{
double r = _r[j];
rewards[i].push_back(r);
DEBUG_PRINT("%lf ", r);
}
DEBUG_PRINT("]\n");
}
}
Data::~Data()
{
for (int i = 0; i < G.N; i++)
{
delete [] G.E[i];
delete [] G.hidden_E[i];
}
delete [] G.E;
delete [] G.adj;
delete [] rewards;
}
class Hyperparams
{
public:
static const std::vector<std::string> fieldNames; // h
static const std::vector<ArrayType> fieldTypes;
static void check(StructArray const &matlabStructArrayHyperparams, std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr);
Hyperparams(StructArray const matlabStructArrayHyperparams);
double alpha;
double std_theta;
double theta_mean;
double std_mu;
double std_r;
double eps;
};
const std::vector<std::string> Hyperparams::fieldNames = {"alpha", "std_theta", "theta_mean", "std_mu", "std_r", "eps"}; // h
const std::vector<ArrayType> Hyperparams::fieldTypes = {ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE};
void Hyperparams::check(StructArray const &matlabStructArrayHyperparams, std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr)
{
checkStructureElements(matlabStructArrayHyperparams, "h", Hyperparams::fieldNames, Hyperparams::fieldTypes, matlabPtr);
}
Hyperparams::Hyperparams(StructArray const matlabStructArrayHyperparams)
{
const TypedArray<double> _alpha = matlabStructArrayHyperparams[0]["alpha"];
alpha = _alpha[0];
const TypedArray<double> _std_theta = matlabStructArrayHyperparams[0]["std_theta"];
std_theta = _std_theta[0];
const TypedArray<double> _theta_mean = matlabStructArrayHyperparams[0]["theta_mean"];
theta_mean = _theta_mean[0];
const TypedArray<double> _std_mu = matlabStructArrayHyperparams[0]["std_mu"];
std_mu = _std_mu[0];
const TypedArray<double> _std_r = matlabStructArrayHyperparams[0]["std_r"];
std_r = _std_r[0];
const TypedArray<double> _eps = matlabStructArrayHyperparams[0]["eps"];
eps = _eps[0];
DEBUG_PRINT("h = %lf %lf %lf %lf %lf %lf\n", alpha, std_theta, theta_mean, std_mu, std_r, eps);
}
class Hierarchy
{
public:
// types -- see https://www.mathworks.com/help/matlab/apiref/matlab.data.arraytype.html
static const std::vector<std::string> fieldNames; // H
static const std::vector<ArrayType> fieldTypes;
static void check(StructArray const &matlabStructArrayH, const Data &D, std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr);
Hierarchy(int _N);
Hierarchy(const Hierarchy &H); // copy constructor
~Hierarchy();
bool Equals(const Hierarchy& H) const;
void InitFromMATLAB(StructArray const matlabStructArrayH);
void InitFromPrior(const Data &D, const Hyperparams &h);
void PopulateCnt();
void Print() const;
double LogPrior(const Data &D, const Hyperparams &h) const;
double LogLik(const Data &D, const Hyperparams &h) const;
double LogPost(const Data &D, const Hyperparams &h) const;
double LogPost_c_i(int c_i_new, int i, const Data &D, const Hyperparams &h);
void Update_c_i(int c_i_new, int i, const Data &D, const Hyperparams &h);
void Update_c_i(int c_i_new, int i, const Data &D, const Hyperparams &h, int /*out*/ &c_i_old, double /*out*/ &theta_old, std::vector<int> /*out*/ &E_old);
void Undo_c_i(int c_i_new, int i, const Data &D, const Hyperparams &h, int c_i_old, double theta_old, const std::vector<int> &E_old);
void Sanity(const Data &D, const Hyperparams &h);
void Sanity();
int N;
int **E;
int *c;
std::vector<int> cnt;
double p;
double q;
double hp; // p'
double tp; // p''
std::vector<double> theta;
double *mu;
};
const std::vector<std::string> Hierarchy::fieldNames = {"c", "p", "q", "tp", "hp", "theta", "mu", "E"}; // H
const std::vector<ArrayType> Hierarchy::fieldTypes = {ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE, ArrayType::DOUBLE};
void Hierarchy::check(StructArray const &matlabStructArrayH, const Data &D, std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr)
{
checkStructureElements(matlabStructArrayH, "H", Hierarchy::fieldNames, Hierarchy::fieldTypes, matlabPtr);
const TypedArray<double> _c = matlabStructArrayH[0]["c"];
if (_c.getNumberOfElements() != D.G.N)
{
displayError("H.c should have D.G.N elements", matlabPtr);
}
const TypedArray<double> _theta = matlabStructArrayH[0]["theta"];
// TODO this is wrong; needs to be max(c)
// also, wtf try to pass Hout as input argument -> Busy
//if (_theta.getNumberOfElements() != D.G.N)
//{
// displayError("H.theta should have D.G.N elements");
//}
const TypedArray<double> _mu = matlabStructArrayH[0]["mu"];
if (_mu.getNumberOfElements() != D.G.N)
{
displayError("H.mu should have D.G.N elements", matlabPtr);
}
const TypedArray<double> _E = matlabStructArrayH[0]["E"];
if (_E.getNumberOfElements() != D.G.N * D.G.N)
{
displayError("H.E must have D.G.N^2 elements.", matlabPtr);
}
}
// P(H|D) for updates of c_i
// i.e. with new c's up to c_i, the candidate c_i, then old c's after (and old rest of H)
//
double Hierarchy::LogPost_c_i(int c_i_new, int i, const Data &D, const Hyperparams &h) // notice it's not const b/c it temporarily changes H for efficiency
{
#if (DEBUG)
Hierarchy H(*this);
#endif
int c_i_old;
double theta_old;
std::vector<int> E_old;
this->Update_c_i(c_i_new, i, D, h, c_i_old, theta_old, E_old);
double logP = this->LogPost(D, h); // TODO much more efficiently, maybe
this->Undo_c_i(c_i_new, i, D, h, c_i_old, theta_old, E_old);
#if (DEBUG)
ASSERT(this->Equals(H), "this->Equals(H)"); // TODO rm in prod
#endif
this->Sanity(D, h);
return logP;
}
// set c[i] = c_i_new and update stuff accordingly
void Hierarchy::Update_c_i(int c_i_new, int i, const Data &D, const Hyperparams &h)
{
int c_i_old;
double theta; // dummies
std::vector<int> E_old;
Update_c_i(c_i_new, i, D, h, c_i_old, theta, E_old);
}
// set c[i] = c_i_new and update stuff accordingly
// also returns stuff that can redo the op
// careful with off-by-one everywhere
//
void Hierarchy::Update_c_i(int c_i_new, int i, const Data &D, const Hyperparams &h, int /*out*/ &c_i_old, double /*out*/ &theta_old, std::vector<int> /*out*/ &E_old)
{
c_i_old = this->c[i];
this->c[i] = c_i_new;
ASSERT(c_i_old - 1 >= 0, "c_i_old - 1 >= 0, Update_c_i");
ASSERT(c_i_old - 1 < this->cnt.size(), "c_i_old - 1 < this->cnt.size(), Update_c_i");
ASSERT(this->cnt[c_i_old - 1] > 0, "this->cnt[c_i_old - 1] > 0, Update_c_i");
this->cnt[c_i_old - 1]--;
// removed a singleton cluster TODO make theta logic similar
E_old.clear();
if (this->cnt[c_i_old - 1] == 0)
{
for (int k = 0; k < D.G.N; k++)
{
ASSERT(this->E[c_i_old - 1][k] == this->E[k][c_i_old - 1], "this->E[c_i_old - 1][k] == this->E[k][c_i_old - 1]");
E_old.push_back(this->E[c_i_old - 1][k]);
this->E[c_i_old - 1][k] = -1;
this->E[k][c_i_old - 1] = -1;
}
}
ASSERT(c_i_new - 1 >= 0, "c_i_new - 1 >= 0, Update_c_i");
ASSERT(c_i_new - 1 <= this->cnt.size(), "c_i_new - 1 <= this->cnt.size(), Update_c_i"); // note we allow equality
// creating new cluster
if (c_i_new - 1 == this->cnt.size())
{
this->cnt.push_back(0);
this->theta.push_back(nan(""));
}
this->cnt[c_i_new - 1]++;
theta_old = this->theta[c_i_new - 1];
if (this->cnt[c_i_new - 1] == 1)
{
// created a new cluster, so create a new theta -- note that we could be reusing an old one, so we take care to save the theta in case we need to undo this, e.g. when computing the MCMC updates
//this->theta[c_i_new - 1] = NormRnd(h.theta_mean, h.std_theta); // InitFromPrior
this->theta[c_i_new - 1] = this->mu[i]; // sort-of empirical prior TODO is this legit?
ASSERT(this->cnt.size() <= D.G.N, "this->cnt.size() <= D.G.N");
for (int k = 0; k < this->cnt.size(); k++)
{
if (this->cnt[k] > 0)
{
this->E[c_i_new - 1][k] = UnifRnd() < this->p;
this->E[k][c_i_new - 1] = this->E[c_i_new - 1][k];
}
}
this->E[c_i_new - 1][c_i_new - 1] = 0;
}
DEBUG_PRINT(" update_c_i -- c_i_new = %d, i = %d; c_i_old = %d\n", c_i_new, i, c_i_old);
this->Print();
this->Sanity(D, h); // TODO DEBUG only
}
// undo Update_c_i; notice we go in reverse order
// careful with off-by-one everywhere
//
void Hierarchy::Undo_c_i(int c_i_new, int i, const Data &D, const Hyperparams &h, int c_i_old, double theta_old, const std::vector<int> &E_old)
{
ASSERT(c_i_new - 1 >= 0, "c_i_new - 1 >= 0, Undo_c_i");
ASSERT(c_i_new - 1 < this->cnt.size(), "c_i_new - 1 < this->cnt.size(), Undo_c_i"); // notice strict < here
if (this->cnt[c_i_new - 1] == 1)
{
this->theta[c_i_new - 1] = theta_old;
ASSERT(c_i_new - 1 < D.G.N, "c_i_new - 1 < D.G.N");
for (int k = 0; k < D.G.N; k++)
{
this->E[k][c_i_new - 1] = -1;
this->E[c_i_new - 1][k] = -1;
}
}
ASSERT(this->cnt[c_i_new - 1] > 0, "this->cnt[c_i_new - 1] > 0, Undo_c_i");
this->cnt[c_i_new - 1]--;
if (c_i_new == this->cnt.size() && isnan(theta_old))
{
// we added a new cluster -> remove it
this->cnt.pop_back();
this->theta.pop_back();
}
ASSERT(c_i_old - 1 >= 0, "c_i_old - 1 >= 0, Undo_c_i");
ASSERT(c_i_old - 1 < this->cnt.size(), "c_i_old - 1 < this->cnt.size(), Undo_c_i");
if (this->cnt[c_i_old - 1] == 0)
{
ASSERT(E_old.size() == D.G.N, "E_old.size() == D.G.N");
for (int k = 0; k < D.G.N; k++)
{
this->E[c_i_old - 1][k] = E_old[k];
this->E[k][c_i_old - 1] = E_old[k];
}
}
this->cnt[c_i_old - 1]++;
this->c[i] = c_i_old;
DEBUG_PRINT(" undo_c_i -- c_i_new = %d, i = %d; c_i_old = %d\n", c_i_new, i, c_i_old);
this->Print();
this->Sanity(D, h); // TODO DEBUG only
}
void Hierarchy::Sanity(const Data &D, const Hyperparams &h)
{
#if DEBUG == 1
ASSERT(D.G.N == this->N, "D.G.N == this->N, Sanity");
this->Sanity();
#endif
}
void Hierarchy::Sanity()
{
#if DEBUG == 1
ASSERT(this->cnt.size() == this->theta.size(), "this->cnt.size() == this->theta.size(), Sanity");
int K = *std::max_element(this->c, this->c + N); // # of clusters
ASSERT(this->cnt.size() >= K, "this->cnt.size() >= K, Sanity");
std::vector<int> cnt(this->cnt.size());
for (int i = 0; i < this->N; i++)
{
cnt[this->c[i] - 1]++;
}
int sum = 0;
for (int k = 0; k < K; k++)
{
sum += this->cnt[k];
ASSERT(this->cnt[k] == cnt[k], "this->cnt[k] == cnt[k], Sanity");
ASSERT(!isnan(this->theta[k]), "!isnan(this->theta[k])");
}
ASSERT(sum == this->N, "sum == this->N, Sanity");
for (int i = 0; i < this->N; i++)
{
ASSERT(this->c[i] - 1 >= 0, "this->c[i] - 1 >= 0, Sanity");
ASSERT(this->c[i] - 1 < this->theta.size(), "this->c[i] - 1 < this->theta.size(), Sanity");
ASSERT(this->c[i] - 1 < this->cnt.size(), "this->c[i] - 1 < this->cnt.size(), Sanity");
}
for (int k = 0; k < this->N; k++)
{
for (int l = 0; l <= k; l++)
{
ASSERT(this->E[k][l] == this->E[l][k], "this->E[k][l] == this->E[l][k]");
if (k < this->cnt.size() && this->cnt[k] > 0 && l < this->cnt.size() && this->cnt[l] > 0)
{
ASSERT(this->E[k][l] != -1, "this->E[k][l] != -1, Sanity");
}
}
}
#endif
}
bool Hierarchy::Equals(const Hierarchy& H) const
{
if (this->N != H.N) return false;
if (fabs(this->p - H.p) > EPS) return false;
if (fabs(this->q - H.q) > EPS) return false;
if (fabs(this->tp - H.tp) > EPS) return false;
if (fabs(this->hp - H.hp) > EPS) return false;
for (int i = 0; i < this->N; i++)
{
if (this->c[i] != H.c[i]) return false;
if (fabs(this->mu[i] - H.mu[i]) > EPS) return false;
}
for (int k = 0; k < this->cnt.size(); k++)
{
if (this->cnt[k] != H.cnt[k]) return false;
if (fabs(this->theta[k] - H.theta[k]) > EPS) return false;
}
for (int k = 0; k < this->N; k++)
{
for (int l = 0; l < this->N; l++)
{
if (this->E[k][l] != H.E[k][l])
{
return false;
}
}
}
return true;
}
// populate cluster cnt counts from cluster assignments c
//
void Hierarchy::PopulateCnt()
{
int K = *std::max_element(this->c, this->c + N); // # of clusters
this->cnt.clear();
this->cnt.resize(K);
for (int i = 0; i < this->N; i++)
{
this->cnt[this->c[i] - 1]++;
}
// pad with zeros in case there were empty clusters; this occurs
// e.g. if we return H to MATLAB after sampling, which erases this->cnt
//
// EDIT: DON'T bad -- might screw up the prior b/c it will count a bunch of useless thetas
//while (this->cnt.size() < this->theta.size())
//{
// this->cnt.push_back(0);
//}
// remove thetas for empty clusters; happens b/c of MATLAB
// agni
if (this->theta.size() > K)
{
this->theta.resize(K);
}
DEBUG_PRINT("H.cnt = [");
for (int k = 0; k < K; k++)
{
DEBUG_PRINT("%d ", this->cnt[k]);
}
DEBUG_PRINT("]\n");
}
// TODO pass entryIndex and use instead of [0]
void Hierarchy::InitFromMATLAB(StructArray const matlabStructArrayH)
{
const TypedArray<double> _c = matlabStructArrayH[0]["c"];
for (int i = 0; i < _c.getNumberOfElements(); i++)
{
this->c[i] = _c[i];
}
const TypedArray<double> _p = matlabStructArrayH[0]["p"];
this->p = _p[0];
const TypedArray<double> _q = matlabStructArrayH[0]["q"];
this->q = _q[0];
const TypedArray<double> _tp = matlabStructArrayH[0]["tp"];
this->tp = _tp[0];
const TypedArray<double> _hp = matlabStructArrayH[0]["hp"];
this->hp = _hp[0];
const TypedArray<double> _theta = matlabStructArrayH[0]["theta"];
this->theta.clear();
for (int k = 0; k < _theta.getNumberOfElements(); k++)
{
this->theta.push_back(_theta[k]);
}
const TypedArray<double> _mu = matlabStructArrayH[0]["mu"];
for (int i = 0; i < _mu.getNumberOfElements(); i++)
{
this->mu[i] = _mu[i];
}
const TypedArray<double> _E = matlabStructArrayH[0]["E"];
for (int k = 0; k < this->N; k++)
{
for (int l = 0; l < this->N; l++)
{
this->E[k][l] = _E[k][l];
}
}
this->PopulateCnt();
this->Sanity();
}
void Hierarchy::Print() const
{
#if (DEBUG)
DEBUG_PRINT("H.c = [");
for (int i = 0; i < this->N; i++)
{
DEBUG_PRINT("%d ", this->c[i]);
}
DEBUG_PRINT("]\n");
DEBUG_PRINT("H.cnt = [");
for (int k = 0; k < this->cnt.size(); k++)
{
DEBUG_PRINT("%d ", this->cnt[k]);
}
DEBUG_PRINT("]\n");
DEBUG_PRINT("H.p q tp hp = [%lf %lf %lf %lf]\n", this->p, this->q, this->tp, this->hp);
DEBUG_PRINT("H.theta = [");
for (int k = 0; k < this->theta.size(); k++)
{
DEBUG_PRINT("%lf ", this->theta[k]);
}
DEBUG_PRINT("]\n");
DEBUG_PRINT("H.mu = [");
for (int i = 0; i < this->N; i++)
{
DEBUG_PRINT("%lf ", this->mu[i]);
}
DEBUG_PRINT("]\n");
DEBUG_PRINT("H.E = \n");
for (int k = 0; k < this->N; k++)
{
for (int l = 0; l < this->N; l++)
{
DEBUG_PRINT("%d ", this->E[k][l]);
}
DEBUG_PRINT("\n");
}
#endif
}
// transpiled from init_H.m
// careful with off-by-ones
//
void Hierarchy::InitFromPrior(const Data &D, const Hyperparams &h)
{
this->c[0] = 1;
this->cnt.clear();
this->cnt.push_back(1);
for (int i = 1; i < D.G.N; i++)
{
std::vector<double> p(this->cnt.begin(), this->cnt.end()); // TODO optimize -- no need to copy, could be done in O(1)
p.push_back(h.alpha);
int c_new = CatRnd(p) + 1; // careful with off-by-one
if (c_new - 1 >= this->cnt.size())
{
this->cnt.push_back(1);
}
else
{
this->cnt[c_new - 1]++;
}
this->c[i] = c_new;
}
std::random_shuffle(this->c, this->c + this->N);
this->p = BetaRnd(1, 1);
this->q = BetaRnd(1, 1);
this->tp = BetaRnd(1, 1);
this->hp = BetaRnd(1, 1);
int K = this->cnt.size();
this->theta.clear();
for (int k = 0; k < K; k++)
{
this->theta.push_back(NormRnd(h.theta_mean, h.std_theta));
}
for (int i = 0; i < D.G.N; i++)
{
ASSERT(this->c[i] - 1 >= 0, "this->c[i] - 1 >= 0, InitFromPrior");
ASSERT(this->c[i] - 1 < this->theta.size(), "this->c[i] - 1 < this->theta.size(), InitFromPrior");
this->mu[i] = NormRnd(this->theta[this->c[i] - 1], h.std_mu);
}
for (int k = 0; k < D.G.N; k++)
{
for (int l = 0; l < k; l++)
{
if (k >= this->cnt.size() || l >= this->cnt.size() || this->cnt[k] == 0 || this->cnt[l] == 0)
{
this->E[k][l] = -1;
}
else
{
this->E[k][l] = UnifRnd() < this->p;
}
this->E[l][k] = this->E[k][l];
}
if (k >= this->cnt.size() || this->cnt[k] == 0)
{
this->E[k][k] = -1;
}
else
{
this->E[k][k] = 0;
}
}
this->Sanity(D, h);
}
Hierarchy::Hierarchy(int _N)
{
N = _N;
c = new int[N];
mu = new double[N];
E = new int*[N];
for (int k = 0; k < N; k++)
{
E[k] = new int[N];
}
}
Hierarchy::Hierarchy(const Hierarchy &H)
{
N = H.N;
cnt = H.cnt;
theta = H.theta;
p = H.p;
q = H.q;
hp = H.hp;
tp = H.tp;
c = new int[N];
for (int i = 0; i < this->N; i++)
{
c[i] = H.c[i];
}
mu = new double[N];
for (int i = 0; i < this->N; i++)
{
mu[i] = H.mu[i];
}
E = new int*[N];
for (int k = 0; k < N; k++)
{
E[k] = new int[N];
for (int l = 0; l < N; l++)
{
E[k][l] = H.E[k][l];
}
}
}
Hierarchy::~Hierarchy()
{
delete [] c;
delete [] mu;
for (int k = 0; k < N; k++)
{
delete [] E[k];
}
delete [] E;
}
double Hierarchy::LogPrior(const Data &D, const Hyperparams &h) const
{
ASSERT(D.G.N == this->N, "D.G.N == this->N, LogPrior");
double logP = 0;
// cluster assignments
//
std::vector<int> cnt(this->cnt.size()); // temporary count
ASSERT(this->c[0] - 1 < cnt.size(), "this->c[0] - 1 < cnt.size()");
cnt[this->c[0] - 1] = 1;
for (int i = 1; i < this->N; i++)
{
int c = this->c[i];
ASSERT(c - 1 < this->cnt.size(), "c - 1 < this->cnt.size()");
if (cnt[c - 1] == 0)
{
logP += log(h.alpha) - log(i + h.alpha);
}
else
{
logP += log(cnt[c - 1]) - log(i + h.alpha);
}
cnt[c - 1]++;
}
// TODO optimize by having beta for object
// TODO or marginalize over them
// TODO restore when hyperprior is introduced; right now this is just 0
// logP += log(BetaPDF(this->p, 1, 1)) + log(BetaPDF(this->q, 1, 1)) + log(BetaPDF(this->tp, 1, 1)) + log(BetaPDF(this->hp, 1, 1)); // TODO const
// hierarchical edges
// TODO same problem as thetas -- more clusters just additionally reduces the prior???; screws up mines10 ...
//
/*
int K = this->cnt.size();
ASSERT(K <= D.G.N, "K <= D.G.N");
for (int k = 0; k < K; k++)
{
if (this->cnt[k] == 0)
{
continue;
}
for (int l = 0; l < k; l++)
{
if (this->cnt[l] == 0)
{
continue;
}
ASSERT(this->E[k][l] != -1, "this->E[k][l] != -1, LogPrior");
if (this->E[k][l])
{
logP += log(this->hp);
}
else
{
logP += log(1 - this->hp);
}
}
}
*/
// cluster rewards
//
// TODO discuss w/ Sam
ASSERT(this->cnt.size() == this->theta.size(), "this->cnt.size() == this->theta.size()");
for (int k = 0; k < this->theta.size(); k++)
{
// don't do for empty clusters TODO think about it more carefully TODO might be a bug in MATLAB version
//if (this->cnt[k] > 0) // agni <------------- OMG IT'S THIS!!!!! that screws up mines10 ...
{
// TODO optimize with norm dist objects for each k for H
//DEBUG_PRINT("theta k [%d] = %.4lf\n", k, this->theta[k]);
double p = log(NormPDF(this->theta[k], h.theta_mean, h.std_theta));
if (isinf(p))
{
// prevent -Infs = impossible events; equivalent to using a
// Gaussian + uniform mixture
// do it in a "soft" way so MCMC can recover one by one