-
Notifications
You must be signed in to change notification settings - Fork 6
/
algorithm.cpp
1485 lines (1427 loc) · 65 KB
/
algorithm.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
/**
Copyright 2019 Gary K. Chen ([email protected])
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
#include<iostream>
#include<math.h>
#include<iomanip>
#include<time.h>
#include "simulator.h"
using namespace std;
EdgePtr GraphBuilder::getRandomEdgeOnTree(double & dSplitPoint,
double dRandomSpot){
if (this->bEndGeneConversion && dSplitPoint!=-1.){
dSplitPoint = gcNewEdge->getBottomNodeRef()->getHeight()+0.;
return this->gcNewEdge;
}
bool found = false;
double dRunningLength = 0.0;
EdgePtrVector::iterator it = pEdgeVectorInTree->begin();
EdgePtr curEdge;
// the linked list of tree edges are lined up so that a uniform point
// on the tree can be selected for where the crossover occurs
unsigned int counter=0;
while(!found && counter<iTotalTreeEdges){
curEdge = *it;
if (!curEdge->bDeleted){
if (dRandomSpot<dRunningLength+curEdge->getLength()){
// the random spot is within the current segment
// the reference var splitpoint returns the position
// relative to the bottom of this edge that the xover
// occurs
dSplitPoint = curEdge->getBottomNodeRef()->getHeight()+
(dRandomSpot - dRunningLength);
found = true;
}else{
dRunningLength+=curEdge->getLength();
//if (pConfig->bDebug){
//cerr<<"getRandomEdge: running length: "<<dRunningLength<<", random spot "<<dRandomSpot<<"\n";
//}
}
}else{
//if (pConfig->bDebug){
//cerr<<"getRandomEdge: Sorry edge was deleted\n";
//}
}
++counter;
++it;
}
if (!found) throw "RandomSpot was out of range for xover";
return curEdge;
}
EdgePtr GraphBuilder::getRandomEdgeToCoalesce(EdgePtr & coalescingEdge,
double dHeight){
if (this->bEndGeneConversion){
return this->gcOldEdge;
}
int iPopulation = coalescingEdge->getBottomNodeRef()->getPopulation();
EdgePtrVector & pEdgeVector = this->pEdgeVectorByPop->at(iPopulation);
EdgeIndexQueue & pVectorIndicesToRecycle = this->pVectorIndicesToRecycle->at(iPopulation);
unsigned int edgeVectorSize = pEdgeVector.size();
if (pConfig->bDebug){
cerr<<"getRandomEdgeToCoalesce: selecting population "<<iPopulation<<" with avail edges: "<< edgeVectorSize<<"\n";
}
bool found = false;
int iUnifPick =-1;
int out_of_range = 0,already_deleted=0;
while(!found){
// guessing by randomly selecting elements from the vector of graph
// edges appears to work pretty well here
iUnifPick = static_cast<int>(pRandNumGenerator->unifRV()*
edgeVectorSize);
EdgePtr edge = pEdgeVector[iUnifPick];
if (edge->bDeleted){
// if this is marked for deletion, take the opportunity
// to store the vector index in a queue so this element can
// recycled when a new edge is to be added
if (!edge->bInQueue){
pVectorIndicesToRecycle.push(iUnifPick);
edge->bInQueue = true;
}
if (pConfig->bDebug){
//cerr<<"getRandomEdgeToCoalesce: edge already deleted \n";
++already_deleted;
}
// if the proposed coalescing time is within the endpoints of this
// randomly picked edge, select this edge
}else if (edge->getBottomNodeRef()->getHeight()<dHeight
&& edge->getTopNodeRef()->getHeight()>dHeight) {
found = true;
}else{
if (pConfig->bDebug){
//cerr<<"getRandomEdgeToCoalesce: Edge out of range\n";
++out_of_range;
}
}
}
EdgePtr & edge = pEdgeVector[iUnifPick];
if (pConfig->bDebug){
cerr<<"Stats: out of range edges: "<<out_of_range<<" and already deleted: "<<already_deleted<<endl;
cerr<<"Edge to coalesce: "<<edge->getBottomNodeRef()->getHeight()<<" to "<<
edge->getTopNodeRef()->getHeight()<<endl;
}
return edge;
}
void GraphBuilder::mutateBelowEdge(EdgePtr & edge){
NodePtr & bottomNode = edge->getBottomNodeRef();
if (bottomNode->getType()==Node::SAMPLE ){
SampleNode* sample = static_cast<SampleNode*>(bottomNode.get());
// mark this sampled node as affected.
sample->bAffected = true;
}else{
for (unsigned int i=0;i<bottomNode->getBottomEdgeSize();++i){
#ifdef DIAG
if (bottomNode->getBottomEdgeByIndex(i)->bDeleted){
throw "Mutate below edge: this edge should have been removed";
}
#endif
EdgePtr edge = bottomNode->getBottomEdgeByIndex(i);
if (edge->iGraphIteration==iGraphIteration){
mutateBelowEdge(edge);
}
}
}
}
bool GraphBuilder::markEdgesAbove(bool bFirstSample,bool bCalledFromParent,
EdgePtr & selectedEdge, unsigned int & iSampleIndex){
if (bFirstSample || bCalledFromParent || !selectedEdge->bInCurrentTree){
if (!selectedEdge->bInCurrentTree) addEdgeToCurrentTree(selectedEdge);
NodePtr topNode = selectedEdge->getTopNodeRef();
double dTopHeight = topNode->getHeight();
double dproposedOriginHt = localMRCA->getHeight();
if (dTopHeight>=dproposedOriginHt &&
topNode->getType()==Node::COAL){
// If we reach at least as high as proposed MRCA
// save this edge as the vector
// so we don't traverse from the bottom
pTreeEdgesToCoalesceArray[iSampleIndex]=selectedEdge;
if (bFirstSample){
if (dTopHeight>dproposedOriginHt)
// establish a new proposed MRCA
// for susequent samples to try reaching
localMRCA = topNode;
// proceed to the next sampled node
return true;
}else{
if (dTopHeight>dproposedOriginHt){
// if we surpassed a MRCA height previously proposed
// upgrade the proposed MRCA height
localMRCA = topNode;
// start over in the loop to sample 0
return false;
}else{
if (localMRCA!=topNode){
cerr<<"proposed grandMRCA != top Node\n";
}
// here the current height is EQUAL to the proposed MRCA,
// this is good and we can proceed to the next sampled node
return true;
}
}
}
else{
// if we come across a crossover, there are two edges above,
// we choose the one with the more recent (larger) tree label
if (topNode->getType()==Node::XOVER){
EdgePtr edge0 =topNode->getTopEdgeByIndex(0);
EdgePtr edge1 =topNode->getTopEdgeByIndex(1);
int iter0=-1,iter1=-1;
if (edge0!=NULL) iter0=edge0->iGraphIteration;
if (edge1!=NULL) iter1=edge1->iGraphIteration;
if (iter0==-1 && iter1==-1) throw "In mark edges above, both edges above xover were missing";
EdgePtr & nextEdge = (iter0>iter1)? edge0:edge1;
return markEdgesAbove(bFirstSample,false,nextEdge,
iSampleIndex);
// for other nodes, just choose the single edge above it
// recursively call this method again
}else{
EdgePtr edge = topNode->getTopEdgeByIndex(0);
return markEdgesAbove(bFirstSample,false,edge,
iSampleIndex);
}
}
}else{
// the selected edge was in the current tree already and this is for
// a sampled node after the first one and was called by this method.
// the latter condition implies that we previously explored up this
// node. in this case, save time and proceed to the next node
return true;
}
}
void GraphBuilder::markEdgesBelow(EdgePtr & selectedEdge){
selectedEdge->iGraphIteration = iGraphIteration;
NodePtr & bottomNode = selectedEdge->getBottomNodeRef();
if (bottomNode->getType()==Node::COAL||
bottomNode->getType()==Node::SAMPLE) return;
else{
EdgePtr bottomEdge = bottomNode->getBottomEdgeByIndex(0);
markEdgesBelow(bottomEdge);
}
}
void GraphBuilder::pruneEdgesBelow(EdgePtr & selectedEdge){
NodePtr & bottomNode = selectedEdge->getBottomNodeRef();
if (bottomNode->getType()==Node::COAL){
// this is the terminating condition and should be the new
// lower MRCA
grandMRCA = bottomNode;
grandMRCA->clearTopEdges();
}else{
// we didn't find a coalescent node (MRCA) so keep searching down
bottomNode->removeEvent();
EdgePtr bottomEdge = bottomNode->getBottomEdgeByIndex(0);
pruneEdgesBelow(bottomEdge);
}
deleteEdge(selectedEdge);
}
void GraphBuilder::pruneEdgesAbove(EdgePtr & selectedEdge){
NodePtr & topNode = selectedEdge->getTopNodeRef();
short int topNodeType = topNode->getType();
if (topNodeType==Node::COAL){
EdgePtr edge0 = topNode->getBottomEdgeByIndex(0);
EdgePtr edge1 = topNode->getBottomEdgeByIndex(1);
if (topNode->getTopEdgeSize()==0){
#ifdef DIAG
if (topNode!=grandMRCA) throw "Top node is NOT grandMRCA!\n";
#endif
EdgePtr & otherEdge = edge0==selectedEdge ?
edge1 : edge0;
pruneEdgesBelow(otherEdge);
}else{
// just some coal node below the grandMRCA. fuse the other two edges.
EdgePtr edgeAboveNode = topNode->getTopEdgeByIndex(0);
EdgePtr & edgeBelowNode = edge0==
selectedEdge?edge1:edge0;
mergeEdges(edgeAboveNode,edgeBelowNode);
}
}else{
#ifdef DIAG
if (topNodeType!=Node::MIGRATION
&& topNodeType!=Node::QUERY){
cerr<<"At edge with "<<selectedEdge->getBottomNodeRef()->getHeight()<<
" and "<<selectedEdge->getTopNodeRef()->getHeight()<<endl;
throw "Prune up did not find a migration node";
}
#endif
EdgePtr topEdge = topNode->getTopEdgeByIndex(0);
pruneEdgesAbove(topEdge);
}
topNode->removeEvent();
deleteEdge(selectedEdge);
}
void GraphBuilder::invokeRecombination(GeneConversionPtr & geneConversionPtr){
double dSplitPoint=0.0;
double dRandomSpot = pRandNumGenerator->unifRV() * dLastTreeLength;
EdgePtr selectedXoverEdge = getRandomEdgeOnTree(dSplitPoint,dRandomSpot);
xOverNode = NodePtr(new Node(Node::XOVER,
selectedXoverEdge->getBottomNodeRef()->getPopulation(),dSplitPoint));
// save old edge if gene conversion
if (this->bBeginGeneConversion) geneConversionPtr->xOverNode = xOverNode;
if(pConfig->bDebug){
cerr<<"Adding xover point at "<<dSplitPoint<<
" for edge "<<selectedXoverEdge->getBottomNodeRef()->getHeight()<<
" to "<<selectedXoverEdge->getTopNodeRef()->getHeight()<<
" of population "<<selectedXoverEdge->getBottomNodeRef()->getPopulation()<<endl;
}
EventPtr pXoverEventWrapper = EventPtr(new XoverEvent
(Event::XOVER,dSplitPoint,xOverNode->getPopulation()));
// insert the xover node at the selected edge
insertNodeInEdge(xOverNode,selectedXoverEdge);
// mark the edge above the xover. this is the old coalescing line to prune.
// set up a coalescing line that is visible to the
// event building method
NodePtr nodeAboveXover = NodePtr(new Node
(Node::QUERY,xOverNode->getPopulation(),Node::MAX_HEIGHT));
coalescingEdge = EdgePtr(new Edge(nodeAboveXover,xOverNode));
nodeAboveXover->addNewEdge(Node::BOTTOM_EDGE,coalescingEdge);
xOverNode->addNewEdge(Node::TOP_EDGE,coalescingEdge);
// similarly, set up a line that runs straight up from the grandMRCA
// in case migration events need to be inserted above the grandMRCA.
NodePtr nodeAboveOrigin = NodePtr(new Node
(Node::QUERY,grandMRCA->getPopulation(),Node::MAX_HEIGHT));
originExtension = EdgePtr(new Edge(nodeAboveOrigin,grandMRCA));
nodeAboveOrigin->addNewEdge(Node::BOTTOM_EDGE,originExtension);
grandMRCA->addNewEdge(Node::TOP_EDGE,originExtension);
// now initialize the parameters that will be sent to the event traversal routine
EventPtr newCoalEvent;
// Traverse the events to find the proper coalescent waiting time.
if (pConfig->bDebug){
cerr<<"Calling traverse events\n";
}
traverseEvents(true,xOverNode,newCoalEvent);
if (pConfig->bDebug){
cerr<<"Traverse events completed successfully\n";
}
dSplitPoint = newCoalEvent->getTime();
bool bNewOrigin = false;
EdgePtr selectedCoalEdge;
if (dSplitPoint<this->grandMRCA->getHeight()){
if(pConfig->bDebug) cerr<<"Coalescing at height "<<dSplitPoint<<endl;
try{
selectedCoalEdge = getRandomEdgeToCoalesce(
coalescingEdge,dSplitPoint);
}catch(unsigned int numEdges){
printDataStructures();
throw
"Didn't find an edge to coalesce with, exiting\n";
}
}else{
bNewOrigin = true;
}
NodePtr coalNode;
// save the previous grand MRCA
NodePtr oldGrandMRCA = grandMRCA;
// discard the grandMRCA extending edge above the grandMRCA
grandMRCA = originExtension->getBottomNodeRef();
grandMRCA->clearTopEdges();
if (bNewOrigin){
coalNode = NodePtr(new Node(Node::COAL,
grandMRCA->getPopulation(),dSplitPoint));
if(pConfig->bDebug) cerr<<"Creating new grand ancestor at "<<
coalNode->getHeight()<<endl;
#ifdef DIAG
if (grandMRCA->getPopulation()!=coalNode->getPopulation()){
throw "Old grandMRCA and new grandMRCA don't match in pop\n";
}
#endif
EdgePtr shortEdge = EdgePtr(new Edge(coalNode,grandMRCA));
shortEdge->iGraphIteration=iGraphIteration;
addEdge(shortEdge);
grandMRCA->addNewEdge(Node::TOP_EDGE,shortEdge);
grandMRCA = coalNode;
grandMRCA->addNewEdge(Node::BOTTOM_EDGE,shortEdge);
}else{
coalNode = NodePtr(new Node(
Node::COAL,coalescingEdge->getBottomNodeRef()->getPopulation(),
dSplitPoint));
insertNodeInEdge(coalNode,selectedCoalEdge);
}
// set the variable proposed grandMRCA so that marking current tree can reach at least this
// height
localMRCA = coalNode;
coalNode->setEvent(newCoalEvent);
EdgePtr coalEdgeCopy = coalescingEdge;
coalescingEdge = EdgePtr(new Edge(coalNode,coalescingEdge->getBottomNodeRef()));
coalescingEdge->iGraphIteration = coalEdgeCopy->iGraphIteration;
coalescingEdge->getBottomNodeRef()->replaceOldWithNewEdge(Node::TOP_EDGE,
coalEdgeCopy,coalescingEdge);
coalescingEdge->getTopNodeRef()->addNewEdge(Node::BOTTOM_EDGE,
coalescingEdge);
addEdge(coalescingEdge);
coalescingEdge->iGraphIteration=iGraphIteration;
EdgePtr edgeBelowXover = xOverNode->getBottomEdgeByIndex(0);
markEdgesBelow(edgeBelowXover);
}
void GraphBuilder::markCurrentTree(){
iTotalTreeEdges = 0;
unsigned int iTotalSamples=pConfig->iSampleSize;
for(unsigned int i=0;i<iTotalSamples;++i){
NodePtr & node = pSampleNodeArray[i];
pTreeEdgesToCoalesceArray[i]=node->getTopEdgeByIndex(0);
}
unsigned int iIndex = 0;
int iIterations = 0;
bool bFirstSample = true;
while(iIndex<iTotalSamples){
EdgePtr & curEdge = pTreeEdgesToCoalesceArray[iIndex];
if (markEdgesAbove(bFirstSample,true,curEdge,iIndex)){
++iIndex;
}else{
// start over
iIndex = 0;
}
bFirstSample = false;
++iIterations;
}
#ifdef DIAG
if (localMRCA->getBottomEdgeByIndex(0)->iGraphIteration!=
localMRCA->getBottomEdgeByIndex(1)->iGraphIteration){
printDataStructures();
cerr<<"Proposed grandMRCA at :"<<localMRCA->getHeight()<<endl;
throw "Proposed grandMRCA's edges' histories don't match";
}
#endif
}
void GraphBuilder::traverseEvents(bool bBuildFromEventList,
NodePtr & xOverNode, EventPtr & newCoalEvent){
short int iRequestedPop = -1;
short int iOriginPop = -1;
double dXoverHeight = 0.;
if (bBuildFromEventList){
iRequestedPop = xOverNode->getPopulation();
iOriginPop = grandMRCA->getPopulation();
dXoverHeight = xOverNode->getHeight();
}
// copy stuff over from Configuration object
int iTotalPops = pConfig->iTotalPops;
// make a copy of the population information to the dynamic vector
PopVector pPopList = pConfig->pPopList;
// make a copy of the the migration matrix over to our dynamic 2-d vector
//if (pConfig->bMigrationChangeEventDefined){
//dMigrationMatrix.clear();
dMigrationMatrix = pConfig->dMigrationMatrix;
//}
if (pConfig->bDebug){
//cerr<<"Migration Matrix from copy\n";
//for (int j=0;j<iTotalPops;++j){
// for (int k=0;k<iTotalPops;++k){
// cerr<<" "<<dMigrationMatrix[j][j];
// }
// cerr<<endl;
// }
}
// set up pile of coalesced nodes for building the prior tree
NodePtrSet * pCoalescedNodes = NULL;
if (!bBuildFromEventList){
// store coalesced nodes in a temp vector
//pCoalescedNodes = new NodePtrList();
pCoalescedNodes = new NodePtrSet();
// set up the node list
int iCounter = 0,iId=0;
for (int i=0;i<iTotalPops;++i){
int iSampleSize = pConfig->pPopList[i].getChrSampled();
for (int j=0;j<iSampleSize;++j){
NodePtr newNode = NodePtr(new SampleNode
(i,iId++));
this->pSampleNodeArray[iCounter++]=newNode;
pCoalescedNodes->insert(newNode);
}
}
}
// remove any leading events that are marked for deletion.
if (pConfig->bDebug){
cerr<<"Removing leading events marked for deletion\n";
}
EventPtrList::iterator currentEventIt = pEventList->begin();
EventPtrList::iterator lastEventIt = pEventList->end();
EventPtr pNextNewEvent;
if (currentEventIt!=lastEventIt){
pNextNewEvent = *currentEventIt;
while (pNextNewEvent->bMarkedForDelete){
currentEventIt = pEventList->erase(currentEventIt);
pNextNewEvent = *currentEventIt;
}
}
unsigned int iChromCounter = bBuildFromEventList?0:pCoalescedNodes->size();
bool bDoneBuild = false,bIsEvent = false,
bUserEventAvailable = false,bAboveOrigin = false,
bAboveXoverHeight = false,bProposeNewCoal = false;
short int iCoalescingPop = -1;
unsigned long int iCoalRate = 0;
double dTime = 0.0,dMigration = 0.0,dLastTime = 0.0,dWaitTime=0.;
if (pConfig->bDebug){
cerr<<"Beginning events traversal\n";
}
while (!bDoneBuild){
int iEventType = -1;
if (currentEventIt!=lastEventIt){
pNextNewEvent = *currentEventIt;
bUserEventAvailable = true;
if (bBuildFromEventList){
//cerr<<"Xover height "<<dXoverHeight<<endl;
if (dXoverHeight>dLastTime &&
dXoverHeight<=pNextNewEvent->getTime()){
EventPtr eventWrapper = EventPtr(new XoverEvent(
Event::XOVER,dXoverHeight,iRequestedPop));
xOverNode->setEvent(eventWrapper);
pEventList->insert(currentEventIt,eventWrapper);
pNextNewEvent = eventWrapper;
currentEventIt--;
}
}
}else{
bUserEventAvailable = false;
}
if (bBuildFromEventList){
if (dTime==dXoverHeight){
bAboveXoverHeight = true;
bProposeNewCoal = true;
}
if (dTime==grandMRCA->getHeight()){
bAboveOrigin = true;
}
}
if (!bBuildFromEventList || bAboveXoverHeight){
bIsEvent = false;
double dProposedWaitTime = 0.;
// BEGIN COALESCENT SECTION
if(bProposeNewCoal ||!bBuildFromEventList){
// attempt a coalescent event
for(int pop=0; pop<iTotalPops ; ++pop) { //coalescent
int iChrSampled=(pPopList[pop].getPopSize()>0.)?pPopList[pop].getChrSampled():0;
if (bProposeNewCoal){
iCoalRate = iRequestedPop==pop?(iChrSampled-1)*2:0;
}else{
iCoalRate = iChrSampled*(iChrSampled-1);
}
if( iCoalRate > 0 ) {
if (pPopList[pop].getGrowthAlpha() == 0. ){
dProposedWaitTime = pRandNumGenerator->expRV(
iCoalRate/pPopList[pop].getPopSize());
} else { // support pop growth
double dRandomVar=pRandNumGenerator->unifRV();
double dCoalRateAlpha =
1. - pPopList[pop].getGrowthAlpha()*
pPopList[pop].getPopSize()*
exp(-pPopList[pop].getGrowthAlpha()*
(dTime - pPopList[pop].getLastTime() ) )*
log(dRandomVar) / iCoalRate;
if( dCoalRateAlpha > 0.0 ){
// if <= 0, no coalescent within interval
dProposedWaitTime = log(dCoalRateAlpha) /
pPopList[pop].getGrowthAlpha();
}
}
if (!bIsEvent||dProposedWaitTime<dWaitTime) {
iCoalescingPop = pop;
dWaitTime = dProposedWaitTime;
}
iEventType = Event::NEW_COAL;
bIsEvent = true;
if (this->bEndGeneConversion){
dWaitTime = 0.0;
}
}
}
}
// END COALESCENT SECTION
// BEGIN MIGRATION SECTION
dMigration = 0.0;
if (bBuildFromEventList){
if (bAboveOrigin){
dMigration = dMigrationMatrix[iRequestedPop][iRequestedPop]+
dMigrationMatrix[iOriginPop][iOriginPop];
}else{
dMigration = dMigrationMatrix[iRequestedPop][iRequestedPop];
}
}else{
for(int i=0; i<iTotalPops; ++i){
dMigration +=
pPopList[i].getChrSampled()*dMigrationMatrix[i][i];
}
}
// Attempt a migration event
if(dMigration > 0.0 ) { // migration
dProposedWaitTime = pRandNumGenerator->expRV(dMigration);
if(!bIsEvent || dProposedWaitTime < dWaitTime){
dWaitTime = dProposedWaitTime;
iEventType = Event::NEW_MIGRATION;
bIsEvent = true;
}
}else{
#ifdef DIAG
if (dMigration<0.0)
throw "Negative migration. Program exiting";
#endif
if(iTotalPops>1 && !bUserEventAvailable){
int iPops = 0;
for(int j=0; j<iTotalPops; ++j) {
if( pPopList[j].getChrSampled() > 0 ) ++iPops;
}
if( iPops > 1 ) {
throw "Infinite coalescent time. No migration";
}
}
}
// END MIGRATION SECTION
}
// Now try one of the user invoked events
if (bUserEventAvailable &&
(!bIsEvent || dTime+dWaitTime > pNextNewEvent->getTime())
){
dTime = pNextNewEvent->getTime();
short int eventType = pNextNewEvent->getType();
//if (pConfig->bDebug) cerr<<"At time "<<dTime<<" event type is "<<eventType<<endl;
if (eventType==Event::PAST_COAL){
CoalEvent * pExistingCoalEvent =
static_cast<CoalEvent *>(pNextNewEvent.get());
iCoalescingPop = pExistingCoalEvent->getPopulation();
pPopList[iCoalescingPop].changeChrSampled(-1);
}else if (eventType==Event::PAST_MIGRATION){
MigrationEvent * pExistingMigEvent =
static_cast<MigrationEvent *>(pNextNewEvent.get());
short int iSourcePop = pExistingMigEvent->getPopMigratedFrom();
short int iDestPop = pExistingMigEvent->getPopMigratedTo();
// GKC 2015-07-05 disabled the code in condition below.
// Should not be necessary if POPSPLIT happens epsilon before
// this time.
iTotalPops = pPopList.size();
if (false && iDestPop==iTotalPops){
// we need to split the populations
// GKC: 2015-07-01 Changed iTotalPops to iTotalPops-1
vector <double> newRow(iTotalPops);
for (int j=0;j<iTotalPops;++j){
newRow[j]=pConfig->dGlobalMigration;
}
dMigrationMatrix.push_back(newRow);
Population newPop;
pPopList.push_back(newPop);
iTotalPops = pPopList.size();
for (int j=0;j<iTotalPops;++j){
dMigrationMatrix[j].push_back(pConfig->dGlobalMigration);
}
if (pConfig->bDebug) cerr<<"dMigrationMatrix has dim "<<dMigrationMatrix.size()<<endl;
}
if ((iSourcePop>=iTotalPops||
iDestPop>=iTotalPops)) {
cerr<<"Invalid past migration event at time "
<<dTime<<",source,dest pop "<<iSourcePop<<","<<
iDestPop<<endl;
throw "Num of pops is too small for migration!";
}
pPopList[iSourcePop].changeChrSampled(-1);
pPopList[iDestPop].changeChrSampled(1);
}else if (eventType==Event::XOVER){ //recombination
XoverEvent * pXoverEvent =
static_cast<XoverEvent *>(pNextNewEvent.get());
pPopList[pXoverEvent->getPopulation()].changeChrSampled(1);
}else if (eventType==Event::MIGRATION_MATRIX_RATE){
MigrationRateMatrixEvent* migRateMatrixEvent = static_cast
<MigrationRateMatrixEvent*>(pNextNewEvent.get());
dMigrationMatrix = migRateMatrixEvent->getMigrationMatrix();
if (dMigrationMatrix.size()!=pPopList.size()){
cerr<<"Error in specifying new migration matrix event. The dimension of the matrix "<<dMigrationMatrix.size()<<" must equal the number of populations: "<<pPopList.size()<<endl;
throw "Invalid migration matrix";
}
}else if (eventType==Event::MIGRATION_RATE){
MigrationRateEvent* migRateEvent = static_cast
<MigrationRateEvent*>(pNextNewEvent.get());
short int iSourcePop = migRateEvent->getSourcePop();
short int iDestPop = migRateEvent->getDestPop();
double dMigRate = migRateEvent->getRate();
if (pConfig->bDebug){
cerr<<"Mig matrix has dim "<<dMigrationMatrix.size()<<" and source,Dest is "<<iSourcePop<<","<<iDestPop<<endl;
}
dMigrationMatrix[iSourcePop][iSourcePop]+=
dMigRate-dMigrationMatrix[iSourcePop][iDestPop];
dMigrationMatrix[iSourcePop][iDestPop] = dMigRate;
}else if (eventType==Event::GLOBAL_MIGRATIONRATE){
GenericEvent * pGeneriEvent =
static_cast<GenericEvent *>(pNextNewEvent.get());
for(short unsigned int i=0;i<iTotalPops;++i){
for(short unsigned int j=0;j<iTotalPops;++j){
dMigrationMatrix[i][j] =
pGeneriEvent->getParamValue()/(iTotalPops-1);
}
}
for(short unsigned int i=0;i<dMigrationMatrix.size();++i){
dMigrationMatrix[i][i] =
pGeneriEvent->getParamValue();
}
}else if (eventType==Event::GROWTH){
PopSizeChangeEvent * growthEvent = static_cast
<PopSizeChangeEvent *>(pNextNewEvent.get());
short int pop = growthEvent->getPopulationIndex();
pPopList[pop].setPopSize(pPopList[pop].getPopSize()*
exp( - pPopList[pop].getGrowthAlpha()*(
dTime-pPopList[pop].getLastTime()) )) ;
pPopList[pop].setGrowthAlpha(growthEvent->getPopChangeParam());
pPopList[pop].setLastTime(dTime);
}else if (eventType==Event::POPSIZE){
PopSizeChangeEvent * growthEvent = static_cast
<PopSizeChangeEvent *>(pNextNewEvent.get());
short int pop = growthEvent->getPopulationIndex();
pPopList[pop].setPopSize(growthEvent->getPopChangeParam());
pPopList[pop].setGrowthAlpha(0);
}else if (eventType==Event::POPJOIN){
// merge pop i into pop j (join)
PopJoinEvent * joinEvent = static_cast
<PopJoinEvent *>(pNextNewEvent.get());
short int iSourcePop = joinEvent->getSourcePop();
short int iDestPop = joinEvent->getDestPop();
if (pConfig->bDebug){
cerr<<"POPJOIN event encountered at time "<<dTime<<" from "<< iSourcePop<<" to "<<iDestPop <<"\n";
}
if (iSourcePop>=iTotalPops){
cerr <<"Source pop and total pops are "<<iSourcePop<<","<<iTotalPops<<" in POP JOIN event at history "<<iGraphIteration<<". It is recommended that you increase the migration rates and/or number of sampled chromosomes.\n";
throw "Invalid data structure";
}
if (iDestPop>=iTotalPops){
cerr <<"Dest pop and total pops are "<<iDestPop<<","<<iTotalPops<<" in POP JOIN event\n";
throw "Invalid data structure";
}
if (iDestPop==iTotalPops){
// we need to split the populations
Population newPop;
pPopList.push_back(newPop);
iTotalPops = pPopList.size();
vector <double> newRow(iTotalPops);
for (int j=0;j<iTotalPops;++j)
newRow[j]=0.0;
dMigrationMatrix.push_back(newRow);
for (int j=0;j<iTotalPops;++j)
dMigrationMatrix[j].push_back(0.0);
if (pConfig->bDebug){
cerr<<"In pop join, dMigrationMatrix dim is "<<dMigrationMatrix.size()<<endl;
}
}
if (!bBuildFromEventList){
NodePtrList nodesToMigrate;
for (NodePtrSet::iterator it=pCoalescedNodes->begin();
it!=pCoalescedNodes->end();++it){
NodePtr node = *it;
if (node->getPopulation()==iSourcePop){
nodesToMigrate.push_back(node);
}
}
for (NodePtrList::iterator it=nodesToMigrate.begin();
it!=nodesToMigrate.end();++it){
NodePtr node = *it;
NodePtr childNode = node;
NodePtr parentNode =
NodePtr(new Node(Node::MIGRATION,
iDestPop,dTime));
EdgePtr newEdge = EdgePtr(
new Edge(parentNode,childNode));
this->addEdge(newEdge);
parentNode->addNewEdge(Node::BOTTOM_EDGE,newEdge);
childNode->addNewEdge(Node::TOP_EDGE,newEdge);
pCoalescedNodes->erase(childNode);
pCoalescedNodes->insert(parentNode);
// store this new event
EventPtr eventWrapper = EventPtr(new MigrationEvent(
Event::PAST_MIGRATION,dTime,
iDestPop,iSourcePop));
parentNode->setEvent(eventWrapper);
pEventList->insert(currentEventIt,eventWrapper);
}
}else{
if (iRequestedPop==iSourcePop &&
coalescingEdge->getBottomNodeRef()->getHeight() < dTime &&
dTime < coalescingEdge->getTopNodeRef()->getHeight()){
NodePtr migrNode = NodePtr(new Node
(Node::MIGRATION,iDestPop,dTime));
insertNodeInRunningEdge(migrNode,coalescingEdge);
iRequestedPop = iDestPop;
}
if (iOriginPop==iSourcePop &&
originExtension->getBottomNodeRef()->getHeight() < dTime &&
dTime < originExtension->getTopNodeRef()->getHeight()){
NodePtr migrNode = NodePtr(new Node
(Node::MIGRATION,iDestPop,dTime));
insertNodeInRunningEdge(migrNode,originExtension);
iOriginPop = iDestPop;
// store this new event
EventPtr eventWrapper = EventPtr(new MigrationEvent(
Event::PAST_MIGRATION,dTime,
iDestPop,iSourcePop));
migrNode->setEvent(eventWrapper);
pEventList->insert(currentEventIt,eventWrapper);
}
}
pPopList[iDestPop].changeChrSampled(pPopList[iSourcePop]
.getChrSampled()) ;
pPopList[iSourcePop].setChrSampled(0);
// 2013-06-23 GKC begin codefix to revise migration matrix
for (int j=0;j<iTotalPops;++j){
if (j==iSourcePop){
for (int k=0;k<iTotalPops;++k){
// this population is dead and doesn't accept migrants
dMigrationMatrix[j][k] = 0.;
}
}else{
// look for the emigration rate of the dead pop
for (int k=0;k<iTotalPops;++k){
if (k==iSourcePop){
dMigrationMatrix[j][j] -= dMigrationMatrix[j][k];
dMigrationMatrix[j][k] = 0;;
break;
}
}
}
}
if (pConfig->bDebug){
cerr<<"POPJOIN event completed\n";
}
// 2013-06-23 GKC end codefix to revise migration matrix
}else if (eventType==Event::POPSPLIT){
PopSizeChangeEvent *splitEvent = static_cast
<PopSizeChangeEvent *>(pNextNewEvent.get());
short int iSourcePop = splitEvent->getPopulationIndex();
short int iDestPop = iTotalPops;
if (pConfig->bDebug){
cerr<<"POPSPLIT event encountered at time "<<dTime<<
" from "<<iSourcePop<<" to "<<iDestPop<<"\n";
// if (iGraphIteration==887) throw "test exit";
}
double dProportion = splitEvent->getPopChangeParam();
// GKC: 2015-07-05 Add epsilon to migration node
// to make sure POPSPLIT happens first
double dMigrationTime = dTime;
// GKC: 2015-07-01 Changed iTotalPops to iTotalPops-1
// begin expand migration matrix
Population newPop;
iTotalPops = pPopList.size();
vector <double> newRow(iTotalPops);
for (int j=0;j<(iTotalPops);++j)
newRow[j]=pConfig->dGlobalMigration;
dMigrationMatrix.push_back(newRow);
pPopList.push_back(newPop);
iTotalPops = pPopList.size();
for (int j=0;j<iTotalPops;++j){
dMigrationMatrix[j].push_back(pConfig->dGlobalMigration);
}
if(pConfig->bDebug) cerr<<"POPSPLIT migration matrix expanded "
<<"to "<<dMigrationMatrix.size()<<" rows.\n";
// end expand migration matrix
if (!bBuildFromEventList){
NodePtrList nodesToMigrate;
for (NodePtrSet::iterator it=pCoalescedNodes->begin();
it!=pCoalescedNodes->end();++it){
NodePtr node = *it;
if (node->getPopulation()==iSourcePop &&
pRandNumGenerator->unifRV()<dProportion){
nodesToMigrate.push_back(node);
}
}
//GKC 2015-07-05 make sure the migration event happens
// after the pop split
if(nodesToMigrate.size()>0) ++currentEventIt;
for (NodePtrList::iterator it=nodesToMigrate.begin();
it!=nodesToMigrate.end();++it){
NodePtr node = *it;
NodePtr childNode = node;
NodePtr parentNode =
NodePtr(new Node(Node::MIGRATION,
iDestPop,dMigrationTime));
if(pConfig->bDebug) cerr<<
"POPSPLIT in build tree, migration node at time "
<<dMigrationTime<<
endl;
EdgePtr newEdge =
EdgePtr(new Edge(parentNode,childNode));
this->addEdge(newEdge);
parentNode->addNewEdge(Node::BOTTOM_EDGE,newEdge);
childNode->addNewEdge(Node::TOP_EDGE,newEdge);
pCoalescedNodes->erase(childNode);
pCoalescedNodes->insert(parentNode);
pPopList[iDestPop].changeChrSampled(1) ;
pPopList[iSourcePop].changeChrSampled(-1);
// store this new event
EventPtr eventWrapper = EventPtr(new MigrationEvent(
Event::PAST_MIGRATION,dMigrationTime,
iDestPop,iSourcePop));
parentNode->setEvent(eventWrapper);
pEventList->insert(currentEventIt,eventWrapper);
}
//GKC 2015-07-05 make sure the migration event happens
// after the pop split
if(nodesToMigrate.size()>0) --currentEventIt;
if (pConfig->bDebug) {
cerr<<"In pop split mig dim is size "<<dMigrationMatrix.size()<<endl;
}
}else{
iDestPop=iTotalPops-1;
if (pConfig->bDebug){
cerr<<"In POPSPLIT: destpop,sourcepop,size: "<<iDestPop<<","<<iSourcePop<<","<<pPopList.size()<<endl;
}
double random = pRandNumGenerator->unifRV();
bool internal_edge_condition =
iRequestedPop==iSourcePop &&
coalescingEdge->getBottomNodeRef()->getHeight() <
dMigrationTime && dMigrationTime <
coalescingEdge->getTopNodeRef()->getHeight();
bool external_edge_condition =
iOriginPop&&
originExtension->getBottomNodeRef()->getHeight() <
dMigrationTime && dMigrationTime <
originExtension->getTopNodeRef()->getHeight();
if(random < dProportion && (internal_edge_condition ||
external_edge_condition)){
//if (iRequestedPop==iSourcePop&&
//coalescingEdge->getBottomNodeRef()->getHeight() <
//dMigrationTime && dMigrationTime < coalescingEdge->getTopNodeRef()->getHeight()&&
// random<dProportion){
NodePtr migrNode = NodePtr(new Node
(Node::MIGRATION,iDestPop,dMigrationTime));
if(internal_edge_condition){
insertNodeInRunningEdge(migrNode,coalescingEdge);
iRequestedPop = iDestPop;
}
if(external_edge_condition){
insertNodeInRunningEdge(migrNode,originExtension);
iOriginPop = iDestPop;
}
pPopList[iDestPop].changeChrSampled(1) ;
pPopList[iSourcePop].changeChrSampled(-1);
// store this new event
EventPtr eventWrapper = EventPtr(new MigrationEvent(
Event::PAST_MIGRATION,dMigrationTime,
iDestPop,iSourcePop));
migrNode->setEvent(eventWrapper);
//GKC 2015-07-05 make sure the migration event happens
// after the pop split
++currentEventIt;
pEventList->insert(currentEventIt,eventWrapper);
--currentEventIt;
}
//}
//if (iOriginPop&&
//originExtension->getBottomNodeRef()->getHeight() <
//dMigrationTime && dMigrationTime <
//originExtension->getTopNodeRef()->getHeight()&&
// random<dProportion){
//NodePtr migrNode = NodePtr(new Node
//(Node::MIGRATION,iDestPop,dMigrationTime));
//insertNodeInRunningEdge(migrNode,originExtension);
//iOriginPop = iDestPop;
//pPopList[iDestPop].changeChrSampled(1) ;
//pPopList[iSourcePop].changeChrSampled(-1);
//// store this new event
//EventPtr eventWrapper = EventPtr(new MigrationEvent(
//Event::PAST_MIGRATION,dMigrationTime,
//iDestPop,iSourcePop));
//migrNode->setEvent(eventWrapper);
////GKC 2015-07-05 make sure the migration event happens
//// after the pop split
//++currentEventIt;
//pEventList->insert(currentEventIt,eventWrapper);
//}
}
}else if (eventType==Event::GLOBAL_POPGROWTH){
GenericEvent * pGeneriEvent =
static_cast<GenericEvent *>(pNextNewEvent.get());
for(short unsigned int iPop=0;iPop<pPopList.size();++iPop){
Population & pop = pPopList[iPop];
pop.setPopSize(pop.getPopSize()*exp( - pop.getGrowthAlpha()*(dTime - pop.getLastTime())));
pop.setGrowthAlpha(pGeneriEvent->getParamValue());
pop.setLastTime(dTime);
}
}else if (eventType==Event::GLOBAL_POPSIZE){
GenericEvent * pGeneriEvent =
static_cast<GenericEvent *>(pNextNewEvent.get());
for(short unsigned int iPop=0;iPop<pPopList.size();++iPop){
Population & pop = pPopList[iPop];
pop.setPopSize(pGeneriEvent->getParamValue());
pop.setGrowthAlpha(0);
}
}else{
cerr<<"Found an event of type "<<pNextNewEvent->getType()
<<endl;
throw "Event is not implemented yet!";
}
++currentEventIt;
//if (pConfig->bDebug) cerr<<"looking for events to mark for deletion\n";
bool found = false;
while(!found && currentEventIt!=lastEventIt){
if (*currentEventIt==NULL) cerr<<"null\n";
if ((*currentEventIt)->bMarkedForDelete) {
if(pConfig->bDebug)cerr<<"Deleting event at "<<(*currentEventIt)->getTime()<<endl;
currentEventIt=pEventList->erase(currentEventIt);
}
else found = true;
}
//if (pConfig->bDebug) cerr<<"user event processing complete\n";
}else{
dTime += dWaitTime;
//if(pConfig->bDebug) cerr<<"Handling migration or coalescence at time "<<dTime<<endl;