Debian Codegraph @

src/dr/evomodel/epidemiology/casetocase/PartitionedTreeModel.java

raw symbols SCIP
1 /*
2 * PartitionedTreeModel.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.evomodel.epidemiology.casetocase;
27
28 import dr.evolution.tree.NodeRef;
29 import dr.evolution.tree.Tree;
30 import dr.evolution.tree.TreeUtils;
31 import dr.evolution.util.Taxon;
32 import dr.evomodel.tree.TreeModel;
33 import dr.inference.model.*;
34 import dr.math.MathUtils;
35
36 import java.io.BufferedReader;
37 import java.io.FileReader;
38 import java.io.IOException;
39 import java.util.*;
40
41 /**
42 * TreeModel plus partition information
43 *
44 * todo a lot of methods should eventually move here
45 */
46 public class PartitionedTreeModel extends TreeModel {
47
48 private final AbstractOutbreak outbreak;
49 private BranchMapModel branchMap;
50 private final int elementCount;
51
52 public final static String PARTITIONED_TREE_MODEL = "partitionedTreeModel";
53 Set<NodeRef> partitionsQueue = new HashSet<NodeRef>();
54
55 public PartitionedTreeModel(String id, Tree tree, AbstractOutbreak outbreak){
56 super(id, tree);
57 this.outbreak = outbreak;
58 elementCount = outbreak.infectedSize();
59 branchMap = new BranchMapModel(this);
60 partitionAccordingToRandomTT(false);
61 }
62
63 public PartitionedTreeModel(String id, Tree tree, AbstractOutbreak outbreak, String startingTTFileName){
64 super(id, tree);
65 this.outbreak = outbreak;
66 elementCount = outbreak.infectedSize();
67 branchMap = new BranchMapModel(this);
68 partitionAccordingToSpecificTT(startingTTFileName);
69 }
70
71 public PartitionedTreeModel(TreeModel treeModel, AbstractOutbreak outbreak){
72 this(PARTITIONED_TREE_MODEL, treeModel, outbreak);
73 }
74
75 public PartitionedTreeModel(TreeModel treeModel, AbstractOutbreak outbreak, String startingTTFileName){
76 this(PARTITIONED_TREE_MODEL, treeModel, outbreak, startingTTFileName);
77 }
78
79 public void partitionsChangingAlert(HashSet<AbstractCase> casesToRecalculate){
80 // TreeLikelihood and TreeParameter listeners are irrelevant
81 listenerHelper.fireModelChanged(this, new PartitionsChangedEvent(casesToRecalculate));
82 }
83
84 public void partitionChangingAlert(AbstractCase caseToRecalculate){
85 HashSet<AbstractCase> out = new HashSet<AbstractCase>();
86 out.add(caseToRecalculate);
87
88 partitionsChangingAlert(out);
89 }
90
91 public void universalAlert(){
92 HashSet<AbstractCase> allCases = new HashSet<AbstractCase>(Arrays.asList(branchMap.getArrayCopy()));
93 partitionsChangingAlert(allCases);
94 }
95
96 public BranchMapModel getBranchMap(){
97 return branchMap;
98 }
99
100 protected void handleModelChangedEvent(Model model, Object object, int index) {
101
102 // shouldn't be any
103
104 }
105
106 public class PartitionsChangedEvent{
107
108 private final HashSet<AbstractCase> casesToRecalculate;
109
110 public PartitionsChangedEvent(HashSet<AbstractCase> casesToRecalculate){
111 this.casesToRecalculate = casesToRecalculate;
112 }
113
114 public HashSet<AbstractCase> getCasesToRecalculate(){
115 return casesToRecalculate;
116 }
117 }
118
119
120 public void pushNodePartitionsChangedEvent(NodeRef node){
121 int nodeNumber = node.getNumber();
122
123 if(!inTreeEdit()){
124 partitionChangingAlert(branchMap.get(nodeNumber));
125 } else {
126 partitionsQueue.add(node);
127 }
128 }
129
130
131 public void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
132 super.handleVariableChangedEvent(variable, index, type);
133
134 if (type == Parameter.ChangeType.ALL_VALUES_CHANGED) {
135 //this signals events where values in all dimensions of a parameter is changed.
136 universalAlert();
137 } else {
138
139 final NodeRef node = getNodeOfParameter((Parameter) variable);
140
141 partitionsChangingAlert(adjacentElements(node));
142 }
143 }
144
145 public HashSet<AbstractCase> adjacentElements(NodeRef node){
146 HashSet<AbstractCase> changedCases = new HashSet<AbstractCase>();
147 ArrayList<NodeRef> affectedNodes = new ArrayList<NodeRef>();
148
149 affectedNodes.add(node);
150 affectedNodes.add(getParent(node));
151 affectedNodes.add(getChild(node, 0));
152 affectedNodes.add(getChild(node, 1));
153
154 for(NodeRef aNode : affectedNodes){
155 if(aNode!=null){
156 changedCases.add(branchMap.get(aNode.getNumber()));
157 }
158 }
159
160 return changedCases;
161 }
162
163 private void flushQueue(){
164 if(inTreeEdit()){
165 throw new RuntimeException("Wait until you've finished editing the tree before flushing the partition" +
166 "queue");
167 }
168
169 for(NodeRef node : partitionsQueue){
170 AbstractCase nodeElement = branchMap.get(node.getNumber());
171 partitionChangingAlert(nodeElement);
172 NodeRef parent = getParent(node);
173 if(parent!=null && branchMap.get(node.getNumber())!=branchMap.get(parent.getNumber())){
174 partitionChangingAlert(branchMap.get(parent.getNumber()));
175 }
176 }
177
178 partitionsQueue.clear();
179
180 }
181
182 public void addChild(NodeRef p, NodeRef c) {
183
184 pushNodePartitionsChangedEvent(p);
185 pushNodePartitionsChangedEvent(c);
186
187 super.addChild(p, c);
188 }
189
190 public void removeChild(NodeRef p, NodeRef c) {
191
192 pushNodePartitionsChangedEvent(p);
193 pushNodePartitionsChangedEvent(c);
194
195 super.removeChild(p, c);
196
197 }
198
199 public void setNodeHeight(NodeRef n, double height) {
200
201 partitionsChangingAlert(adjacentElements(n));
202
203 super.setNodeHeight(n, height);
204 }
205
206
207
208 // anything you do to the partitions must be finished before you call this.
209
210 public void endTreeEdit() {
211 super.endTreeEdit();
212
213 // todo in the end, want to check the tree partitions are sane here before flushing the queue
214
215 flushQueue();
216 }
217
218 public boolean checkPartitions(){
219 return checkPartitions(branchMap, true);
220 }
221
222 protected boolean checkPartitions(BranchMapModel map, boolean verbose){
223 boolean foundProblem = false;
224 for(int i=0; i<getInternalNodeCount(); i++){
225 boolean foundTip = false;
226 for(Integer nodeNumber : samePartitionElement(getInternalNode(i))){
227 if(isExternal(getNode(nodeNumber))){
228 foundTip = true;
229 }
230 }
231 if(!foundProblem && !foundTip){
232 foundProblem = true;
233 if(verbose){
234 System.out.println("Node "+(i+getExternalNodeCount()) + " is not connected to a tip");
235 }
236 }
237
238 }
239
240 // @todo wasteful - something accessible should keep a list of cases
241
242 for(int i=0; i<getExternalNodeCount(); i++){
243 AbstractCase aCase = branchMap.get(i);
244
245
246 NodeRef tipMRCA = caseMRCA(aCase);
247
248 if(branchMap.get(tipMRCA.getNumber())!=aCase){
249 throw new BadPartitionException("Node partition disconnected");
250 }
251
252
253 }
254
255
256 return !foundProblem;
257 }
258
259 //Return a set of nodes that are not descendants of (or equal to) the current node and are in the same partition as
260 // it.
261
262
263 public HashSet<Integer> samePartitionElementUpTree(NodeRef node){
264 HashSet<Integer> out = new HashSet<Integer>();
265 AbstractCase elementCase = branchMap.get(node.getNumber());
266 NodeRef currentNode = node;
267 NodeRef parentNode = getParent(node);
268 while(parentNode!=null && branchMap.get(parentNode.getNumber())==elementCase){
269 out.add(parentNode.getNumber());
270 if(countChildrenInSameElement(parentNode)==2){
271 NodeRef otherChild = sibling(this, currentNode);
272 out.add(otherChild.getNumber());
273 out.addAll(samePartitionElementDownTree(otherChild));
274 }
275 currentNode = parentNode;
276 parentNode = getParent(currentNode);
277 }
278 return out;
279 }
280
281 //Return a set of nodes that are descendants (and not equal to) the current node and are in the same partition as
282 // it.
283
284 public HashSet<Integer> samePartitionElementDownTree(NodeRef node){
285 HashSet<Integer> out = new HashSet<Integer>();
286 AbstractCase elementCase = branchMap.get(node.getNumber());
287 for(int i=0; i< getChildCount(node); i++){
288 if(branchMap.get(getChild(node,i).getNumber())==elementCase){
289 out.add(getChild(node,i).getNumber());
290 out.addAll(samePartitionElementDownTree(getChild(node, i)));
291 }
292 }
293 return out;
294 }
295
296
297 public Integer[] samePartitionElement(NodeRef node){
298 HashSet<Integer> out = new HashSet<Integer>();
299 out.add(node.getNumber());
300 out.addAll(samePartitionElementUpTree(node));
301 out.addAll(samePartitionElementDownTree(node));
302 return out.toArray(new Integer[out.size()]);
303 }
304
305 public int[] allTipsForThisCase(AbstractCase thisCase){
306 ArrayList<Integer> listOfRefs = new ArrayList<Integer>();
307
308 for(int i=0; i<getExternalNodeCount(); i++){
309 if(branchMap.get(i)==thisCase){
310 listOfRefs.add(i);
311 }
312
313 }
314
315 int[] out = new int[listOfRefs.size()];
316
317 for(int i=0; i<out.length; i++){out[i] = listOfRefs.get(i);}
318
319 return out;
320
321 }
322
323
324 public NodeRef getEarliestNodeInElement(AbstractCase thisCase){
325 if(thisCase.wasEverInfected()) {
326
327 NodeRef tipMRCA = caseMRCA(thisCase);
328
329 if(branchMap.get(tipMRCA.getNumber())!=thisCase){
330 throw new BadPartitionException("Node partition element disconnected");
331 }
332
333 NodeRef child = tipMRCA;
334 NodeRef parent = getParent(child);
335 boolean transmissionFound = parent == null;
336 while (!transmissionFound) {
337
338 if (branchMap.get(child.getNumber()) != branchMap.get(parent.getNumber())) {
339 transmissionFound = true;
340 } else {
341 child = parent;
342 parent = getParent(child);
343 if (parent == null) {
344 transmissionFound = true;
345 }
346 }
347
348 }
349 return child;
350 }
351 return null;
352 }
353
354 public HashSet<AbstractCase> getDescendants(AbstractCase thisCase){
355 HashSet<AbstractCase> out = new HashSet<AbstractCase>(getInfectees(thisCase));
356
357 if(thisCase.wasEverInfected()) {
358 for (AbstractCase child : out) {
359 out.addAll(getDescendants(child));
360 }
361 }
362 return out;
363 }
364
365 /* Return the case that infected this case */
366
367 public AbstractCase getInfector(AbstractCase thisCase){
368 if(thisCase.wasEverInfected()) {
369
370 NodeRef tipMRCA = caseMRCA(thisCase);
371
372 if(branchMap.get(tipMRCA.getNumber())!=thisCase){
373 throw new BadPartitionException("Node partition element disconnected");
374 }
375
376 NodeRef currentNode = tipMRCA;
377
378 while(branchMap.get(currentNode.getNumber())==thisCase){
379 currentNode = getParent(currentNode);
380 if(currentNode==null){
381 return null;
382 }
383 }
384 return branchMap.get(currentNode.getNumber());
385
386
387 }
388 return null;
389 }
390
391 public AbstractCase getRootCase(){
392 return branchMap.get(getRoot().getNumber());
393 }
394
395
396
397 public HashSet<AbstractCase> getInfectees(AbstractCase thisCase){
398 if(thisCase.wasEverInfected()) {
399 return getInfecteesInClade(getEarliestNodeInElement(thisCase));
400 }
401 return new HashSet<AbstractCase>();
402 }
403
404 public HashSet<AbstractCase> getInfecteesInClade(NodeRef node){
405 HashSet<AbstractCase> out = new HashSet<AbstractCase>();
406 if(isExternal(node)){
407 return out;
408 } else {
409 AbstractCase thisCase = branchMap.get(node.getNumber());
410 for(int i=0; i<getChildCount(node); i++){
411 NodeRef child = getChild(node, i);
412 AbstractCase childCase = branchMap.get(child.getNumber());
413 if(childCase!=thisCase){
414 out.add(childCase);
415 } else {
416 out.addAll(getInfecteesInClade(child));
417 }
418 }
419 return out;
420 }
421 }
422
423 //infector of the case assigned to this node
424
425 public AbstractCase getInfector(NodeRef node){
426 if(isRoot(node) || node.getNumber() == getRoot().getNumber()){
427 return null;
428 } else {
429 AbstractCase nodeCase = branchMap.get(node.getNumber());
430 if(branchMap.get(getParent(node).getNumber())!=nodeCase){
431 return branchMap.get(getParent(node).getNumber());
432 } else {
433 return getInfector(getParent(node));
434 }
435 }
436 }
437
438
439 /* Return the partition element of the parent of this node */
440
441 public AbstractCase getParentCase(NodeRef node){
442 return branchMap.get(getParent(node).getNumber());
443 }
444
445
446 public int getElementCount(){
447 return elementCount;
448 }
449
450
451 //Counts the children of the current node which are in the same partition element as itself
452
453
454
455 public int countChildrenInSameElement(NodeRef node){
456 if(isExternal(node)){
457 return -1;
458 } else {
459 int count = 0;
460 AbstractCase parentCase = branchMap.get(node.getNumber());
461 for(int i=0; i< getChildCount(node); i++){
462 if(branchMap.get(getChild(node,i).getNumber())==parentCase){
463 count++;
464 }
465 }
466 return count;
467 }
468 }
469
470
471
472 public static NodeRef sibling(TreeModel tree, NodeRef node){
473 if(tree.isRoot(node)){
474 return null;
475 } else {
476 NodeRef parent = tree.getParent(node);
477 for(int i=0; i<tree.getChildCount(parent); i++){
478 if(tree.getChild(parent,i)!=node){
479 return tree.getChild(parent,i);
480 }
481 }
482 }
483 return null;
484 }
485
486
487 public NodeRef caseMRCA(AbstractCase aCase, boolean checkConnectedness){
488 int[] caseTips = allTipsForThisCase(aCase);
489 NodeRef mrca = TreeUtils.getCommonAncestor(this, caseTips);
490
491 if(checkConnectedness) {
492 if (branchMap.get(mrca.getNumber()) != aCase) {
493 throw new BadPartitionException("A partition element is disconnected");
494 }
495 }
496
497 return mrca;
498 }
499
500 public NodeRef caseMRCA(AbstractCase aCase){
501 return caseMRCA(aCase, true);
502 }
503
504 private HashSet<NodeRef> getDescendantTips(NodeRef node){
505 HashSet<NodeRef> out = new HashSet<NodeRef>();
506 if(isExternal(node)){
507 out.add(node);
508 return out;
509 } else {
510 out.addAll(getDescendantTips(getChild(node, 0)));
511 out.addAll(getDescendantTips(getChild(node, 1)));
512 }
513 return out;
514 }
515
516 public boolean isAncestral(NodeRef node){
517 AbstractCase currentCase = branchMap.get(node.getNumber());
518
519 for(NodeRef tip : getDescendantTips(node)){
520 if(branchMap.get(tip.getNumber())==currentCase){
521 return true;
522 }
523 }
524
525 return false;
526 }
527
528 public boolean isRootBlockedBy(AbstractCase aCase, AbstractCase potentialBlocker){
529 return directDescendant(caseMRCA(aCase), caseMRCA(potentialBlocker));
530 }
531
532 public boolean isRootBlocked(AbstractCase aCase){
533 for(AbstractCase anotherCase : outbreak.getCases()){
534 if(anotherCase.wasEverInfected && anotherCase!=aCase){
535 if(isRootBlockedBy(aCase, anotherCase)){
536 return true;
537 }
538 }
539 }
540 return false;
541 }
542
543 private HashSet<NodeRef> getTipsInThisPartitionElement(AbstractCase aCase){
544 HashSet<NodeRef> out = new HashSet<NodeRef>();
545 // todo check that external nodes come first
546
547 for(int i=0; i<getExternalNodeCount(); i++){
548 if(branchMap.get(i)==aCase){
549 out.add(getExternalNode(i));
550 }
551 }
552
553 return out;
554 }
555
556 private boolean directDescendant(NodeRef node, NodeRef possibleAncestor){
557 NodeRef currentNode = node;
558
559 while(currentNode!=null){
560 if(currentNode==possibleAncestor){
561 return true;
562 }
563 currentNode = getParent(currentNode);
564 }
565 return false;
566 }
567
568 private boolean directRelationship(NodeRef node1, NodeRef node2){
569 return directDescendant(node1, node2) || directDescendant(node2, node1);
570 }
571
572 /* Populates the branch map for external nodes */
573
574 private AbstractCase[] prepareExternalNodeMap(AbstractCase[] map){
575 for(int i=0; i< getExternalNodeCount(); i++){
576 TreeModel.Node currentExternalNode = (TreeModel.Node) getExternalNode(i);
577 Taxon currentTaxon = currentExternalNode.taxon;
578 for(AbstractCase thisCase : outbreak.getCases()){
579 if(thisCase.wasEverInfected()) {
580 for (Taxon caseTaxon : thisCase.getAssociatedTaxa()) {
581 if (caseTaxon.equals(currentTaxon)) {
582 map[currentExternalNode.getNumber()] = thisCase;
583 }
584 }
585 }
586 }
587 }
588 return map;
589 }
590
591 /* The CSV file should have a header, and then lines matching each case to its infector*/
592
593 private void partitionAccordingToSpecificTT(String networkFileName){
594 System.out.println("Using specified starting transmission tree.");
595 try{
596 BufferedReader reader = new BufferedReader (new FileReader(networkFileName));
597 HashMap<AbstractCase, AbstractCase> specificParentMap = new HashMap<AbstractCase, AbstractCase>();
598 // skip header line
599 reader.readLine();
600 String currentLine = reader.readLine();
601 while(currentLine!=null){
602 currentLine = currentLine.replace("\"", "");
603 String[] splitLine = currentLine.split("\\,");
604 if(!splitLine[1].equals("Start")){
605 specificParentMap.put(outbreak.getCase(splitLine[0]), outbreak.getCase(splitLine[1]));
606 } else {
607 specificParentMap.put(outbreak.getCase(splitLine[0]), null);
608 }
609 currentLine = reader.readLine();
610 }
611 reader.close();
612 partitionAccordingToSpecificTT(specificParentMap);
613 } catch(IOException e){
614 throw new RuntimeException("Cannot read file: " + networkFileName );
615 }
616 }
617
618
619 private void partitionAccordingToSpecificTT(HashMap<AbstractCase, AbstractCase> map){
620 branchMap.setAll(prepareExternalNodeMap(new AbstractCase[getNodeCount()]), true);
621
622 //various sanity checks
623
624 for(AbstractCase aCase : map.keySet()){
625 if(!aCase.wasEverInfected){
626 throw new RuntimeException("This starting transmission tree involves never-infected cases");
627 }
628 }
629
630 AbstractCase firstCase=null;
631 int indexCaseCount = 0;
632
633 for(AbstractCase aCase : outbreak.getCases()){
634 if(aCase.wasEverInfected()) {
635 if (map.get(aCase) == null) {
636 firstCase = aCase;
637 indexCaseCount++;
638 }
639 }
640 }
641 if(indexCaseCount==0){
642 throw new RuntimeException("Given starting transmission tree appears to have a cycle");
643 }
644 if(indexCaseCount>1){
645 throw new RuntimeException("Given starting transmission tree appears not to be connected");
646 }
647
648
649 NodeRef root = getRoot();
650 specificallyPartitionDownwards(root, firstCase, map);
651 if(!checkPartitions()){
652 throw new RuntimeException("Given starting transmission tree is not compatible with the starting tree");
653 }
654
655 }
656
657 private void specificallyPartitionDownwards(NodeRef node, AbstractCase thisCase,
658 HashMap<AbstractCase, AbstractCase> map){
659 if(isExternal(node)){
660 return;
661 }
662 branchMap.set(node.getNumber(), thisCase, true);
663 if(isAncestral(node)){
664 for(int i=0; i<getChildCount(node); i++){
665 specificallyPartitionDownwards(getChild(node, i), thisCase, map);
666 }
667 } else {
668 branchMap.set(node.getNumber(), null, true);
669 HashSet<AbstractCase> children = new HashSet<AbstractCase>();
670 for(AbstractCase aCase : outbreak.getCases()){
671 if(map.get(aCase)==thisCase){
672 children.add(aCase);
673 }
674 }
675 HashSet<AbstractCase> relevantChildren = new HashSet<AbstractCase>(children);
676 for(AbstractCase child: children){
677
678 NodeRef caseMRCA = caseMRCA(child);
679
680 //either ALL the tips need to be a descendant of this node, or none. Otherwise not compatible.
681
682 if(directDescendant(node, caseMRCA)){
683 throw new RuntimeException("Starting transmission tree is incompatible with starting phylogeny");
684 }
685
686 if(caseMRCA==node){
687 //I'm afraid I must insist...
688 relevantChildren = new HashSet<AbstractCase>();
689 relevantChildren.add(child);
690 break;
691 }
692
693 NodeRef currentNode = caseMRCA;
694 while(currentNode!=node && currentNode!=null){
695 currentNode = getParent(currentNode);
696 }
697 if(currentNode==null){
698 relevantChildren.remove(child);
699 }
700 }
701 if(relevantChildren.size()==1){
702 //this ends an infection branch
703 AbstractCase child = relevantChildren.iterator().next();
704 branchMap.set(node.getNumber(), child, true);
705 } else {
706
707 //this can't end an infection branch
708 branchMap.set(node.getNumber(), thisCase, true);
709 }
710 for(int i=0; i<getChildCount(node); i++){
711 specificallyPartitionDownwards(getChild(node, i), branchMap.get(node.getNumber()), map);
712 }
713 }
714
715 }
716
717
718 /*
719 todo - The trouble with initialising this without the likelihood class is that lots of starting trees might
720 todo - fail. Need to think about how best to deal with this.
721
722 Generally allowCreep is a bad idea, since it tends to place infections after tip times and tip times
723 are frequently noninfectiousness times. Might be useful for some pathogens, however.
724 */
725
726
727 private void partitionAccordingToRandomTT(boolean allowCreep){
728
729 System.out.println("Generating a random starting partition of the tree");
730
731 branchMap.setAll(prepareExternalNodeMap(new AbstractCase[getNodeCount()]), true);
732
733 NodeRef root = getRoot();
734 randomlyAssignNode(root, allowCreep);
735
736 }
737
738
739 private AbstractCase randomlyAssignNode(NodeRef node, boolean allowCreep){
740
741 if(isExternal(node)){
742 return branchMap.get(node.getNumber());
743 } else {
744
745 //If this is a descendant of a case MRCA and an ancestor of one of that case's tips, it must be
746 //assigned that case. If it is that of two cases then this tree is incompatible
747
748 ArrayList<AbstractCase> forcedByTopology = new ArrayList<AbstractCase>();
749
750 for(AbstractCase aCase : outbreak.getCases()){
751 if(aCase.wasEverInfected) {
752 NodeRef caseMRCA = caseMRCA(aCase, false);
753 HashSet<NodeRef> caseTips = getTipsInThisPartitionElement(aCase);
754
755 for (NodeRef caseTip : caseTips) {
756 if (directDescendant(node, caseMRCA) && directDescendant(caseTip, node)) {
757 if(!forcedByTopology.contains(aCase)) {
758 forcedByTopology.add(aCase);
759 }
760 }
761 }
762 }
763 }
764
765 if(forcedByTopology.size()>1){
766 throw new RuntimeException("Starting phylogeny is incompatible with this tip partition");
767 } else if(forcedByTopology.size()==1){
768 branchMap.set(node.getNumber(), forcedByTopology.get(0), true);
769
770 for (int i = 0; i < getChildCount(node); i++) {
771 if(!isExternal(getChild(node, i))){
772 randomlyAssignNode(getChild(node, i), allowCreep);
773 }
774 }
775
776 return forcedByTopology.get(0);
777 } else {
778 //not mandated by the topology
779 //three choices - case of child 1, case of child 2, case of parent, unless this is the root
780
781 AbstractCase[] choices = new AbstractCase[2];
782
783
784
785 for (int i = 0; i < getChildCount(node); i++) {
786 if(!isExternal(getChild(node, i))){
787 choices[i] = randomlyAssignNode(getChild(node, i), allowCreep);
788 } else {
789 choices[i] = branchMap.get(getChild(node,i).getNumber());
790 }
791 }
792 //if both choices are null and we're at the root, try again
793
794 while(isRoot(node) && choices[0]==null && choices[1]==null){
795 for (int i = 0; i < getChildCount(node); i++) {
796 if(!isExternal(getChild(node, i))){
797 choices[i] = randomlyAssignNode(getChild(node, i), allowCreep);
798 } else {
799 choices[i] = branchMap.get(getChild(node,i).getNumber());
800 }
801 }
802 }
803
804 int randomSelection;
805 if (isRoot(node)) {
806 //must make a choice at this point
807 randomSelection = MathUtils.nextInt(2);
808 //they can't both be null
809 if(choices[randomSelection]==null){
810 randomSelection = 1-randomSelection;
811 }
812 AbstractCase winner = choices[randomSelection];
813 fillDownTree(node, winner);
814 return winner;
815
816 } else {
817 randomSelection = MathUtils.nextInt(allowCreep ? 3 : 2);
818 }
819 if (randomSelection != 2) {
820 AbstractCase winner = choices[randomSelection];
821 AbstractCase loser = choices[1-randomSelection];
822
823 // check that this isn't going to cause a timings problem
824
825 if(getNodeHeight(getChild(node, randomSelection)) >
826 loser.getInfectionBranchPosition().getParameterValue(0)
827 *getBranchLength(getChild(node, 1-randomSelection))
828 + getNodeHeight(getChild(node, 1-randomSelection))) {
829 winner = loser;
830 }
831
832 if(winner!=null) {
833 fillDownTree(node, winner);
834 } else {
835 branchMap.set(node.getNumber(), null, true);
836 }
837
838 return winner;
839
840 } else {
841 //parent partition element will creep to here, but we don't know what that is yet
842 return null;
843 }
844 }
845 }
846 }
847
848 private void fillDownTree(NodeRef node, AbstractCase aCase){
849 if(branchMap.get(node.getNumber())==null){
850 branchMap.set(node.getNumber(), aCase, true);
851 for(int i=0; i<2; i++){
852 fillDownTree(getChild(node, i), aCase);
853 }
854 }
855 }
856
857 }