-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTreeNode.hpp
More file actions
1647 lines (1506 loc) · 62.1 KB
/
Copy pathTreeNode.hpp
File metadata and controls
1647 lines (1506 loc) · 62.1 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
#define _USE_MATH_DEFINES
#ifndef TREENODE_H
#define TREENODE_H
#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <cstdlib>
#include <math.h>
#include <boost/lexical_cast.hpp>
#include <boost/numeric/ublas/vector.hpp>
//#include <boost/thread.hpp>
#include <string>
#include <limits>
#include "GaussianVector.hpp"
#include "Settings.hpp"
#include <boost/math/special_functions/fpclassify.hpp>
using namespace std;
// Belief propagation message to "sample" from the Gaussian factor
// mean: incoming message from mean
// variance: known variance
GaussianVector SampleAverageConditional(GaussianVector mean, double variance)
{
//cout << "Mean=" << mean << " prec=" << prec << endl;
double prec = 1.0 / variance;
if (mean.isPoint)
{
boost::numeric::ublas::vector<double> temp(mean.size());
temp &= prec;
return GaussianVector(mean.GetMean() * prec, temp);
}
else
{
boost::numeric::ublas::vector<double> R;
R = (mean.Precision + prec) / prec;
return GaussianVector(mean.MeanTimesPrecision / R, mean.Precision / R);
}
};
class TreeNode;
// Potential branch point. If isExistingBranchPoint this this at an existing branch point (PYDT setting only)
// specified by "child". If not isExistingBranchPoint this is on the edge between "parent" and "child", at time
// "time"
class BranchPoint
{
public:
TreeNode* parent;
TreeNode* child;
double time;
bool isExistingBranchPoint;
bool onPath;
void AttachSubtree(TreeNode* subtree, BaseSettings &settings);
string ToString();
bool IsBefore(BranchPoint &other);
BranchPoint() {};
BranchPoint(TreeNode* parent, TreeNode* child, double time, bool isExistingBranchPoint, bool onPath) :
parent(parent),
child(child),
time(time),
isExistingBranchPoint(isExistingBranchPoint),
onPath(onPath) {};
BranchPoint(TreeNode* parent, TreeNode* child, double time, bool isExistingBranchPoint) :
parent(parent),
child(child),
time(time),
isExistingBranchPoint(isExistingBranchPoint) {};
};
template <typename T>
T listIndexOf(list<T> l, int index)
{
int counter=0;
for (typename list<T>::iterator i=l.begin(); i != l.end(); ++i)
{
if (counter==index)
return *i;
counter++;
}
throw 1;
}
// Return whether the list has N elements
template <typename T>
bool ListHasOnlyNElements(list<T> l, int N)
{
//typename T;
typename list<T>::iterator it;
it=l.begin();
for (int i=0; i<N; i++)
{
if (it==l.end())
return false; // list has i elements
it++;
}
if (it!=l.end())
return false; // list has more than 1 element
return true;
}
// Return whether the list has only one element
template <typename T>
bool ListHasOnlyOneElement(list<T> l)
{
return ListHasOnlyNElements<T>(l, 1);
}
// Class representing a node in the tree
class TreeNode {
friend ostream &operator<<(ostream &output, const TreeNode &node)
{
output << node.time << endl;
return output;
}
public:
// Divergence times
double time;
// List of children
list<TreeNode*> children;
// Ideally we wouldn't store this but makes some operations much easier
TreeNode* parent;
// Number of leaf nodes found down the tree from here
int numDescendants;
// Whether this is a leaf node
bool isLeaf;
// A text label for this node
string label;
// Marginal location, also used for instantiated location
GaussianVector Marg_Location;
// BP message from this to parent
GaussianVector Msg_Normal_ParentLocation;
// BP message from parent to this
GaussianVector Msg_Normal_Location;
// list of Poisson events on the branch from parent to this
list<double> events;
// list of Poisson events on the branch from parent to this
double node_event;
// Constructor: t is time, il = isLeaf
TreeNode (double t, bool il) {
time = t;
isLeaf=il;
numDescendants = 1;
label="";
node_event = 0.0;
};
void SetupParents(TreeNode* theparent, bool check=false){
if (check)
assert(parent==theparent);
parent=theparent;
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
(*i)->SetupParents(this,check);
}
// Check that the BP messages are consistent with the marginal
void CheckConsistency()
{
GaussianVector temp = Msg_Normal_Location;
if (!isLeaf)
{
int childCount = 0;
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
temp *= (*i)->Msg_Normal_ParentLocation;
assert( (*i)->Msg_Normal_ParentLocation.Precision[0] > 0 ) ;
(*i)->CheckConsistency();
childCount++;
}
assert(childCount > 1);
assert( sumVector( applyFunc(temp.GetMean() - Marg_Location.GetMean(),abs) ) < 0.001 );
if (!isLeaf){
assert( temp.Precision[0] > 0 );
assert( Msg_Normal_Location.Precision[0] > 0 );
}
}
}
// Delete a subtree recursively free-ing associated memory
static void deleteSubtree(TreeNode* subtree)
{
for (list<TreeNode*>::iterator i=subtree->children.begin(); i != subtree->children.end(); ++i)
{
deleteSubtree(*i);
}
delete subtree;
};
// Get a deep copy of this subtree recursively
TreeNode* DeepCopy()
{
TreeNode* result = new TreeNode(time, isLeaf);
result->numDescendants=numDescendants;
result->label=label;
if (isLeaf)
result->Marg_Location=Marg_Location; // observed data!
// NB: not copying messages!
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
result->children.push_back((*i)->DeepCopy());
}
return result;
}
// Used for aggregating depth statistics about the tree: how many leaves are there
// at each depth
void LeafDepthHist(map<int,int> &hist, int depth = 0)
{
if (!isLeaf)
{
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
(*i)->LeafDepthHist(hist,depth+1);
}
}
else
{
if (hist.count(depth)==0)
hist[depth]=0;
hist[depth]++;
}
}
int sumBranchingFactor()
{
if (!isLeaf)
{
int sum=children.size();
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
sum += (*i)->sumBranchingFactor();
}
return sum;
}
else
{
return 0;
}
}
int maxBranchingFactor()
{
if (!isLeaf)
{
int maxbf=children.size();
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
maxbf = max( (*i)->maxBranchingFactor(), maxbf );
}
return maxbf;
}
else
{
return 0;
}
}
// Detach a subtree. Returns who the root should be. logProb is the (hypothetical) probability of attaching here
TreeNode* DetachSubtree(TreeNode* subtree, TreeNode* parent, BranchPoint* originalPosition = NULL)
{
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
if (subtree==*i) // this child is the subtree to be removed
{
if (originalPosition != NULL) // record where the subtree was
{
originalPosition->parent=parent;
originalPosition->child=this;
originalPosition->time=(*i)->time;
originalPosition->isExistingBranchPoint=true;
}
children.remove(*i); // remove it from our list of children
numDescendants -= subtree->numDescendants;
// if removing this child meant we now only have one child
// then delete this
if (ListHasOnlyOneElement<TreeNode*>(children))
{
if (originalPosition != NULL)
{
originalPosition->parent=parent;
originalPosition->child=children.front();
originalPosition->time=time;
originalPosition->isExistingBranchPoint=false;
}
TreeNode* toreturn= children.front();
toreturn->parent=parent;
delete this;
return toreturn;
}
else
{
return this;
}
}
TreeNode* temp = (*i)->DetachSubtree(subtree,this,originalPosition);
if (temp!=NULL) // if subtree was detached below this child...
{
numDescendants -= subtree->numDescendants;
(*i) = temp; // the child may have been deleted
return this;
}
}
return NULL; // the subtree to detach was not in the subtree rooted at this node
}
BranchPoint Detach(BaseSettings &settings, double &ml_change, double &time_prior_change, double &struct_prior_change)
{
BranchPoint originalPosition;
ml_change=0;
time_prior_change=0;
struct_prior_change=0;
originalPosition.isExistingBranchPoint=parent->children.size()>2;
if (originalPosition.isExistingBranchPoint){
TreeNode* atnode=parent;
ml_change -= atnode->local_factor(false,settings.D); // likelihood
struct_prior_change -= atnode->LogEvidenceStructureOnlyUp(settings,0); // times
time_prior_change -= atnode->LogEvidenceTimesOnlyUp(settings,0); // structure prior
time_prior_change -= LocalEvidenceTimes(parent->time,settings); // remove my time likelihood contrib
parent->children.remove(this);
originalPosition.time=parent->time;
originalPosition.child=parent;
originalPosition.parent=NULL;
parent->numDescendants -= numDescendants;
parent->Marg_Location /= Msg_Normal_ParentLocation;
parent->bpSweepUp(-numDescendants);
ml_change += atnode->local_factor(false,settings.D);
time_prior_change += atnode->LogEvidenceTimesOnlyUp(settings,0);
struct_prior_change += atnode->LogEvidenceStructureOnlyUp(settings,0); // numdescendants already updated
} else {
originalPosition.parent=parent->parent;
if (originalPosition.parent->time!=0.0){ // i.e. if originalPosition.parent != zero
ml_change -= parent->parent->local_factor(false,settings.D,parent);
}
ml_change -= parent->local_factor(false,settings.D);
struct_prior_change -= parent->LogEvidenceStructureOnlyUp(settings,0);
time_prior_change -= LogEvidenceTimesOnlyUp(settings,0);
parent->children.remove(this);
originalPosition.time=parent->time;
assert( parent->children.size() == 1 );
originalPosition.child=parent->children.front();
time_prior_change -= originalPosition.child->LocalEvidenceTimes(parent->time,settings);
originalPosition.parent->numDescendants -= numDescendants;
originalPosition.parent->Marg_Location /= parent->Msg_Normal_ParentLocation;
originalPosition.child->Msg_Normal_ParentLocation = SampleAverageConditional( originalPosition.child->Marg_Location / originalPosition.child->Msg_Normal_Location, originalPosition.child->time - originalPosition.parent->time);
originalPosition.parent->Marg_Location *= originalPosition.child->Msg_Normal_ParentLocation;
originalPosition.parent->children.remove(parent);
originalPosition.parent->children.push_back(originalPosition.child);
originalPosition.child->parent = originalPosition.parent;
originalPosition.parent->bpSweepUp(-numDescendants);
if (originalPosition.parent->time==0.0){
boost::numeric::ublas::vector<double> zeros(settings.D);
zeros &= 0.0;
ml_change += sumVector(originalPosition.child->Msg_Normal_ParentLocation.GetLogProb(zeros));
} else {
ml_change += originalPosition.parent->local_factor(false,settings.D);
}
struct_prior_change += originalPosition.parent->LogEvidenceStructureOnlyUp(settings,0);
time_prior_change += originalPosition.child->LogEvidenceTimesOnlyUp(settings,0);
delete parent;
parent=NULL;
// I THINK the message down into op.child is unchanged...
}
return originalPosition;
}
// Initialise messages before performing a sweep of BP
void initialise(BaseSettings &settings)
{
Msg_Normal_ParentLocation.SetToUniform(settings.D);
Msg_Normal_Location.SetToUniform(settings.D);
if (!isLeaf)
{
Marg_Location.SetToUniform(settings.D);
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
(*i)->initialise(settings);
}
};
// Add a leaf according to the generative process. Returns the attachment depth
int AddChild(BaseSettings& s, TreeNode* leaf, int depth=0) {
double u = s.fRand(0,numDescendants+s.theta);
u -= s.theta+s.alpha*(double)(int)children.size();
numDescendants++;
if (u < 0) // create a new branch at an existing branch point (PYDT only)
{
children.push_back(leaf);
return depth;
}
else
{
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
u -= (*i)->numDescendants - s.alpha;
if (u < 0) // go down this branch
{
// decide whether to diverge on this branch, and if so, when
double At = s.A(time)+exp(s.logDivergenceRateFactor((*i)->numDescendants))*(-log(s.fRand(0,1)));
double td= s.invA(At);
if (td>(*i)->time) // don't diverge off this branch
return (*i)->AddChild(s,leaf,depth+1);
else // diverge
{
// create new internal node
TreeNode * temp = new TreeNode(td,false);
temp->children.push_back(*i);
temp->children.push_back(leaf);
temp->numDescendants = (*i)->numDescendants+1;
*i=temp;
return depth+1;
}
}
}
}
throw 1; // should never get here!
};
// NOTE: this assumes sigma=1
GaussianVector PredictionSimple(BaseSettings& s) {
double u = s.fRand(0,numDescendants+s.theta);
u -= s.theta+s.alpha*(double)(int)children.size();
GaussianVector result;
if (u < 0) // create a new branch at an existing branch point (PYDT only)
{
//result= new GaussianVector();
boost::numeric::ublas::vector<double> variance(s.D);
variance &= 1.0 - time;
result.SetMeanAndVariance(Marg_Location.GetMean(), variance);
return result;
}
else
{
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
u -= (*i)->numDescendants - s.alpha;
if (u < 0) // go down this branch
{
// decide whether to diverge on this branch, and if so, when
double At = s.A(time)+exp(s.logDivergenceRateFactor((*i)->numDescendants))*(-log(s.fRand(0,1)));
double td= s.invA(At);
if (td>(*i)->time) // don't diverge off this branch
return (*i)->PredictionSimple(s);
else // diverge
{
// create new internal node
//result= new GaussianVector();
boost::numeric::ublas::vector<double> variance(s.D);
variance &= 1.0 - td;
boost::numeric::ublas::vector<double> mean = (Marg_Location.GetMean()*(td-time)) + ((*i)->Marg_Location.GetMean()*((*i)->time-td));
mean /= (*i)->time - time;
result.SetMeanAndVariance(mean, variance);
return result;
}
}
}
}
throw 1; // should never get here!
};
// Try to attach the subtree using the generative process
// Return whether this was successful
// isZero: whether this is the very first node in the tree (above the root) so branching
// directly from here is not allowed
// Returns whether we successfully attached the subtree
bool AttachSubtree(BaseSettings& s, TreeNode* subtree,BranchPoint &where, bool isZero = true) {
if (subtree->time < time)
return false;
double u = s.fRand(0.0,numDescendants+s.theta) ;
u -= s.theta+s.alpha*(int)children.size();
// form a new branch from this existing branch point
if ((!isZero) && u < 0.0)
{
children.push_back(subtree);
where.parent=this;
where.child=NULL;
where.time=time;
where.isExistingBranchPoint=true;
numDescendants+=subtree->numDescendants;
//cout << "new branch" << endl;
return true;
}
else
{
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
u -= (*i)->numDescendants-s.alpha;
if (isZero || u < 0.0) // go down this branch
{
// effective modification to the rate as a result of the multiple datapoints in the subtree
double logDivRateFactor=s.logDivergenceRateFactor((*i)->numDescendants);
double At = s.A(time)+exp(logDivRateFactor)*(-log(s.fRand()));
double td= s.invA(At);
if (td>(*i)->time) {
bool temp=(*i)->AttachSubtree(s,subtree,where,false);
if (temp) // if the subtree was attached below us in the tree then need to update numDescendants
{
numDescendants+=subtree->numDescendants;
}
return temp;
}
else
{
if (td<subtree->time) // check that the branch length will be positive
{
//cout << "attached at " << td << endl;
TreeNode * temp = new TreeNode(td,false);
temp->children.push_back(*i);
where.child=*i;
temp->children.push_back(subtree);
temp->numDescendants = (*i)->numDescendants+subtree->numDescendants;
children.remove(*i);
children.push_back(temp);
numDescendants+=subtree->numDescendants;
where.parent=this;
where.time=td;
where.isExistingBranchPoint=false;
return true;
}
else
return false; // did not attach
}
}
}
}
throw 1;
};
// Get the probability of having attached subtree at its current location
bool GetProbOfAttachSubtree(BaseSettings& s, TreeNode* subtree, double &logProb)
{
// If subtree is one of our children find the factor for this
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
if ((*i)==subtree)
{
if (ListHasOnlyNElements(children,2)) // adding subtree resulted in the creation of this node
logProb += log(s.a(time)) + s.singleTerm(numDescendants-subtree->numDescendants); // prob of diverging here
else
logProb += log(s.theta+s.alpha*(int)(children.size()-1)) - log(numDescendants-subtree->numDescendants+s.theta);
return true;
}
}
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
double temp = 0.0;
bool attached = (*i)->GetProbOfAttachSubtree(s, subtree, temp);
if (attached)
{
//cout << logProb << endl;
logProb += (s.A(time)-s.A((*i)->time)) * exp(s.singleTerm((*i)->numDescendants-subtree->numDescendants)); // prob not diverging until td
// cout << logProb << endl;
logProb += log((*i)->numDescendants-subtree->numDescendants-s.alpha) - log(numDescendants-subtree->numDescendants+s.theta); // prob going down this branch
//cout << logProb << endl;
logProb += temp;
// cout << logProb << endl;
return true;
}
}
return false;
};
// Output in Newick format, with divergence times
string newick(double parentTime)
{
string res; // result string
if (isLeaf) // just put the label if this is a leaf
{
res = label;
}
else // build up the string
{
res = "(";
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); )
{
res += (*i)->newick(time);
++i;
if (i != children.end())
res += ",";
}
res += ")";
}
// append the divergence time
// note that some plotting packages expect time-parentTime here.
res += ":" + boost::lexical_cast<string>(time) + "-" + boost::lexical_cast<string>(parentTime);
return res;
};
string newick_struct(BaseSettings &settings)
{
string res; // result string
if (isLeaf) // just put the label if this is a leaf
{
res = label;
}
else // build up the string
{
res = "(";
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); )
{
res += (*i)->newick_struct(settings);
++i;
if (i != children.end())
res += ",";
}
res += ")";
}
res += ":" + boost::lexical_cast<string>(LocalEvidenceStructure(settings));
return res;
};
string newick_times_evidence(double parenttime, BaseSettings &settings)
{
string res; // result string
if (isLeaf) // just put the label if this is a leaf
{
res = label;
}
else // build up the string
{
res = "(";
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); )
{
res += (*i)->newick_times_evidence(time,settings);
++i;
if (i != children.end())
res += ",";
}
res += ")";
}
res += ":" + boost::lexical_cast<string>(LocalEvidenceTimes(parenttime,settings));
return res;
};
// Output tree in newick format (structure only)
string newick()
{
string res;
if (isLeaf)
{
res = label;
}
else
{
res = "(";
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); )
{
res += (*i)->newick();
++i;
if (i != children.end())
res += ",";
}
res += ")";
}
//if (!events.empty())
//res += ":" + boost::lexical_cast<string>(events.front());
return res;
};
// Output tree in newick format including divergence times AND locations
string newick2(double parentTime)
{
string res;
if (isLeaf)
{
res = label;
}
else
{
res = "(";
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); )
{
res += (*i)->newick2(time);
++i;
if (i != children.end())
res += ",";
}
res += ")";
}
stringstream s;
s << Marg_Location.GetMean();
res += ":" + s.str() + "-" + boost::lexical_cast<string>(time);
return res;
};
// Count the number of leaves.
// check: whether to throw an exception if numDescendants is incorrect
int countLeaves(bool check = false, bool countAll = false)
{
if (isLeaf)
return 1;
int leaves = 0;
int childrenCount = 0;
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i,childrenCount++)
leaves += (*i)->countLeaves(check, countAll);
if (check && (leaves != numDescendants))
{
cerr << "Number of leaves: " << leaves << " cached number=" << numDescendants << endl;
cout << newick() << endl;
throw 1;
}
else if (check && childrenCount==1)
throw 1;
else if (!countAll)
numDescendants=leaves;
return leaves + (countAll ? 1 : 0);
};
// Upwards sweep of sampling
void sampleSweepUp(TreeNode& parent, BaseSettings &settings)
{
parent.Marg_Location /= Msg_Normal_ParentLocation; // remove the current contribution
if (!Marg_Location.isPoint)
Marg_Location.SetPoint(Marg_Location.Sample(settings.gen)); // sample point
if (isLeaf)
{
// calculate the new message
Msg_Normal_ParentLocation = SampleAverageConditional(Marg_Location, time-parent.time);
}
else
{
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
(*i)->sampleSweepUp(*this, settings); // recurse down the structure
// ... then calculate messages
Msg_Normal_ParentLocation = SampleAverageConditional(Marg_Location, time-parent.time);
}
// update the parent marginal
parent.Marg_Location *= Msg_Normal_ParentLocation;
// cout << Msg_Normal_ParentLocation << time - parent.time << endl;
};
// Upwards sweep of belief propagation
void bpSweepUp(TreeNode& parent)
{
parent.Marg_Location /= Msg_Normal_ParentLocation; // remove the current contribution
if (isLeaf)
{
// calculate the new message
Msg_Normal_ParentLocation = SampleAverageConditional(Marg_Location, time-parent.time);
}
else
{
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
(*i)->bpSweepUp(*this); // recurse down the structure
// ... then calculate messages
Msg_Normal_ParentLocation = SampleAverageConditional(Marg_Location / Msg_Normal_Location, time-parent.time);
}
// update the parent marginal
parent.Marg_Location *= Msg_Normal_ParentLocation;
// cout << Msg_Normal_ParentLocation << time - parent.time << endl;
if (isnan(Msg_Normal_ParentLocation.Precision[0])) throw 1;
};
// Upwards sweep of belief propagation starting at subtree attachment or detachment
void bpSweepUp(int numDescendantsToAdd)
{
if (parent!=NULL){
parent->Marg_Location /= Msg_Normal_ParentLocation; // remove the current contribution
// calculate the new message
Msg_Normal_ParentLocation = SampleAverageConditional(isLeaf ? Marg_Location : (Marg_Location / Msg_Normal_Location), time-parent->time);
// update the parent marginal
parent->Marg_Location *= Msg_Normal_ParentLocation;
parent->numDescendants += numDescendantsToAdd;
assert(!isnan(Msg_Normal_ParentLocation.Precision[0]));
parent->bpSweepUp(numDescendantsToAdd);
}
};
// Upwards sweep of belief propagation
double bpSweepUp2(GaussianVector &msg_up, bool isRoot,int D)
{
if (isLeaf) {
msg_up = Marg_Location;
return 0.0;
}
else
{
double ml=0.0;
boost::numeric::ublas::vector<double> prod_v(D), sum_m2_over_v(D);
prod_v &= 1.0 ;
sum_m2_over_v &= 0.0;
msg_up.SetToUniform(D);
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i){
GaussianVector up_msg;
ml += (*i)->bpSweepUp2(up_msg,false,D); // recurse down the structure
GaussianVector norm_up=SampleAverageConditional(up_msg, (*i)->time - time);
msg_up *= norm_up;
boost::numeric::ublas::vector<double> mi=norm_up.GetMean();
boost::numeric::ublas::vector<double> ti=norm_up.GetVariance();
prod_v *= ti;
sum_m2_over_v += mi*mi/ti;
}
if (isRoot){
GaussianVector prior;
prior.SetToUniform(D);
prior.Precision &= 1.0 / time;
msg_up *= prior;
boost::numeric::ublas::vector<double> mi=prior.GetMean();
boost::numeric::ublas::vector<double> ti=prior.GetVariance();
prod_v *= ti;
sum_m2_over_v += mi*mi/ti;
}
boost::numeric::ublas::vector<double> m =msg_up.GetMean();
boost::numeric::ublas::vector<double> v=msg_up.GetVariance();
ml += -((double)children.size()- (isRoot?0.0:1.0))*(double)D*GaussianVector::lnSqrt2Pi + .5 * ( sumVector(applyFunc(v,log)) - sumVector(applyFunc(prod_v,log)) + sumVector(m*m/v) - sumVector(sum_m2_over_v) );
if (isnan(ml)) throw 1;
return ml;
}
};
double local_factor(bool excludeLast,int D,TreeNode* child_to_exclude=NULL){
if (isLeaf) throw 1;
boost::numeric::ublas::vector<double> prod_v(D), sum_m2_over_v(D);
prod_v &= 1.0 ;
sum_m2_over_v &= 0.0;
GaussianVector msg_up;
msg_up.SetToUniform(D);
int counter=0,nchildren=children.size();
bool found_child_to_exclude=false;
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i){
if (excludeLast && counter==nchildren-1)
continue;
if (child_to_exclude!=NULL && child_to_exclude==*i){
found_child_to_exclude=true;
continue;
}
GaussianVector norm_up=(*i)->Msg_Normal_ParentLocation;
msg_up *= norm_up;
boost::numeric::ublas::vector<double> mi=norm_up.GetMean();
boost::numeric::ublas::vector<double> ti=norm_up.GetVariance();
prod_v *= ti;
sum_m2_over_v += mi*mi/ti;
counter++;
}
if (child_to_exclude)
assert(found_child_to_exclude);
msg_up *= Msg_Normal_Location;
boost::numeric::ublas::vector<double> mi=Msg_Normal_Location.GetMean();
boost::numeric::ublas::vector<double> ti=Msg_Normal_Location.GetVariance();
prod_v *= ti;
sum_m2_over_v += mi*mi/ti;
boost::numeric::ublas::vector<double> m =msg_up.GetMean();
boost::numeric::ublas::vector<double> v=msg_up.GetVariance();
double ml= -(double)counter*(double)D*GaussianVector::lnSqrt2Pi + .5 * ( sumVector(applyFunc(v,log)) - sumVector(applyFunc(prod_v,log)) + sumVector(m*m/v) - sumVector(sum_m2_over_v) );
assert(!isnan(ml));
return ml;
}
static double local_factor(list<GaussianVector*> &in,int D){
boost::numeric::ublas::vector<double> prod_v(D), sum_m2_over_v(D);
prod_v &= 1.0 ;
sum_m2_over_v &= 0.0;
GaussianVector msg_up;
msg_up.SetToUniform(D);
for (list<GaussianVector*>::iterator i=in.begin(); i != in.end(); ++i){
GaussianVector* norm_up = *i;
msg_up *= *norm_up;
boost::numeric::ublas::vector<double> mi=norm_up->GetMean();
boost::numeric::ublas::vector<double> ti=norm_up->GetVariance();
prod_v *= ti;
sum_m2_over_v += mi*mi/ti;
}
boost::numeric::ublas::vector<double> m =msg_up.GetMean();
boost::numeric::ublas::vector<double> v=msg_up.GetVariance();
return -((double)in.size()-1.0)*(double)D*GaussianVector::lnSqrt2Pi + .5 * ( sumVector(applyFunc(v,log)) - sumVector(applyFunc(prod_v,log)) + sumVector(m*m/v) - sumVector(sum_m2_over_v) );
}
// Downward sweep of belief propagation
void bpSweepDown(TreeNode& parent)
{
if (isLeaf)
{
Msg_Normal_Location = SampleAverageConditional(parent.Marg_Location / Msg_Normal_ParentLocation, time-parent.time);
}
else
{
Marg_Location /= Msg_Normal_Location; // remove the current contribution
// calculate the ne message
Msg_Normal_Location = SampleAverageConditional(parent.Marg_Location / Msg_Normal_ParentLocation, time-parent.time);
Marg_Location *= Msg_Normal_Location; // add in new contribution
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
(*i)->bpSweepDown(*this); // recurse down the structure
//cout << "Marginal: " << Marg_Location << endl;
}
if (isnan(Msg_Normal_Location.Precision[0])) throw 1;
//cout << "Marginal: " << Marg_Location << endl;
};
// Sample synthetic data at the leaves
void sampleData(boost::numeric::ublas::vector<double> &parentLocation, double parentTime, BaseSettings &s)
{
// sample the diffusion process for this branch
boost::numeric::ublas::vector<double> ones(parentLocation.size());
ones &= 1.0;
boost::numeric::ublas::vector<double> temp = GaussianVector::Sample(s.gen, parentLocation, ones * (time-parentTime));
if (isLeaf)
{
Marg_Location.SetPoint(temp);
//cout << label << " " << temp << endl;
}
else
{
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
(*i)->sampleData(temp, time, s);
}
};
double LocalEvidenceTimes(double parent_time, BaseSettings &settings){
double lnEvidence = 0.0;
if (!isLeaf)
{
lnEvidence += (settings.A(parent_time) - settings.A(time))*settings.H(numDescendants-1);
lnEvidence += log(settings.a(time));
}
assert(!isnan(lnEvidence));
return lnEvidence;
}
double LocalEvidenceStructure(BaseSettings &settings){
double lnEvidence = 0.0;
if (!isLeaf)
{
// is this correct?
int l=1;
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
{
if (l >= 3)
lnEvidence += log(settings.theta+((double)l-1.0)*settings.alpha);
lnEvidence += lgamma((*i)->numDescendants-settings.alpha);
l++;
}
lnEvidence -= lgamma(numDescendants+settings.theta);
int numBranches = l - 1;
lnEvidence -= ((double)numBranches-1.0)*lgamma(1.0-settings.alpha);
}
assert(!isnan(lnEvidence));
return lnEvidence;
}
// log evidence contribution for the structure and divergence times
double LogEvidenceStructure(double parent_time, BaseSettings &settings)
{
double lnEvidence = LocalEvidenceStructure(settings);
lnEvidence += LocalEvidenceTimes(parent_time,settings);
for (list<TreeNode*>::iterator i=children.begin(); i != children.end(); ++i)
lnEvidence += (*i)->LogEvidenceStructure(time, settings);
return lnEvidence;
}
// additional_descendants is used to simulated the effect of adding a subtree
double LogEvidenceStructureUp(BaseSettings &settings,int additional_descendants)
{
double lnEvidence = 0.0;
if (parent != NULL) { // i.e. stop at zero!