-
Notifications
You must be signed in to change notification settings - Fork 25
/
PhyloCTMCClado.h
1902 lines (1504 loc) · 76.3 KB
/
PhyloCTMCClado.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 PhyloCTMCClado_H
#define PhyloCTMCClado_H
#include "AbstractCladogenicStateFunction.h"
#include "CharacterHistory.h"
#include "ChromosomesCladogenicStateFunction.h"
#include "CladogeneticProbabilityMatrix.h"
#include "AbstractPhyloCTMCSiteHomogeneous.h"
#include "BiogeographicCladoEvent.h"
#include "DistributionExponential.h"
#include "RateMatrix.h"
#include "RbBitSet.h"
#include "RbException.h"
#include "RbVector.h"
#include "Simplex.h"
#include "MatrixReal.h"
#include "Taxon.h"
#include "Tree.h"
#include "TopologyNode.h"
#include "TransitionProbabilityMatrix.h"
#include "TypedDistribution.h"
#include "RandomNumberGenerator.h"
namespace RevBayesCore {
template<class charType>
class PhyloCTMCClado : public AbstractPhyloCTMCSiteHomogeneous<charType> {
public:
// AbstractPhyloCTMCSiteHomogeneous(const TypedDagNode<Tree> *t, size_t nChars, size_t nMix, bool c, size_t nSites, bool amb, bool wd = false, bool internal = false, bool gapmatch = true );
PhyloCTMCClado(const TypedDagNode< Tree > *t, size_t nChars, bool c, size_t nSites, bool amb, bool internal, bool gapmatch);
PhyloCTMCClado(const PhyloCTMCClado &n);
virtual ~PhyloCTMCClado(void); //!< Virtual destructor
// public member functions
PhyloCTMCClado* clone(void) const; //!< Create an independent clone
virtual double computeLnProbability(void);
virtual std::vector<charType> drawAncestralStatesForNode(const TopologyNode &n);
virtual void drawJointConditionalAncestralStates(std::vector<std::vector<charType> >& startStates, std::vector<std::vector<charType> >& endStates);
virtual void recursivelyDrawJointConditionalAncestralStates(const TopologyNode &node, std::vector<std::vector<charType> >& startStates, std::vector<std::vector<charType> >& endStates, const std::vector<size_t>& sampledSiteRates);
virtual void redrawValue(void);
void setCladogenesisMatrix(const TypedDagNode< CladogeneticProbabilityMatrix > *r);
void setCladogenesisMatrix(const TypedDagNode< RbVector< CladogeneticProbabilityMatrix > >* r);
void setCladogenesisTimes(const TypedDagNode< RbVector< RbVector< double > > >* rm);
protected:
virtual void resizeLikelihoodVectors(void);
void computeRootLikelihood(size_t root, size_t l, size_t r);
void computeRootLikelihood(size_t root, size_t l, size_t r, size_t m);
void computeInternalNodeLikelihood(const TopologyNode &n, size_t nIdx, size_t l, size_t r);
void computeInternalNodeLikelihood(const TopologyNode &n, size_t nIdx, size_t l, size_t r, size_t m);
void computeTipLikelihood(const TopologyNode &node, size_t nIdx);
void updateTransitionProbabilities(size_t node_idx);
virtual void computeMarginalNodeLikelihood(size_t node_idx, size_t parentIdx);
virtual void computeMarginalRootLikelihood();
virtual std::vector< std::vector< double > >* sumMarginalLikelihoods(size_t node_index);
virtual void swapParameterInternal(const DagNode *oldP, const DagNode *newP); //!< Swap a parameter
// the likelihoods
double* cladoPartialLikelihoods;
double* cladoMarginalLikelihoods;
// offsets for nodes
size_t cladoActiveLikelihoodOffset;
size_t cladoNodeOffset;
size_t cladoMixtureOffset;
size_t cladoSiteOffset;
private:
virtual void simulate(const TopologyNode& node, std::vector< DiscreteTaxonData< charType > > &t, const std::vector<size_t> &perSiteRates);
virtual double sumRootLikelihood( void );
void updateTransitionProbabilityMatrices(void);
const TypedDagNode< CladogeneticProbabilityMatrix >* homogeneousCladogenesisMatrix;
const TypedDagNode< RbVector< CladogeneticProbabilityMatrix > >* heterogeneousCladogenesisMatrices;
const TypedDagNode< RbVector< RbVector< double > > >* cladogenesisTimes;
bool useObservedCladogenesis;
bool useSampledCladogenesis;
bool branchHeterogeneousCladogenesis;
bool store_internal_nodes;
bool gap_match_clamped;
};
}
#include "AbstractCharacterHistoryBirthDeathProcess.h"
#include "BranchHistory.h"
#include "ConstantNode.h"
#include "StochasticNode.h"
#include "DECCladogeneticStateFunction.h"
#include "CladogeneticProbabilityMatrixFunction.h"
#include "DiscreteCharacterState.h"
#include "RateMatrix_JC.h"
#include "RandomNumberFactory.h"
#include <cmath>
#include <cstring>
#include <map>
#include <vector>
// AbstractPhyloCTMCSiteHomogeneous(const TypedDagNode<Tree> *t, size_t nChars, size_t nMix, bool c, size_t nSites, bool amb, bool wd = false, bool internal = false, bool gapmatch = true );
template<class charType>
RevBayesCore::PhyloCTMCClado<charType>::PhyloCTMCClado(const TypedDagNode<Tree> *t, size_t nChars, bool c, size_t nSites, bool amb, bool internal, bool gapmatch) : AbstractPhyloCTMCSiteHomogeneous<charType>( t, nChars, 1, c, nSites, amb, false, false, true ),
cladoPartialLikelihoods(NULL),
cladoMarginalLikelihoods(NULL),
useObservedCladogenesis(false),
useSampledCladogenesis(false),
branchHeterogeneousCladogenesis(false),
store_internal_nodes(internal),
gap_match_clamped(gapmatch)
{
// unsigned numReducedChar = (unsigned)( log( nChars ) / log( 2 ) );
// std::vector<std::string> et;
// et.push_back("s");
// et.push_back("a");
// const TypedDagNode< RevBayesCore::RbVector<RevBayesCore::RbVector<long> > >* events, const TypedDagNode<RevBayesCore::RbVector<double> >* probs, int n_states
// create a dummy matrix of identical cladogenetic inheritance triplets
RevBayesCore::RbVector<RevBayesCore::RbVector<long> >* clado_events_mtx_tmp = new RevBayesCore::RbVector<RevBayesCore::RbVector<long> >();
for (size_t i = 0; i < nChars; i++) {
clado_events_mtx_tmp->push_back( RevBayesCore::RbVector<long>(3, i) );
}
// populate a dummy node with those events
TypedDagNode< RevBayesCore::RbVector<RevBayesCore::RbVector<long> > >* clado_events_tmp;
clado_events_tmp = new RevBayesCore::ConstantNode< RevBayesCore::RbVector< RevBayesCore::RbVector<long> > >(".cladogenetic_events", clado_events_mtx_tmp);
// populate a dummy event probs vector where each event has prob = 1
TypedDagNode< RevBayesCore::RbVector<double> >* clado_probs_tmp;
clado_probs_tmp = new RevBayesCore::ConstantNode<RevBayesCore::RbVector<double> >(".probabilities", new RevBayesCore::RbVector<double>(clado_events_mtx_tmp->size(), 1.0));
// build a dummy cladogenetic probability matrix function
CladogeneticProbabilityMatrixFunction* clado_func_tmp = new CladogeneticProbabilityMatrixFunction( clado_events_tmp, clado_probs_tmp, (int)nChars );
// place that function into a dummy deterministic node
DeterministicNode<CladogeneticProbabilityMatrix>* clado_node_tmp = new DeterministicNode<CladogeneticProbabilityMatrix>( "cladogenesisMatrix", clado_func_tmp );
// finally, assign our dummy node to the model's cladogenetic probability matrix variable
homogeneousCladogenesisMatrix = clado_node_tmp;
/*
homogeneousCladogenesisMatrix = new DeterministicNode<CladogeneticProbabilityMatrix>( "cladogenesisMatrix",
new DECCladogeneticStateFunction(
new ConstantNode<Simplex>( "", new Simplex(2, 0.5)),
new ConstantNode<RbVector<RbVector<double> > >("", new RbVector<RbVector<double> >(nChars, RbVector<double>(nChars, 1))),
new ConstantNode<RbVector<RbVector<double> > >("", new RbVector<RbVector<double> >(nChars, RbVector<double>(nChars, 1))),
numReducedChar,
2,
et)
);
*/
heterogeneousCladogenesisMatrices = NULL;
cladogenesisTimes = NULL;
cladoActiveLikelihoodOffset = this->num_nodes*this->num_site_rates*this->num_patterns*this->num_chars*this->num_chars;
cladoNodeOffset = this->num_site_rates*this->num_patterns*this->num_chars*this->num_chars;
cladoMixtureOffset = this->num_patterns*this->num_chars*this->num_chars;
cladoSiteOffset = this->num_chars*this->num_chars;
// check if the tree is a stochastic node before getting its distribution
if ( this->tau->isStochastic() )
{
if ( dynamic_cast<const AbstractCharacterHistoryBirthDeathProcess* >( &this->tau->getDistribution() ) != NULL )
useSampledCladogenesis = true;
}
// add the parameters to our set (in the base class)
// in that way other class can easily access the set of our parameters
// this will also ensure that the parameters are not getting deleted before we do
this->addParameter( homogeneousCladogenesisMatrix );
this->addParameter( heterogeneousCladogenesisMatrices );
this->addParameter( cladogenesisTimes );
}
template<class charType>
RevBayesCore::PhyloCTMCClado<charType>::PhyloCTMCClado(const PhyloCTMCClado &n) :
AbstractPhyloCTMCSiteHomogeneous<charType>( n ),
cladoPartialLikelihoods(NULL),
cladoMarginalLikelihoods(NULL),
useObservedCladogenesis(n.useObservedCladogenesis),
useSampledCladogenesis(n.useSampledCladogenesis),
store_internal_nodes(n.store_internal_nodes),
gap_match_clamped(n.gap_match_clamped),
branchHeterogeneousCladogenesis(n.branchHeterogeneousCladogenesis)
{
// initialize with default parameters
homogeneousCladogenesisMatrix = n.homogeneousCladogenesisMatrix;
heterogeneousCladogenesisMatrices = n.heterogeneousCladogenesisMatrices;
cladogenesisTimes = n.cladogenesisTimes;
// copy the partial likelihoods if necessary
if ( this->in_mcmc_mode == true )
{
cladoPartialLikelihoods = new double[2*this->num_nodes*this->num_site_rates*this->num_sites*this->num_chars*this->num_chars];
memcpy(cladoPartialLikelihoods, n.cladoPartialLikelihoods, 2*this->num_nodes*this->num_site_rates*this->num_patterns*this->num_chars*this->num_chars*sizeof(double));
}
// copy the marginal likelihoods if necessary
if ( this->useMarginalLikelihoods == true )
{
cladoMarginalLikelihoods = new double[this->num_nodes*this->num_site_rates*this->num_sites*this->num_chars*this->num_chars];
memcpy(cladoMarginalLikelihoods, n.cladoMarginalLikelihoods, this->num_nodes*this->num_site_rates*this->num_sites*this->num_chars*this->num_chars*sizeof(double));
}
cladoActiveLikelihoodOffset = this->num_nodes*this->num_site_rates*this->num_patterns*this->num_chars*this->num_chars;
cladoNodeOffset = this->num_site_rates*this->num_patterns*this->num_chars*this->num_chars;
cladoMixtureOffset = this->num_patterns*this->num_chars*this->num_chars;
cladoSiteOffset = this->num_chars*this->num_chars;
}
template<class charType>
RevBayesCore::PhyloCTMCClado<charType>::~PhyloCTMCClado( void ) {
// We don't delete the parameters, because they might be used somewhere else too. The model needs to do that!
delete [] cladoPartialLikelihoods;
delete [] cladoMarginalLikelihoods;
}
template<class charType>
RevBayesCore::PhyloCTMCClado<charType>* RevBayesCore::PhyloCTMCClado<charType>::clone( void ) const {
return new PhyloCTMCClado<charType>( *this );
}
template<class charType>
double RevBayesCore::PhyloCTMCClado<charType>::computeLnProbability( void )
{
// if we are not in MCMC mode, then we need to (temporarily) allocate memory
if ( this->in_mcmc_mode == false )
{
cladoPartialLikelihoods = new double[2*this->num_nodes*this->num_site_rates*this->num_sites*this->num_chars*this->num_chars];
}
double lnL = RevBayesCore::AbstractPhyloCTMCSiteHomogeneous<charType>::computeLnProbability();
// if we are not in MCMC mode, then we need to (temporarily) free memory
if ( this->in_mcmc_mode == false )
{
// free the partial likelihoods
delete [] cladoPartialLikelihoods;
cladoPartialLikelihoods = NULL;
}
return lnL;
}
template<class charType>
void RevBayesCore::PhyloCTMCClado<charType>::computeRootLikelihood( size_t root, size_t left, size_t right)
{
// get the root frequencies
const std::vector<double> &f = this->getRootFrequencies();
const TopologyNode& node = this->tau->getValue().getRoot();
std::map<std::vector<unsigned>, double> eventMapProbs = ( branchHeterogeneousCladogenesis ?
heterogeneousCladogenesisMatrices->getValue()[root].getEventMap(node.getAge()) :
homogeneousCladogenesisMatrix->getValue().getEventMap(node.getAge()) );
// bypass cladogenetic probs if it's a sampled ancestor
bool has_sampled_ancestor_child = node.getChild(0).isSampledAncestor() || node.getChild(1).isSampledAncestor();
// get the pointers to the partial likelihoods of the left and right subtree
double* p_node = this->partialLikelihoods + this->activeLikelihood[root] * this->activeLikelihoodOffset + root * this->nodeOffset;
const double* p_left = this->partialLikelihoods + this->activeLikelihood[left] * this->activeLikelihoodOffset + left * this->nodeOffset;
const double* p_right = this->partialLikelihoods + this->activeLikelihood[right] * this->activeLikelihoodOffset + right * this->nodeOffset;
// iterate over all mixture categories
for (size_t mixture = 0; mixture < this->num_site_rates; ++mixture)
{
// get the pointers to the likelihood for this mixture category
size_t offset = mixture*this->mixtureOffset;
double* p_site_mixture = p_node + offset;
const double* p_site_mixture_left = p_left + offset;
const double* p_site_mixture_right = p_right + offset;
// compute the per site probabilities
for (size_t site = 0; site < this->num_patterns ; ++site)
{
// first compute clado probs at younger end of branch
std::map<std::vector<unsigned>, double>::iterator it;
for (size_t i = 0; i < this->num_chars; i++)
p_site_mixture[i] = 0.0;
// cladogenetic probs for bifurcations
if (!has_sampled_ancestor_child)
{
for ( it = eventMapProbs.begin(); it != eventMapProbs.end(); ++it)
{
// sparse elements from map
const std::vector<unsigned>& idx = it->first;
const size_t c1 = idx[0];
const size_t c2 = idx[1];
const size_t c3 = idx[2];
const double pl = *(p_site_mixture_left + c2);
const double pr = *(p_site_mixture_right + c3);
const double pcl = it->second;
p_site_mixture[c1] += pl * pr * pcl;
}
}
// no cladogenetic probs for sampled ancestors
else
{
for (size_t c1 = 0; c1 < this->num_chars; ++c1) {
const double pl = *(p_site_mixture_left + c1);
const double pr = *(p_site_mixture_right + c1);
p_site_mixture[c1] += pl * pr;
}
}
for (size_t i = 0; i < this->num_chars; i++)
p_site_mixture[i] *= f[i];
// increment the pointers to the next site
p_site_mixture_left += this->siteOffset;
p_site_mixture_right += this->siteOffset;
p_site_mixture += this->siteOffset;
} // end-for over all sites (=patterns)
} // end-for over all mixtures (=rate-categories)
return;
}
template<class charType>
void RevBayesCore::PhyloCTMCClado<charType>::computeRootLikelihood( size_t root, size_t left, size_t right, size_t middle)
{
computeRootLikelihood(root, left, right);
}
template<class charType>
void RevBayesCore::PhyloCTMCClado<charType>::computeInternalNodeLikelihood(const TopologyNode &node, size_t node_index, size_t left, size_t right, size_t middle)
{
computeInternalNodeLikelihood(node, node_index, left, right);
}
template<class charType>
void RevBayesCore::PhyloCTMCClado<charType>::computeInternalNodeLikelihood(const TopologyNode &node, size_t node_index, size_t left, size_t right)
{
std::map<std::vector<unsigned>, double> eventMapProbs = ( branchHeterogeneousCladogenesis ?
heterogeneousCladogenesisMatrices->getValue()[node_index].getEventMap(node.getAge()) :
homogeneousCladogenesisMatrix->getValue().getEventMap(node.getAge()) );
// bypass cladogenetic probs if it's a sampled ancestor
bool has_sampled_ancestor_child = node.getChild(0).isSampledAncestor() || node.getChild(1).isSampledAncestor();
// compute the transition probability matrix
this->updateTransitionProbabilities( node_index );
// get the pointers to the partial likelihoods for this node and the two descendant subtrees
const double* p_left = this->partialLikelihoods + this->activeLikelihood[left]*this->activeLikelihoodOffset + left*this->nodeOffset;
const double* p_right = this->partialLikelihoods + this->activeLikelihood[right]*this->activeLikelihoodOffset + right*this->nodeOffset;
double* p_node = this->partialLikelihoods + this->activeLikelihood[node_index]*this->activeLikelihoodOffset + node_index*this->nodeOffset;
double* p_clado_node = this->cladoPartialLikelihoods + this->activeLikelihood[node_index]*this->cladoActiveLikelihoodOffset + node_index*this->cladoNodeOffset;
// iterate over all mixture categories
for (size_t mixture = 0; mixture < this->num_site_rates; ++mixture)
{
// the transition probability matrix for this mixture category
const double* tp_begin = this->transition_prob_matrices[mixture].theMatrix;
// get the pointers to the likelihood for this mixture category
size_t offset = mixture*this->mixtureOffset;
double* p_site_mixture = p_node + offset;
double* p_clado_site_mixture = p_clado_node + mixture * this->cladoMixtureOffset;
const double* p_site_mixture_left = p_left + offset;
const double* p_site_mixture_right = p_right + offset;
// compute the per site probabilities
for (size_t site = 0; site < this->num_patterns ; ++site)
{
// first compute clado probs at younger end of branch
std::map<std::vector<unsigned>, double>::iterator it;
for (size_t i = 0; i < this->num_chars; i++)
p_clado_site_mixture[i] = 0.0;
// cladogenetic probs for bifurcations
if (!has_sampled_ancestor_child)
{
for ( it = eventMapProbs.begin(); it != eventMapProbs.end(); ++it)
{
// sparse elements from map
const std::vector<unsigned>& idx = it->first;
const size_t c1 = idx[0];
const size_t c2 = idx[1];
const size_t c3 = idx[2];
const double pl = *(p_site_mixture_left + c2);
const double pr = *(p_site_mixture_right + c3);
const double pcl = it->second;
p_clado_site_mixture[c1] += pl * pr * pcl;
}
}
// no cladogenetic probs for sampled ancestors
else
{
for (size_t c1 = 0; c1 < this->num_chars; ++c1) {
const double pl = *(p_site_mixture_left + c1);
const double pr = *(p_site_mixture_right + c1);
p_clado_site_mixture[c1] += pl * pr;
}
}
// get the pointers for this mixture category and this site
const double* tp_a = tp_begin;
// start state at older end of branch
for (size_t c0 = 0; c0 < this->num_chars; ++c0) {
double sum_ana = 0.0;
for (size_t c1 = 0; c1 < this->num_chars; ++c1) {
sum_ana += tp_a[c1] * p_clado_site_mixture[c1];
}
// store the likelihood for this starting state
p_site_mixture[c0] = sum_ana;
// increment the pointers to the next starting state
tp_a+=this->num_chars;
}
// increment the pointers to the next site
p_site_mixture_left += this->siteOffset;
p_site_mixture_right += this->siteOffset;
p_site_mixture += this->siteOffset;
p_clado_site_mixture += this->cladoSiteOffset;
} // end-for over all sites (=patterns)
} // end-for over all mixtures (=rate-categories)
}
template<class charType>
void RevBayesCore::PhyloCTMCClado<charType>::computeMarginalNodeLikelihood( size_t node_index, size_t parentnode_index )
{
// get cladogenic transition probs
const TopologyNode& node = this->tau->getValue().getNode(node_index);
std::map<std::vector<unsigned>, double> eventMapProbs = ( branchHeterogeneousCladogenesis ? heterogeneousCladogenesisMatrices->getValue()[node_index].getEventMap(node.getAge()) : homogeneousCladogenesisMatrix->getValue().getEventMap(node.getAge()) );
// compute the transition probability matrix
this->updateTransitionProbabilities( node_index );
// get the pointers to the partial likelihoods and the marginal likelihoods
const double* p_node = this->partialLikelihoods + this->activeLikelihood[node_index]*this->activeLikelihoodOffset + node_index*this->nodeOffset;
const double* p_parent_node_marginal = this->marginalLikelihoods + parentnode_index*this->nodeOffset;
double* p_node_marginal = this->marginalLikelihoods + node_index*this->nodeOffset;
const double* p_clado_node = this->cladoPartialLikelihoods + this->activeLikelihood[node_index]*this->cladoActiveLikelihoodOffset + node_index*this->cladoNodeOffset;
const double* p_clado_parent_node_marginal = this->cladoMarginalLikelihoods + parentnode_index*this->cladoNodeOffset;
double* p_clado_node_marginal = this->cladoMarginalLikelihoods + node_index*this->cladoNodeOffset;
// get pointers the likelihood for both subtrees
const double* p_mixture = p_node;
const double* p_parent_mixture_marginal = p_parent_node_marginal;
double* p_mixture_marginal = p_node_marginal;
const double* p_clado_mixture = p_clado_node;
const double* p_clado_parent_mixture_marginal = p_clado_parent_node_marginal;
double* p_clado_mixture_marginal = p_clado_node_marginal;
// iterate over all mixture categories
for (size_t mixture = 0; mixture < this->num_site_rates; ++mixture)
{
// the transition probability matrix for this mixture category
const double* tp_begin = this->transition_prob_matrices[mixture].theMatrix;
// get pointers to the likelihood for this mixture category
const double* p_site_mixture = p_mixture;
const double* p_parent_site_mixture_marginal = p_parent_mixture_marginal;
double* p_site_mixture_marginal = p_mixture_marginal;
const double* p_clado_site_mixture = p_clado_mixture;
const double* p_clado_parent_site_mixture_marginal = p_clado_parent_mixture_marginal;
double* p_clado_site_mixture_marginal = p_clado_mixture_marginal;
// iterate over all sites
for (size_t site = 0; site < this->num_patterns; ++site)
{
// get the pointers to the likelihoods for this site and mixture category
const double* p_site_j = p_site_mixture;
double* p_site_marginal_j = p_site_mixture_marginal;
// iterate over all end states, after anagenesis
for (size_t j=0; j<this->num_chars; ++j)
{
const double* p_parent_site_marginal_k = p_parent_site_mixture_marginal;
*p_site_marginal_j = 0.0;
// iterator over all start states, before anagenesis
for (size_t k=0; k<this->num_chars; ++k)
{
// transition probability for k->j
const double tp_kj = *p_parent_site_marginal_k * tp_begin[ k * this->num_chars + j ];
// add the probability of starting from this state
*p_site_marginal_j += *p_site_j * tp_kj;
// next parent state
++p_parent_site_marginal_k;
}
// increment pointers
++p_site_j; ++p_site_marginal_j;
}
// iterate over all (X_L, X_R) states, after cladogenesis
std::map< std::vector<unsigned>, double >::iterator it;
for (it = eventMapProbs.begin(); it != eventMapProbs.end(); it++)
{
;
}
// increment the pointers to the next site
p_site_mixture += this->siteOffset;
p_site_mixture_marginal += this->siteOffset;
p_parent_site_mixture_marginal += this->siteOffset;
p_clado_site_mixture += this->cladoSiteOffset;
p_clado_site_mixture_marginal += this->cladoSiteOffset;
p_clado_parent_site_mixture_marginal += this->cladoSiteOffset;
} // end-for over all sites (=patterns)
// increment the pointers to the next mixture category
p_mixture += this->mixtureOffset;
p_mixture_marginal += this->mixtureOffset;
p_parent_mixture_marginal += this->mixtureOffset;
p_clado_mixture += this->cladoMixtureOffset;
p_clado_mixture_marginal += this->cladoMixtureOffset;
p_clado_parent_mixture_marginal += this->cladoMixtureOffset;
} // end-for over all mixtures (=rate categories)
}
template<class charType>
void RevBayesCore::PhyloCTMCClado<charType>::computeMarginalRootLikelihood( void )
{
// get the root node
const TopologyNode &root = this->tau->getValue().getRoot();
// get the index of the root node
size_t node_index = root.getIndex();
// get the root frequencies
const std::vector<double> &f = this->getRootFrequencies();
std::vector<double>::const_iterator f_end = f.end();
std::vector<double>::const_iterator f_begin = f.begin();
// get the pointers to the partial likelihoods and the marginal likelihoods
const double* p_node = this->partialLikelihoods + this->activeLikelihood[node_index]*this->activeLikelihoodOffset + node_index*this->nodeOffset;
double* p_node_marginal = this->marginalLikelihoods + node_index*this->nodeOffset;
// get pointers the likelihood for both subtrees
const double* p_mixture = p_node;
double* p_mixture_marginal = p_node_marginal;
// iterate over all mixture categories
for (size_t mixture = 0; mixture < this->num_site_rates; ++mixture)
{
// get pointers to the likelihood for this mixture category
const double* p_site_mixture = p_mixture;
double* p_site_mixture_marginal = p_mixture_marginal;
// iterate over all sites
for (size_t site = 0; site < this->num_patterns; ++site)
{
// get the pointer to the stationary frequencies
std::vector<double>::const_iterator f_j = f_begin;
// get the pointers to the likelihoods for this site and mixture category
const double* p_site_j = p_site_mixture;
double* p_site_marginal_j = p_site_mixture_marginal;
// iterate over all starting states
for (; f_j != f_end; ++f_j)
{
// add the probability of starting from this state
*p_site_marginal_j = *p_site_j * *f_j;
// increment pointers
++p_site_j; ++p_site_marginal_j;
}
// increment the pointers to the next site
p_site_mixture+=this->siteOffset; p_site_mixture_marginal+=this->siteOffset;
} // end-for over all sites (=patterns)
// increment the pointers to the next mixture category
p_mixture+=this->mixtureOffset; p_mixture_marginal+=this->mixtureOffset;
} // end-for over all mixtures (=rate categories)
}
template<class charType>
void RevBayesCore::PhyloCTMCClado<charType>::computeTipLikelihood(const TopologyNode &node, size_t node_index)
{
double* p_node = this->partialLikelihoods + this->activeLikelihood[node_index]*this->activeLikelihoodOffset + node_index*this->nodeOffset;
// get the current correct tip index in case the whole tree change (after performing an empiricalTree Proposal)
size_t data_tip_index = this->taxon_name_2_tip_index_map[ node.getName() ];
const std::vector<bool> &gap_node = this->gap_matrix[data_tip_index];
const std::vector<unsigned long> &char_node = this->char_matrix[data_tip_index];
const std::vector<RbBitSet> &amb_char_node = this->ambiguous_char_matrix[data_tip_index];
// compute the transition probabilities
this->updateTransitionProbabilities( node_index );
double* p_mixture = p_node;
// iterate over all mixture categories
for (size_t mixture = 0; mixture < this->num_site_mixtures; ++mixture)
{
// the transition probability matrix for this mixture category
const double* tp_begin = this->transition_prob_matrices[mixture].theMatrix;
// get the pointer to the likelihoods for this site and mixture category
double* p_site_mixture = p_mixture;
// iterate over all sites
for (size_t site = 0; site != this->pattern_block_size; ++site)
{
// is this site a gap?
if ( gap_node[site] )
{
// since this is a gap we need to assume that the actual state could have been any state
// iterate over all initial states for the transitions
for (size_t c1 = 0; c1 < this->num_chars; ++c1)
{
// store the likelihood
p_site_mixture[c1] = 1.0;
}
}
else // we have observed a character
{
// iterate over all possible initial states
for (size_t c1 = 0; c1 < this->num_chars; ++c1)
{
if ( this->using_ambiguous_characters == true && this->using_weighted_characters == false)
{
// compute the likelihood that we had a transition from state c1 to the observed state org_val
// note, the observed state could be ambiguous!
const RbBitSet &val = amb_char_node[site];
// get the pointer to the transition probabilities for the terminal states
const double* d = tp_begin+(this->num_chars*c1);
double tmp = 0.0;
for ( size_t i=0; i<val.size(); ++i )
{
// check whether we observed this state
if ( val.test(i) == true )
{
// add the probability
tmp += *d;
}
// increment the pointer to the next transition probability
++d;
} // end-while over all observed states for this character
// store the likelihood
p_site_mixture[c1] = tmp;
}
else if ( this->using_weighted_characters == true )
{
// compute the likelihood that we had a transition from state c1 to the observed state org_val
// note, the observed state could be ambiguous!
const RbBitSet &val = amb_char_node[site];
// get the pointer to the transition probabilities for the terminal states
const double* d = tp_begin+(this->num_chars*c1);
double tmp = 0.0;
std::vector< double > weights = this->value->getCharacter(node_index, site).getWeights();
for ( size_t i=0; i<val.size(); ++i )
{
// check whether we observed this state
if ( val.test(i) == true )
{
// add the probability
tmp += *d * weights[i] ;
}
// increment the pointer to the next transition probability
++d;
} // end-while over all observed states for this character
// store the likelihood
p_site_mixture[c1] = tmp;
}
else // no ambiguous characters in use
{
unsigned long org_val = char_node[site];
// store the likelihood
p_site_mixture[c1] = tp_begin[c1*this->num_chars+org_val];
}
} // end-for over all possible initial character for the branch
} // end-if a gap state
// increment the pointers to next site
p_site_mixture+=this->siteOffset;
} // end-for over all sites/patterns in the sequence
// increment the pointers to next mixture category
p_mixture+=this->mixtureOffset;
} // end-for over all mixture categories
}
/**
* Draw a vector of ancestral states from the marginal distribution (non-conditional of the other ancestral states).
* Here we assume that the marginal likelihoods have been updated.
*/
template<class charType>
std::vector<charType> RevBayesCore::PhyloCTMCClado<charType>::drawAncestralStatesForNode(const TopologyNode &node)
{
size_t node_index = node.getIndex();
// get the marginal likelihoods
std::vector< std::vector<double> >* marginals = sumMarginalLikelihoods(node_index);
RandomNumberGenerator* rng = GLOBAL_RNG;
std::vector< charType > ancestralSeq = std::vector<charType>();
for ( size_t i = 0; i < this->num_sites; ++i )
{
size_t pattern = i;
// if the matrix is compressed use the pattern for this site
if (this->compressed)
{
pattern = this->site_pattern[i];
}
// create the character
charType c = charType( this->template_state );
// sum the likelihoods for each character state
const std::vector<double> siteMarginals = (*marginals)[pattern];
double sumMarginals = 0.0;
for (int j = 0; j < siteMarginals.size(); j++)
{
sumMarginals += siteMarginals[j];
}
double u = rng->uniform01();
if (sumMarginals == 0.0)
{
// randomly draw state if all states have 0 probability
c.setStateByIndex((size_t)(u*c.getNumberOfStates()));
}
else
{
// the marginals don't add up to 1, so rescale u
u *= sumMarginals;
// draw the character state
size_t stateIndex = 0;
while ( true )
{
u -= siteMarginals[stateIndex];
if ( u > 0.0 )
{
stateIndex++;
if ( stateIndex == c.getNumberOfStates() )
{
stateIndex = 0;
c.setToFirstState();
}
else
{
c++;
}
}
else
{
break;
}
}
}
// add the character to the sequence
ancestralSeq.push_back( c );
}
// we need to free the vector
delete marginals;
return ancestralSeq;
}
/**
* Draw a vector of ancestral states from the joint-conditional distribution of states.
*/
template<class charType>
void RevBayesCore::PhyloCTMCClado<charType>::drawJointConditionalAncestralStates(std::vector<std::vector<charType> >& startStates, std::vector<std::vector<charType> >& endStates)
{
RandomNumberGenerator* rng = GLOBAL_RNG;
this->sampled_site_mixtures.resize(this->num_sites);
const TopologyNode &root = this->tau->getValue().getRoot();
size_t node_index = root.getIndex();
size_t right = root.getChild(0).getIndex();
size_t left = root.getChild(1).getIndex();
// get working variables
const std::vector<double> &f = this->getRootFrequencies();
std::vector<double> siteProbVector(1,1.0);
if (this->site_rates_probs != NULL)
{
siteProbVector = this->site_rates_probs->getValue();
}
// get cladogenesis values
std::map<std::vector<unsigned>, double> eventMapProbs = ( branchHeterogeneousCladogenesis ? heterogeneousCladogenesisMatrices->getValue()[node_index].getEventMap(root.getAge()) : homogeneousCladogenesisMatrix->getValue().getEventMap(root.getAge()) );
std::map<std::vector<unsigned>, double> sampleProbs;
std::map<std::vector<unsigned>, double>::iterator it_s;
std::map<std::vector<unsigned>, double>::iterator it_p;
// get the pointers to the partial likelihoods and the marginal likelihoods
double* p_node = this->partialLikelihoods + this->activeLikelihood[node_index]*this->activeLikelihoodOffset + node_index*this->nodeOffset;
const double* p_left = this->partialLikelihoods + this->activeLikelihood[left]*this->activeLikelihoodOffset + left*this->nodeOffset;
const double* p_right = this->partialLikelihoods + this->activeLikelihood[right]*this->activeLikelihoodOffset + right*this->nodeOffset;
// get pointers the likelihood for both subtrees
const double* p_site = p_node;
const double* p_left_site = p_left;
const double* p_right_site = p_right;
// sample root states
std::vector<size_t> sampledSiteRates(this->num_sites,0);
for (size_t i = 0; i < this->num_sites; i++)
{
// sum to sample
double sum = 0.0;
// if the matrix is compressed use the pattern for this site
size_t pattern = i;
if (this->compressed)
{
pattern = this->site_pattern[i];
}
// get ptr to first mixture cat for site
p_site = p_node + pattern * this->siteOffset;
p_left_site = p_left + pattern * this->siteOffset;
p_right_site = p_right + pattern * this->siteOffset;
// iterate over all mixture categories
for (size_t mixture = 0; mixture < this->num_site_rates; ++mixture)
{
// get pointers to the likelihood for this mixture category
const double* p_site_mixture_j = p_site;
const double* p_left_site_mixture_j = p_left_site;
const double* p_right_site_mixture_j = p_right_site;
// iterate over possible end-anagenesis states for each site given start-anagenesis state
for (it_p = eventMapProbs.begin(); it_p != eventMapProbs.end(); it_p++)
{
// triplet of (A,L,R) states
const std::vector<unsigned>& v = it_p->first;
p_site_mixture_j = p_site + v[0];
p_left_site_mixture_j = p_left_site + v[1];
p_right_site_mixture_j = p_right_site + v[2];
std::vector<unsigned> key = it_p->first;
key.push_back((unsigned)mixture);
sampleProbs[ key ] = *p_site_mixture_j * *p_left_site_mixture_j * *p_right_site_mixture_j * f[v[0]] * siteProbVector[mixture] * it_p->second;
sum += sampleProbs[ key ];
// increment the pointers to the next state for (site,rate)
}
// increment the pointers to the next mixture category for given site
p_site += this->mixtureOffset;
p_left_site += this->mixtureOffset;
p_right_site += this->mixtureOffset;
} // end-for over all mixtures (=rate categories)
// sample char from p
bool stop = false;
charType ca = charType( this->template_state );
charType cl = charType( this->template_state );
charType cr = charType( this->template_state );
double u = rng->uniform01() * sum;
for (it_s = sampleProbs.begin(); it_s != sampleProbs.end(); it_s++)
{
u -= it_s->second;
if (u < 0.0)
{
const std::vector<unsigned>& v = it_s->first;
ca += v[0];
cl += v[1];
cr += v[2];
endStates[node_index][i] = ca;
startStates[node_index][i] = ca;
startStates[left][i] = cl;
startStates[right][i] = cr;
sampledSiteRates[i] = v[3];
stop = true;
break;
}
}
}
// recurse
std::vector<TopologyNode*> children = root.getChildren();
for (size_t i = 0; i < children.size(); i++)
{
// recurse towards tips
if (!children[i]->isTip())
{
recursivelyDrawJointConditionalAncestralStates(*children[i], startStates, endStates, sampledSiteRates);
}
else
{
AbstractPhyloCTMCSiteHomogeneous<charType>::tipDrawJointConditionalAncestralStates(*children[i], startStates, endStates, sampledSiteRates);
}
}
}
template<class charType>
void RevBayesCore::PhyloCTMCClado<charType>::recursivelyDrawJointConditionalAncestralStates(const TopologyNode &node, std::vector<std::vector<charType> >& startStates, std::vector<std::vector<charType> >& endStates, const std::vector<size_t>& sampledSiteRates)
{