-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistributions.h
2011 lines (1821 loc) · 66.3 KB
/
distributions.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 distributions.h
*
* <!-- Created on: Jul 31, 2015
* Author: asaparov -->
*/
#ifndef DISTRIBUTIONS_H_
#define DISTRIBUTIONS_H_
#include <core/random.h>
#include "multiset.h"
#include "sparse_vector.h"
#include "log.h"
/* TODO: add documentation */
#define CATEGORICAL_MAX_THRESHOLD 16.0
#define CATEGORICAL_MIN_THRESHOLD 1.0e-5
/* forward declarations */
#if !defined(DOXYGEN_IGNORE)
template<typename V> struct dirichlet;
#endif
/**
* Returns the natural logarithm of the
* [rising factorial](https://en.wikipedia.org/wiki/Falling_and_rising_factorials):
* \f[ \log a^{(n)} = \log \left\{ \prod_{i=0}^{n-1} a^i \right\}, \f]
* where `base` is \f$ a \f$ and `exponent` is \f$ n \f$.
*/
inline double log_rising_factorial(double base, unsigned int exponent) {
return lgamma(base + exponent) - lgamma(base);
}
/* \tparam V satisfies [is_arithmetic](http://en.cppreference.com/w/cpp/types/is_arithmetic). */
template<typename V>
struct array_categorical {
V* log_probabilities;
V* probabilities; /* unnormalized */
V maximum; /* of log_probabilities */
array_categorical(unsigned int length) : log_probabilities(NULL), probabilities(NULL)
{
if (!initialize(length))
exit(EXIT_FAILURE);
}
~array_categorical() { free(); }
inline bool resize(unsigned int new_length) {
return core::resize(log_probabilities, new_length)
&& core::resize(probabilities, new_length);
}
void place(unsigned int i, const V& log_probability) {
log_probabilities[i] = log_probability;
}
void renormalize(unsigned int length) {
maximum = max(log_probabilities, length);
for (unsigned int i = 0; i < length; i++)
probabilities[i] = exp(log_probabilities[i] - maximum);
}
static inline void move(const array_categorical<V>& src, array_categorical<V>& dst) {
dst.log_probabilities = src.log_probabilities;
dst.probabilities = src.probabilities;
dst.maximum = src.maximum;
}
static inline void swap(array_categorical<V>& first, array_categorical<V>& second) {
core::swap(first.log_probabilities, second.log_probabilities);
core::swap(first.probabilities, second.probabilities);
core::swap(first.maximum, second.maximum);
}
/* NOTE: this function assumes that the type V has constant size */
static inline long unsigned int size_of(const array_categorical<V>& categorical, unsigned int length) {
return sizeof(V) * (2 * length + 1);
}
static inline void free(array_categorical<V>& categorical) {
categorical.free();
}
private:
inline bool initialize(unsigned int length) {
log_probabilities = (V*) malloc(sizeof(V) * length);
if (log_probabilities == NULL) {
fprintf(stderr, "array_categorical ERROR: Out of memory.\n");
return false;
}
probabilities = (V*) malloc(sizeof(V) * length);
if (probabilities == NULL) {
fprintf(stderr, "array_categorical ERROR: Out of memory.\n");
core::free(probabilities);
return false;
}
return true;
}
inline void free() {
core::free(log_probabilities);
core::free(probabilities);
}
template<typename A>
friend bool init(array_categorical<A>&, unsigned int);
};
template<typename V>
bool init(array_categorical<V>& categorical, unsigned int length) {
return categorical.initialize(length);
}
/**
* A structure representing a symmetric Dirichlet distribution, which is a
* regular [Dirichlet distribution](https://en.wikipedia.org/wiki/Dirichlet_distribution),
* where all the elements of the concentration parameter vector *pi* have the
* same value.
*
* The following example constructs a Dirichlet distribution with dimension 3,
* and concentration parameter [0.1, 0.1, 0.1]. It proceeds to generate two
* samples from this distribution. The expected output is
* `[0.004223, 0.995777, 0.000000] [0.964576, 0.035400, 0.000024]`.
*
* ```{.cpp}
* #include <math/distributions.h>
* using namespace core;
*
* template<typename V>
* struct custom_vector {
* V* elements;
*
* custom_vector(unsigned int length) {
* elements = (V*) malloc(sizeof(V) * length);
* }
*
* ~custom_vector() { free(elements); }
*
* inline V get(unsigned int index) const {
* return elements[index];
* }
*
* void set(unsigned int index, const V& value) {
* elements[index] = value;
* }
* };
*
* int main() {
* set_seed(100);
* symmetric_dirichlet<double> dir(3, 0.1);
*
* custom_vector<double> output(3);
* for (unsigned int i = 0; i < 2; i++) {
* sample(dir, output);
* print(output.elements, 3, stdout); print(' ', stdout);
* }
* }
* ```
*
* \tparam V satisfies [is_arithmetic](http://en.cppreference.com/w/cpp/types/is_arithmetic).
*/
template<typename V>
struct symmetric_dirichlet {
/**
* The type of the probabilities.
*/
typedef V value_type;
/**
* The value of each element of the concentration parameter.
*/
V pi;
/**
* The number of dimensions of the Dirichlet distribution.
*/
unsigned int atom_count;
/**
* The negative logarithm of `symmetric_dirichlet::atom_count`.
*/
V log_prob;
/**
* The sum of the elements in the concentration parameter vector. In the
* case of a symmetric Dirichlet distribution, this simply
* `symmetric_dirichlet::pi * symmetric_dirichlet::atom_count`.
*/
V total;
/**
* Constructs a symmetric Dirichlet distribution by copying the fields from
* the given symmetric Dirichlet distribution.
*/
symmetric_dirichlet(const symmetric_dirichlet<V>& prior) :
pi(prior.pi), atom_count(prior.atom_count), log_prob(-log(atom_count)), total(prior.pi * atom_count) { }
/**
* Constructs a symmetric Dirichlet distribution with the given dimension
* and concentration parameter.
*/
symmetric_dirichlet(unsigned int atom_count, const V& prior) :
pi(prior), atom_count(atom_count), log_prob(-log(atom_count)), total(prior * atom_count) { }
/**
* Checks if symmetric_dirichlet::atom_count is smaller than the given
* `new_atom_count`. If so, symmetric_dirichlet::atom_count is set to
* `new_atom_count` and symmetric_dirichlet::total is updated accordingly.
*/
inline void ensure_atom_count(unsigned int new_atom_count) {
if (new_atom_count > atom_count)
atom_count = new_atom_count;
total = pi * atom_count;
}
/**
* Returns the sum of the elements in the concentration parameter vector
* (symmetric_dirichlet::total).
*/
inline V sum() const {
return total;
}
/**
* Returns the maximum of the elements in the concentration parameter
* vector. In the case of the symmetric Dirichlet distribution, this is
* simply symmetric_dirichlet::pi.
*/
inline V max() const {
return pi;
}
/**
* Returns the element at the given `index` in the concentration parameter
* vector. In the case of the symmetric Dirichlet distribution, this
* function always returns symmetric_dirichlet::pi.
*/
inline V get_at_index(unsigned int index) const {
return pi;
}
/**
* Returns the element at the given `atom` in the concentration parameter
* vector. The atom is a non-empty element drawn from a categorical
* distribution with a Dirichlet prior. In the case of the symmetric
* Dirichlet distribution, this function always returns
* symmetric_dirichlet::pi.
*/
template<typename K>
inline V get_for_atom(const K& atom) const {
return pi;
}
template<typename K>
inline void add(sparse_vector<K, V>& vector) const {
vector.unspecified = pi;
}
inline void print(FILE* out) const {
fprintf(out, "pi: %lf\n", pi);
fprintf(out, "atom count: %u\n", atom_count);
}
/**
* Returns the parameters that may be used to construct this distribution,
* using either the constructor or init.
*/
inline const symmetric_dirichlet<V>& get_parameters() const {
return *this;
}
/**
* Samples from this symmetric Dirichlet distribution and puts the result in `dst`.
* \tparam Destination a vector type that implements the public member
* function `set(unsigned int, const V&)`.
*/
template<typename Destination>
inline void sample(Destination& dst) const {
std::gamma_distribution<V> distribution(pi, 1.0);
V sum = 0.0;
for (unsigned int i = 0; i < atom_count; i++) {
V value = distribution(engine);
dst.set(i, value);
sum += value;
}
for (unsigned int i = 0; i < atom_count; i++)
dst.set(i, dst.get(i) / sum);
}
/**
* Returns the log probability of a single observation `atom`, drawn from a
* Dirichlet-categorical distribution, where the Dirichlet is represented
* by this object. In the case of the symmetric Dirichlet distribution,
* this function always returns symmetric_dirichlet::log_prob.
*/
V log_probability(unsigned int item) const {
return log_prob;
}
template<typename Metric>
static inline long unsigned int size_of(const symmetric_dirichlet<V>& distribution, const Metric& metric) {
return core::size_of(distribution.atom_count) + core::size_of(distribution.log_prob)
+ core::size_of(distribution.pi) + core::size_of(distribution.total);
}
/**
* Frees the given symmetric Dirichlet distribution. Since
* symmetric_dirichlet does not allocate additional memory, this function
* is a no-op.
*/
static inline void free(symmetric_dirichlet<V>& distribution) { }
private:
bool initialize(unsigned int length, const V& pi_src) {
pi = pi_src;
atom_count = length;
log_prob = -log(atom_count);
total = pi * atom_count;
return true;
}
bool initialize(unsigned int length, const V* pi_src) {
fprintf(stderr, "symmetric_dirichlet_prior.initialize ERROR: "
"Dense parameterization for the prior is not supported"
" with a symmetric Dirichlet prior.");
return false;
}
template<typename A>
friend bool init(
symmetric_dirichlet<A>& prior,
const symmetric_dirichlet<A>& src);
};
/**
* Initializes the given symmetric_dirichlet `distribution` by copying its
* fields from the given symmetric_dirichlet `src`.
*/
template<typename V>
inline bool init(symmetric_dirichlet<V>& distribution,
const symmetric_dirichlet<V>& src)
{
return distribution.initialize(src.atom_count, src.pi);
}
/**
* Since a symmetric Dirichlet is a special case of a Dirichlet distribution,
* this function prints an error and exits.
*/
template<typename V>
inline bool init(symmetric_dirichlet<V>& distribution, const dirichlet<V>& src) {
fprintf(stderr, "init ERROR: Unsupported initialization of "
"symmetric_dirichlet_prior with a dirichlet_prior argument.\n");
exit(EXIT_FAILURE);
}
/**
* Reads a symmetric_dirichlet `distribution` from `in`.
*/
template<typename V>
inline bool read(symmetric_dirichlet<V>& distribution, FILE* in) {
if (!read(distribution.pi, in)) return false;
if (!read(distribution.atom_count, in)) return false;
distribution.log_prob = -log(distribution.atom_count);
return true;
}
/**
* Writes the symmetric_dirichlet `distribution` to `out`.
*/
template<typename V>
inline bool write(const symmetric_dirichlet<V>& distribution, FILE* out) {
if (!write(distribution.pi, out)) return false;
return write(distribution.atom_count, out);
}
/**
* Samples from the given symmetric Dirichlet `distribution` and puts the result in `dst`.
* \tparam Destination a vector type that implements the public member function
* `set(unsigned int, const V&)`.
*/
template<typename V, typename Destination>
inline bool sample(const symmetric_dirichlet<V>& distribution, Destination& dst) {
distribution.sample(dst);
return true;
}
/**
* A structure representing a finite [Dirichlet distribution](https://en.wikipedia.org/wiki/Dirichlet_distribution),
* which is a generalization of the symmetric Dirichlet distribution (see struct symmetric_dirichlet).
*
* The following example constructs a Dirichlet distribution with dimension 3,
* and concentration parameter [10, 1, 2]. It proceeds to generate two samples
* from this distribution. The expected output is
* `[0.491806, 0.023958, 0.484236] [0.804916, 0.019964, 0.175120]`.
*
* ```{.cpp}
* #include <math/distributions.h>
* using namespace core;
*
* template<typename V>
* struct custom_vector {
* V* elements;
*
* custom_vector(unsigned int length) {
* elements = (V*) malloc(sizeof(V) * length);
* }
*
* ~custom_vector() { free(elements); }
*
* inline V get(unsigned int index) const {
* return elements[index];
* }
*
* void set(unsigned int index, const V& value) {
* elements[index] = value;
* }
* };
*
* int main() {
* set_seed(100);
* double alpha[] = {10.0, 1.0, 2.0};
* dirichlet<double> dir(3, alpha);
*
* custom_vector<double> output(3);
* for (unsigned int i = 0; i < 2; i++) {
* sample(dir, output);
* print(output.elements, 3, stdout); print(' ', stdout);
* }
* }
* ```
*
* \tparam V satisfies [is_arithmetic](http://en.cppreference.com/w/cpp/types/is_arithmetic).
*/
template<typename V>
struct dirichlet {
/**
* The type of the probabilities.
*/
typedef V value_type;
/**
* The concentration parameter.
*/
V* pi;
/**
* The sum of all elements in the concentration parameter dirichlet::pi.
*/
V pi_sum;
/**
* The number of dimensions of this Dirichlet distribution.
*/
unsigned int atom_count;
/**
* Constructs a Dirichlet distribution by copying the fields from the given
* symmetric Dirichlet distribution.
*/
dirichlet(const symmetric_dirichlet<V>& prior) {
if (!initialize(prior.atom_count, prior.prior))
exit(EXIT_FAILURE);
}
/**
* Constructs a Dirichlet distribution by copying the fields from the given
* Dirichlet distribution.
*/
dirichlet(const dirichlet<V>& prior) {
if (!initialize(prior.atom_count, prior.pi))
exit(EXIT_FAILURE);
}
/**
* Constructs a Dirichlet distribution with the given dimension
* `atom_count` and symmetric concentration parameter `prior`.
*/
dirichlet(unsigned int atom_count, const V& prior) {
if (!initialize(atom_count, prior))
exit(EXIT_FAILURE);
}
/**
* Constructs a Dirichlet distribution with the given dimension
* `atom_count` and concentration parameter vector `prior`.
*/
dirichlet(unsigned int atom_count, const V* prior) {
if (!initialize(atom_count, prior))
exit(EXIT_FAILURE);
}
~dirichlet() { free(); }
/**
* Checks if dirichlet::atom_count is smaller than the given
* `new_atom_count`. If so, dirichlet::atom_count is set to
* `new_atom_count`.
*/
inline void ensure_atom_count(unsigned int new_atom_count) {
if (new_atom_count <= atom_count)
return;
fprintf(stderr, "dirichlet.ensure_atom_count ERROR: This is not implemented.\n");
}
/**
* Returns the sum of the elements in the concentration parameter vector
* (dirichlet::pi_sum).
*/
inline V sum() const {
return pi_sum;
}
/**
* Returns the element at the given `index` in the concentration parameter
* vector. This function does not perform any bounds checking.
*/
inline V get_at_index(unsigned int index) const {
return pi[index];
}
/**
* Returns the element at the given `atom` in the concentration parameter
* vector. The atom is a non-zero unsigned integer drawn from a categorical
* distribution with a Dirichlet prior. Thus, the atom `n` corresponds to
* the index `n - 1`. This function does not perform any bounds checking.
*/
inline V get_for_atom(unsigned int atom) const {
return pi[atom - 1];
}
template<typename K>
void add(sparse_vector<K, V>& vector) const {
for (unsigned int i = 0; i < vector.length; i++)
vector.set(i + 1, pi[i]);
}
void print(FILE* out) const {
if (atom_count == 0) {
fprintf(out, "pi: []\n");
return;
}
fprintf(out, "pi: [%lf", pi[0]);
for (unsigned int i = 1; i < atom_count; i++)
fprintf(out, ", %lf", pi[i]);
fprintf(out, "]\n");
fprintf(out, "atom count: %u\n", atom_count);
}
/**
* Returns the parameters that may be used to construct this distribution,
* using either the constructor or init.
*/
inline const dirichlet<V>& get_parameters() const {
return *this;
}
/**
* Samples from this Dirichlet distribution and puts the result in `dst`.
* \tparam Destination a vector type that implements the public member
* function `set(unsigned int, const V&)`.
*/
template<typename Destination>
inline void sample(Destination& dst) const {
V sum = 0.0;
for (unsigned int i = 0; i < atom_count; i++) {
std::gamma_distribution<V> distribution(pi[i], 1.0);
V value = distribution(engine);
dst.set(i, value);
sum += value;
}
for (unsigned int i = 0; i < atom_count; i++)
dst.set(i, dst.get(i) / sum);
}
/**
* Returns the log probability of a single observation `atom`, drawn from a
* Dirichlet-categorical distribution, where the Dirichlet is represented
* by this object.
*/
V log_probability(unsigned int atom) const {
return log(pi[atom - 1]) - log(pi_sum);
}
/* NOTE: this function assumes that the type V has constant size */
template<typename Metric>
static inline long unsigned int size_of(const dirichlet<V>& distribution, const Metric& metric) {
return core::size_of(distribution.atom_count) + core::size_of(distribution.pi_sum) + sizeof(V) * distribution.atom_count;
}
/**
* Frees dirichlet::pi in the given Dirichlet distribution.
*/
static inline void free(dirichlet<V>& distribution) {
distribution.free();
}
private:
bool initialize(unsigned int length, const V& pi_src) {
atom_count = length;
pi = (V*) malloc(sizeof(V) * atom_count);
if (pi == NULL) {
fprintf(stderr, "dirichlet_prior.initialize ERROR: Out of memory.\n");
return false;
}
for (unsigned int i = 0; i < atom_count; i++)
pi[i] = pi_src;
pi_sum = pi_src * atom_count;
return true;
}
bool initialize(unsigned int length, const V* pi_src) {
atom_count = length;
pi = (V*) malloc(sizeof(V) * atom_count);
if (pi == NULL) {
fprintf(stderr, "dirichlet_prior.initialize ERROR: Out of memory.\n");
return false;
}
pi_sum = 0.0;
for (unsigned int i = 0; i < atom_count; i++) {
pi[i] = pi_src[i];
pi_sum += pi_src[i];
}
return true;
}
inline void free() {
core::free(pi);
}
template<typename K>
friend bool init(dirichlet<K>&, const symmetric_dirichlet<K>&);
template<typename K>
friend bool init(dirichlet<K>&, const dirichlet<K>&);
};
/**
* Initializes the given Dirichlet `distribution` by copying its fields from
* the given symmetric_dirichlet distribution `src`.
*/
template<typename V>
inline bool init(dirichlet<V>& distribution,
const symmetric_dirichlet<V>& src)
{
return distribution.initialize(src.atom_count, src.pi);
}
/**
* Initializes the given Dirichlet `distribution` by copying its fields from
* the given Dirichlet distribution `src`.
*/
template<typename V>
inline bool init(dirichlet<V>& distribution, const dirichlet<V>& src)
{
return distribution.initialize(src.atom_count, src.pi);
}
/**
* Reads a dirichlet `distribution` from `in`.
*/
template<typename V>
inline bool read(dirichlet<V>& distribution, FILE* in) {
if (!read(distribution.atom_count, in))
return false;
distribution.pi = (V*) malloc(sizeof(V) * distribution.atom_count);
if (distribution.pi == NULL) return false;
if (!read(distribution.pi, in, distribution.atom_count)) {
free(distribution.pi);
return false;
}
distribution.pi_sum = 0.0;
for (unsigned int i = 0; i < distribution.atom_count; i++)
distribution.pi_sum += distribution.pi[i];
return true;
}
/**
* Writes the given dirichlet `distribution` to `out`.
*/
template<typename V>
inline bool write(const dirichlet<V>& distribution, FILE* out) {
if (!write(distribution.atom_count, out)) return false;
return write(distribution.pi, out, distribution.atom_count);
}
/**
* Samples from the given Dirichlet `distribution` and puts the result in `dst`.
* \tparam Destination a vector type that implements the public member function
* `set(unsigned int, const V&)`.
*/
template<typename V, typename Destination>
inline bool sample(const dirichlet<V>& distribution, Destination& dst) {
distribution.sample(dst);
return true;
}
/**
* <!-- Some useful type traits for Dirichlet distribution structures. -->
*/
/**
* A type trait that is [true_type](http://en.cppreference.com/w/cpp/types/integral_constant)
* if and only if `T` is either symmetric_dirichlet or dirichlet.
*/
template<typename T>
struct is_dirichlet : std::false_type { };
template<typename V>
struct is_dirichlet<symmetric_dirichlet<V>> : std::true_type { };
template<typename V>
struct is_dirichlet<dirichlet<V>> : std::true_type { };
/**
* This struct represents a categorical distribution, where the probabilities
* are represented as a sum of uniform and a non-uniform component. The
* non-uniform component is stored as a core::hash_map from atoms to
* probabilities. The dense_categorical struct instead stores all probabilities
* contiguously as a single native array. dense_categorical should be used if
* the dimension is small or if the probabilities cannot be easily represented
* sparsely as a sum of uniform and non-uniform components. Unlike
* dense_categorical, the observations do not necessarily have type `unsigned
* int`, and can have generic type `K`.
*
* The following is an example where a sparse_categorical distribution is
* constructed over the domain <code>{'a', 'b', 'c', 'd', 'e'}</code>. The probability of
* each event is specified and 10 samples are drawn. The expected output is
* `d, b, d, d, b, c, a, b, e, e,`.
* ```{.cpp}
* #include <math/distributions.h>
* using namespace core;
*
* int main() {
* set_seed(100);
* sparse_categorical<char, double> categorical(5);
* categorical.set('a', 0.1);
* categorical.set('b', 0.4);
* categorical.set('c', 0.1);
* categorical.set('d', 0.2);
* categorical.set('e', 0.2);
*
* for (unsigned int i = 0; i < 10; i++) {
* char c;
* sample(categorical, c);
* printf("%c, ", c);
* }
* }
* ```
*
* \tparam K the generic type of the observations. `K` must satisfy either:
* 1. [is_fundamental](http://en.cppreference.com/w/cpp/types/is_fundamental),
* 2. [is_enum](http://en.cppreference.com/w/cpp/types/is_enum),
* 3. [is_pointer](http://en.cppreference.com/w/cpp/types/is_pointer),
* 4. implements the public static method `unsigned int hash(const T&)`,
* the public static method `void is_empty(const T&)`, implements the
* operators `==`, satisfies [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable),
* and core::is_moveable. **NOTE:** The first argument to the `==`
* operator may be empty.
* \tparam V satisfies [is_arithmetic](http://en.cppreference.com/w/cpp/types/is_arithmetic).
*/
template<typename K, typename V>
struct sparse_categorical
{
/**
* The type of the probabilities.
*/
typedef V value_type;
/**
* A hash_map that encodes the non-uniform component of the categorical
* distribution. It maps from atoms to pairs, where the first entry in the
* pair contains the probability and the second entry contains the log
* probability.
*/
hash_map<K, pair<V, V>> probabilities;
/**
* The number of dimensions of the categorical distribution.
*/
unsigned int atom_count;
/**
* Stores the probability of every atom in the uniform component of the
* categorical distribution (i.e. every atom that is not a key in
* sparse_categorical::probabilities).
*/
V prob;
/**
* Stores the total probability mass in the non-uniform component of the
* categorical distribution (i.e. the sum of the probabilities in
* sparse_categorical::probabilities).
*/
V dense_prob;
/**
* The natural logarithm of sparse_categorical::prob.
*/
V log_prob;
/**
* Initializes this categorical distribution with the given dimension
* `atom_count`, setting all probabilities to zero.
*/
sparse_categorical(unsigned int atom_count) :
probabilities(16), atom_count(atom_count),
prob(1.0 / atom_count), dense_prob(0.0), log_prob(-log(atom_count)) { }
/**
* Initializes this categorical distribution by copying its fields from the
* given sparse_categorical distribution `src`.
*/
sparse_categorical(const sparse_categorical<K, V>& src) : probabilities(src.probabilities.table.capacity),
atom_count(src.atom_count), prob(src.prob), dense_prob(src.dense_prob), log_prob(src.log_prob)
{
if (!initialize(src))
exit(EXIT_FAILURE);
}
~sparse_categorical() { free(); }
/**
* Sets the `probability` of the given observation `key`. This function
* will make the key part of the non-uniform component of the categorical
* distribution.
*/
bool set(const K& key, const V& probability) {
if (!probabilities.check_size())
return false;
bool contains; unsigned int index;
pair<V, V>& value = probabilities.get(key, contains, index);
if (!contains) {
probabilities.table.keys[index] = key;
probabilities.table.size++;
value.key = probability;
value.value = log(probability);
} else dense_prob -= value.key;
dense_prob += probability;
if (probabilities.table.size >= atom_count) {
prob = 0.0;
log_prob = -std::numeric_limits<V>::infinity();
} else {
prob = (1.0 - dense_prob) / (atom_count - probabilities.table.size);
log_prob = log(prob);
}
return true;
}
/**
* Computes the conditional probability of observing the given `item` drawn
* from this constant distribution, *conditioned* on a collection of
* observations `conditioned`. This function assumes all the elements in
* `conditioned` are identical, and that `item` and `conditioned` have
* non-zero probability according to `prior`.
* \returns `true` if `item` is equivalent to the first element in `conditioned`.
* \returns `false` otherwise.
* \tparam PriorDistribution the type of the prior distribution. This function does not use `prior`.
*/
template<typename PriorDistribution>
static inline V conditional(const PriorDistribution& prior,
const K& item, const array_multiset<K>& conditioned)
{
for (unsigned int i = 0; i < conditioned.counts.size; i++) {
if (conditioned.counts.keys[i] == item) {
return (prior.get_for_atom(item) + conditioned.counts.values[i])
/ (prior.sum() + conditioned.total());
}
}
return (prior.get_for_atom(item)) / (prior.sum() + conditioned.total());
}
/**
* Returns the log probability of observing the given `item`, drawn from a
* categorical distribution, which is itself drawn from the given `prior`
* distribution, *conditioned* on the set of observations `conditioned`. It
* is assumed the given `prior` is a Dirichlet.
* \tparam PriorDistribution a distribution type with public member
* functions `V get_for_atom(unsigned int)` and `V sum()`.
*/
template<typename PriorDistribution>
static inline V log_conditional(const PriorDistribution& prior,
const K& item, const array_multiset<K>& conditioned)
{
for (unsigned int i = 0; i < conditioned.counts.size; i++) {
if (conditioned.counts.keys[i] == item) {
return log((prior.get_for_atom(item) + conditioned.counts.values[i]))
- log(prior.sum() + conditioned.total());
}
}
return log(prior.get_for_atom(item)) - log(prior.sum() + conditioned.total());
}
/**
* Returns the probability of observing the given collection of `items`,
* each drawn independently and identically from a categorical
* distribution, which is itself drawn from the given `prior` distribution,
* *conditioned* on the set of observations `conditioned`. It is assumed
* the given `prior` is a Dirichlet.
* \tparam PriorDistribution a distribution type with public member
* functions `V get_for_atom(unsigned int)` and `V sum()`.
*/
template<typename PriorDistribution>
static inline V log_conditional(const PriorDistribution& prior,
const array_multiset<K>& items, const array_multiset<K>& conditioned)
{
V log_probability = 0.0;
for (unsigned int i = 0; i < items.counts.size; i++) {
bool contains;
unsigned int count = conditioned.counts.get(items.counts.keys[i], contains);
if (contains) {
log_probability += log_rising_factorial(
prior.get_for_atom(items.counts.keys[i]) + count, items.counts.values[i]);
} else {
log_probability += log_rising_factorial(
prior.get_for_atom(items.counts.keys[i]), items.counts.values[i]);
}
}
return log_probability;
}
/**
* Returns the probability of the given observation `key`.
*/
inline V probability(const K& observation) const {
bool contains;
const pair<V, V>& entry = probabilities.get(observation, contains);
if (contains) return entry.key;
else return prob;
}
/**
* Returns the log probability of the given observation `key`.
*/
inline V log_probability(const K& observation) const {
bool contains;
const pair<V, V>& entry = probabilities.get(observation, contains);
if (contains) return entry.value;
else return log_prob;
}
/**
* Frees the given sparse_categorical `distribution` by releasing the
* memory resources associated with sparse_categorical::probabilities,
* along with all of its elements.
*/
static inline void free(sparse_categorical<K, V>& distribution) {
distribution.free();
core::free(distribution.probabilities);
}
private:
inline bool initialize(const sparse_categorical<K, V>& src) {
for (unsigned int i = 0; i < src.probabilities.table.capacity; i++) {
if (!is_empty(src.probabilities.table.keys[i])) {
if (!init(probabilities.table.keys[i], src.probabilities.table.keys[i])) {
set_empty(probabilities.table.keys[i]);
return false;
}
probabilities.values[i] = src.probabilities.values[i];
probabilities.table.size++;
}
}
return true;
}
inline void free() {
for (auto entry : probabilities)
core::free(entry.key);
}
template<typename A, typename B>
friend bool init(sparse_categorical<A, B>&, const sparse_categorical<A, B>&);
};
/**
* Initializes the given sparse_categorical `distribution` by copying its
* fields from the given sparse_categorical distribution `src`.
*/
template<typename K, typename V>
inline bool init(sparse_categorical<K, V>& distribution, const sparse_categorical<K, V>& src) {
distribution.atom_count = src.atom_count;
distribution.prob = src.prob;
distribution.log_prob = src.log_prob;
distribution.dense_prob = src.dense_prob;
if (!hash_map_init(distribution.probabilities, src.probabilities.table.capacity)) {
fprintf(stderr, "init ERROR: Unable to initialize hash_map in sparse_categorical.\n");