-
Notifications
You must be signed in to change notification settings - Fork 1
/
mcmc.h
4614 lines (4138 loc) · 166 KB
/
mcmc.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
/**
* \file mcmc.h
*
* This file implements Markov chain Monte Carlo inference for Dirichlet
* processes (DP) and hierarchical Dirichlet processes (HDP). More
* specifically, this file implements a Gibbs sampler for the Chinese
* restaurant representation. See hdp.h for a description of DPs, HDPs, and the
* Chinese restaurant representation.
*
* Code example
* ------------
*
* The following is an example of an HDP mixture model where the base
* distribution is a symmetric Dirichlet distribution with parameter 1. The
* likelihood distribution is a categorical over the set of ASCII characters,
* which we encode as an unsigned int in `{1, 2, ..., 256}`.
* ```{.cpp}
* #include <hdp/mcmc.h>
* using namespace core;
*
* constexpr unsigned int depth = 2;
*
* template<typename BaseDistribution, typename Likelihood, typename K, typename V>
* void posterior_predictive_probability(
* const hdp_sampler<BaseDistribution, Likelihood, K, V>& sampler,
* const cache<BaseDistribution, Likelihood, K, V>& cache,
* const K& observation)
* {
* array<weighted_feature_set<V>> paths(32);
* auto root_probabilities = cache.compute_root_probabilities(sampler, observation);
* predict(sampler, observation, paths, root_probabilities);
* cleanup_root_probabilities(root_probabilities, sampler.posterior.length);
*
* sort(paths, feature_set_sorter(depth));
* for (unsigned int i = 0; i < paths.length; i++) {
* unsigned int*& path = paths[i].features.features;
* print("probability of drawing '", stdout);
* print((char) observation, stdout);
* if (path[0] == IMPLICIT_NODE) {
* print("' from any other child node: ", stdout);
* } else {
* print("' from child node ", stdout);
* print(path[0], stdout); print(": ", stdout);
* }
* print(exp(paths[i].log_probability), stdout);
* print('\n', stdout);
* free(paths[i]);
* }
* }
*
* template<typename BaseDistribution, typename Likelihood, typename K, typename V>
* void do_inference(hdp<BaseDistribution, Likelihood, K, V>& h) {
* hdp_sampler<BaseDistribution, Likelihood, K, V> sampler(h);
* cache<BaseDistribution, Likelihood, K, V> cache(sampler);
*
* prepare_sampler(sampler, cache);
* for (unsigned int i = 0; i < 200; i++)
* sample_hdp<true>(sampler, cache);
* for (unsigned int i = 0; i < 800; i++) {
* sample_hdp<true>(sampler, cache);
* if (i % 5 == 0) sampler.add_sample();
* }
*
* posterior_predictive_probability(sampler, cache, (unsigned int) '+');
* posterior_predictive_probability(sampler, cache, (unsigned int) '-');
* posterior_predictive_probability(sampler, cache, (unsigned int) 'a');
* }
*
* int main() {
* double alpha[] = {1.0e6, 1.0e-2};
* dirichlet<double> base_distribution(256, 1.0);
* hdp<dirichlet<double>, dense_categorical<double>, unsigned int, double> h(base_distribution, alpha, depth);
*
* unsigned int first_child[] = { 1 };
* unsigned int second_child[] = { 2 };
* for (unsigned int i = 0; i < 100; i++) {
* add(h, first_child, depth, (unsigned int) '+');
* add(h, second_child, depth, (unsigned int) '-');
* }
*
* do_inference(h);
* }
* ```
* In this example, we use the following model:
* \f[
* \begin{align*}
* H &= \text{Dirichlet}([1, \ldots, 1]), \\
* G^{\textbf{0}} &\sim DP(H, 10^6), \\
* G^{\textbf{1}}, G^{\textbf{2}}, G^{\textbf{3}} &\sim DP(G_{\textbf{0}}, 10^{-2}), \\
* x^{\textbf{1}}_1, \ldots, x^{\textbf{1}}_{100} &\sim G_{\textbf{1}}, \\
* x^{\textbf{2}}_1, \ldots, x^{\textbf{2}}_{100} &\sim G_{\textbf{2}}, \\
* y^{\textbf{1}}_i &\sim \text{Categorical}(x^{\textbf{1}}_i) \text{ for } i = 1, \ldots, 100, \\
* y^{\textbf{2}}_i &\sim \text{Categorical}(x^{\textbf{2}}_i) \text{ for } i = 1, \ldots, 100.
* \end{align*}
* \f]
* The only variables we observe are: \f$ y^{\textbf{1}}_i = \texttt{`+'} \f$
* and \f$ y^{\textbf{2}}_i = \texttt{`-'} \f$ for
* \f$ i = 1, \ldots, 100 \f$. We want to compute the probabilities of:
* \f[
* \begin{equation*}
* p(y^{\textbf{1}}_{new} | \boldsymbol{y}), p(y^{\textbf{2}}_{new} | \boldsymbol{y}), p(y^{\textbf{3}}_{new} | \boldsymbol{y}),
* \end{equation*}
* \f]
* where \f$ \boldsymbol{y} \triangleq \{y^{\textbf{1}}_1, \ldots, y^{\textbf{1}}_{100}, y^{\textbf{2}}_1, \ldots, y^{\textbf{2}}_{100}\} \f$
* is the set of all observations, and each \f$ y^{\textbf{n}}_{new} \f$ is a
* new (previously unobserved) sample drawn from \f$ x^{\textbf{n}}_{new} \f$
* which is in turn drawn from \f$ G^{\textbf{n}} \f$ (i.e. the posterior
* predictive distribution). The above code does exactly this, and the expected
* output is:
* ```
* probability of drawing '+' from child node 1: 0.283680
* probability of drawing '+' from child node 2: 0.002809
* probability of drawing '+' from any other child node: 0.003907
* probability of drawing '-' from child node 1: 0.002809
* probability of drawing '-' from child node 2: 0.283680
* probability of drawing '-' from any other child node: 0.003907
* probability of drawing 'a' from child node 1: 0.002809
* probability of drawing 'a' from child node 2: 0.002809
* probability of drawing 'a' from any other child node: 0.003906
* ```
*
* The function `do_inference` constructs the hdp_sampler and ::cache
* structures necessary to perform MCMC sampling. hdp_sampler (and
* node_sampler) stores the variables used by the sampling algorithm. ::cache
* is a structure that optimizes the sampling algorithm for particular choices
* of the base distribution and likelihood. Once constructed, the function then
* executes 200 "burn-in" iterations, to allow the MCMC to mix (converge to the
* true posterior). Then, it performs 800 more iterations, keeping every fifth
* sample (to minimize autocorrelation among samples, since we want them to be
* as independent as possible). Finally, the function
* `posterior_predictive_probability` is called to compute the above
* probabilities.
*
* A unit test is also available in mcmc.cpp, as another example.
*
* <!-- Created on: Jul 26, 2015
* Author: asaparov -->
*/
#ifndef MCMC_H_
#define MCMC_H_
#include <core/io.h>
#include <math/distributions.h>
#include <math/log.h>
#include <algorithm>
#include "hdp.h"
#include "cache.h"
namespace detail {
template<typename Stream, typename Printer> static auto test_level_printable(int) ->
decltype(bool(print(0u, std::declval<Stream&>(), 0u, std::declval<Printer&>())), std::true_type{});
template<typename Stream, typename Printer> static auto test_level_printable(long) -> std::false_type;
}
template<typename Stream, typename Printer> struct is_level_printable : decltype(::detail::test_level_printable<Stream, Printer>(0)){};
template<typename Stream, typename Printer,
typename std::enable_if<!is_level_printable<Stream, Printer>::value>::type* = nullptr>
inline bool print(unsigned int u, Stream& stream, unsigned int level, Printer& printer) {
return print(u, stream, printer);
}
/* forward declarations */
#if !defined(DOXYGEN_IGNORE)
template<typename DataDistribution, typename NodeType, typename BaseDistribution, typename Observations>
inline bool sample_initial_assignment(
NodeType& n,
const BaseDistribution& pi,
const Observations& observations,
unsigned int& assignment);
template<bool Collapsed, typename NodeType, typename Observations, typename Cache>
bool select_table(NodeType& n,
const Observations& observations,
unsigned int old_table,
unsigned int selected_table,
unsigned int& new_table,
Cache& cache);
#endif
static inline bool compare_histograms(
const unsigned int* first, const unsigned int* second,
unsigned int first_length, unsigned int second_length)
{
if (first_length < second_length) {
for (unsigned int i = 0; i < first_length; i++)
if (first[i] != second[i])
return false;
for (unsigned int i = first_length; i < second_length; i++)
if (second[i] != 0)
return false;
} else {
for (unsigned int i = 0; i < second_length; i++)
if (first[i] != second[i])
return false;
for (unsigned int i = second_length; i < first_length; i++)
if (first[i] != 0)
return false;
}
return true;
}
static inline void add_to_histogram(unsigned int* histogram,
unsigned int histogram_length, unsigned int item)
{
#if !defined(NDEBUG)
if (item >= histogram_length)
fprintf(stderr, "add_to_histogram WARNING: Index out of bounds.\n");
#endif
histogram[item]++;
}
template<typename V>
struct node_sample {
unsigned int* table_sizes;
unsigned int* root_assignments;
unsigned int customer_count;
unsigned int table_count;
unsigned int* table_assignments;
node_sample(unsigned int table_count, unsigned int observation_count) {
if (!initialize(table_count, observation_count)) {
fprintf(stderr, "node_sample ERROR: Error during initialization.\n");
exit(EXIT_FAILURE);
}
}
inline unsigned int root_assignment(unsigned int i) const {
return root_assignments[i];
}
template<typename Metric>
static inline long unsigned int size_of(const node_sample<V>& sample, const Metric& metric) {
return 2 * sample.table_count * sizeof(unsigned int)
+ sample.customer_count * sizeof(unsigned int)
+ core::size_of(sample.table_count) + core::size_of(sample.customer_count);
}
static inline void free(node_sample<V>& sample) {
sample.free();
}
private:
inline bool initialize(unsigned int num_tables, unsigned int observation_count) {
table_sizes = (unsigned int*) malloc(sizeof(unsigned int) * num_tables);
if (table_sizes == NULL) {
fprintf(stderr, "node_sample.initialize ERROR: Unable to initialize table_sizes.\n");
return false;
}
if (observation_count == 0)
observation_count = 1;
table_assignments = (unsigned int*) malloc(sizeof(unsigned int) * observation_count);
if (table_assignments == NULL) {
fprintf(stderr, "node_sample.initialize ERROR: Unable to initialize table_assignments.\n");
core::free(table_sizes);
return false;
}
table_count = num_tables;
root_assignments = (unsigned int*) malloc(sizeof(unsigned int) * num_tables);
if (root_assignments == NULL) {
fprintf(stderr, "node_sample.initialize ERROR: Unable to initialize root_assignments.\n");
core::free(table_sizes);
core::free(table_assignments);
return false;
}
return true;
}
inline void free() {
core::free(table_sizes);
core::free(table_assignments);
core::free(root_assignments);
}
template<typename A>
friend bool init(node_sample<A>&, unsigned int, unsigned int);
};
template<typename V>
bool init(node_sample<V>& sample, unsigned int table_count, unsigned int observation_count) {
return sample.initialize(table_count, observation_count);
}
template<typename AtomScribe>
struct node_sample_scribe {
AtomScribe& atom_scribe;
unsigned int observation_count;
unsigned int root_cluster_count;
node_sample_scribe(AtomScribe& atom_scribe, unsigned int observation_count, unsigned int root_cluster_count) :
atom_scribe(atom_scribe), observation_count(observation_count), root_cluster_count(root_cluster_count) { }
};
template<typename V, typename AtomReader>
bool read(node_sample<V>& sample, FILE* in, node_sample_scribe<AtomReader>& reader) {
if (!read(sample.table_count, in)) return false;
sample.table_sizes = (unsigned int*) malloc(sizeof(unsigned int) * sample.table_count);
if (sample.table_sizes == NULL)
return false;
sample.root_assignments = (unsigned int*) malloc(sizeof(unsigned int) * sample.table_count);
if (sample.root_assignments == NULL) {
free(sample.table_sizes);
return false;
}
sample.table_assignments = (unsigned int*) malloc(sizeof(unsigned int) * reader.observation_count);
if (sample.table_assignments == NULL) {
free(sample.root_assignments);
free(sample.table_sizes);
return false;
}
if (!read(sample.table_sizes, in, sample.table_count)) return false;
if (!read(sample.root_assignments, in, sample.table_count)) return false;
if (!read(sample.table_assignments, in, reader.observation_count)) return false;
sample.customer_count = 0;
for (unsigned int i = 0; i < sample.table_count; i++)
sample.customer_count += sample.table_sizes[i];
return true;
}
template<typename V, typename AtomWriter>
bool write(const node_sample<V>& sample, FILE* out, node_sample_scribe<AtomWriter>& writer) {
if (!write(sample.table_count, out)) return false;
if (!write(sample.table_sizes, out, sample.table_count)) return false;
if (!write(sample.root_assignments, out, sample.table_count)) return false;
if (!write(sample.table_assignments, out, writer.observation_count)) return false;
return true;
}
/**
* This structure stores Gibbs sampling variables for a single HDP non-root
* node (i.e. a ::node object). These "sampler" structures form a tree parallel
* to the HDP hierarchy consisting of ::hdp and ::node objects.
*
* Since the Gibbs sampler is derived using the Chinese restaurant
* representation, every node_sampler contains an infinite number of tables,
* but we only store the non-empty tables. The number of non-empty tables is
* given by node_sampler::table_count. However, during inference, the number of
* occupied tables may increase and decrease. As such, the node keeps a larger
* "capacity" of tables node_sampler::table_capacity to avoid reallocating
* memory at every sampling step. As long as `table_count <= table_capacity`,
* the algorithm doesn't need to reallocate memory. Every observation drawn
* from this node is assigned to a table (just as a customer picks a table at
* which to sit). All tables in this node are, in turn, sampled from the
* distribution of the parent node. As such, the tables in this node are
* assigned a table in the parent node.
*
* For an example of how to perform MCMC inference with DPs and HDPs, see the
* [code example above](#code-example).
*
* \tparam K the generic type of the observations drawn from this distribution.
* \tparam V the type of the probabilities.
*/
template<typename K, typename V>
struct node_sampler
{
/**
* The generic type of the observations drawn from this distribution.
*/
typedef K atom_type;
/**
* The type of the probabilities.
*/
typedef V value_type;
/**
* The type of a child node of this node in the sampler hierarchy.
*/
typedef node_sampler<K, V> child_type;
/**
* The "sampler" structures form a tree parallel to the HDP hierarchy which
* consists of ::hdp and ::node objects. This typedef returns the type of
* the object that this node_sampler represents in the HDP hierarchy.
*/
typedef node<K, V> node_type;
/**
* A native array containing the child nodes of this node in the sampler
* hierarchy. This array is parallel to the node::children and
* hdp::children array maps.
*/
node_sampler<K, V>* children;
/**
* A pointer to the parent node in the sampler hierarchy.
*/
node_sampler<K, V>* parent;
/**
* The "sampler" structures form a tree parallel to the HDP hierarchy which
* consists of ::hdp and ::node objects. This is a pointer to the node in
* the HDP hierarchy that is parallel to this node.
*/
node<K, V>* n;
/**
* <!-- state variables for Gibbs sampling -->
*/
/**
* An array parallel to node::observations that indicates which table in
* this node each observation is assigned to.
*/
unsigned int* observation_assignments;
/**
* An array with length node_sampler::table_count (and capacity
* node_sampler::table_capacity) that keeps track of the number of
* customers sitting at each table.
*/
unsigned int* table_sizes;
/**
* Each table in this node is assigned to a table in the parent node. This
* array with length node_sampler::table_count (and capacity
* node_sampler::table_capacity) keeps track the assignments of tables in
* this node to tables in the parent node.
*/
unsigned int* table_assignments;
/**
* Since every table in every node in the sampler hierarchy is assigned to
* a table in the parent node, we can follow the chain of table assignments
* to tables in the root node. This array with length
* node_sampler::table_count (and capacity node_sampler::table_capacity)
* keeps track of the assignemnts of tables in this node to tables in the
* root node.
*/
unsigned int* root_assignments;
/**
* This array of array_multiset objects keeps track, for each table in this
* node, the set of observations assigned to this table, either directly or
* indirectly via descendant nodes in the hierarchy. This array has length
* node_sampler::table_count and capacity node_sampler::table_capacity.
*/
array_multiset<K>* descendant_observations;
/**
* The number of occupied tables in the Chinese restaurant represented by
* this sampler node.
*/
unsigned int table_count;
/**
* The current capacity of tables in this sampler node.
*/
unsigned int table_capacity;
/**
* The total number of customers sitting at all tables at this sampler node.
*/
unsigned int customer_count;
array<node_sample<V>> posterior;
template<typename BaseDistribution, typename DataDistribution>
node_sampler(
const hdp_sampler<BaseDistribution, DataDistribution, K, V>& root,
const node<K, V>& n, const child_type* parent, unsigned int table_capacity) :
n(&n), parent(parent), posterior(4)
{
if (!initialize(root, table_capacity))
exit(EXIT_FAILURE);
}
~node_sampler() { free(); }
inline V alpha() const {
return n->get_alpha();
}
inline V log_alpha() const {
return n->get_log_alpha();
}
inline unsigned int child_count() const {
return (unsigned int) n->children.size;
}
inline const child_type& get_child(unsigned int key, bool& contains) const {
unsigned int index = n->children.index_of(key);
contains = (index < child_count());
return children[index];
}
inline unsigned int child_key(unsigned int index) const {
return n->children.keys[index];
}
inline unsigned int observation_count() const {
return (unsigned int) n->observations.length;
}
inline const K& get_observation(unsigned int index) const {
return n->observations[index];
}
inline unsigned int root_assignment(unsigned int i) const {
return root_assignments[i];
}
inline unsigned int table_assignment(unsigned int i) const {
return table_assignments[i];
}
template<typename Cache>
inline void relabel_tables(const unsigned int* table_map, const Cache& cache) {
/* apply the table map to the tables in the child nodes */
for (unsigned int i = 0; i < child_count(); i++)
children[i].relabel_parent_tables(table_map);
for (unsigned int i = 0; i < observation_count(); i++)
observation_assignments[i] = table_map[observation_assignments[i]];
}
void relabel_parent_tables(const unsigned int* parent_table_map) {
for (unsigned int i = 0; i < table_count; i++)
table_assignments[i] = parent_table_map[table_assignments[i]];
}
bool get_observations(array_multiset<K>& dst, unsigned int assignment) const {
for (unsigned int i = 0; i < table_count; i++) {
if (table_assignments[i] == assignment && !dst.add(descendant_observations[i])) {
fprintf(stderr, "node_sampler.get_observations ERROR: Unable "
"to add descendant observations to multiset.\n");
return false;
}
}
return true;
}
template<typename Cache>
inline void move_table(unsigned int src, unsigned int dst, const Cache& cache) {
table_assignments[dst] = table_assignments[src];
table_sizes[dst] = table_sizes[src];
root_assignments[dst] = root_assignments[src];
array_multiset<K>::move(descendant_observations[src], descendant_observations[dst]);
}
template<typename Observations, typename Cache>
inline bool move_to_table(const Observations& observations,
unsigned int src, unsigned int dst, Cache& cache)
{
if (!descendant_observations[dst].add(observations)) {
fprintf(stderr, "node_sampler.move_to_table ERROR: Unable to add observations to new table.\n");
return false;
}
descendant_observations[src].subtract(observations);
descendant_observations[src].remove_zeros();
cache.on_move_to_table(*this, src, dst, observations);
return true;
}
template<typename Observations, typename Cache>
inline bool move_to_new_table(const Observations& observations, unsigned int src, Cache& cache)
{
if (!descendant_observations[table_count - 1].add(observations)) {
fprintf(stderr, "node_sampler.move_to_new_table ERROR: Unable to add observations to new table.\n");
return false;
}
descendant_observations[src].subtract(observations);
descendant_observations[src].remove_zeros();
cache.on_move_to_new_table(*this, src, observations);
return true;
}
template<typename Observations, typename Cache>
inline bool add_to_table(
const Observations& observations,
unsigned int table, Cache& cache)
{
if (!descendant_observations[table].add(observations)) {
fprintf(stderr, "node_sampler.add_to_table ERROR: Unable to add observations to new table.\n");
return false;
}
cache.on_add_to_table(*this, table, observations);
return true;
}
template<typename Observations, typename Cache>
inline bool add_to_new_table(const Observations& observations, Cache& cache)
{
if (!descendant_observations[table_count - 1].add(observations)) {
fprintf(stderr, "node_sampler.add_to_new_table ERROR: Unable to add observations to new table.\n");
return false;
}
cache.on_add_to_new_table(*this, observations);
return true;
}
template<typename Observations, typename Cache>
inline bool remove_from_table(
const Observations& observations,
unsigned int table, Cache& cache)
{
descendant_observations[table].subtract(observations);
descendant_observations[table].remove_zeros();
cache.on_remove_from_table(*this, table, observations);
return true;
}
inline bool new_table() {
unsigned int new_capacity = table_capacity;
while (new_capacity < table_count + 2)
new_capacity *= 2;
if (table_capacity != new_capacity && !resize(new_capacity)) {
fprintf(stderr, "node_sampler.new_table ERROR: Unable to expand table array.\n");
return false;
}
table_capacity = new_capacity;
if (!init(descendant_observations[table_count], 4)) {
fprintf(stderr, "node_sampler.new_table ERROR: Unable to initialize new table.\n");
return false;
}
table_count++;
return true;
}
/* NOTE: this does not change the total number of tables */
inline void free_table(unsigned int i) {
core::free(descendant_observations[i]);
}
inline void set_table_count(unsigned int new_count) {
table_count = new_count;
}
inline bool add_sample() {
return add_sample(table_count);
}
bool add_sample(unsigned int root_cluster_count) {
for (unsigned int i = 0; i < child_count(); i++)
children[i].add_sample(root_cluster_count);
if (!posterior.ensure_capacity(posterior.length + 1)) {
fprintf(stderr, "node_sampler.add_sample ERROR: Unable to expand posterior sample array.\n");
return false;
} else if (!init(posterior[(unsigned int) posterior.length], table_count, observation_count())) {
fprintf(stderr, "node_sampler.add_sample ERROR: Unable to initialize new sample.\n");
return false;
}
node_sample<V>& sample = posterior[(unsigned int) posterior.length];
for (unsigned int i = 0; i < observation_count(); i++)
sample.table_assignments[i] = observation_assignments[i];
for (unsigned int i = 0; i < table_count; i++) {
sample.root_assignments[i] = root_assignments[i];
sample.table_sizes[i] = table_sizes[i];
}
sample.customer_count = customer_count;
posterior.length++;
return true;
}
void clear_samples() {
for (unsigned int i = 0; i < child_count(); i++)
children[i].clear_samples();
for (unsigned int i = 0; i < posterior.length; i++)
core::free(posterior[i]);
posterior.clear();
}
static inline void move(
const node_sampler<K, V>& src,
node_sampler<K, V>& dst)
{
dst.table_sizes = src.table_sizes;
core::move(src.observation_assignments, dst.observation_assignments);
core::move(src.posterior, dst.posterior);
dst.table_assignments = src.table_assignments;
dst.root_assignments = src.root_assignments;
dst.descendant_observations = src.descendant_observations;
dst.table_count = src.table_count;
dst.table_capacity = src.table_capacity;
dst.customer_count = src.customer_count;
dst.children = src.children;
dst.parent = src.parent;
dst.n = src.n;
}
template<typename Metric>
static inline long unsigned int size_of(
const node_sampler<K, V>& n, const Metric& metric)
{
long unsigned int sum = core::size_of(n.observation_assignments)
+ core::size_of(n.children, make_key_value_metric(default_metric(), metric))
+ core::size_of(n.customer_count) + core::size_of(n.parent)
+ core::size_of(n.observations, metric) + core::size_of(n.table_count)
+ core::size_of(n.table_capacity) + core::size_of(n.posterior);
for (unsigned int i = 0; i < n.table_count; i++)
sum += core::size_of(n.descendant_observations[i], metric);
sum += sizeof(array_multiset<K>) * (n.table_capacity - n.table_count);
sum += 3 * sizeof(unsigned int) * n.table_capacity;
return sum;
}
static inline void free(node_sampler<K, V>& n) {
n.free();
core::free(n.posterior);
}
private:
template<typename BaseDistribution, typename DataDistribution>
inline bool initialize(
const hdp_sampler<BaseDistribution, DataDistribution, K, V>& root,
unsigned int initial_table_capacity)
{
table_sizes = NULL;
table_count = 0;
table_capacity = initial_table_capacity;
table_assignments = NULL;
root_assignments = NULL;
descendant_observations = NULL;
observation_assignments = NULL;
children = NULL;
customer_count = 0;
children = (node_sampler<K, V>*) malloc(sizeof(node_sampler<K, V>) * n->children.capacity);
observation_assignments = (unsigned int*) calloc(n->observations.capacity, sizeof(unsigned int));
if (children == NULL || observation_assignments == NULL || !resize(initial_table_capacity)) {
fprintf(stderr, "node_sampler.initialize ERROR: Unable to initialize tables.\n");
free(0); return false;
}
/* add the observations from the hdp node */
for (unsigned int i = 0; i < n->children.size; i++) {
if (!init(children[i], root, n->children.values[i], this, 8)) {
fprintf(stderr, "node_sampler.initialize ERROR: Unable to initialize child node.\n");
free(i); return false;
}
for (unsigned int j = 0; j < children[i].table_count; j++) {
/* assign the tables in the child nodes to tables in this node */
if (!sample_initial_assignment<DataDistribution>(
*this, root.pi(), children[i].descendant_observations[j], children[i].table_assignments[j]))
{
fprintf(stderr, "node_sampler.initialize ERROR: Unable to add to descendant_observations.\n");
free(i + 1); return false;
}
}
}
for (unsigned int i = 0; i < observation_count(); i++) {
if (!sample_initial_assignment<DataDistribution>(
*this, root.pi(), n->observations[i], observation_assignments[i]))
{
fprintf(stderr, "node_sampler.initialize ERROR: Unable to add to descendant_observations.\n");
free(0); return false;
}
}
return true;
}
inline void free_children(unsigned int child_count, const unsigned int* indices = NULL) {
if (indices == NULL) {
for (unsigned int i = 0; i < child_count; i++)
core::free(children[i]);
} else {
for (unsigned int i = 0; i < child_count; i++)
core::free(children[indices[i]]);
}
core::free(children);
}
inline void free(unsigned int child_count, const unsigned int* indices = NULL) {
if (children != NULL)
free_children(child_count, indices);
for (unsigned int i = 0; i < posterior.length; i++)
core::free(posterior[i]);
for (unsigned int i = 0; i < table_count; i++)
core::free(descendant_observations[i]);
if (table_assignments != NULL) core::free(table_assignments);
if (root_assignments != NULL) core::free(root_assignments);
if (descendant_observations != NULL) core::free(descendant_observations);
if (observation_assignments != NULL) core::free(observation_assignments);
if (table_sizes != NULL) core::free(table_sizes);
}
inline void free() { free(child_count()); }
inline bool resize(unsigned int new_capacity)
{
unsigned int* new_sizes = (unsigned int*) realloc(
table_sizes, sizeof(unsigned int) * new_capacity);
if (new_sizes == NULL) {
fprintf(stderr, "node_sampler.resize ERROR: Unable to expand table_sizes.\n");
return false;
}
table_sizes = new_sizes;
unsigned int* new_table_assignments = (unsigned int*) realloc(
table_assignments, sizeof(unsigned int) * new_capacity);
if (new_table_assignments == NULL) {
fprintf(stderr, "node_sampler.resize ERROR: Unable to expand table_assignments.\n");
return false;
}
table_assignments = new_table_assignments;
unsigned int* new_root_assignments = (unsigned int*) realloc(
root_assignments, sizeof(unsigned int) * new_capacity);
if (new_root_assignments == NULL) {
fprintf(stderr, "node_sampler.resize ERROR: Unable to expand root_assignments.\n");
return false;
}
root_assignments = new_root_assignments;
array_multiset<K>* new_descendant_observations = (array_multiset<K>*) realloc(
static_cast<void*>(descendant_observations), sizeof(array_multiset<K>) * new_capacity);
if (new_descendant_observations == NULL) {
fprintf(stderr, "node_sampler.resize ERROR: Unable to expand descendant_observations.\n");
return false;
}
descendant_observations = new_descendant_observations;
return true;
}
template<typename A, typename B, typename C, typename D>
friend bool init(node_sampler<C, D>&, const hdp_sampler<A, B, C, D>&,
node<C, D>&, node_sampler<C, D>*, unsigned int);
template<typename A, typename B, typename C>
friend bool read_sampler_node(A&, B&, typename A::node_type&, C&);
template<typename A, typename B, typename C, typename D, typename E>
friend bool read(node_sampler<A, B>&, C&, node<A, B>&, D&, E&);
};
template<typename BaseDistribution, typename DataDistribution, typename K, typename V>
inline bool init(node_sampler<K, V>& sampler,
const hdp_sampler<BaseDistribution, DataDistribution, K, V>& root,
node<K, V>& n, node_sampler<K, V>* parent, unsigned int table_capacity)
{
sampler.n = &n;
sampler.parent = parent;
if (!array_init(sampler.posterior, 32)) {
fprintf(stderr, "init ERROR: Unable to initialize posterior sample array in node.\n");
return false;
} else if (!sampler.initialize(root, table_capacity)) {
fprintf(stderr, "init ERROR: Error during initialization of node.\n");
free(sampler.posterior);
return false;
}
return true;
}
template<typename K, typename V>
bool copy(const node_sampler<K, V>& src, node_sampler<K, V>& dst,
const hash_map<const node<K, V>*, node<K, V>*>& node_map,
node_sampler<K, V>* parent = NULL)
{
dst.n = node_map.get(src.n);
dst.parent = parent;
dst.table_count = src.table_count;
dst.table_capacity = src.table_count;
dst.customer_count = src.customer_count;
if (!array_init(dst.posterior, 1))
return false;
dst.children = (node_sampler<K, V>*) malloc(sizeof(node_sampler<K, V>) * src.child_count());
if (dst.children == NULL) {
free(dst.posterior);
return false;
}
dst.observation_assignments = (unsigned int*) malloc(sizeof(unsigned int) * src.observation_count());
if (dst.observation_assignments == NULL) {
free(dst.posterior);
free(dst.children);
return false;
}
memcpy(dst.observation_assignments, src.observation_assignments, sizeof(unsigned int) * src.observation_count());
dst.descendant_observations = (array_multiset<K>*) malloc(sizeof(array_multiset<K>) * src.table_count);
if (dst.descendant_observations == NULL) {
free(dst.posterior);
free(dst.observation_assignments);
free(dst.children);
return false;
}
dst.table_sizes = (unsigned int*) malloc(sizeof(unsigned int) * src.table_count);
if (dst.table_sizes == NULL) {
free(dst.posterior);
free(dst.observation_assignments);
free(dst.children);
free(dst.descendant_observations);
return false;
}
memcpy(dst.table_sizes, src.table_sizes, sizeof(unsigned int) * src.table_count);
dst.root_assignments = (unsigned int*) malloc(sizeof(unsigned int) * src.table_count);
if (dst.root_assignments == NULL) {
free(dst.posterior);
free(dst.observation_assignments);
free(dst.children);
free(dst.descendant_observations);
free(dst.table_sizes);
return false;
}
memcpy(dst.root_assignments, src.root_assignments, sizeof(unsigned int) * src.table_count);
dst.table_assignments = (unsigned int*) malloc(sizeof(unsigned int) * src.table_count);
if (dst.table_assignments == NULL) {
free(dst.posterior);
free(dst.observation_assignments);
free(dst.children);
free(dst.descendant_observations);
free(dst.table_sizes);
free(dst.root_assignments);
return false;
}
memcpy(dst.table_assignments, src.table_assignments, sizeof(unsigned int) * src.table_count);
for (unsigned int i = 0; i < src.table_count; i++)
if (!init(dst.descendant_observations[i], src.descendant_observations[i]))
return false; /* TODO: free memory (also add appropriate error messages) */
for (unsigned int i = 0; i < src.child_count(); i++)
if (!copy(src.children[i], dst.children[i], node_map, &dst))
return false; /* TODO: free memory (also add appropriate error messages) */
return true;
}
template<typename K, typename V>
struct collapsed_root_sample {
array_multiset<K>* descendant_observations;
unsigned int* table_sizes;
unsigned int table_count;
unsigned int customer_count;
unsigned int* table_assignments;
collapsed_root_sample(unsigned int table_count, unsigned int observation_count) : table_count(table_count) {
if (!initialize(table_count, observation_count)) {
fprintf(stderr, "collapsed_root_sample ERROR: Error during initialization.\n");
exit(EXIT_FAILURE);
}
}
~collapsed_root_sample() { free(); }
inline unsigned int root_assignment(unsigned int i) const {
return i;
}
template<typename Metric>
static inline long unsigned int size_of(const collapsed_root_sample<K, V>& sample, const Metric& metric) {
long unsigned int sum = core::size_of(sample.table_count) + core::size_of(sample.customer_count);
for (unsigned int i = 0; i < sample.table_count; i++)
sum += core::size_of(sample.descendant_observations[i], metric);
return sum + (sample.table_count + sample.customer_count) * sizeof(unsigned int);
}
static void free(collapsed_root_sample<K, V>& sample) {
sample.free();
}
private:
inline bool initialize(unsigned int table_count, unsigned int observation_count) {
descendant_observations = (array_multiset<K>*) malloc(sizeof(array_multiset<K>) * table_count);
if (descendant_observations == NULL) {
fprintf(stderr, "collapsed_root_sample.initialize ERROR: Unable to"
" initialize descendant_observations.\n");
return false;
}
table_sizes = (unsigned int*) malloc(sizeof(unsigned int) * table_count);
if (table_sizes == NULL) {
fprintf(stderr, "collapsed_root_sample.initialize ERROR:"
" Unable to initialize table_sizes.\n");
core::free(descendant_observations);
return false;
}
if (observation_count == 0)
observation_count = 1;
table_assignments = (unsigned int*) malloc(sizeof(unsigned int) * observation_count);
if (table_assignments == NULL) {
fprintf(stderr, "collapsed_root_sample.initialize ERROR:"
" Unable to initialize table_assignments.\n");
core::free(descendant_observations);
core::free(table_sizes);
return false;
}
return true;
}
inline void free() {
for (unsigned int i = 0; i < table_count; i++)