-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultinomialDistribution.hpp
More file actions
1706 lines (1549 loc) · 57.7 KB
/
Copy pathMultinomialDistribution.hpp
File metadata and controls
1706 lines (1549 loc) · 57.7 KB
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 MultinomialDistribution.hpp
* \author D'Oleris Paul Thatcher Edlefsen paul@galosh.org
* \par Library:
* galosh::prolific
* \brief
* Class definition for the galosh::MultinomialDistribution class. It
* represents a discrete distribution over a finite set of categories.
* \par Overview:
* This file is part of prolific, a library of useful C++ classes for
* working with genomic sequence data and Profile HMMs. Please see the
* document CITING, which should have been included with this file. You may
* use at will, subject to the license (Apache v2.0), but *please cite the
* relevant papers* in your documentation and publications associated with
* uses of this library. Thank you!
*
* \copyright © 2008, 2011 by Paul T. Edlefsen, Fred Hutchinson Cancer
* Research Center.
* \par License:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#if _MSC_VER > 1000
#pragma once
#endif
#ifndef __GALOSH_MULTINOMIALDISTRIBUTION_HPP__
#define __GALOSH_MULTINOMIALDISTRIBUTION_HPP__
#include "Prolific.hpp"
#include <string>
using std::string;
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
#include <limits>
using std::numeric_limits;
#include <math.h>
#include </usr/include/stdint.h>
#include </usr/include/assert.h>
#include "Random.hpp"
#include "Ambiguous.hpp"
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/list.hpp>
#include <boost/serialization/version.hpp>
#include <boost/lexical_cast.hpp> ///TAH 2/12
#include <seqan/basic.h>
#include "Algebra.hpp"
//#include <seqan/sequence.h>
using seqan::ordValue;
namespace galosh {
/**
* A MultinomialDistribution is a map from an enumerated type to a
* probability type. There are requirements on ValueType: it should support:
* ValueSize<ValueType>::VALUE, and should support ValueType( unsigned ). See
* Residue.hpp for examples.
*/
template <typename ValueType,
typename ProbabilityType>
class MultinomialDistribution
{
// Boost serialization
private:
friend class boost::serialization::access;
template<class Archive>
void serialize ( Archive & ar, const unsigned int /* file_version */ )
{
ar & BOOST_SERIALIZATION_NVP( m_probs );
} // serialize( Archive &, const unsigned int )
public:
// NOTE These should be protected but have to be public because different
// template instantiations need to directly access each other's values...
static uint32_t const m_elementCount = seqan::ValueSize<ValueType>::VALUE;
ProbabilityType m_probs[ m_elementCount ];
std::string
toString () const;
/**
* Inner class for ambiguous values with callbacks for any change. Note
* that the AmbiguousValue will not change if you alter the
* MultinomialDistribution via a different interface; the callbacks only
* work the other way: if you alter the AmbiguousValue, the
* MultinomialDistribution will be altered. Note also that most methods
* are not implemented. At this point, only operator= and operator+= are
* implemented.
*/
template <typename AmbiguityCodeType>
class AmbiguousValue : public ProbabilityType
{
AmbiguityCodeType const & m_ambiguityCode;
MultinomialDistribution & m_callbackDistribution;
public:
AmbiguousValue (
AmbiguityCodeType const & ambiguity_code,
MultinomialDistribution & callback_distribution
) :
ProbabilityType(),
m_ambiguityCode( ambiguity_code ),
m_callbackDistribution( callback_distribution )
{
// Do nothing else
} // <init>( AmbiguityCodeType const &, MultinomialDistribution & )
template <typename T>
AmbiguousValue (
AmbiguityCodeType const & ambiguity_code,
MultinomialDistribution & callback_distribution,
T const & v
) :
ProbabilityType( v ),
m_ambiguityCode( ambiguity_code ),
m_callbackDistribution( callback_distribution )
{
// Do nothing else
} // <init>( AmbiguityCodeType const &, MultinomialDistribution &, T const & )
AmbiguousValue (
AmbiguousValue const & copy_from
) :
ProbabilityType( copy_from.toProbabilityType() ),
m_ambiguityCode( copy_from.m_ambiguityCode ),
m_callbackDistribution( copy_from.m_callbackDistribution )
{
// Do nothing else
} // <init>( AmbiguousValue const & )
template <typename T>
AmbiguousValue &
operator= ( T const & v )
{
return this->ambiguousAssign( v );
} // operator= ( T const & )
template <typename T>
AmbiguousValue &
unambiguousAssign ( T const & v )
{
ProbabilityType::operator=( v );
return *this;
} // unambiguousAssign ( T const & )
template <typename T>
AmbiguousValue &
ambiguousAssign ( T const & v )
{
const size_t num_ambiguous_elements =
ambiguousCount( m_ambiguityCode, ValueType() );
// Actually divide the value evenly among the ambiguous elements
ProbabilityType prob_to_assign = v;
prob_to_assign /= num_ambiguous_elements;
this->unambiguousAssign( v );
ValueType possible_value;
for( size_t i = 0; i < num_ambiguous_elements; i++ ) {
galosh::ambiguousAssign( possible_value, m_ambiguityCode, i );
m_callbackDistribution.m_probs[ ordValue( possible_value ) ] =
prob_to_assign;
}
return *this;
} // ambiguousAssign ( T const & )
template <typename T>
AmbiguousValue &
operator+= ( T const & v )
{
return ambiguousIncrement( v );
}
template <typename T>
AmbiguousValue &
unambiguousIncrement ( T const & v )
{
ProbabilityType::operator+=( v );
return *this;
} // unambiguousIncrement ( T const & )
template <typename T>
AmbiguousValue &
ambiguousIncrement ( T const & v )
{
const size_t num_ambiguous_elements =
ambiguousCount( m_ambiguityCode, ValueType() );
// Actually divide the value evenly among the ambiguous elements
ProbabilityType prob_to_add = v;
prob_to_add /= num_ambiguous_elements;
this->unambiguousAssign( 0 );
ValueType possible_value;
for( size_t i = 0; i < num_ambiguous_elements; i++ ) {
galosh::ambiguousAssign( possible_value, m_ambiguityCode, i );
m_callbackDistribution.m_probs[ ordValue( possible_value ) ] += prob_to_add;
this->unambiguousIncrement( m_callbackDistribution.m_probs[ ordValue( possible_value ) ] );
}
return *this;
} // ambiguousIncrement ( T const & )
ProbabilityType
toProbabilityType () const
{
return *this;
} // toProbabilityType () const
// NOT (YET) IMPLEMENTED:
template <typename T>
AmbiguousValue &
operator-= ( T const & v )
{
return this->ambiguousDecrement( v );
}
// NOT (YET) IMPLEMENTED:
template <typename T>
AmbiguousValue &
operator*= ( T const & v )
{
return this->ambiguousMultiplyAssign( v );
}
// NOT (YET) IMPLEMENTED:
template <typename T>
AmbiguousValue &
operator/= ( T const & v )
{
return this->ambiguousDivideAssign( v );
}
// NOT (YET) IMPLEMENTED:
template <typename T>
AmbiguousValue
operator+ ( T const & v )
{
return this->ambiguousAdd( v );
}
// NOT (YET) IMPLEMENTED:
template <typename T>
AmbiguousValue
operator- ( T const & v )
{
return this->ambiguousSubtract( v );
}
// NOT (YET) IMPLEMENTED:
template <typename T>
AmbiguousValue
operator* ( T const & v )
{
return this->ambiguousMultiply( v );
}
// NOT (YET) IMPLEMENTED:
template <typename T>
AmbiguousValue
operator/ ( T const & v )
{
return this->ambiguousDivide( v );
}
}; // Inner class MultinomialDistribution::AmbiguousValue
public:
// Starts out with an even distribution
MultinomialDistribution ();
// Copy constructor
template <typename AnyProbabilityType>
MultinomialDistribution ( MultinomialDistribution<ValueType,AnyProbabilityType> const & copy_from );
// Start out with an even distribution.
void
reinitialize ();
uint32_t
size () const;
/**
* How many free parameters are there? If we consider this a
* MultinomialDistribution, its probabilities should sum to 1, so there are
* ( size() - 1 ) free parameters.
*/
uint32_t
freeParameterCount () const;
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType> &
operator= ( MultinomialDistribution<ValueType,AnyProbabilityType> const& other_dist );
MultinomialDistribution<ValueType,ProbabilityType> &
operator= ( MultinomialDistribution<ValueType,ProbabilityType> const& other_dist );
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType> &
operator= ( AnyProbabilityType const & set_to );
/**
* Add to each probability the corresponding probability in the given
* distribution. Note that this may violate the rule that the
* probabilities sum to 1.
*/
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType> &
operator+= ( MultinomialDistribution<ValueType,AnyProbabilityType> const& other_dist );
/**
* Add to each probability the given value. Note that this may violate the
* rule that the probabilities sum to 1.
*/
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType> &
operator+= ( AnyProbabilityType const& value );
/**
* Subtract from each probability the corresponding probability in the
* given distribution. Note that this may violate the rule that the
* probabilities are greater than 0. If it does, you may later run into
* problems (it is not checked here).
*/
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType> &
operator-= ( MultinomialDistribution<ValueType,AnyProbabilityType> const& other_dist );
/**
* Subtract from each probability the given value. Note that this may
* violate the rule that the probabilities are greater than 0. If it does,
* you may later run into problems (it is not checked here).
*/
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType> &
operator-= ( AnyProbabilityType const& value );
/**
* Multiply each probability by the corresponding probability in the given
* distribution.
*/
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType> &
operator*= (
MultinomialDistribution<ValueType,AnyProbabilityType> const& other_dist
);
/**
* Create a new Multinomial distribution that is the product of this and
* another.
*/
// Note that this copies its result to the caller...
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType>
operator* (
MultinomialDistribution<ValueType,AnyProbabilityType> const& other_dist
);
/**
* Multiply each probability by the given value.
*/
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType> &
operator*= (
AnyProbabilityType const& scalar
);
/**
* Divide each probability value by denominator. Note that
* this violates the rule that the probabilities sum to 1.
*/
template <typename AnyProbabilityType>
MultinomialDistribution<ValueType,ProbabilityType> &
operator/= ( AnyProbabilityType const& denominator );
template <typename AnyProbabilityType>
bool
operator== ( MultinomialDistribution<ValueType,AnyProbabilityType> const& other_dist );
bool
operator== ( MultinomialDistribution<ValueType,ProbabilityType> const& other_dist );
template <typename AnyProbabilityType>
bool
operator== ( AnyProbabilityType const & compare_to );
template <typename AnyType>
bool
operator!= ( AnyType const& other_thing );
ProbabilityType &
operator[] ( const ValueType & which );
ProbabilityType const&
operator[] ( const ValueType & which ) const;
ProbabilityType &
operator[] ( const uint32_t which );
ProbabilityType const&
operator[] ( const uint32_t which ) const;
template <typename AnyValueType>
AmbiguousValue<AnyValueType> const
operator[] ( const AnyValueType & which ) const
{
// This should not compile if attempted with something that is not ambiguous...
return ambiguousSum( which, typename IsAmbiguous<AnyValueType, ValueType>::Type() );
} // operator[] ( AnyValueType const & ) const
template <typename AnyValueType>
AmbiguousValue<AnyValueType>
operator[] ( const AnyValueType & which )
{
// This should not compile if attempted with something that is not ambiguous...
return ambiguousSum( which, typename IsAmbiguous<AnyValueType, ValueType>::Type() );
} // operator[] ( AnyValueType const & )
// Not const, because the return AmbiguousValue can be altered, altering
// this MultinomialDistribution.
template <typename AnyValueType>
AmbiguousValue<AnyValueType>
ambiguousSum ( const AnyValueType & ambiguity_code, seqan::True const tag = seqan::True() )
{
const size_t num_ambiguous_elements =
ambiguousCount( ambiguity_code, ValueType() );
AmbiguousValue<AnyValueType> prob( ambiguity_code, *this, 0 );
ValueType v;
for( size_t i = 0; i < num_ambiguous_elements; i++ ) {
galosh::ambiguousAssign( v, ambiguity_code, i );
prob.unambiguousIncrement( m_probs[ seqan::ordValue( v ) ] );
}
return prob;
} // ambiguousSum ( AnyValueType const & [, seqan::True ] )
// Not const, because the return AmbiguousValue can be altered, altering
// this MultinomialDistribution.
template <typename AnyValueType>
AmbiguousValue<AnyValueType>
ambiguousSum ( const AnyValueType & ambiguity_code, seqan::True const tag = seqan::True() ) const
{
const size_t num_ambiguous_elements =
ambiguousCount( ambiguity_code, ValueType() );
AmbiguousValue<AnyValueType> prob( ambiguity_code, ( *const_cast<MultinomialDistribution *>( this ) ), 0 );
ValueType v;
for( size_t i = 0; i < num_ambiguous_elements; i++ ) {
galosh::ambiguousAssign( v, ambiguity_code, i );
prob.unambiguousIncrement( m_probs[ ordValue( v ) ] );
}
return prob;
} // ambiguousSum ( AnyValueType const & [, seqan::True ] ) const
// Evenly distributes value to be added, among all of the values to which
// the ambiguity code refers, so that the total amount added is the value
// given.
template <typename AnyValueType, typename AnyProbabilityType>
void
ambiguousIncrement ( const AnyValueType & ambiguity_code, AnyProbabilityType const & value )
{
const size_t num_ambiguous_elements =
ambiguousCount( ambiguity_code, ValueType() );
// Actually divide the value evenly among the ambiguous elements
ProbabilityType prob_to_add = value;
prob_to_add /= num_ambiguous_elements;
ValueType v;
for( size_t i = 0; i < num_ambiguous_elements; i++ ) {
galosh::ambiguousAssign( v, ambiguity_code, i );
m_probs[ ordValue( v ) ] += prob_to_add;
}
return;
} // ambiguousIncrement ( AnyValueType const &, AnyProbabilityType const & )
/**
* Stream reader.
*/
friend std::istream &
operator>> (
std::istream & is,
MultinomialDistribution<ValueType,ProbabilityType> & md
)
{
md.readMultinomialDistribution( is );
return is;
} // friend operator>> ( istream &, MultinomialDistribution<ValueType> & )
void
readMultinomialDistribution (
std::istream& is
);
/**
* Stream writer.
*/
template<class CharT, class Traits>
friend std::basic_ostream<CharT,Traits>&
operator<< (
std::basic_ostream<CharT,Traits>& os,
MultinomialDistribution<ValueType,ProbabilityType> const& md
)
{
md.writeMultinomialDistribution( os );
return os;
} // friend operator<< ( basic_ostream &, MultinomialDistribution<ValueType> const& )
template<class CharT, class Traits>
void
writeMultinomialDistribution (
std::basic_ostream<CharT,Traits>& os
) const;
/**
* Set all values to 0. Note that this violates the rule that the values
* sum to 1.
*/
void
zero ();
/**
* Set all values to be the same (evenly distributed).
*/
void
even ();
/**
* Set all values to a random quantity, uniformly distributed over the
* simplex.
*/
void
uniform ( Random & random );
/**
* Adjust values such that they sum to one. This is just like saying *this
* /= this->total().
*/
void
normalize ();
/**
* Adjust values such that they sum to one, enforcing the given minimum
* value.
*/
template <typename other_type>
void
normalize ( other_type const & min );
/**
* Adjust values such that they sum to one, enforcing the given minimum
* value.
*/
void
normalize ( ProbabilityType const & min );
/**
* We do not enforce that values sum to 1. This method calculates and
* returns the sum.
*/
ProbabilityType
total () const;
/**
* Return the lowest of the probabilities contained herein.
*/
ProbabilityType
minimumValue () const;
/**
* Return the largest of the probabilities contained herein.
*/
ProbabilityType
maximumValue () const;
/**
* Return the ValueType with the largest of the probabilities contained
* herein.
*/
ValueType
maximumValueType () const;
/**
* Calculate and return the Euclidean distance between this distribution and
* another distribution (over the same values, with the same probability
* type).
*
* NOTE: this uses only the first (m_elementCount - 1) values, under the
* assumption that the final value is just 1-(the sum of the rest). This
* is arbitrary! Choosing to use a different subset will result in a
* different euclideanDistance calculation. If you know that the
* distributions aren't normalized, you should either normalize them first,
* or (if you don't want them to be normalized), add the squared distance
* between the last two components yourself.
*/
double
euclideanDistance (
MultinomialDistribution<ValueType, ProbabilityType> const& another_dist
) const;
/**
* Calculate and return the square of the Euclidean distance between this
* distribution and another distribution (over the same values, with the
* same probability type).
*
* NOTE: this uses only the first (m_elementCount - 1) values, under the
* assumption that the final value is just 1-(the sum of the rest). This
* is arbitrary! Choosing to use a different subset will result in a
* different euclideanDistance calculation. If you know that the
* distributions aren't normalized, you should either normalize them first,
* or (if you don't want them to be normalized), add the squared distance
* between the last two components yourself.
*/
double
euclideanDistanceSquared (
MultinomialDistribution<ValueType, ProbabilityType> const& another_dist
) const;
/**
* Calculate a vector of expected distances, in which expected_distances[ v
* ] is the expected distance from v to the other values (averaged over
* this distribution of other values).
*/
template <typename DistanceMatrixType,
typename ExpectedDistanceType>
void
calculateExpectedDistances (
MultinomialDistribution<ValueType, MultinomialDistribution<ValueType, DistanceMatrixType> > const & distance_matrix,
MultinomialDistribution<ValueType, ExpectedDistanceType> & expected_distances
) const
{
// Note that expected_distances[ i ] will be the expected distance *from*
// i, averaged over distances *to* another value.
static MultinomialDistribution<ValueType, ExpectedDistanceType> tmp_vec =
MultinomialDistribution<ValueType, ExpectedDistanceType>();
for( uint32_t i = 0; i < m_elementCount; i++ ) {
tmp_vec = *this;
tmp_vec *=
distance_matrix[ i ];
// TODO: REMOVE
//cout << "calculateExpectedDistances: tmp_vec is " << tmp_vec << endl;
expected_distances[ i ] = tmp_vec.total();
}
} // calculateExpectedDistances( MultinomialDistribution<ValueType, MultinomialDistribution<ValueType, DistanceMatrixType> > const &, MultinomialDistribution<ValueType, ExpectedDistanceType> & ) const
/**
* Calculate a vector of expected distances, in which expected_distances[ v
* ] is the expected distance from v to the other values (averaged over
* this distribution of other values).
*/
// overloaded for ExpectedValueType==double as a workaround, since there's
// no direct casting from Probabilities to doubles.
template <typename DistanceMatrixType>
void
calculateExpectedDistances (
MultinomialDistribution<ValueType, MultinomialDistribution<ValueType, DistanceMatrixType> > const & distance_matrix,
MultinomialDistribution<ValueType, double> & expected_distances
) const
{
// Note that expected_distances[ i ] will be the expected distance *from*
// i, averaged over distances *to* another value.
double dist;
uint32_t j;
for( uint32_t i = 0; i < m_elementCount; i++ ) {
expected_distances[ i ] = 0.0;
for( j = 0; j < m_elementCount; j++ ) {
dist = std::toDouble( ( *this )[ j ] );
dist *= std::toDouble( distance_matrix[ i ][ j ] );
expected_distances[ i ] += dist;
}
}
} // calculateExpectedDistances( MultinomialDistribution<ValueType, MultinomialDistribution<ValueType, DistanceMatrixType> > const &, MultinomialDistribution<ValueType, double> & ) const
/**
* Calculate the expected value, given a vector of values. This is just
* the average of the given values, where the average is taken over this
* distribution.
*/
template <typename ExpectedValueType>
ExpectedValueType
calculateExpectedValue (
MultinomialDistribution<ValueType, ExpectedValueType> const & values
) const
{
static MultinomialDistribution<ValueType, ExpectedValueType> tmp_vec =
MultinomialDistribution<ValueType, ExpectedValueType>();
tmp_vec = values;
tmp_vec *= *this;
// TODO: REMOVE
//cout << "calculateExpectedValue: tmp_vec is " << tmp_vec << endl;
return tmp_vec.total();
} // calculateExpectedValue( MultinomialDistribution<ValueType, ExpectedValuyeType> const & ) const
/**
* Calculate the expected value, given a vector of values. This is just
* the average of the given values, where the average is taken over this
* distribution.
*/
// overloaded for ExpectedValueType==double as a workaround, since there's
// no direct casting from Probabilities to doubles.
double
calculateExpectedValue (
MultinomialDistribution<ValueType, double> const & values
) const
{
double total = 0.0;
for( uint32_t i = 0; i < m_elementCount; i++ ) {
total += ( values[ i ] * std::toDouble( ( *this )[ i ] ) );
}
return total;
} // calculateExpectedValue( MultinomialDistribution<ValueType, double> const & ) const
/**
* Return a value drawn randomly according to this distribution.
*
* NOTE: You must ensure that the distribution is normalized first. For
* efficiency the test is not performed in this method. Use (total() == 1),
* or just call normalize().
*/
ValueType
draw ( Random & random ) const;
/**
* Change the probabilities of this Multinomial to values drawn from a
* dirichlet distribution with the given counts. The counts vector must,
* of course, be of length m_elementCount. VectorCountType can be a vector
* of a Real type (anything coercible to a double using toDouble( count )).
*/
template <class VectorCountType>
void
fromDirichlet ( VectorCountType const & counts, Random & random );
// Note that this copies its result to the caller. See the other
// toBoltzmannGibbs for an alternative.
template <typename RealType>
MultinomialDistribution<ValueType, RealType>
toBoltzmannGibbs ( double const temperature );
template <typename RealType>
void
toBoltzmannGibbs (
RealType const temperature,
MultinomialDistribution<ValueType, RealType> & boltzmann_gibbs_to_be_filled
) const;
template <typename RealType>
void
fromBoltzmannGibbs (
RealType const temperature,
MultinomialDistribution<ValueType, RealType> from_dist
);
public:
class DistanceMatrix :
public MultinomialDistribution<
ValueType,
MultinomialDistribution<ValueType, ProbabilityType> >
{
public:
bool isSymmetric;
bool isProximityMatrix; // versus a distance matrix
bool isMultiplicative; // versus additive
DistanceMatrix () :
isSymmetric( false ),
isProximityMatrix( false ), // no, it's a *distance* matrix
isMultiplicative( false ) // no, it's *additive*
{
// Do nothing else
} // <init>()
// Why do I have to explicitly delegate this? I dunno.
template <typename AnyType>
MultinomialDistribution<ValueType, ProbabilityType> &
operator= ( AnyType const& set_to )
{
MultinomialDistribution<ValueType, MultinomialDistribution<ValueType, ProbabilityType> >::operator=( set_to );
} // operator=( AnyType const & )
}; // End inner class MultinomialDistribution::DistanceMatrix
}; // End class MultinomialDistribution
//======//// potentially non-inline implementations ////========//
////// Class galosh::MultinomialDistribution ////
template <typename ValueType,
typename ProbabilityType>
GALOSH_INLINE_INIT
MultinomialDistribution<ValueType, ProbabilityType>::
// Starts out with an even distribution
MultinomialDistribution () : m_probs()
{
// Start out with an even distribution.
even();
} // <init>()
template <typename ValueType,
typename ProbabilityType>
template <typename AnyProbabilityType>
GALOSH_INLINE_INIT
MultinomialDistribution<ValueType, ProbabilityType>::
// Copy constructor
MultinomialDistribution ( MultinomialDistribution<ValueType,AnyProbabilityType> const & copy_from ) : m_probs()
{
// Call operator=
*this = copy_from;
} // <init>( MultinomialDistribution<AnyProbabilityType> const & )
/**
* \fn std::string MultinomialDistribution::toString() const
* \brief create a string representation of a MultinomialDistribution object.
*
* This has been split off from Paul's original writeMultinomialDistribution, so
* so that the string for applications other than direct output (e.g. output to
* somewhere other than cout.
*
* TAH 1/12
*/
template <typename ValueType,
typename ProbabilityType>
GALOSH_INLINE_INIT
std::string
MultinomialDistribution<ValueType,ProbabilityType>::
toString() const {
if(m_elementCount == 0) return "()";
std::string retVal = "(";
for( uint32_t i = 0; i < m_elementCount; i++ )
{
if( i != 0 ) {
retVal += ",";
}
retVal += ValueType( i );
retVal += "=";
/// Paul's original note from writeMultnomialDistribution
/// The cast to double forces the printed output to be how a double
/// prints, not how a ProbabilityType prints. This is safe because we
/// generally keep values above some minimal value. See normalize(
/// ProbabilityType ).
/// os << ( double )m_probs[ i ];
///
/// \todo Here we're using lexical_cast instead of ( double ) - this is after
/// hours of suffering with "createRandomSequence" which uses "floatrealspace"
/// for its ProbabilityType and somehow failed to compile. It would be good
/// to understand the compilation failure.
std::ostringstream oss;
oss << m_probs[ i ];
retVal += oss.str();
}
retVal += ")";
return retVal;
}
template <typename ValueType,
typename ProbabilityType>
GALOSH_INLINE_REINITIALIZE
void
MultinomialDistribution<ValueType, ProbabilityType>::
reinitialize ()
{
// Start out with an even distribution.
even();
} // reinitialize()
template <typename ValueType,
typename ProbabilityType>
GALOSH_INLINE_ACCESSOR
uint32_t
MultinomialDistribution<ValueType, ProbabilityType>::
size () const
{
return m_elementCount;
} // size() const
template <typename ValueType,
typename ProbabilityType>
GALOSH_INLINE_ACCESSOR
uint32_t
MultinomialDistribution<ValueType, ProbabilityType>::
/**
* How many free parameters are there? If we consider this a
* MultinomialDistribution, its probabilities should sum to 1, so there are
* ( size() - 1 ) free parameters.
*/
freeParameterCount () const
{
return m_elementCount - 1;
} // freeParameterCount() const
template <typename ValueType,
typename ProbabilityType>
template <typename AnyProbabilityType>
GALOSH_INLINE_COPY
MultinomialDistribution<ValueType, ProbabilityType> &
MultinomialDistribution<ValueType, ProbabilityType>::
operator= ( MultinomialDistribution<ValueType,AnyProbabilityType> const& other_dist )
{
for( uint32_t i = 0; i < m_elementCount; i++ ) {
m_probs[ i ] = other_dist.m_probs[ i ];
}
return *this;
} // operator=( MultinomialDistribution<ValueType,AnyProbabilityType>& )
template <typename ValueType,
typename ProbabilityType>
GALOSH_INLINE_COPY
MultinomialDistribution<ValueType, ProbabilityType> &
MultinomialDistribution<ValueType, ProbabilityType>::
operator= ( MultinomialDistribution<ValueType,ProbabilityType> const& other_dist )
{
for( uint32_t i = 0; i < m_elementCount; i++ ) {
m_probs[ i ] = other_dist.m_probs[ i ];
}
return *this;
} // operator=( MultinomialDistribution<ValueType,ProbabilityType>& )
template <typename ValueType,
typename ProbabilityType>
template <typename AnyProbabilityType>
GALOSH_INLINE_REINITIALIZE
MultinomialDistribution<ValueType, ProbabilityType> &
MultinomialDistribution<ValueType,ProbabilityType>::
operator= ( AnyProbabilityType const & set_to )
{
if( set_to == 0 ) {
zero();
} else{
for( uint32_t i = 0; i < m_elementCount; i++ ) {
m_probs[ i ] = set_to;
}
}
return *this;
} // operator=( AnyProbabilityType const & )
template <typename ValueType,
typename ProbabilityType>
template <typename AnyProbabilityType>
GALOSH_INLINE_MULTINOMIALDISTRIBUTION_ARITHMETIC
MultinomialDistribution<ValueType,ProbabilityType> &
MultinomialDistribution<ValueType, ProbabilityType>::
/**
* Add to each probability the corresponding probability in the given
* distribution. Note that this may violate the rule that the
* probabilities sum to 1.
*/
operator+= ( MultinomialDistribution<ValueType,AnyProbabilityType> const& other_dist )
{
for( uint32_t i = 0; i < m_elementCount; i++ ) {
m_probs[ i ] += other_dist.m_probs[ i ];
}
return *this;
} // operator+=( MultinomialDistribution<ValueType,AnyProbabilityType> const& )
template <typename ValueType,
typename ProbabilityType>
template <typename AnyProbabilityType>
GALOSH_INLINE_MULTINOMIALDISTRIBUTION_ARITHMETIC
MultinomialDistribution<ValueType,ProbabilityType> &
MultinomialDistribution<ValueType, ProbabilityType>::
/**
* Add to each probability the given value. Note that this may violate the
* rule that the probabilities sum to 1.
*/
operator+= ( AnyProbabilityType const& value )
{
for( uint32_t i = 0; i < m_elementCount; i++ ) {
m_probs[ i ] += value;
}
return *this;
} // operator+=( AnyProbabilityType const& )
template <typename ValueType,
typename ProbabilityType>
template <typename AnyProbabilityType>
GALOSH_INLINE_MULTINOMIALDISTRIBUTION_ARITHMETIC
MultinomialDistribution<ValueType,ProbabilityType> &
MultinomialDistribution<ValueType, ProbabilityType>::
/**
* Subtract from each probability the corresponding probability in the