-
Notifications
You must be signed in to change notification settings - Fork 3
/
theory_prior.h
2702 lines (2451 loc) · 109 KB
/
theory_prior.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
#ifndef THEORY_PRIOR_H_
#define THEORY_PRIOR_H_
#include "higher_order_logic.h"
#include <core/random.h>
#include <math/log.h>
#include <math/multiset.h>
using namespace core;
//#define DEBUG_LOG_PROBABILITY
struct poisson_distribution {
typedef unsigned int ObservationType;
double lambda, log_lambda;
poisson_distribution(double lambda) : lambda(lambda), log_lambda(log(lambda)) { }
poisson_distribution(const poisson_distribution& src) : lambda(src.lambda), log_lambda(src.log_lambda) { }
};
inline double log_probability(unsigned int k, const poisson_distribution& prior) {
return k * prior.log_lambda - prior.lambda - lgamma(k + 1);
}
struct geometric_distribution {
typedef unsigned int ObservationType;
double p, log_p, log_one_minus_p;
geometric_distribution(double p) : p(p), log_p(log(p)), log_one_minus_p(log(1.0 - p)) { }
geometric_distribution(const geometric_distribution& src) : p(src.p), log_p(src.log_p), log_one_minus_p(src.log_one_minus_p) { }
};
inline double log_probability(unsigned int k, const geometric_distribution& prior) {
return k * prior.log_one_minus_p + prior.log_p;
}
unsigned int sample(const geometric_distribution& prior, unsigned int min, unsigned int max) {
/* we use inverse transform sampling */
double min_cdf = 1.0 - pow(1 - prior.p, min);
double max_cdf = (max == UINT_MAX ? 1.0 : (1.0 - pow(1 - prior.p, max + 1)));
double u = sample_uniform<double>() * (max_cdf - min_cdf) + min_cdf;
return (unsigned int) floor(log(1.0 - u) / prior.log_one_minus_p);
}
struct very_light_tail_distribution {
typedef unsigned int ObservationType;
double log_lambda, log_normalization;
very_light_tail_distribution(double log_lambda) : log_lambda(log_lambda), log_normalization(0.0) {
for (unsigned int k = 0; ; k++) {
double old_log_normalization = log_normalization;
log_normalization = logsumexp(log_normalization, (k * k) * log_lambda);
if (log_normalization == old_log_normalization)
break;
}
}
very_light_tail_distribution(const very_light_tail_distribution& src) : log_lambda(src.log_lambda), log_normalization(src.log_normalization) { }
};
inline double log_probability(unsigned int k, const very_light_tail_distribution& prior) {
return prior.log_normalization + (k * k) * prior.log_lambda;
}
template<typename T>
struct dummy_array {
dummy_array() { }
inline constexpr bool add(const T& item) const { return true; }
};
template<typename T>
struct default_array {
array<T> a;
default_array() : a(16) { }
default_array(const default_array<T>& src) = delete;
inline bool add(const T& item) {
return a.add(item);
}
inline auto begin() -> decltype(a.begin()) {
return a.begin();
}
inline auto end() -> decltype(a.end()) {
return a.end();
}
inline auto begin() const -> decltype(a.begin()) {
return a.begin();
}
inline auto end() const -> decltype(a.end()) {
return a.end();
}
static inline void move(const default_array<T>& src, default_array<T>& dst) {
core::move(src.a, dst.a);
}
static inline void free(default_array<T>& array) {
core::free(array.a);
}
};
template<typename T>
inline bool init(default_array<T>& array) {
return array_init(array.a, 16);
}
template<typename T>
inline size_t size(const default_array<T>& array) {
return array.a.length;
}
template<typename T, typename Stream>
inline bool print(const default_array<T>& array, Stream& out) {
return print(array.a, out);
}
template<typename T>
struct default_array_multiset {
array_multiset<T, true> a;
default_array_multiset() : a(16) { }
default_array_multiset(const default_array_multiset<T>& src) = delete;
inline bool add(const T& item) {
return a.add(item);
}
static inline void move(const default_array_multiset<T>& src, default_array_multiset<T>& dst) {
core::move(src.a, dst.a);
}
static inline void free(default_array_multiset<T>& multiset) {
core::free(multiset.a);
}
};
template<typename T>
inline bool init(default_array_multiset<T>& multiset) {
return init(multiset.a, 16);
}
template<typename T>
inline void free_all(default_array_multiset<T>& a) { }
template<typename T>
struct default_hash_multiset {
hash_multiset<T, true> a;
default_hash_multiset() : a(16) { }
default_hash_multiset(const default_hash_multiset<T>& src) : a(src.a.counts.table.capacity)
{
for (const auto& entry : src.a.counts)
a.counts.put(entry.key, entry.value);
a.sum = src.a.sum;
}
inline bool add(const T& item) {
return a.add(item);
}
inline bool add(const default_array_multiset<T>& changes) {
return a.add(changes.a);
}
inline void subtract(const default_array_multiset<T>& changes) {
a.template subtract<true>(changes.a);
}
static inline void move(const default_hash_multiset<T>& src, default_hash_multiset<T>& dst) {
core::move(src.a, dst.a);
}
static inline void free(default_hash_multiset<T>& multiset) {
core::free(multiset.a);
}
};
template<typename T>
inline bool init(default_hash_multiset<T>& multiset) {
return init(multiset.a, 16);
}
template<typename T>
inline bool init(default_hash_multiset<T>& multiset, const default_hash_multiset<T>& src) {
if (!init(multiset.a, src.a.counts.table.capacity))
return false;
for (const auto& entry : src.a.counts)
multiset.a.counts.put(entry.key, entry.value);
multiset.a.sum = src.a.sum;
return true;
}
template<typename T>
inline bool clone(const default_hash_multiset<T>& src, default_hash_multiset<T>& dst) {
return init(dst, src);
}
template<typename T, typename Stream>
bool read(default_hash_multiset<T>& state, Stream& in) {
decltype(state.a.counts.table.size) histogram_size;
if (!read(histogram_size, in)
|| !init(state.a, 1 << (core::log2(RESIZE_THRESHOLD_INVERSE * (histogram_size == 0 ? 1 : histogram_size)) + 1)))
return false;
T& key = *((T*) alloca(sizeof(T)));
for (unsigned int i = 0; i < histogram_size; i++) {
if (!read(key, in)) {
free(state.a);
return false;
}
unsigned int bucket = state.a.counts.table.index_to_insert(key);
if (!read(state.a.counts.values[bucket], in)) {
free(key);
free(state.a);
return false;
}
move(key, state.a.counts.table.keys[bucket]);
state.a.counts.table.size++;
state.a.sum += state.a.counts.values[bucket];
}
return true;
}
template<typename T, typename Stream>
bool write(const default_hash_multiset<T>& state, Stream& out) {
if (!write(state.a.counts.table.size, out))
return false;
for (const auto& entry : state.a.counts) {
if (!write(entry.key, out)
|| !write(entry.value, out))
return false;
}
return true;
}
template<typename T>
inline void free_all(default_hash_multiset<T>& a) { }
template<typename T>
inline unsigned int size(const default_array_multiset<T>& multiset) {
return multiset.a.counts.size;
}
template<typename T>
inline unsigned int size(const default_hash_multiset<T>& multiset) {
return multiset.a.counts.table.size;
}
template<typename T>
inline const T& get_key(const default_array_multiset<T>& multiset, unsigned int i) {
return multiset.a.counts.keys[i];
}
template<typename T>
inline unsigned int get_value(const default_array_multiset<T>& multiset, unsigned int i) {
return multiset.a.counts.values[i];
}
template<typename T>
unsigned int sum(const default_array_multiset<T>& multiset) {
return multiset.a.sum;
}
template<typename T, bool AutomaticallyFree>
inline unsigned int size(const array_multiset<T, AutomaticallyFree>& multiset) {
return multiset.counts.size;
}
template<typename T, bool AutomaticallyFree>
inline const T& get_key(const array_multiset<T, AutomaticallyFree>& multiset, unsigned int i) {
return multiset.counts.keys[i];
}
template<typename T, bool AutomaticallyFree>
inline unsigned int get_value(const array_multiset<T, AutomaticallyFree>& multiset, unsigned int i) {
return multiset.counts.values[i];
}
template<typename T, bool AutomaticallyFree>
unsigned int sum(const array_multiset<T, AutomaticallyFree>& multiset) {
return multiset.sum;
}
struct empty_prior_state {
template<typename T>
inline constexpr bool add(const T& changes) const { return true; }
template<typename T>
inline void subtract(const T& changes) const { }
static inline void move(const empty_prior_state& src, const empty_prior_state& dst) { }
static inline void free(const empty_prior_state& state) { }
};
constexpr bool init(const empty_prior_state& new_state) { return true; }
constexpr unsigned int size(const empty_prior_state& new_state) { return 0; }
constexpr bool clone(const empty_prior_state& src, const empty_prior_state& dst) { return true; }
template<typename Stream, typename... Reader>
constexpr bool read(const empty_prior_state& state, Stream& in, Reader&&... reader) { return true; }
template<typename Stream, typename... Writer>
constexpr bool write(const empty_prior_state& state, Stream& out, Writer&&... writer) { return true; }
template<typename T>
struct iid_uniform_distribution
{
typedef empty_prior_state PriorState;
typedef default_array<T> PriorStateChanges;
typedef T ObservationType;
typedef default_array<T> ObservationCollection;
double log_n;
iid_uniform_distribution(unsigned int n) : log_n(log(n)) { }
iid_uniform_distribution(const iid_uniform_distribution<T>& src) : log_n(src.log_n) { }
~iid_uniform_distribution() { }
private:
iid_uniform_distribution() { }
template<typename A> friend iid_uniform_distribution<A> make_iid_uniform_distribution_from_log_n(double);
};
template<typename T>
inline iid_uniform_distribution<T> make_iid_uniform_distribution(unsigned int n) {
return iid_uniform_distribution<T>(n);
}
template<typename T>
inline iid_uniform_distribution<T> make_iid_uniform_distribution_from_log_n(double log_n) {
iid_uniform_distribution<T> dist;
dist.log_n = log_n;
return dist;
}
template<typename T, typename ObservationCollection>
inline double log_probability(
const ObservationCollection& observations,
const iid_uniform_distribution<T>& prior)
{
double value = -(size(observations) * prior.log_n);
#if defined(DEBUG_LOG_PROBABILITY)
fprintf(stderr, "log_probability of `iid_uniform_distribution`: %lf.\n", value);
print(" Observations: ", stderr); print(observations, stderr); print('\n', stderr);
#endif
return value;
}
template<typename T, typename ObservationCollection>
inline double log_probability_ratio(
const empty_prior_state& dummy,
const ObservationCollection& old_observations,
const ObservationCollection& new_observations,
const iid_uniform_distribution<T>& prior)
{
return (size(old_observations) * prior.log_n) - (size(new_observations) * prior.log_n);
}
template<typename T, typename ObservationCollection>
inline double log_probability_ratio(
const empty_prior_state& dummy,
const ObservationCollection& old_observations,
const ObservationCollection& new_observations,
const iid_uniform_distribution<T>& prior,
const default_array<T>& old_prior_changes,
const default_array<T>& new_prior_changes)
{
return (size(old_observations) * prior.log_n) - (size(new_observations) * prior.log_n);
}
template<typename T>
struct chinese_restaurant_process
{
typedef default_array_multiset<T> ObservationCollection;
typedef default_hash_multiset<T> PriorState;
typedef default_array_multiset<T> PriorStateChanges;
double alpha, log_alpha;
double d, log_d, lgamma_one_minus_d;
chinese_restaurant_process(double alpha, double d) :
alpha(alpha), log_alpha(log(alpha)), d(d), log_d(log(d)), lgamma_one_minus_d(lgamma(1.0 - d))
{ }
chinese_restaurant_process(const chinese_restaurant_process<T>& src) :
alpha(src.alpha), log_alpha(log(alpha)), d(src.d), log_d(src.log_d), lgamma_one_minus_d(src.lgamma_one_minus_d)
{ }
~chinese_restaurant_process() { }
};
template<typename MultisetType, typename T>
double log_probability(
const MultisetType& observations,
const chinese_restaurant_process<T>& prior)
{
double value = 0.0;
#if defined(DEBUG_LOG_PROBABILITY)
fprintf(stderr, "log_probability of `chinese_restaurant_process`:\n");
#endif
for (unsigned int i = 0; i < size(observations); i++) {
double current_value = lgamma(get_value(observations, i) - prior.d) - prior.lgamma_one_minus_d;
#if defined(DEBUG_LOG_PROBABILITY)
fprintf(stderr, " Observation "); print(get_key(observations, i), stderr);
fprintf(stderr, " has count %u and log probability: %lf.\n", get_value(observations, i), current_value);
#endif
value += current_value;
}
double normalization;
if (prior.alpha <= 1.0e11)
normalization = lgamma(prior.alpha) - lgamma(prior.alpha + sum(observations));
else normalization = -(double) sum(observations) * log(prior.alpha + sum(observations));
if (prior.d == 0.0) {
normalization += prior.log_alpha * size(observations);
} else {
normalization += prior.log_d * size(observations);
double ratio = prior.alpha/prior.d;
if (ratio <= 1.0e11)
normalization += lgamma(ratio + size(observations)) - lgamma(ratio);
else normalization += (double) size(observations) * log(ratio + size(observations));
}
#if defined(DEBUG_LOG_PROBABILITY)
fprintf(stderr, " Prior: %lf.\n", normalization);
#endif
value += normalization;
#if defined(DEBUG_LOG_PROBABILITY)
fprintf(stderr, " Total: %lf.\n", value);
#endif
return value;
}
template<typename Stream>
inline bool print(const hol_term* term, Stream& stream) {
return print(*term, stream);
}
template<typename MultisetType,
template<typename> class Collection, typename T>
double log_probability(
const MultisetType& observations,
const chinese_restaurant_process<T>& prior,
Collection<T>& clusters)
{
double value = 0.0;
#if defined(DEBUG_LOG_PROBABILITY)
fprintf(stderr, "log_probability of `chinese_restaurant_process`:\n");
#endif
for (unsigned int i = 0; i < size(observations); i++) {
clusters.add(get_key(observations, i));
double current_value = lgamma(get_value(observations, i) - prior.d) - prior.lgamma_one_minus_d;
#if defined(DEBUG_LOG_PROBABILITY)
fprintf(stderr, " Observation "); print(get_key(observations, i), stderr);
fprintf(stderr, " has count %u and log probability: %lf.\n", get_value(observations, i), current_value);
#endif
value += current_value;
}
double normalization;
if (prior.alpha <= 1.0e11)
normalization = lgamma(prior.alpha) - lgamma(prior.alpha + sum(observations));
else normalization = -(double) sum(observations) * log(prior.alpha + sum(observations));
if (prior.d == 0.0) {
normalization += prior.log_alpha * size(observations);
} else {
normalization += prior.log_d * size(observations);
double ratio = prior.alpha/prior.d;
if (ratio <= 1.0e11)
normalization += lgamma(ratio + size(observations)) - lgamma(ratio);
else normalization += (double) size(observations) * log(ratio + size(observations));
}
#if defined(DEBUG_LOG_PROBABILITY)
fprintf(stderr, " Prior: %lf.\n", normalization);
#endif
value += normalization;
#if defined(DEBUG_LOG_PROBABILITY)
fprintf(stderr, " Total: %lf.\n", value);
#endif
return value;
}
template<bool AutomaticallyFree, typename T, typename Collection>
inline double log_probability_ratio_old_cluster(
const hash_multiset<T, AutomaticallyFree>& tables,
const T& observation, unsigned int frequency,
const chinese_restaurant_process<T>& prior,
Collection& old_clusters,
unsigned int& old_cluster_count)
{
#if !defined(NDEBUG)
if (!tables.counts.table.contains(observation))
fprintf(stderr, "log_probability_ratio_old_cluster WARNING: This chinese_restaurant_process does not contain the given observation.\n");
#endif
unsigned int count = tables.counts.get(observation);
if (count == frequency) {
old_clusters.add(observation);
old_cluster_count++;
return -lgamma(count - prior.d) - (prior.d == 0 ? prior.log_alpha : prior.log_d) + prior.lgamma_one_minus_d;
} else {
return lgamma(count - frequency - prior.d) - lgamma(count - prior.d);
}
}
template<bool AutomaticallyFree, typename T, typename Collection>
inline double log_probability_ratio_new_cluster(
const hash_multiset<T, AutomaticallyFree>& tables,
const T& observation, unsigned int frequency,
const chinese_restaurant_process<T>& prior,
Collection& new_clusters,
unsigned int& new_cluster_count)
{
bool contains;
unsigned int count = tables.counts.get(observation, contains);
#if !defined(NDEBUG)
if (contains && count == 0)
fprintf(stderr, "log_probability_ratio_new_cluster WARNING: The hash_multiset has an observation with zero count.\n");
#endif
if (contains) {
return lgamma(count + frequency - prior.d) - lgamma(count - prior.d);
} else {
new_clusters.add(observation);
new_cluster_count++;
return (prior.d == 0 ? prior.log_alpha : prior.log_d) + lgamma(frequency - prior.d) - prior.lgamma_one_minus_d;
}
}
template<bool AutomaticallyFree, typename MultisetType, typename Collection, typename T>
double log_probability_ratio(
const hash_multiset<T, AutomaticallyFree>& tables,
const MultisetType& old_observations,
const MultisetType& new_observations,
const chinese_restaurant_process<T>& prior,
Collection& old_clusters, Collection& new_clusters)
{
unsigned int i = 0, j = 0; double value = 0.0;
unsigned int old_cluster_count = 0, new_cluster_count = 0;
while (i < size(old_observations) && j < size(new_observations))
{
if (get_key(old_observations, i) == get_key(new_observations, j)) {
#if !defined(NDEBUG)
bool contains;
const T& key = get_key(old_observations, i);
unsigned int count = tables.counts.get(key, contains);
if (!contains)
print("log_probability_ratio WARNING: The given observation is not in the chinese_restaurant_process.\n", stderr);
#else
unsigned int count = tables.counts.get(get_key(old_observations, i));
#endif
int diff = (int) get_value(new_observations, j) - (int) get_value(old_observations, i);
if (count + diff == 0) {
/* this cluster is being removed */
old_clusters.add(get_key(old_observations, i));
old_cluster_count++;
value += -lgamma(count - prior.d) - (prior.d == 0 ? prior.log_alpha : prior.log_d) + prior.lgamma_one_minus_d;
} else {
value += lgamma(count + diff - prior.d) - lgamma(count - prior.d);
}
i++; j++;
} else if (get_key(old_observations, i) < get_key(new_observations, j)) {
value += log_probability_ratio_old_cluster(tables,
get_key(old_observations, i), get_value(old_observations, i), prior, old_clusters, old_cluster_count);
i++;
} else {
value += log_probability_ratio_new_cluster(tables,
get_key(new_observations, j), get_value(new_observations, j), prior, new_clusters, new_cluster_count);
j++;
}
}
while (i < size(old_observations)) {
value += log_probability_ratio_old_cluster(tables,
get_key(old_observations, i), get_value(old_observations, i), prior, old_clusters, old_cluster_count);
i++;
} while (j < size(new_observations)) {
value += log_probability_ratio_new_cluster(tables,
get_key(new_observations, j), get_value(new_observations, j), prior, new_clusters, new_cluster_count);
j++;
}
if (prior.alpha + tables.sum <= 1.0e11) {
value += lgamma(prior.alpha + tables.sum) - lgamma(prior.alpha + (tables.sum - sum(old_observations) + sum(new_observations)));
} else {
if (sum(new_observations) < sum(old_observations))
value += -((double) sum(new_observations) - sum(old_observations)) * log(prior.alpha + tables.sum);
else value += -((double) sum(new_observations) - sum(old_observations)) * log(prior.alpha + (tables.sum - sum(old_observations) + sum(new_observations)));
}
if (prior.d != 0.0) {
if (prior.alpha/prior.d + tables.counts.table.size <= 1.0e11) {
value += -lgamma(prior.alpha/prior.d + tables.counts.table.size) + lgamma(prior.alpha/prior.d + (tables.counts.table.size - old_cluster_count + new_cluster_count));
} else {
if (new_cluster_count < old_cluster_count)
value += ((double) new_cluster_count - old_cluster_count) * log(prior.alpha/prior.d + tables.counts.table.size);
else value += ((double) new_cluster_count - old_cluster_count) * log(prior.alpha/prior.d + (tables.counts.table.size - old_cluster_count + new_cluster_count));
}
}
return value;
}
template<typename T, bool AutomaticallyFree, typename MultisetType>
inline double log_probability_ratio(
const hash_multiset<T, AutomaticallyFree>& tables,
const MultisetType& old_observations,
const MultisetType& new_observations,
const chinese_restaurant_process<T>& prior)
{
dummy_array<T> dummy;
return log_probability_ratio(tables, old_observations, new_observations, prior, dummy, dummy);
}
template<typename T, typename MultisetType>
inline double log_probability_ratio(
const default_hash_multiset<T>& tables,
const MultisetType& old_observations,
const MultisetType& new_observations,
const chinese_restaurant_process<T>& prior)
{
return log_probability_ratio(tables.a, old_observations, new_observations, prior);
}
template<typename BaseDistribution>
struct dirichlet_process
{
struct prior_state {
typename BaseDistribution::PriorState base_prior_state;
prior_state() { }
template<typename... Args>
prior_state(const prior_state& src, Args&&... args) : base_prior_state(src.base_prior_state, std::forward<Args>(args)...) { }
inline bool add(const typename BaseDistribution::PriorStateChanges& changes) {
return base_prior_state.add(changes);
}
inline bool add(
const typename BaseDistribution::ObservationType& observation,
const dirichlet_process<BaseDistribution>& prior)
{
return base_prior_state.add(observation, prior.base_distribution);
}
inline void subtract(const typename BaseDistribution::PriorStateChanges& changes) {
base_prior_state.subtract(changes);
}
inline void subtract(
const typename BaseDistribution::ObservationType& observation,
const dirichlet_process<BaseDistribution>& prior)
{
base_prior_state.subtract(observation, prior.base_distribution);
}
template<typename... Args>
static inline bool get_formula_map(const prior_state& state, Args&&... args) {
return BaseDistribution::PriorState::get_formula_map(state.base_prior_state, std::forward<Args>(args)...);
}
template<typename Stream, typename... Reader>
static inline bool read(prior_state& state,
Stream& in, Reader&&... reader)
{
return BaseDistribution::PriorState::read(state.base_prior_state, in, std::forward<Reader>(reader)...);
}
template<typename Stream, typename... Writer>
static inline bool write(
const prior_state& state,
Stream& out, Writer&&... writer)
{
return BaseDistribution::PriorState::write(state.base_prior_state, out, std::forward<Writer>(writer)...);
}
template<typename... Cloner>
static inline bool clone(const prior_state& src, prior_state& dst, Cloner&&... cloner)
{
return BaseDistribution::PriorState::clone(src.base_prior_state, dst.base_prior_state, std::forward<Cloner>(cloner)...);
}
static inline void free(prior_state& state) {
core::free(state.base_prior_state);
}
};
typedef typename BaseDistribution::ObservationType ObservationType;
typedef default_array_multiset<ObservationType> ObservationCollection;
typedef prior_state PriorState;
typedef typename BaseDistribution::PriorStateChanges PriorStateChanges;
chinese_restaurant_process<ObservationType> restaurant;
BaseDistribution base_distribution;
dirichlet_process(double alpha, const BaseDistribution& base_distribution) :
restaurant(alpha, 0.0), base_distribution(base_distribution)
{ }
dirichlet_process(const dirichlet_process<BaseDistribution>& src) :
restaurant(src.restaurant), base_distribution(src.base_distribution)
{ }
};
template<typename BaseDistribution>
inline dirichlet_process<BaseDistribution> make_dirichlet_process(
double alpha, const BaseDistribution& base_distribution)
{
return dirichlet_process<BaseDistribution>(alpha, base_distribution);
}
template<typename T, typename std::enable_if<std::is_pointer<T>::value>::type* = nullptr>
inline void free_all(const default_array<T>& a) { }
template<typename T, typename std::enable_if<!std::is_pointer<T>::value>::type* = nullptr>
inline void free_all(default_array<T>& a) {
for (T& element : a)
free(element);
}
template<typename MultisetType, typename BaseDistribution>
double log_probability(
const MultisetType& restaurant_tables,
const dirichlet_process<BaseDistribution>& prior)
{
typedef typename BaseDistribution::ObservationCollection Clusters;
Clusters clusters;
double value = log_probability(restaurant_tables, prior.restaurant, clusters);
value += log_probability(clusters, prior.base_distribution);
free_all(clusters);
return value;
}
template<typename MultisetType, typename BaseDistribution>
inline double log_probability(
const MultisetType& restaurant_tables,
const dirichlet_process<BaseDistribution>& prior,
typename BaseDistribution::ObservationCollection& clusters)
{
return log_probability(restaurant_tables, prior.restaurant, clusters);
}
template<typename MultisetType, typename BaseDistribution>
double log_probability(
const MultisetType& restaurant_tables,
const array<typename BaseDistribution::ObservationType>& extra_observations,
const dirichlet_process<BaseDistribution>& prior)
{
typedef typename BaseDistribution::ObservationCollection Clusters;
Clusters clusters;
double value = log_probability(restaurant_tables, prior.restaurant, clusters);
for (const typename BaseDistribution::ObservationType& extra_observation : extra_observations) {
bool contains = false;
for (const typename BaseDistribution::ObservationType& existing_observation : clusters) {
if (existing_observation == extra_observation || *existing_observation == *extra_observation) {
contains = true;
break;
}
}
if (!contains)
clusters.add(extra_observation);
}
value += log_probability(clusters, prior.base_distribution);
free_all(clusters);
return value;
}
template<typename MultisetType, typename T, bool AutomaticallyFree, typename BaseDistribution>
double log_probability_ratio(
const MultisetType& restaurant_tables,
const array_multiset<T, AutomaticallyFree>& old_observations,
const array_multiset<T, AutomaticallyFree>& new_observations,
const dirichlet_process<BaseDistribution>& prior,
const typename dirichlet_process<BaseDistribution>::prior_state& prior_state,
typename BaseDistribution::PriorStateChanges& old_prior_changes,
typename BaseDistribution::PriorStateChanges& new_prior_changes)
{
typedef typename BaseDistribution::ObservationCollection Clusters;
Clusters old_clusters, new_clusters;
double value = log_probability_ratio(restaurant_tables, old_observations, new_observations, prior.restaurant, old_clusters, new_clusters);
value += log_probability_ratio(prior_state.base_prior_state, old_clusters, new_clusters, prior.base_distribution, old_prior_changes, new_prior_changes);
free_all(old_clusters);
free_all(new_clusters);
return value;
}
template<typename MultisetType, typename T, bool AutomaticallyFree, typename BaseDistribution>
double log_probability_ratio(
const MultisetType& restaurant_tables,
const array_multiset<T, AutomaticallyFree>& old_observations,
const array_multiset<T, AutomaticallyFree>& new_observations,
const array<T>& old_extra_observations,
const array<T>& new_extra_observations,
const dirichlet_process<BaseDistribution>& prior,
const typename dirichlet_process<BaseDistribution>::prior_state& prior_state,
typename BaseDistribution::PriorStateChanges& old_prior_changes,
typename BaseDistribution::PriorStateChanges& new_prior_changes)
{
typedef typename BaseDistribution::ObservationCollection Clusters;
Clusters old_clusters, new_clusters;
double value = log_probability_ratio(restaurant_tables, old_observations, new_observations, prior.restaurant, old_clusters, new_clusters);
for (const T& extra_observation : old_extra_observations) {
bool contains = false;
for (const T& existing_observation : old_clusters) {
if (existing_observation == extra_observation || *existing_observation == *extra_observation) {
contains = true;
break;
}
}
if (!contains)
old_clusters.add(extra_observation);
} for (const T& extra_observation : new_extra_observations) {
bool contains = false;
for (const T& existing_observation : new_clusters) {
if (existing_observation == extra_observation || *existing_observation == *extra_observation) {
contains = true;
break;
}
}
if (!contains)
new_clusters.add(extra_observation);
}
bool debug_flag = false;
if (debug_flag) {
print("new_clusters:\n", stderr);
for (hol_term* formula : new_clusters) {
print(" ", stderr); print(*formula, stderr); print('\n', stderr);
}
print("old_clusters:\n", stderr);
for (hol_term* formula : old_clusters) {
print(" ", stderr); print(*formula, stderr); print('\n', stderr);
}
}
value += log_probability_ratio(prior_state.base_prior_state, old_clusters, new_clusters, prior.base_distribution, old_prior_changes, new_prior_changes);
free_all(old_clusters);
free_all(new_clusters);
return value;
}
template<typename ConstantDistribution, typename PredicateDistribution, typename TypeDistribution>
struct simple_constant_distribution
{
struct prior_state_changes {
typename ConstantDistribution::PriorStateChanges constants;
typename PredicateDistribution::PriorStateChanges predicates;
array_map<unsigned int, array_multiset<hol_term>> types;
prior_state_changes() : types(8) { }
~prior_state_changes() {
for (auto entry : types) core::free(entry.value);
}
inline bool add_constant(unsigned int constant) {
return constants.add(constant);
}
inline bool add_predicate(unsigned int predicate) {
return predicates.add(predicate);
}
inline bool add_type(const hol_term* type, unsigned int constant) {
if (!types.ensure_capacity(types.size + 1))
return false;
unsigned int index = types.index_of(constant);
if (index == types.size) {
if (!init(types.values[index], 4)) {
return false;
} else if (!types.values[index].add(*type)) {
free(types.values[index]);
return false;
}
types.keys[index] = constant;
types.size++;
insertion_sort(types.keys, types.values, types.size, default_sorter());
return true;
} else {
return types.values[index].add(*type);
}
}
};
struct prior_state {
typename ConstantDistribution::PriorState constants;
typename PredicateDistribution::PriorState predicates;
hash_map<unsigned int, hash_multiset<hol_term>> types;
hash_multiset<hol_term> root_types;
prior_state() : types(16), root_types(16) { }
prior_state(const prior_state& src) : constants(src.constants), predicates(src.predicates), types(src.types.table.capacity), root_types(src.root_types.counts.table.capacity) {
if (!init_helper(src))
exit(EXIT_FAILURE);
}
~prior_state() { free_helper(); }
inline bool add(const prior_state_changes& changes) {
if (!constants.add(changes.constants)) {
return false;
} else if (!predicates.add(changes.predicates)) {
constants.subtract(changes.constants);
return false;
}
if (!types.check_size(types.table.size + changes.types.size)) {
constants.subtract(changes.constants);
predicates.subtract(changes.predicates);
return false;
}
array_multiset<hol_term> new_root_types(8);
for (unsigned int i = 0; i < changes.types.size; i++) {
bool contains; unsigned int index;
hash_multiset<hol_term>& value = types.get(changes.types.keys[i], contains, index);
if (!contains) {
if (!init(types.values[index], 4)) {
constants.subtract(changes.constants);
predicates.subtract(changes.predicates);
for (unsigned int j = 0; j < i; j++)
types.get(changes.types.keys[j]).subtract(changes.types.values[j]);
return false;
}
types.table.keys[index] = changes.types.keys[i];
types.table.size++;
}
if (!value.counts.check_size(value.counts.table.size + changes.types.values[i].counts.size)
|| !new_root_types.counts.ensure_capacity(new_root_types.counts.size + changes.types.values[i].counts.size))
{
constants.subtract(changes.constants);
predicates.subtract(changes.predicates);
for (unsigned int j = 0; j < i; j++)
types.get(changes.types.keys[j]).subtract(changes.types.values[j]);
return false;
}
for (const auto& entry : changes.types.values[i].counts) {
unsigned int& count = value.counts.get(entry.key, contains, index);
if (contains) {
count += entry.value;
} else {
value.counts.values[index] = entry.value;
value.counts.table.keys[index] = entry.key;
value.counts.table.size++;
new_root_types.add(entry.key);
}
value.sum += entry.value;
}
}
if (!root_types.add(new_root_types)) {
constants.subtract(changes.constants);
predicates.subtract(changes.predicates);
for (unsigned int j = 0; j < changes.types.size; j++)
types.get(changes.types.keys[j]).subtract(changes.types.values[j]);
return false;
}
return true;
}
inline bool add(const prior_state_changes& changes,
const simple_constant_distribution<ConstantDistribution, PredicateDistribution, TypeDistribution>& prior)
{
return add(changes);
}
inline void subtract(const prior_state_changes& changes) {
constants.subtract(changes.constants);
predicates.subtract(changes.predicates);
for (unsigned int i = 0; i < changes.types.size; i++) {
bool contains; unsigned int index;
hash_multiset<hol_term>& value = types.get(changes.types.keys[i], contains, index);
#if !defined(NDEBUG)
if (!contains)
fprintf(stderr, "simple_constant_distribution.prior_state.subtract WARNING: The given key does not exist in `types`.\n");
#endif
const array_multiset<hol_term>& items = changes.types.values[i];
for (unsigned int j = 0; j < items.counts.size; j++) {
bool contains; unsigned int bucket;
unsigned int& count = value.counts.get(items.counts.keys[j], contains, bucket);
#if !defined(NDEBUG)
if (!contains || count < items.counts.values[j]) {
fprintf(stderr, "simple_constant_distribution.prior_state.subtract "
"WARNING: Attempted to remove more items from a bin than it contains.\n");
count = 0;
} else count -= items.counts.values[j];
#else
count -= items.counts.values[j];
#endif
if (count == 0) {
value.counts.remove_at(bucket);