-
Notifications
You must be signed in to change notification settings - Fork 2
/
time_estimate.cpp
2286 lines (2121 loc) · 77 KB
/
time_estimate.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
/**
* Standalone example of reading --enumerate output from `main` and `main-simple`.
*
* This example shows how to read the text format and construct the ARGraph class from it.
*
* Notes:
*
* 1) If data is enumerated from a VCF, the position and range values refer to VCF row numbers.
* If enumerating plain-text, the position and range values refer to column numbers.
*
* 2) All id values refer to unique IDs of the nodes (32bit unsigned int). The root node has always id 0.
* Leaf nodes are represented by id value in range from 1 to the total number of leaves.
*
* Small usage example:
* ./main --input test.input --plaintext --verbose --debug --no-prediction --enumerate | ./time_estimate
*
* For large data, you need to recompile all the software with compiler optimizations (`-O2 -DNDEBUG` recommended)
* and use commandline options e.g.
*
* ./main --input <(zcat large.vcf.gz) --vcf --verbose --no-prediction --enumerate | ./time_estimate
*
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <utility>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <limits>
#include <random>
using namespace std;
// Note: disable this for large inputs
#define VALIDATE_STRUCTURE
// Enable this to output range distributions (per node and total sum)
//#define OUTPUT_RANGE_DISTRIBUTION
typedef unsigned NodeId;
typedef unsigned ChildId;
typedef unsigned Position;
// Example class structure to be constructed
class ARGraph
{
public:
void PrintARG(){
for (unsigned i = 0; i < nodes.size(); i++){
cerr << "id = " << i;
for (unsigned j = 0; j < nodes[i].child.size(); j++){
cerr << "\t" << nodes[i].child[j].id;
}
cerr << endl;
}
}
struct ReportTMP{
double time, weight;
Position pos;
};
struct ARGchild
{
NodeId id; // Unique ID of the node; 0 == root
Position lRange; // Range corresponds to VCF row numbers
Position rRange;
Position lbp; // Range over bp's
Position rbp;
bool include;
bool recomb; // Was cut at position rRange due to recomb
ARGchild()
: id(0), lRange(0), rRange(0), include(true), recomb(false)
{ }
};
struct Edge
{
unsigned childRef;
double weight;
double nevents;
};
struct Mutation
{
ChildId id; // id points to the child array
Position pos;
Position bp; // Position as bp's
Mutation(ChildId id_, Position pos_, Position bp_)
: id(id_), pos(pos_), bp(bp_)
{ }
};
class ARNode
{
public:
enum event_t { mutation_event = 0, insert_child_event, delete_child_event };
vector<struct ARGchild> child;
map<Position,NodeId> parent;
vector<struct Mutation> mutation;
#ifdef OUTPUT_RANGE_DISTRIBUTION
map<unsigned,unsigned> rangeDist;
#endif
bool edgesKnown;
map<NodeId, pair<double, double> > edgesCh;
map<NodeId, pair<double, double> > edgesP;
unsigned edgesChNum, edgesPNum;
unsigned childToCheck;
double timestamp;
bool inStack;
bool timeAssigned;
int popl_count;
int popr_count;
unsigned long total_npairs;
//TODO set node range at the construction lNodeRange = min rangeMode?child.lbp:child.lRange over all child nodes
unsigned lNodeRange, rNodeRange;
unsigned sliceDegree;
bool inComponent;
unsigned idInSlice;
unsigned clustId;
bool reached, reset;
double weight;
double cumulTime, cumulWeight;
vector< ReportTMP > timeDistr;
ARNode()
: child(), mutation(), edgesKnown(false), edgesChNum(0), edgesPNum(0), childToCheck(0), timestamp(-1.0), inStack(false), timeAssigned(false), popl_count(0), popr_count(0), total_npairs(0), sliceDegree(0), inComponent(false), clustId(0), reached(false), reset(true), weight(1.0), cumulTime(0), cumulWeight(0)
{ }
// Return parent node at step i and next rRange
pair<NodeId,Position> getParent(Position i)
{
map<Position,NodeId>::iterator z = parent.lower_bound(i);
assert (z != parent.end());
return make_pair(z->second, z->first);
}
//Return value: first of each pair is event type: mutation - 0, inserte child - 1, delete child - 2; second of each pair is a pointer to event: if mutation - index in ARNode.mutation, otherwise index in ARNode.child
vector<pair<event_t,unsigned> > getEvents()
{
vector<pair<event_t,unsigned> > events;
for( size_t i = 0; i < mutation.size(); i++ )
if ( child[mutation[i].id].include )//TODO - prevents from compiling due to referring to "ARGraph.nodes" instead of "ARNode.child"
events.push_back(std::make_pair(mutation_event, i));
for( size_t i = 0; i < child.size(); i++ )
if (child[i].include)
{
events.push_back(std::make_pair(insert_child_event, i));
events.push_back(std::make_pair(delete_child_event, i));
}
std::sort(events.begin(), events.end(), compareEvents(this) );
return events;
}
unsigned getPosition(const pair<event_t,unsigned> &ev)
{
switch (ev.first)
{
case mutation_event:
return rangeMode?mutation[ev.second].bp:mutation[ev.second].pos;
case insert_child_event:
return rangeMode?child[ev.second].lbp:child[ev.second].lRange;
case delete_child_event:
return ( rangeMode?child[ev.second].rbp:child[ev.second].rRange ) + 1;
default:
assert (0);
}
return 0;
}
unsigned getID(const pair<event_t,unsigned> &ev)
{
switch (ev.first)
{
case mutation_event:
return child[mutation[ev.second].id].id;
case insert_child_event:
return child[ev.second].id;
case delete_child_event:
return child[ev.second].id;
default:
assert (0);
}
return 0;
}
struct compareEvents : std::binary_function<pair<event_t,unsigned>,pair<event_t,unsigned>,bool>
{
compareEvents(ARNode * p)
: instance(p)
{ }
bool operator() (const pair<event_t,unsigned>& o1, const pair<event_t,unsigned>& o2) {
return instance->compareEvents_(o1, o2);
}
ARNode * instance;
};
bool compareEvents_(const pair<event_t,unsigned> &e1, const pair<event_t,unsigned> &e2)
{
unsigned pos1, pos2;
pos1 = getPosition(e1);
pos2 = getPosition(e2);
return pos1 < pos2;
}
};
ARGraph()
: nodes(), knuthShuffle(), nleaves(0), rRangeMax(0), rbpMax(0), ok_(true), mu(0.00000001), rho(0.00000001)
{
ok_ = construct();
}
void SetRangeMode(bool mode){
rangeMode = mode;
cerr << "Ranges are measured in ";
if (mode)
cerr << "BP (basepairs).";
else
cerr << "SNP (positions).";
cerr << endl;
}
bool ok() const
{ return ok_; }
bool validate()
{
if (!ok())
return false;
// Validate the data structure
// here
assert (nleaves > 0);
#ifdef VALIDATE_STRUCTURE
cerr << "warning: VALIDATE_STRUCTURE was defined in time_estimate.cpp; validating data structure now, which can take large amount of time on large inputs." << endl;
for (Position i = 0; i <= rRangeMax; i++)
if (!traverseCol(i))
return false;
#else
cerr << "warning: VALIDATE_STRUCTURE was not defined; no validation performed" << endl;
#endif
return true;
}
void SetSlice(Position lSlice, Position rSlice, double mint = -1.0, double maxt = -1.0){
lSliceRange = lSlice;
rSliceRange = rSlice;
min_time = mint;
max_time = maxt;
if (max_time != -1.0 && min_time >= max_time){
cerr << "Error in ARGraph::SetSlice(): max_time (" << max_time << ") < min_time (" << min_time << ")" << endl;
exit(0);
}
setNodeRanges();
for (vector< ARNode >::iterator it = nodes.begin(); it != nodes.end(); ++it){
NodeId nodeRef = it - nodes.begin();
if ( isInSlice( nodeRef ) ){
nodes[nodeRef].idInSlice = SliceNodes.size();
SliceNodes.push_back(nodeRef);
}
}
}
bool isInSlice(NodeId nodeRef){
unsigned leftR = nodes[nodeRef].lNodeRange;
unsigned rightR = nodes[nodeRef].rNodeRange;
if (rightR < lSliceRange)
return false;
if (rSliceRange < leftR)
return false;
if (nodes[nodeRef].timestamp <= min_time)
return false;
if (max_time != -1.0 && max_time < nodes[nodeRef].timestamp)
return false;
return true;
}
void setNodeRanges(){
for (vector< ARNode >::iterator it = nodes.begin(); it != nodes.end(); ++it){
bool printEnable = false;
if (it - nodes.begin() == 604 && false)
printEnable = true;
it->lNodeRange = rangeMode?rbpMax:rRangeMax + 2;
it->rNodeRange = 0;
if (it->child.size() == 0){
it->lNodeRange = 0;
it->rNodeRange = rangeMode?rbpMax:rRangeMax + 1;
}
for (vector< ARGchild >::iterator itt = it->child.begin(); itt != it->child.end(); ++itt){
if (printEnable){
Position tmp1 = rangeMode?itt->lbp:itt->lRange;
Position tmp2 = rangeMode?itt->rbp:itt->rRange;
cerr << "chRange: " << tmp1 << "\t" << tmp2 << endl;
}
if ( it->lNodeRange > (rangeMode?itt->lbp:itt->lRange) ){
if (printEnable) cerr << "lRange update from " << it->lNodeRange;
it->lNodeRange = rangeMode?itt->lbp:itt->lRange;
if (printEnable) cerr << "\tto " << it->lNodeRange << endl;
}
if ( it->rNodeRange < (rangeMode?itt->rbp:itt->rRange) ){
if (printEnable) cerr << "lRange update from " << it->rNodeRange;
it->rNodeRange = rangeMode?itt->rbp:itt->rRange;
if (printEnable) cerr << "\tto " << it->rNodeRange << endl;
}
}
if (printEnable) cerr << "Range: " << it->lNodeRange << "\t" << it->rNodeRange << endl;
}
}
unsigned VisitComponent(NodeId nodeRef, bool output = false){
static unsigned nodesInComponents = 0;
unsigned nodesInOtherComponents = nodesInComponents;
nodesInComponents++;
nodes[nodeRef].inComponent = true;
for (map<NodeId, pair<double, double> >::iterator it = nodes[ nodeRef ].edgesCh.begin(); it != nodes[ nodeRef ].edgesCh.end(); ++it){
if ( !isInSlice(it->first) )
continue;
if (output)
cout << nodes[nodeRef].idInSlice << "\t" << nodes[it->first].idInSlice << "\t1\n";
if ( !nodes[it->first].inComponent )
VisitComponent(it->first, output);
}
for (map<NodeId, pair<double, double> >::iterator it = nodes[ nodeRef ].edgesP.begin(); it != nodes[ nodeRef ].edgesP.end(); ++it){
if ( !isInSlice(it->first) )
continue;
if ( !nodes[it->first].inComponent )
VisitComponent(it->first, output);
}
return nodesInComponents - nodesInOtherComponents;
}
NodeId CheckConnectedness(bool output = false){
unsigned NumComponents = 0;
unsigned maxSize = 0;
NodeId nodeSeed = 0;
for (std::vector< NodeId >::iterator it = SliceNodes.begin(); it != SliceNodes.end(); ++it){
if ( nodes[*it].inComponent )
continue;
if (output)
cout << "Component " << NumComponents << endl;
NumComponents++;
unsigned componentSize = VisitComponent( *it, output );
if (maxSize < componentSize){
maxSize = componentSize;
nodeSeed = *it;
}
cerr << "Component contains " << componentSize << " nodes." << endl;
}
cerr << "Number of components found: " << NumComponents << endl;
cerr << "Total number of nodes in the slice " << SliceNodes.size() << endl;
return nodeSeed;
}
void ResetComponents(){
for (std::vector< NodeId >::iterator it = SliceNodes.begin(); it != SliceNodes.end(); ++it)
nodes[*it].inComponent = false;
}
void OutputSlice(){
cout << "Slice nodes" << endl;
for (std::vector< NodeId >::iterator it = SliceNodes.begin(); it != SliceNodes.end(); ++it)
cout << *it << "\t" << nodes[*it].idInSlice << "\t" << nodes[*it].timestamp << "\t" << nodes[*it].lNodeRange << "\t" << nodes[*it].rNodeRange << endl;
}
unsigned ReadClust(){
int nentries;
NodeId nId;
unsigned clust;
unsigned clustNum = 0;
cin >> nentries;
cerr << "Reading " << nentries << " cluster entries." << endl;
while (nentries--)
{
// Read parent header
cin >> nId;
cin >> clust;
nodes[nId].clustId = clust;
if (clustNum < clust)
clustNum = clust;
}
return clustNum;
}
class PaintChunk{
public:
NodeId hap;
Position lRange, rRange;
NodeId nodeRef;
PaintChunk(NodeId h){
hap = h;
}
void Set(unsigned lr, unsigned rr, NodeId nid){
lRange = lr;
rRange = rr;
nodeRef = nid;
}
};
void PaintHaplotype(NodeId hap, vector< PaintChunk > &chunks){
vector< PaintChunk > chunksStack;
PaintChunk chu(hap), curChu(hap), chuTmp(hap);
curChu.Set(lSliceRange, rSliceRange, hap);
chunksStack.push_back(curChu);
while( chunksStack.size() ){
curChu = chunksStack.back();
chunksStack.pop_back();
for (std::map<NodeId, std::pair<double, double> >::iterator it = nodes[curChu.nodeRef].edgesP.begin(); it != nodes[curChu.nodeRef].edgesP.end(); ++it){
Position lr = rSliceRange+1, rr = rSliceRange+1;
for (vector< ARGchild >::iterator itt = nodes[it->first].child.begin(); itt != nodes[it->first].child.end(); ++itt){
if(itt->id == curChu.nodeRef){
lr = itt->lbp;
rr = itt->rbp;
break;
}
}
if (rr < curChu.lRange || lr > curChu.rRange)
continue;
else{
lr = lr>curChu.lRange?lr:curChu.lRange;
rr = rr<curChu.rRange?rr:curChu.rRange;
}
chuTmp.Set(lr, rr, it->first);
if (nodes[it->first].clustId == 0){
chunksStack.push_back(chuTmp);
}
else{
chunks.push_back(chuTmp);
}
}
}
}
void PaintHaps(unsigned clustNum){
vector< PaintChunk > chunks;
cerr << "Painting haplotypes..." << endl;
unsigned inClustNodes = 0;
for (vector< ARNode >::iterator it = nodes.begin(); it != nodes.end(); ++it){
if (it->clustId != 0)
inClustNodes++;
}
cout << "Number of nodes in clusters: " << inClustNodes << endl;
for (unsigned i = 1; i <= nleaves; i++)
PaintHaplotype(i, chunks);
cout << "Total number of chunks: " << chunks.size() << endl;
vector<double> fin, gbr, sar;
vector<unsigned> clustSize;
// double fin[4], gbr[4], sar[4];
for (unsigned i = 0; i < clustNum + 1; i++){
fin.push_back(0);
gbr.push_back(0);
sar.push_back(0);
clustSize.push_back(0);
}
/* for (int j = 0; j < 4; j++){
fin[j] = 0; gbr[j] = 0; sar[j] = 0;
}*/
for (vector< PaintChunk >::iterator it = chunks.begin(); it != chunks.end(); ++it){
if (it->hap <= 2000)
fin[ nodes[it->nodeRef].clustId ] += (it->rRange - it->lRange);
if (2001 <= it->hap && it->hap <= 4000)
gbr[ nodes[it->nodeRef].clustId ] += (it->rRange - it->lRange);
if (4001 <= it->hap)
sar[ nodes[it->nodeRef].clustId ] += (it->rRange - it->lRange);
}
for (vector< ARNode >::iterator it = nodes.begin(); it != nodes.end(); ++it){
clustSize[it->clustId]++;
}
for (int i = 0; i < clustNum + 1; i++)
cout << clustSize[i] << "\t";
cout << endl;
double sum = 0;
for (unsigned i = 0; i < clustNum + 1; i++)
sum += fin[i];
sum = sum==0?1:sum;
for (int i = 0; i < clustNum + 1; i++)
cout << fin[i]/(fin[i]+gbr[i]+sar[i]) << "\t";
cout << endl;
sum = 0;
for (unsigned i = 0; i < clustNum + 1; i++)
sum += gbr[i];
sum = sum==0?1:sum;
for (int i = 0; i < clustNum + 1; i++)
cout << gbr[i]/(fin[i]+gbr[i]+sar[i]) << "\t";
cout << endl;
sum = 0;
for (unsigned i = 0; i < clustNum + 1; i++)
sum += sar[i];
sum = sum==0?1:sum;
for (int i = 0; i < clustNum + 1; i++)
cout << sar[i]/(fin[i]+gbr[i]+sar[i]) << "\t";
cout << endl;
}
void NodeImpactDistribution(string filename, unsigned npop, double t_min, double t_max, bool allLeaves = true, double sampleRate = 0.01){
vector<bool> leaves;
vector<unsigned> pops;
unsigned selectedNodes = 0;
unsigned eligibleNodes = 0;
ofstream fh;
fh.open(filename.c_str());
cerr << "NodeImpactDistribution() called" << endl;
if (nleaves % npop != 0){
cerr << "nleaves is not devisible by npop" << endl;
exit(0);
}
ComputeWeights();
for (unsigned i = 0; i < nleaves; i++)
leaves.push_back(false);
DebugReset(leaves);
for (unsigned i = 0; i < npop; i++)
pops.push_back(0);
for (vector< ARNode >::iterator it = nodes.begin() + nleaves + 1; it != nodes.end(); ++it){
if (it->timestamp < t_min || (t_max != -1 && it->timestamp > t_max) )
continue;
if (it->lNodeRange > rSliceRange || it->rNodeRange < lSliceRange)
continue;
eligibleNodes++;
if (rand() % 1 > sampleRate)
continue;
selectedNodes++;
if (selectedNodes % 10000 == 0)
cerr << selectedNodes << " nodes processed for impact." << endl;
FindReachableLeaves( it - nodes.begin(), leaves, allLeaves );
unsigned sum = ComputePopImpact( leaves, npop, pops );
fh << it - nodes.begin() << "\t" << sum ;
for (unsigned i = 0; i < npop; i++){
fh << "\t" << double(pops[i])/double(sum);
}
fh << "\t" << it->weight << "\t" << it->timestamp;
fh << "\n";
ResetFlagsReachableLeaves( it - nodes.begin(), leaves );
DebugReset(leaves);
for (unsigned i = 0; i < npop; i++)
pops[i] = 0;
}
fh.close();
cerr << selectedNodes << " nodes sampled for node impact distribution out of " << eligibleNodes << "within time period " << t_min << " to " << t_max << "." << endl;
}
// gunzip -c data/hrc_chr20_ARG_subset.txt.gz | ./time_estimate 0 1 200 1 100 2 ... > tmp.txt
void DebugReset(vector<bool>& leaves){
for (vector< ARNode >::iterator it = nodes.begin(); it != nodes.end(); ++it){
if ( it->reached ){
cerr << "reached not reset" << endl ;
exit(0);
}
if ( !it->reset ){
cerr << "reset not reset" << endl ;
exit(0);
}
}
for (unsigned i = 0; i < nleaves; i++){
if ( leaves[i] ){
cerr << i << " id, " << leaves[i] << endl;
cerr << "leaf not reset" << endl ;
exit(0);
}
}
}
unsigned ComputePopImpact( vector<bool>& leaves, unsigned npop, vector<unsigned>& pops ){
unsigned sum = 0;
for (unsigned i = 0; i < nleaves; i++){
if (!leaves[i])
continue;
unsigned popSize = nleaves/npop;
unsigned j = i/popSize;
if (j >= npop ){
cerr << "ComputePopImpact() segmentation fault." << endl;
cerr << "leaf id-1 = " << i << "\tpopulation id " << j << endl;
exit(0);
}
pops[j]++;
sum++;
}
return sum;
}
void FindReachableLeaves( NodeId nodeRef, vector<bool>& leaves, bool allLeaves){
vector<NodeId> stack;
stack.push_back(nodeRef);
nodes[nodeRef].reached = true;
nodes[nodeRef].reset = false;
unsigned lr = nodes[nodeRef].lNodeRange;
unsigned rr = nodes[nodeRef].rNodeRange;
bool printEnabled = false;
if (nodeRef == 831 && false)
printEnabled = true;
while( stack.size() ){
NodeId curNode = stack.back();
if ( printEnabled )
cerr << curNode << endl;
stack.pop_back();
for (vector< ARGchild >::iterator itt = nodes[curNode].child.begin(); itt != nodes[curNode].child.end(); ++itt){
if ( printEnabled ){
cerr << "\t" << itt->id << "\t" << nodes[itt->id].reached << endl;
cerr << "\t\t" << nodes[itt->id].lNodeRange << "\t" << nodes[itt->id].rNodeRange << endl;
cerr << "\t\t" << lr << "\t" << rr << endl;
}
if (itt->id <= nleaves && itt->id != 0){
leaves[itt->id - 1] = true;
continue;
}
if (!allLeaves){
if ( nodes[itt->id].lNodeRange > rr || nodes[itt->id].rNodeRange < lr)
continue;
}
if (nodes[itt->id].reached)
continue;
stack.push_back(itt->id);
nodes[itt->id].reached = true;
nodes[itt->id].reset = false;
}
}
}
void ResetFlagsReachableLeaves( NodeId nodeRef, vector<bool>& leaves ){
vector<NodeId> stack;
stack.push_back(nodeRef);
nodes[nodeRef].reached = false;
nodes[nodeRef].reset = true;
while( stack.size() ){
NodeId curNode = stack.back();
stack.pop_back();
for (vector< ARGchild >::iterator itt = nodes[curNode].child.begin(); itt != nodes[curNode].child.end(); ++itt){
if (itt->id <= nleaves && itt->id != 0){
leaves[itt->id - 1] = false;
continue;
}
if (nodes[itt->id].reset)
continue;
stack.push_back(itt->id);
nodes[itt->id].reached = false;
nodes[itt->id].reset = true;
}
}
}
void PrintEnumerateARG(){
cout << "ARGraph\t" << nleaves << "\t" << nodes.size() - 1 << "\t" << nodes.size() << "\n";
for (vector< ARNode >::iterator it = nodes.begin() + 1; it != nodes.end(); ++it){
NodeId curNode = it - nodes.begin();
cout << "parent\t" << curNode << "\t" << it->child.size() << "\t" << it->mutation.size() << "\n";
for (vector< ARGchild >::iterator itt = nodes[curNode].child.begin(); itt != nodes[curNode].child.end(); ++itt){
cout << "child\t" << itt->id << "\t" << itt->lRange << "\t" << itt->rRange << "\t" << itt->lbp << "\t" << itt->rbp << "\t" << itt->recomb << "\n";
}
for (vector< Mutation >::iterator itt = it->mutation.begin(); itt != it->mutation.end(); ++itt){
cout << "mutation\t" << it->child[itt->id].id << "\t" << itt->pos << "\t" << itt->bp << "\n";
}
}
}
void PrintSLE(){
cerr << "Number of variables: " << nodes.size() - 1 - nleaves << endl;
cout << "parent\tchild\tx" << endl;
for (vector< ARNode >::iterator it = nodes.begin() + 1 + nleaves; it != nodes.end(); ++it){
NodeId nodeRef = it - nodes.begin();
for (map<NodeId, pair<double, double> >::iterator cht = it->edgesCh.begin(); cht != it->edgesCh.end(); ++cht){
unsigned chId;
if (cht->first > nleaves)
chId = cht->first - nleaves;
else
chId = 0;
cout << nodeRef - nleaves << "\t" << chId << "\t" << cht->second.first/cht->second.second << endl;
}
}
}
struct tree_node{
NodeId arg_id;
vector <unsigned> edges;
};
struct tree_edge{
// unsigned parent;
unsigned child;
double events;
double weight;
};
pair<unsigned, unsigned> SampleLocalTree(std::default_random_engine& generator){
// std::default_random_engine generator;
// generator.seed(time(NULL));
std::exponential_distribution<double> exp_distr(0.1);
static unsigned fail = 0, success = 0;
for (vector<tree_node>::reverse_iterator it = treeNodes.rbegin(); it != treeNodes.rend(); ++it){
if ( it->arg_id <= nleaves && it->arg_id != 0)
continue;
double alpha = 0;
double beta = 1;
double t = 0;
double totalWeight = 0;
double minTime = 0;
for (vector<unsigned>::iterator et = it->edges.begin(); et != it->edges.end(); ++et){
NodeId childId = treeEdges[*et].child;
alpha += treeEdges[*et].events;
t += nodes[childId].timestamp*treeEdges[*et].weight;
totalWeight += treeEdges[*et].weight;
if (minTime < nodes[childId].timestamp)
minTime = nodes[childId].timestamp;
}
assert(it->edges.size() > 0);
assert(totalWeight > 0);
t = t/totalWeight;
bool flag = false;
if(minTime <= t + 100*alpha/totalWeight){
unsigned counter = 0;
std::gamma_distribution<double> gamma_distr(alpha, beta);
nodes[it->arg_id].timestamp = minTime;
while( nodes[it->arg_id].timestamp <= minTime ){
if (counter == 5000){
flag = true;
break;
}
nodes[it->arg_id].timestamp = t + gamma_distr(generator)/totalWeight;
counter++;
}
if(!flag)
success++;
}
else
flag = true;
if (flag){
nodes[it->arg_id].timestamp = minTime + exp_distr(generator)/totalWeight;
fail++;
}
}
return make_pair(success, fail);
}
pair<unsigned, unsigned> TreeSampler(unsigned rep, std::default_random_engine& generator, Position pos){
static unsigned fail = 0, success = 0;
unsigned treeProbNull = 0, treeProbNotNull = 0;
for (unsigned i = 0; i < rep; i++){
pair<unsigned, unsigned> fs = SampleLocalTree(generator);
success += fs.first;
fail += fs.second;
double treeProb = 1;
bool fTmp = false;
NodeId checkNode = 573;
for (vector<tree_node>::iterator it = treeNodes.begin(); it != treeNodes.end(); ++it){
// if ( it->arg_id <= nleaves && it->arg_id != 0)
// continue;
double parentTime = nodes[it->arg_id].timestamp;
for (vector<unsigned>::iterator et = it->edges.begin(); et != it->edges.end(); ++et){
NodeId childId = treeEdges[*et].child;
double childTime = nodes[childId].timestamp;
if (childTime >= parentTime){
cerr << "id = " << it->arg_id << endl;
cerr << "childId = " << childId << endl;
cerr << "childTime = " << childTime << endl;
cerr << "parentTime = " << parentTime << endl;
exit(1);
}
assert(parentTime - childTime >= 0);
double lambda = (parentTime - childTime)*treeEdges[*et].weight;
treeProb = treeProb*Pois(lambda, treeEdges[*et].events);
}
if (it->arg_id == checkNode){
fTmp = true;
}
}
if (fTmp && false){
ReportTMP r;
r.time = nodes[checkNode].timestamp;
r.weight = treeProb;
r.pos = pos;
nodes[checkNode].timeDistr.push_back(r);
}
if(treeProb == 0)
treeProbNull++;
else
treeProbNotNull++;
for (vector<tree_node>::iterator it = treeNodes.begin(); it != treeNodes.end(); ++it){
nodes[it->arg_id].cumulTime += nodes[it->arg_id].timestamp*treeProb;
nodes[it->arg_id].cumulWeight += treeProb;
}
}
return make_pair(success, fail);
}
void EstimateTimesByLocalTrees(unsigned rep){
unsigned fail = 0, success = 0;
unsigned counter = 0;
std::default_random_engine generator;
for (unsigned i = 0; i < rRangeMax; i++){
counter++;
if (counter%10000 == 0)
cerr << counter << " positions processed." << endl;
GetLocalTree( i );
pair<unsigned, unsigned> fs = TreeSampler(rep, generator, i);
success += fs.first;
fail += fs.second;
}
nodes[0].timestamp = -1;
for (vector< ARNode >::iterator it = nodes.begin() + 1 + nleaves; it != nodes.end(); ++it){
assert(!isnan(it->cumulWeight));
it->timestamp = it->cumulTime/it->cumulWeight;
}
// NodeId checkNode = 573;
// cout << "Times sampled: " << nodes[checkNode].timeDistr.size() << endl;
// for (vector< ReportTMP >::iterator pt = nodes[checkNode].timeDistr.begin(); pt != nodes[checkNode].timeDistr.end(); ++pt){
// cout << pt->pos << "\t" << pt->time << "\t" << pt->weight << endl;
// }
cerr << "Sampled with gamma: " << success << endl;
cerr << "Sampled with exp: " << fail << endl;
}
double Pois(double lambda, double k){
double prob = pow(lambda, k);
prob = prob*exp(-lambda);
prob = prob/tgamma(k+1);
return prob;
}
void GetLocalTree(Position position){
tree_node node;
tree_edge edge;
map<NodeId, unsigned> nodesMap;
// vector <NodeId> nodes;
treeNodes.clear();
treeEdges.clear();
vector<NodeId> stack;
double penalty = 1.0;
double recombWeight = double(nmutation)/double(nrecomb)*rho/mu*penalty;
static bool flagTmp = true;
if (flagTmp){
cerr << "rho = " << rho << endl;
cerr << "event rate = " << mu+rho*penalty << endl;
}
flagTmp = false;
/* for (unsigned i = 0; i < nleaves; i++){
node.arg_id = i + 1;
tree_nodes.push_back(node);
}*/
stack.push_back(0);
node.arg_id = 0;
node.edges.clear();
treeNodes.push_back(node);
nodesMap[0] = 0;
while(stack.size() > 0){
NodeId curNode = stack.back();
stack.pop_back();
for (vector< ARGchild >::iterator cht = nodes[curNode].child.begin(); cht != nodes[curNode].child.end(); ++cht){
if (position >= cht->lRange && position <= cht->rRange){
node.edges.clear();
// nodes[cht->id] = nodes.size();
node.arg_id = cht->id;
// edge.parent = curNode;
edge.child = cht->id;
double eventNum = 0;
for (vector<struct Mutation>::iterator mut = nodes[curNode].mutation.begin(); mut != nodes[curNode].mutation.end(); ++mut){
if (nodes[curNode].child[mut->id].id == cht->id)
eventNum++;
}
if (cht->recomb)
eventNum += recombWeight;
edge.events = eventNum;
edge.weight = (mu+rho*penalty)*(cht->rbp - cht->lbp + 1);
stack.push_back(cht->id);
treeNodes.push_back(node);
nodesMap[cht->id] = treeNodes.size() - 1;
treeEdges.push_back(edge);
treeNodes[ nodesMap[curNode] ].edges.push_back(treeEdges.size() - 1);
}
}
}
}
void PrintLocalTree(Position pos){
GetLocalTree(pos);
for (vector<tree_node>::iterator it = treeNodes.begin(); it != treeNodes.end(); ++it){
cout << it->arg_id << "\t" << nodes[it->arg_id].timestamp << endl;
for (vector<unsigned>::iterator et = it->edges.begin(); et != it->edges.end(); ++et)
cout << "\t" << treeEdges[*et].child << "\t" << treeEdges[*et].weight << "\t" << treeEdges[*et].events << endl;
}
}
Position GetPosbyNodeId(NodeId nid){
Position pos = 0;
for (vector< ARGchild >::iterator itt = nodes[nid].child.begin(); itt != nodes[nid].child.end(); ++itt){
pos = (itt->rRange + itt->lRange)/2;
break;
}
return pos;
}
void PrintNode(NodeId nid){
for (vector< ARGchild >::iterator itt = nodes[nid].child.begin(); itt != nodes[nid].child.end(); ++itt)
cerr << itt->id << "\t" << itt->lRange << "\t" << itt->rRange << endl;
}
void assignTimes(int method)
{
std::vector<NodeId> nodeStack;
nodeStack.push_back(0); //root node
while( nodeStack.size() )
{
NodeId nodeRef = nodeStack.back();
if( nodes[ nodeRef ].childToCheck == nodes[ nodeRef ].child.size() )
{
switch(method){
case 1:
assignTime(nodeRef);
break;
case 2:
assignTime2(nodeRef);
break;
default:
cerr << "Unknown assign time method." << endl;
exit(0);
break;
}
nodes[ nodeRef ].timeAssigned = true;
nodes[ nodeRef ].inStack = false;
nodeStack.pop_back();
}
else
{
NodeId childRef = nodes[ nodeRef ].child[ nodes[nodeRef].childToCheck ].id;
nodes[nodeRef].childToCheck++;
if (nodes[childRef].timeAssigned)
continue;
if ( nodes[childRef].inStack )
{
size_t i = nodeStack.size();
do
{
i--;
NodeId n = nodeStack[i];
nodes[n].child[ nodes[n].childToCheck - 1 ].include = false;
} while(i > 0 && nodeStack[i] != childRef);
}
else
{
nodeStack.push_back(childRef);
nodes[childRef].inStack = true;
}
}
}
}
void iterateTimes(bool output, bool keep_order)//1 for f1, 2 for f2, 3 for f3
{
// Initialize Knuth shuffle on first call to this method
if (knuthShuffle.empty())
{
knuthShuffle.resize(nodes.size());
for (unsigned i = 0; i < nodes.size(); ++i)
knuthShuffle[i] = i;
}
// Knuth shuffle
assert (knuthShuffle.size() == nodes.size());
for (unsigned i = 1; i < nodes.size(); ++i)
{
unsigned j = rand() % (nodes.size()-1) + 1; // Not to Skip root
unsigned tmp = knuthShuffle[i];
knuthShuffle[i] = knuthShuffle[j]; // Swap values
knuthShuffle[j] = tmp;
}
it_norm_abs = 0.0;
NodeId it_norm_abs_node = 0;
it_norm_rel = 0.0;
NodeId it_norm_rel_node = 0;
mean_abs_change = 0.0;
mean_rel_change = 0.0;
for (unsigned i = 1; i < nodes.size(); ++i){
NodeId nodeRef = knuthShuffle[i];
double old_time = nodes[nodeRef].timestamp;
UpdateTime(nodeRef, keep_order);
double abs_change = nodes[nodeRef].timestamp - old_time;
double rel_change = 0;
if (nodes[nodeRef].timestamp != 0)
rel_change = abs(nodes[nodeRef].timestamp - old_time)/old_time;
mean_abs_change += abs(abs_change);
mean_rel_change += rel_change;
if ( abs(abs_change) > abs(it_norm_abs) ){
it_norm_abs = abs_change;
it_norm_abs_node = i;
}