-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMCMCEnv.cpp
2060 lines (1787 loc) · 64.1 KB
/
MCMCEnv.cpp
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
#include "MCMCEnv.h"
#include "Random.h"
#include <stdexcept>
#include <deque>
#include <iomanip>
#include <cmath>
#include <sstream>
#define SMALLNUM 1e-200
unsigned long MCMCEnv::NumOfTP = 0;
unsigned long MCMCEnv::NumOfGenes = 0;
unsigned long MCMCEnv::NumOfData = 0;
ClusterTree::NumOfSampleContainer MCMCEnv::DataNumEachTP; // number of data in each time point
matrix MCMCEnv::mu1;
matrix MCMCEnv::mu0;
matrix MCMCEnv::sigma0;
matrix MCMCEnv::sigma1;
double MCMCEnv::beta0;
double MCMCEnv::beta1;
double MCMCEnv::deltar;
double MCMCEnv::alpha;
double MCMCEnv::shape;
double MCMCEnv::bk; // For split_merge move and birth_death move, we give equal probability.
double MCMCEnv::ranc; // Tail birth is given much more porbability.
double MCMCEnv::k1;
double MCMCEnv::k0;
double MCMCEnv::constSigma0;
double MCMCEnv::constSigma1;
bool MCMCEnv::buildForest;
MCMCEnv::SortedULContainer MCMCEnv::TPStartIndex,
MCMCEnv::ReverseTPStartIndex; // the starting index for each time point
using namespace std;
// matrix calculation
// In this function, cluster indicator z is assumbed to be reflaged using 'reflag' function.
// tao_NULL = 1, delete tao=0, otherwise delete tao=1.
// the return matrix is the shrinked version of the data matrix
// taoIndices: the indices for tao == 1
matrix MCMCEnv::reData(unsigned long long ID, bool tao_NULL, const TaoSet &newTao, vector<unsigned long> &taoIndices) const {
// the indices of genes that will go to the result matrix
unsigned long index = 0;
taoIndices.clear();
for(TaoSet::const_iterator itor = newTao.begin(); itor != newTao.end(); itor++, index++) {
if(tao_NULL == *itor) {
taoIndices.push_back(index);
}
}
matrix result(taoIndices.size(), true, NumOfData);
//std::vector<std::vector<long> > mclust = Flags.onezerocluster(ID);
unsigned long length = 0;
for(unsigned long i = 0; i < Flags.rows(); i++){
for(unsigned long j = 0; j < Flags.cols(i); j++) {
if(Flags.getFlag(i, j) == ID || !tao_NULL) {
dvector resultvec;
for(vector<unsigned long>::const_iterator itor = taoIndices.begin();
itor != taoIndices.end(); itor++) {
resultvec.push_back(Data.getValue(length + j, *itor));
}
result.addRow(resultvec);
}
//for(k=0; k<one.cols(); k++) {
// one.setValue(length + j, k, Data.getValue(length + j, k)
// * ((tao_NULL == newTao[k])? (newTao[k]? mclust.at(i).at(j): 1): 0));
//}
}
length += Flags.cols(i);
}
//cout << "reData" << endl << one;
return result;
}
matrix MCMCEnv::reData(unsigned long long ID, bool tao_NULL, const TaoSet &newTao, ostream &os) const {
vector<unsigned long> taoIndices;
matrix one = reData(ID, tao_NULL, newTao, taoIndices);
for(TaoSet::const_iterator itor = newTao.begin();
itor != newTao.end(); itor++) {
os << *itor << ' ';
}
os << endl << "reData" << endl << one;
return one;
}
matrix MCMCEnv::datacov(unsigned long long flag, bool tao_NULL, const TaoSet &newTao, ostream &os) const {
matrix result = datacov(flag, tao_NULL, newTao);
os << "Datacov" << endl << result;
return result;
}
// Notice that when tao_NULL = true, flag is not used in the function
// so any data will be considered
matrix MCMCEnv::datacov(unsigned long long flag, bool tao_NULL, const TaoSet &newTao) const {
long x = (tao_NULL? Flags.flagnum(flag): NumOfData);
vector<unsigned long> taoIndices;
matrix subData = reData(flag, tao_NULL, newTao, taoIndices);
//matrix two = (tao_NULL? mu1: mu0);
unsigned long cols = taoIndices.size();
matrix two(1, cols);
for(unsigned long k = 0; k < cols; k++){
two(0, k) = mu1(0, taoIndices[k]);
}
matrix one_mean = (subData.datasum() * (1.0 / (double) x));
//TimeCoordinate xx;
matrix cov_NULL(cols, cols);
int i,j;
for(i = 0; i < subData.rows(); i++)
{
//xx = IndexToCoor(i);
matrix mid(1, cols, subData.getRowVec(i));
//if((Flags.getFlag(xx.first, xx.second) == flag) || !tao_NULL){
mid -= one_mean;
//} else {
// mid = one.getRow(i);
//}
//std::cout<<"Matrix transpose: "<<std::endl;
//std::cout<<mid<<std::endl;
cov_NULL += mid.transTimesSelf();
}
two -= one_mean;
/*std::cout<<"mu0: "<<std::endl;
std::cout<<two<<std::endl;
std::cout<<"mean: "<<std::endl;
std::cout<<one_mean<<std::endl;*/
return cov_NULL.rbind(two.transTimesSelf());
}
// Caution: if the index is out of bound, will return NumOfTimePoints
MCMCEnv::TimeCoordinate MCMCEnv::IndexToCoor(unsigned long index) const {
SortedULContainer::const_iterator itor = TPStartIndex.upper_bound(index);
itor--;
return TimeCoordinate(itor->second, index - itor->first);
}
unsigned long MCMCEnv::CoorToIndex(const TimeCoordinate &coor) const {
return ReverseTPStartIndex[coor.first] + coor.second;
}
MCMCEnv::MCMCEnv(const TaoSet &tao, const ClusterFlags &flags, const matrix &data)
: ID_max(1), rootIDs(RootIDContainer()), Flags(flags), Tao(tao), UpToDate(false), Data(data)
{
// actually head node need to be initialized here
ClusterTree &ctree = createTree();
//cout << "Tree" << flush;
ctree.fillWeights(1.0);
//cout << "Tree" << flush;
ctree.samples = DataNumEachTP;
}
MCMCEnv MCMCEnv::initMCMCEnv(unsigned long numOfTimePoints, unsigned long numOfGenes,
unsigned long numOfData, const std::vector<unsigned long> &numOfDataInEachTimePoint,
const TaoSet &tao, const ClusterFlags &flags, const matrix &p_data) {
NumOfTP = numOfTimePoints;
NumOfGenes = numOfGenes;
NumOfData = numOfData;
DataNumEachTP.resize(NumOfTP);
DataNumEachTP.assign(numOfDataInEachTimePoint.begin(), numOfDataInEachTimePoint.end());
unsigned long index = 0, time = 0;
TPStartIndex.clear();
ReverseTPStartIndex.clear();
for(ClusterTree::NumOfSampleContainer::const_iterator itor = DataNumEachTP.begin();
itor != DataNumEachTP.end(); itor++) {
TPStartIndex.insert(SortedULContainer::value_type(index, time));
ReverseTPStartIndex.insert(SortedULContainer::value_type(time, index));
index += *itor;
time++;
}
TPStartIndex.insert(SortedULContainer::value_type(index, time));
//cout << NumOfTP << flush;
return MCMCEnv(tao, flags, p_data);
}
MCMCEnv::MCMCEnv(const MCMCEnv &oldenv): MapClusterTrees(oldenv.MapClusterTrees),
ID_max(oldenv.ID_max), rootIDs(oldenv.rootIDs), Flags(oldenv.Flags), Tao(oldenv.Tao),
UpToDate(oldenv.UpToDate), LogDensityValue(oldenv.LogDensityValue), Data(oldenv.Data) {
// NOTICE: I'm not exactly sure if shallow copy of MapClusterTrees works,
// so need verifying
}
MCMCEnv &MCMCEnv::operator=(const MCMCEnv &oldenv) {
MapClusterTrees = oldenv.MapClusterTrees;
ID_max = oldenv.ID_max;
rootIDs = oldenv.rootIDs;
Flags = oldenv.Flags;
Tao = oldenv.Tao;
UpToDate = oldenv.UpToDate;
LogDensityValue = oldenv.LogDensityValue;
// doesn't need to change data
return *this;
}
MCMCEnv::~MCMCEnv(void)
{
//// when environment is destoryed, destory all the trees
//for(TreeContainer::const_iterator itor = MapClusterTrees.begin();
// itor != MapClusterTrees.end(); itor++) {
// if(itor->second) {
// delete itor->second;
// //itor->second = NULL;
// }
//}
}
unsigned long MCMCEnv::getDataNum() {
return NumOfData;
}
void MCMCEnv::initializeParameters(const matrix &p_mu1, const matrix &p_mu0, const matrix &p_sigma1,
const matrix &p_sigma0, double p_beta1, double p_beta0, double p_deltar, double p_alpha,
double p_shape, double p_bk, double p_ranc, bool bForest) {
mu1 = p_mu1;
mu0 = p_mu0;
sigma1 = p_sigma1;
sigma0 = p_sigma0;
beta1 = p_beta1;
beta0 = p_beta0;
deltar = p_deltar;
alpha = p_alpha;
shape = p_shape;
bk = p_bk;
ranc = p_ranc;
constSigma0 = sigma0(0, 0);
constSigma1 = sigma1(0, 0);
buildForest = bForest;
}
//ClusterTree &MCMCEnv::getTreeFromID(unsigned long long ID) {
// if(MapClusterTrees.find(ID) == MapClusterTrees.end()) {
// ostringstream ostr;
// ostr << "ID " << ID << " not in the list!";
// throw(std::logic_error(ostr.str()));
// }
// return MapClusterTrees.find(ID)->second;
//}
//
//const ClusterTree &MCMCEnv::getTreeFromID(unsigned long long ID) const {
// if(MapClusterTrees.find(ID) == MapClusterTrees.end()) {
// ostringstream ostr;
// ostr << "ID " << ID << " not in the list!";
// throw(std::logic_error(ostr.str()));
// }
// return MapClusterTrees.find(ID)->second;
//}
//
unsigned long MCMCEnv::getTreeNumbers() const {
return rootIDs.size();
}
ClusterTree &MCMCEnv::createTree(unsigned long long parentID, unsigned long time) {
unsigned long long newID = ID_max++;
ClusterTree &parent = getTreeFromID(parentID);
//if(parent.getChildID(time)) {
// // there is child here, so throw error
// throw(std::logic_error("Already have a child at the time!"));
//}
parent.setChild(newID, time);
MapClusterTrees.insert(TreeContainer::value_type(newID, ClusterTree(parent, newID, time)));
UpToDate = false;
return getTreeFromID(newID);
}
ClusterTree &MCMCEnv::createTree() {
// creating mother
//if(rootIDs.size()) {
// throw(std::logic_error("Mother node already created!"));
//}
unsigned long long currRootID = ID_max++;
rootIDs.insert(RootIDContainer::value_type(currRootID, 0));
MapClusterTrees.insert(TreeContainer::value_type(currRootID, ClusterTree(currRootID)));
UpToDate = false;
return getTreeFromID(currRootID);
}
void MCMCEnv::removeTree(unsigned long long TreeID) {
if(getTreeFromID(TreeID).getSampleNum()) {
writeTree(cerr);
cerr << "Tree to remove: " << TreeID << endl;
for(unsigned long t = 0; t < NumOfTP; t++) {
cerr << getTreeFromID(TreeID).weights[t] << ' ';
}
for(unsigned long t = 0; t < NumOfTP; t++) {
cerr << getTreeFromID(TreeID).samples[t] << ' ';
}
cerr << endl;
cerr << "Flags" << endl << Flags << endl;
throw(std::logic_error("Tree has data points, cannot be removed."));
}
// check whether the tree is a root
if(!getTreeFromID(TreeID).getBornTime()) {
// is a root
if(rootIDs.size() <= 1) {
throw(std::logic_error("Last tree here, cannot be removed."));
}
rootIDs.erase(TreeID);
}
MapClusterTrees.erase(TreeID);
UpToDate = false;
}
//ClusterTree &MCMCEnv::getTreeHead() {
// return MapClusterTrees.find(root_ID)->second;
//}
//
//const ClusterTree &MCMCEnv::getTreeHead() const {
// return MapClusterTrees.find(root_ID)->second;
//}
MCMCEnv::TreeSet MCMCEnv::getSplitSet(bool hasForest, bool forestOnly) const {
MCMCEnv::TreeSet result;
result.reserve(NumOfTP * 2);
if(buildForest && hasForest) {
// get the new tree split set
for(RootIDContainer::const_iterator itor = rootIDs.begin();
itor != rootIDs.end(); itor++) {
if(getTreeFromID(itor->first).samples[0]) {
result.push_back(TreeSet::value_type(0, itor->first));
}
}
}
//cout << "Generating Split Set ... " << endl;
if(!forestOnly) {
for(TreeContainer::const_iterator itor = MapClusterTrees.begin();
itor != MapClusterTrees.end(); itor++) {
//cout << "ID: " << itor->second.ID << " Parent ID: "
// << itor->second.parentID
// << " Born time: " << itor->second.getBornTime() << endl;
for(unsigned long t = itor->second.getBornTime() + 1; t < itor->second.getDeathTime(); t++) {
// the born time of its child must be at least 1 more than this
//cout << "Samples(" << t << "): " << itor->second.samples[t] << endl;
if(itor->second.samples[t] && !itor->second.children[t]) {
// has sample and no child at time t
result.push_back(MCMCEnv::TreeSet::value_type(t, itor->first));
}
}
}
}
return result;
//long i,j;
//lvector splitone;
////Collect nonempty cluster vector.
//std::vector<long> flags = newz.getTtoTindicator(n_timepoints);
//long midf,midt,mids,sr = 0;
//long fl = flags.size();
//for(i=0; i<fl; i++){
// midf = flags.at(i);
// midt = newz.getEarliestTime(midf);
//
// for(j=1; j<n_timepoints; j++){
// mids = (j==midt-1)?(newchome(0,midf-1)-1):(midf-1);
// if((newtree(j-1,mids)==0)&&(newz.flaginT(midf,j+1))){
// splitone.push_back(j+1);
// splitone.push_back(midf);
// sr++;
// }
// }
//
//}
//return matrixl(sr,2,splitone);
}
MCMCEnv::TreeMergeSet MCMCEnv::getMergeSet(bool hasForest, bool forestOnly) const {
//std::vector<long> flags = newz.getTtoTindicator(n_timepoints);
//std::vector<long> freeflags;
//std::vector<long> nonfreeflags;
//lvector mergeone;
//long i,j,k,s=0;
//long time1, time2, time0;
//long sr=0;
//long n,m,l;
unsigned long long childID, parentID;
TreeMergeSet result;
result.reserve(NumOfTP * 2);
if(buildForest && hasForest) {
for(RootIDContainer::const_iterator itor = rootIDs.begin();
itor != rootIDs.end(); itor++) {
if(!getTreeFromID(itor->first).getNumOfChildren()) {
// root does not have any children
for(RootIDContainer::const_iterator itor_parent = rootIDs.begin();
itor_parent != rootIDs.end(); itor_parent++) {
if(itor_parent->first != itor->first) {
result.push_back(TreeMergeSet::value_type(itor_parent->first,
itor->first));
}
}
}
}
}
if(!forestOnly) {
for(TreeContainer::const_iterator itor = MapClusterTrees.begin();
itor != MapClusterTrees.end(); itor++) {
// first check if the tree doesn't have any children
if(!itor->second.getNumOfChildren()) {
// this tree does not have any children
childID = itor->second.ID;
for(TreeContainer::const_iterator itor_parent = MapClusterTrees.begin();
itor_parent != MapClusterTrees.end(); itor_parent++) {
if(itor_parent->second.ID != itor->second.ID
&& itor_parent->second.getBornTime() < itor->second.getBornTime()
&& itor_parent->second.getDeathTime() > itor->second.getBornTime()) {
// this parent is OK
result.push_back(TreeMergeSet::value_type(itor_parent->second.ID,
itor->second.ID));
}
}
}
}
}
return result;
}
MCMCEnv::TreeMergeSet MCMCEnv::getDeathSet(bool hasForest, bool forestOnly) const {
TreeMergeSet result;
result.reserve(NumOfTP * 2);
unsigned long long childID, parentID;
if(buildForest && hasForest) {
for(RootIDContainer::const_iterator itor = rootIDs.begin();
itor != rootIDs.end(); itor++) {
if(!getTreeFromID(itor->first).getNumOfChildren() && !getTreeFromID(itor->first).getSampleNum()) {
// root does not have any children and empty
for(RootIDContainer::const_iterator itor_parent = rootIDs.begin();
itor_parent != rootIDs.end(); itor_parent++) {
if(itor_parent->first != itor->first) {
result.push_back(TreeMergeSet::value_type(itor_parent->first,
itor->first));
}
}
}
}
}
if(!forestOnly) {
for(TreeContainer::const_iterator itor = MapClusterTrees.begin();
itor != MapClusterTrees.end(); itor++) {
// first check if the tree doesn't have any children
if(!itor->second.getNumOfChildren()) {
// this tree does not have any children
if(!itor->second.getSampleNum()) {
// this tree is empty
childID = itor->second.ID;
for(TreeContainer::const_iterator itor_parent = MapClusterTrees.begin();
itor_parent != MapClusterTrees.end(); itor_parent++) {
if(itor_parent->second.ID != itor->second.ID
&& itor_parent->second.getBornTime() < itor->second.getBornTime()) {
// this parent is OK
result.push_back(TreeMergeSet::value_type(itor_parent->second.ID,
itor->second.ID));
}
}
}
}
}
}
return result;
}
MCMCEnv::TreeSet MCMCEnv::getTailBirthSet(bool hasForest, bool forestOnly) const {
// This actually has nothing to do with forests so both flags will not be used at all.
MCMCEnv::TreeSet result;
result.reserve(NumOfTP * 2);
//cout << "Generating Split Set ... " << endl;
for(TreeContainer::const_iterator itor = MapClusterTrees.begin();
itor != MapClusterTrees.end(); itor++) {
//cout << "ID: " << itor->second.ID << " Parent ID: "
// << itor->second.parentID
// << " Born time: " << itor->second.getBornTime() << endl;
if(itor->second.getDeathTime() < NumOfTP) {
// can birth
result.push_back(MCMCEnv::TreeSet::value_type(itor->second.getDeathTime(), itor->first));
}
}
return result;
}
MCMCEnv::TreeSet MCMCEnv::getTailDeathSet(bool hasForest, bool forestOnly) const {
// This actually has nothing to do with forests so both flags will not be used at all.
MCMCEnv::TreeSet result;
result.reserve(NumOfTP * 2);
//cout << "Generating Split Set ... " << endl;
for(TreeContainer::const_iterator itor = MapClusterTrees.begin();
itor != MapClusterTrees.end(); itor++) {
//cout << "ID: " << itor->second.ID << " Parent ID: "
// << itor->second.parentID
// << " Born time: " << itor->second.getBornTime() << endl;
if(itor->second.getSampleNum()
&& (itor->second.getDeathTime() > itor->second.getEarliestDeathableTime())) {
// can death
for(unsigned long t = itor->second.getEarliestDeathableTime(); t < itor->second.getDeathTime(); t++) {
result.push_back(MCMCEnv::TreeSet::value_type(t, itor->first));
}
}
}
return result;
}
unsigned long long MCMCEnv::flagSplit(double &P_alloc, bool &NULLset, double &f_ui,
const MCMCEnv::TreeSet::value_type &split_pair) {
ClusterTree &parent = getTreeFromID(split_pair.second);
double ut;
f_ui = 1.0;
long s = 0;
unsigned long long childID;
if(parent.samples[split_pair.first] && split_pair.first < parent.getDeathTime()) {
ClusterTree &child = (split_pair.first)?
createTree(split_pair.second, split_pair.first): createTree();
childID = child.ID;
for(unsigned long i = split_pair.first; i < parent.getDeathTime(); i++) {
/*weight*/
ut = ran_beta(2.0,2.0);
double old_weight = parent.weights[i];
f_ui *= (old_weight > SMALLNUM)? betad(ut, 2.0, 2.0): 1.0;
/* This is a good choice for resetting the cluster indicators and weight parameter */
parent.weights[i] = ut * old_weight;
child.weights[i] = (1 - ut) * old_weight;
// flags
if(parent.samples[i]) {
// there are samples in this time point for the parent
for(long k = 0; k < Flags.cols(i); k++){
if(Flags(i,k) == parent.ID) {
Flags(i,k) = ran_nber(parent.ID, child.ID, ut);
if(Flags(i,k) == parent.ID){
//one(i-1,k) = one(i-1,k);
P_alloc *= ut;
// nothing is changed in terms of sample number
} else {
P_alloc *= (1-ut);
(parent.samples[i])--;
(child.samples[i])++;
s++;
}
}
// cluster indicator reloaded.
}
}
}
NULLset = (s == 0);
/*std::cout<<"new"<<std::endl;
std::cout<<one<<std::endl;
std::cout<<two<<std::endl;
std::cout<<newtree<<std::endl;
std::cout<<newchome<<std::endl;
std::cout<<P_alloc<<std::endl;
std::cout<<NULLset<<std::endl;*/
UpToDate = false;
} else {
std::cout<<"This is an empty cluster!"<<std::endl;
std::cout<<"This cluster can not be splitted!"<<std::endl;
}
return childID;
}
void MCMCEnv::flagSplitTest(double &P_alloc, bool &NULLset, double &f_ui,
const MCMCEnv::TreeSet::value_type &split_pair) {
ClusterTree &parent = getTreeFromID(split_pair.second);
double ut;
f_ui = 1.0;
long s = 0;
if((split_pair.first) && (split_pair.first < NumOfTP) &&
(parent.samples[split_pair.first])) {
// first create a new tree if the split_pair
ClusterTree &child = createTree(split_pair.second, split_pair.first);
for(unsigned long i = split_pair.first; i < NumOfTP; i++) {
/*weight*/
ut = ran_beta(2.0,2.0);
double old_weight = parent.weights[i];
f_ui *= 1.0;
/* This is a good choice for resetting the cluster indicators and weight parameter */
// flags
parent.samples[i] = 0;
child.samples[i] = 0;
//if(parent.samples[i]) {
// // there are samples in this time point for the parent
for(long k = 0; k < Flags.cols(i); k++){
if(Flags(i,k) == parent.ID) {
////Flags(i,k) = ran_nber(parent.ID, child.ID, ut);
//if(Flags(i,k) == parent.ID){
// //one(i-1,k) = one(i-1,k);
// P_alloc *= ut;
// // nothing is changed in terms of sample number
//} else {
//P_alloc *= (1-ut);
(parent.samples[i])++;
} else if(Flags(i, k) == child.ID) {
(child.samples[i])++;
//s++;
//}
}
// cluster indicator reloaded.
}
//}
parent.weights[i] = (double) parent.samples[i]
/ (double) (parent.samples[i] + child.samples[i]);
child.weights[i] = (double) child.samples[i]
/ (double) (parent.samples[i] + child.samples[i]);
}
NULLset = false;
/*std::cout<<"new"<<std::endl;
std::cout<<one<<std::endl;
std::cout<<two<<std::endl;
std::cout<<newtree<<std::endl;
std::cout<<newchome<<std::endl;
std::cout<<P_alloc<<std::endl;
std::cout<<NULLset<<std::endl;*/
UpToDate = false;
} else {
std::cout<<"This is an empty cluster!"<<std::endl;
std::cout<<"This cluster can not be splitted!"<<std::endl;
}
}
void MCMCEnv::flagMerge(double &P_alloc, double &f_ui, const TreeMergeSet::value_type &merge_pair) {
unsigned long parentNum, childNum;
double ut;
P_alloc = 1.0;
f_ui = 1.0;
ClusterTree &parent = getTreeFromID(merge_pair.first),
&child = getTreeFromID(merge_pair.second);
unsigned long time = child.getBornTime();
if(parent.getDeathTime() < child.getDeathTime()) {
parent.setDeathTime(child.getDeathTime());
}
for(unsigned long t = time; t < parent.getDeathTime(); t++) {
if(child.weights[t] > SMALLNUM && parent.weights[t] > SMALLNUM) {
ut = parent.weights[t] / (parent.weights[t] + child.weights[t]);
parentNum = Flags.tflagnum(parent.ID, t);
childNum = Flags.tflagnum(child.ID, t);
P_alloc *= pow(ut, (int) parentNum) * pow(1 - ut, (int) childNum);
f_ui *= betad(ut,2.0,2.0);
parent.weights[t] += child.weights[t];
// calc P_alloc and change weights and sample count
}
for(unsigned long k = 0; k < Flags.cols(t); k++){
if(Flags(t, k) == child.ID) {
Flags(t, k) = parent.ID;
}
// change cluster indicator
}
parent.samples[t] += child.samples[t];
child.samples[t] = 0;
}
if(child.getBornTime() > 0) {
// not a root
getTreeFromID(child.parentID).removeChild(time);
}
// remove child from its original parent
//child.parentID = 0; // reset the parentID of the child, mark it for deletion
try {
removeTree(child.ID);
} catch(std::logic_error &e) {
cerr << "Merge at time=" << time << endl;
throw e;
}
UpToDate = false;
}
void MCMCEnv::flagBirth(const TreeSet::value_type &splitPair) {
double weightratio, jacobi, f_wstar;
return flagBirth(splitPair, weightratio, jacobi, f_wstar);
}
void MCMCEnv::flagBirth(const TreeSet::value_type &splitPair,
double &weightratio, double &jacobi, double &f_wstar) {
long j,k,n,timec;
double w_star;
jacobi = 1.0;
f_wstar = 1.0;
weightratio = 1.0;
unsigned long time = splitPair.first;
const ClusterTree &parent = getTreeFromID(splitPair.second);
if((time < NumOfTP) && parent.getSampleNum(time)) {
/*Justify whether clusterindex is an empty cluster.*/
ClusterTree &child = (time? createTree(parent.ID, time): createTree());
for(unsigned long t = time; t < child.getDeathTime(); t++){
/*weight*/
timec = getNoZeroWeights(t);
w_star = ran_beta(1.0, (double) timec);
jacobi *= pow(1 - w_star, timec - 1);
f_wstar *= betad(w_star, 1.0, (double) timec);
weightratio *= (pow(w_star, alpha - 1) * pow(1 - w_star,
(double)timec * (alpha - 1)) / betaf(alpha, (double) timec * alpha));
/* This is a good choice for resetting the cluster indicators and weight parameter */
//two(i-1,clusterindex-1) = (1.0 - w_star) * weight(i-1,clusterindex-1);
child.weights[t] = w_star;
for(TreeContainer::iterator itor = MapClusterTrees.begin();
itor != MapClusterTrees.end(); itor++) {
if(itor->first != child.ID){
itor->second.weights[t] = (1.0 - w_star) * itor->second.weights[t];
}
}
/*weight relocated.*/
}
// Tree reset
// This step is implemented according to the weight setting.
/*std::cout<<"Birth"<<std::endl;
std::cout<<"weightratio"<<std::endl;
std::cout<<weightratio<<std::endl;
std::cout<<"Jacobi"<<std::endl;
std::cout<<jacobi<<std::endl;
std::cout<<"f_wstar"<<std::endl;
std::cout<<f_wstar<<std::endl;*/
UpToDate = false;
} else {
std::cout<<"This is an empty cluster!"<<std::endl;
std::cout<<"This cluster can not be splitted!"<<std::endl;
}
}
void MCMCEnv::flagDeath(const TreeMergeSet::value_type &merge_pair,
double &jacobi, double &weightratio, double &f_wstar) {
long mergeflag, leftflag;
long mergenum, leftnum;
long i,j,k;
double midw,midn;
jacobi = 1.0;
weightratio = 1.0;
f_wstar = 1.0;
ClusterTree &parent = getTreeFromID(merge_pair.first),
&child = getTreeFromID(merge_pair.second);
unsigned long time = child.getBornTime();
//// Mother
//leftflag = clusterindex1;
//// Son
//mergeflag = clusterindex2;
for(unsigned long t = time; t < child.getDeathTime(); t++){
midw = child.weights[t];
if(midw > SMALLNUM){
midn = getNoZeroWeights(t);
f_wstar *= betad(midw, 1.0, (double) midn);
weightratio *= (betaf(alpha, (double) (midn - 1) * alpha)
/ pow(midw, (alpha - 1.0))
/ pow(1.0 - midw, (double) (midn - 1) * (alpha - 1.0)));
jacobi *= pow(1.0 - midw, -1.0 * (double) (midn - 2));
for(TreeContainer::iterator itor = MapClusterTrees.begin();
itor != MapClusterTrees.end(); itor++) {
if(itor->first != child.ID){
itor->second.weights[t] = itor->second.weights[t] / (1.0 - midw);
}
}
}
// cluster indicator reloaded.
}
if(child.getBornTime()){
getTreeFromID(child.parentID).removeChild(time);
}
// remove child from its original parent
//child.parentID = 0; // reset the parentID of the child, mark it for deletion
try {
removeTree(child.ID);
} catch(std::logic_error &e) {
cerr << "Death" << endl;
throw e;
}
UpToDate = false;
/*std::cout<<"Death"<<std::endl;
std::cout<<"weightratio"<<std::endl;
std::cout<<weightratio<<std::endl;
std::cout<<"Jacobi"<<std::endl;
std::cout<<jacobi<<std::endl;
std::cout<<"f_wstar"<<std::endl;
std::cout<<f_wstar<<std::endl;*/
}
void MCMCEnv::flagTailBirth(const TreeSet::value_type &splitPair,
double &weightratio, double &jacobi, double &f_wstar) {
long j,k,n,timec;
double w_star;
jacobi = 1.0;
f_wstar = 1.0;
weightratio = 1.0;
// technically time should just be parent.getDeathTime();
ClusterTree &parent = getTreeFromID(splitPair.second);
unsigned long time = parent.getDeathTime();
parent.tailBirth();
if(time < NumOfTP) {
/*Justify whether clusterindex is an empty cluster.*/
//ClusterTree &child = (time? createTree(parent.ID, time): createTree());
for(unsigned long t = time; t < NumOfTP; t++){
/*weight*/
timec = getNoZeroWeights(t);
w_star = ran_beta(1.0, (double) timec);
jacobi *= pow(1 - w_star, timec - 1);
f_wstar *= betad(w_star, 1.0, (double) timec);
weightratio *= (pow(w_star, alpha - 1) * pow(1 - w_star,
(double)timec * (alpha - 1)) / betaf(alpha, (double) timec * alpha));
/* This is a good choice for resetting the cluster indicators and weight parameter */
//two(i-1,clusterindex-1) = (1.0 - w_star) * weight(i-1,clusterindex-1);
parent.weights[t] = w_star;
for(TreeContainer::iterator itor = MapClusterTrees.begin();
itor != MapClusterTrees.end(); itor++) {
if(itor->first != parent.ID){
itor->second.weights[t] = (1.0 - w_star) * itor->second.weights[t];
}
}
/*weight relocated.*/
}
// Tree reset
// This step is implemented according to the weight setting.
/*std::cout<<"Birth"<<std::endl;
std::cout<<"weightratio"<<std::endl;
std::cout<<weightratio<<std::endl;
std::cout<<"Jacobi"<<std::endl;
std::cout<<jacobi<<std::endl;
std::cout<<"f_wstar"<<std::endl;
std::cout<<f_wstar<<std::endl;*/
UpToDate = false;
} else {
std::cout<<"This is an empty cluster!"<<std::endl;
std::cout<<"This cluster can not be splitted!"<<std::endl;
}
}
void MCMCEnv::flagTailDeath(const TreeSet::value_type &death_set,
double &jacobi, double &weightratio, double &f_wstar) {
long mergeflag, leftflag;
long mergenum, leftnum;
long i,j,k;
double midw,midn;
jacobi = 1.0;
weightratio = 1.0;
f_wstar = 1.0;
ClusterTree &parent = getTreeFromID(death_set.second);
unsigned long time = death_set.first;
//// Mother
//leftflag = clusterindex1;
//// Son
//mergeflag = clusterindex2;
for(unsigned long t = time; t < parent.getDeathTime(); t++){
midw = parent.weights[t];
if(midw > SMALLNUM){
midn = getNoZeroWeights(t);
f_wstar *= betad(midw, 1.0, (double) midn);
weightratio *= (betaf(alpha, (double) (midn - 1) * alpha)
/ pow(midw, (alpha - 1.0))
/ pow(1.0 - midw, (double) (midn - 1) * (alpha - 1.0)));
jacobi *= pow(1.0 - midw, -1.0 * (double) (midn - 2));
for(TreeContainer::iterator itor = MapClusterTrees.begin();
itor != MapClusterTrees.end(); itor++) {
if(itor->first != parent.ID){
itor->second.weights[t] = itor->second.weights[t] / (1.0 - midw);
}
}
}
// cluster indicator reloaded.
}
// remove child from its original parent
//child.parentID = 0; // reset the parentID of the child, mark it for deletion
try {
parent.tailDeath(time);
} catch(std::logic_error &e) {
cerr << "Death" << endl;
throw e;
}
UpToDate = false;
/*std::cout<<"Death"<<std::endl;
std::cout<<"weightratio"<<std::endl;
std::cout<<weightratio<<std::endl;
std::cout<<"Jacobi"<<std::endl;
std::cout<<jacobi<<std::endl;
std::cout<<"f_wstar"<<std::endl;
std::cout<<f_wstar<<std::endl;*/
}
double MCMCEnv::calcLogDensity() const {
if(!UpToDate) {
long taonum = taoCount(Tao);
LogDensityValue = 0.0;
//LogDensityValueNonFlag = 0.0;
//LogDensityValueFlag = 0.0;
/*std::cout<<"taonum"<<std::endl;
std::cout<<taonum<<std::endl;*/
if((taonum > 0) && (taonum < NumOfGenes)){
//cerr << "datacov" << taonum << endl;
LogDensityValue += calcLogDensityNonFlagPart(taonum) + calcLogDensityFlagPart(taonum);
//for(flag=1; flag<=clusternum; flag++){
} else if(taonum==0){
LogDensityValue += calcLogDensityNonFlagPart(taonum);
} else {
LogDensityValue += calcLogDensityFlagPart(taonum);
}
UpToDate = true;
}
return LogDensityValue;
}
long MCMCEnv::taoCount(const TaoSet &newTao) const {
long taonum = 0;
for(unsigned long k = 0; k < NumOfGenes; k++){
taonum += (newTao[k])? 1: 0;
}
//cerr << "acceptedp" << endl;
return taonum;
}
long MCMCEnv::taoCount() const {
return taoCount(Tao);
}