Debian Codegraph @

src/dr/app/tools/TransmissionTreeToVirusTree.java

raw symbols SCIP
1 /*
2 * TransmissionTreeToVirusTree.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.app.tools;
27
28 import dr.app.util.Arguments;
29 import dr.evolution.coalescent.CoalescentSimulator;
30 import dr.evolution.coalescent.ConstantPopulation;
31 import dr.evolution.coalescent.DemographicFunction;
32 import dr.evolution.coalescent.ExponentialGrowth;
33 import dr.evolution.tree.*;
34 import dr.evolution.util.Date;
35 import dr.evolution.util.Taxon;
36 import dr.evolution.util.Units;
37 import dr.evomodel.epidemiology.LogisticGrowthN0;
38
39 import java.io.*;
40 import java.util.ArrayList;
41 import java.util.Collections;
42 import java.util.HashMap;
43
44 /**
45 * Simulated a virus tree given a transmission tree and dates of sampling
46 *
47 * @author mhall
48 */
49
50 public class TransmissionTreeToVirusTree {
51
52 protected static PrintStream progressStream = System.out;
53
54 private enum ModelType{CONSTANT, EXPONENTIAL, LOGISTIC}
55
56 public static final String HELP = "help";
57
58 public static final String DEMOGRAPHIC_MODEL = "demoModel";
59
60 public static final String[] demographics = {"Constant", "Exponential", "Logistic"};
61
62 public static final String STARTING_POPULATION_SIZE = "N0";
63 public static final String GROWTH_RATE = "growthRate";
64 public static final String T50 = "t50";
65
66 private DemographicFunction demFunct;
67 private ArrayList<InfectedUnit> units;
68 private HashMap<String, InfectedUnit> idMap;
69 private String outputFileRoot;
70
71 private double coalescentProbability;
72
73 public TransmissionTreeToVirusTree(String fileName,
74 DemographicFunction demFunct, String outputFileRoot){
75 this.demFunct = demFunct;
76 units = new ArrayList<InfectedUnit>();
77 idMap = new HashMap<String, InfectedUnit>();
78 this.outputFileRoot = outputFileRoot;
79 coalescentProbability = 1;
80 try {
81 readInfectionEvents(fileName);
82 readSamplingEvents(fileName);
83 } catch(IOException e){
84 e.printStackTrace();
85 }
86 }
87
88 public TransmissionTreeToVirusTree(String sampFileName, String transFileName,
89 DemographicFunction demFunct, String outputFileRoot){
90 this.demFunct = demFunct;
91 units = new ArrayList<InfectedUnit>();
92 idMap = new HashMap<String, InfectedUnit>();
93 this.outputFileRoot = outputFileRoot;
94 try {
95 readInfectionEvents(transFileName);
96 readSamplingEvents(sampFileName);
97 } catch(IOException e){
98 e.printStackTrace();
99 }
100 }
101
102
103
104 private enum EventType{
105 INFECTION, SAMPLE
106 }
107
108
109 private void run() throws IOException{
110 ArrayList<FlexibleTree> detailedTrees = makeTrees();
111 ArrayList<FlexibleTree> simpleTrees = new ArrayList<FlexibleTree>();
112
113 for(FlexibleTree tree : detailedTrees) {
114 FlexibleTree wbTree = makeWellBehavedTree(tree);
115 wbTree.setAttribute("firstCase", tree.getAttribute("firstCase"));
116
117 simpleTrees.add(wbTree);
118 }
119
120
121 for(FlexibleTree tree: detailedTrees){
122 NexusExporter exporter = new NexusExporter(new PrintStream(outputFileRoot
123 + tree.getAttribute("firstCase") + "_detailed.nex"));
124 exporter.exportTree(tree);
125 }
126
127 for(FlexibleTree tree: simpleTrees){
128 NexusExporter exporter = new NexusExporter(new PrintStream(outputFileRoot
129 + tree.getAttribute("firstCase") + "_simple.nex"));
130 exporter.exportTree(tree);
131 }
132
133 }
134
135 private void readInfectionEvents(String fileName) throws IOException{
136 BufferedReader reader = new BufferedReader(new FileReader(fileName));
137
138 ArrayList<String[]> keptLines = new ArrayList<String[]>();
139
140 reader.readLine();
141
142 String line = reader.readLine();
143
144 while(line!=null){
145
146 String[] entries = line.split(",");
147 keptLines.add(entries);
148
149 InfectedUnit unit = new InfectedUnit("ID_"+entries[1]);
150 units.add(unit);
151 idMap.put("ID_"+entries[1], unit);
152
153 line = reader.readLine();
154 }
155
156 for(String[] repeatLine: keptLines){
157
158 InfectedUnit infectee = idMap.get("ID_"+repeatLine[1]);
159 if(!repeatLine[2].equals("-1")){
160 InfectedUnit infector = idMap.get("ID_"+repeatLine[2]);
161 Event infection = new Event(EventType.INFECTION, Double.parseDouble(repeatLine[3]), infector, infectee);
162
163 infector.addInfectionEvent(infection);
164 infectee.setInfectionEvent(infection);
165
166 infectee.parent = infector;
167 } else {
168 Event infection = new Event(EventType.INFECTION, Double.parseDouble(repeatLine[3]), null, infectee);
169 infectee.setInfectionEvent(infection);
170 }
171 }
172 }
173
174 private void readSamplingEvents(String fileName) throws IOException{
175 BufferedReader reader = new BufferedReader(new FileReader(fileName));
176
177 reader.readLine();
178
179 String line = reader.readLine();
180
181 while(line!=null){
182
183 String[] entries = line.split(",");
184
185 if(!entries[7].equals("NA")) {
186
187 if (!idMap.containsKey("ID_"+entries[1])) {
188 throw new RuntimeException("Trying to add a sampling event to unit " + entries[2] + " but this " +
189 "unit not previously defined");
190 }
191
192 InfectedUnit unit = idMap.get("ID_"+entries[1]);
193
194 unit.addSamplingEvent(Double.parseDouble(entries[7]));
195 }
196
197 line = reader.readLine();
198 }
199 }
200
201 // events are only relevant if there is a sampling event somewhere further up the tree
202
203 private FlexibleTree makeTreelet(InfectedUnit unit, ArrayList<Event> relevantEvents){
204
205 if(relevantEvents.size()==0){
206 return null;
207 }
208
209 ArrayList<SimpleNode> nodes = new ArrayList<SimpleNode>();
210
211 unit.sortEvents();
212
213 double lastRelevantEventTime = Double.NEGATIVE_INFINITY;
214
215 for(Event event : relevantEvents){
216 if(event.time > lastRelevantEventTime){
217 lastRelevantEventTime = event.time;
218 }
219 }
220
221 double activeTime = lastRelevantEventTime - unit.infectionEvent.time;
222
223 for(Event event : relevantEvents){
224 Taxon taxon;
225 if(event.type == EventType.INFECTION){
226 taxon = new Taxon(event.infectee.id+"_infected_by_"+event.infector.id+"_"+event.time);
227 } else {
228 taxon = new Taxon(unit.id+"_sampled_"+event.time);
229 }
230 taxon.setDate(new Date(event.time - unit.infectionEvent.time, Units.Type.YEARS, false));
231 SimpleNode node = new SimpleNode();
232 node.setTaxon(taxon);
233 nodes.add(node);
234 node.setHeight(unit.infectionEvent.time - event.time);
235 node.setAttribute("Event", event);
236 }
237
238 FlexibleNode treeletRoot;
239
240 if(nodes.size()>1){
241 treeletRoot = simulateCoalescent(nodes, demFunct, activeTime);
242 } else {
243 treeletRoot = new FlexibleNode(new SimpleTree(nodes.get(0)), nodes.get(0), true);
244 treeletRoot.setHeight(0);
245 }
246
247 // add the root branch length
248
249 FlexibleNode infectionNode = new FlexibleNode();
250 infectionNode.setHeight(activeTime);
251 infectionNode.addChild(treeletRoot);
252 treeletRoot.setLength(activeTime - treeletRoot.getHeight());
253 infectionNode.setAttribute("Event", unit.infectionEvent);
254
255 FlexibleTree outTree = new FlexibleTree(infectionNode);
256
257 for(int i=0; i<outTree.getNodeCount(); i++){
258 FlexibleNode node = (FlexibleNode)outTree.getNode(i);
259 node.setAttribute("Unit", unit.id);
260 }
261
262 return outTree;
263 }
264
265 private ArrayList<FlexibleTree> makeTrees(){
266
267 // find the first case
268
269 ArrayList<InfectedUnit> introducedCases = new ArrayList<InfectedUnit>();
270
271 for(InfectedUnit unit : units){
272 if(unit.parent==null){
273 introducedCases.add(unit);
274 }
275 }
276
277 if(introducedCases.size()==0){
278 throw new RuntimeException("Can't find a first case");
279 }
280
281 ArrayList<FlexibleTree> out = new ArrayList<FlexibleTree>();
282
283 for(InfectedUnit introduction : introducedCases) {
284 coalescentProbability = 1;
285
286 System.out.println("Building tree for descendants of " + introduction.id);
287 FlexibleNode outTreeRoot = makeSubtree(introduction);
288
289 if (outTreeRoot != null) {
290 FlexibleTree finalTree = new FlexibleTree(outTreeRoot, false, true);
291 finalTree.setAttribute("firstCase", introduction.id);
292 out.add(finalTree);
293
294 if(coalescentProbability<0.9){
295 progressStream.println("WARNING: any phylogeny for descendants of "+introduction.id+" is quite " +
296 "improbable (p<"+(coalescentProbability)+") given this demographic function. Consider " +
297 "another.");
298 }
299 } else {
300 progressStream.println("This individual has no sampled descendants");
301 }
302 System.out.println();
303
304
305 }
306 return out;
307 }
308
309 // make the tree from this unit up
310
311 private FlexibleNode makeSubtree(InfectedUnit unit){
312
313 HashMap<Event, FlexibleNode> eventToSubtreeRoot = new HashMap<Event, FlexibleNode>();
314
315 ArrayList<Event> relevantEvents = new ArrayList<Event>();
316
317 for(Event event : unit.childEvents){
318
319 if(event.type == EventType.INFECTION){
320
321 FlexibleNode childSubtreeRoot = makeSubtree(event.infectee);
322
323 if(childSubtreeRoot!=null){
324 relevantEvents.add(event);
325 eventToSubtreeRoot.put(event, childSubtreeRoot);
326 }
327
328 } else if(event.type==EventType.SAMPLE) {
329 relevantEvents.add(event);
330 }
331 }
332
333 FlexibleTree unitTreelet = makeTreelet(unit, relevantEvents);
334
335 if(unitTreelet==null){
336 return null;
337 }
338
339 for(int i=0; i<unitTreelet.getExternalNodeCount(); i++){
340
341 FlexibleNode tip = (FlexibleNode)unitTreelet.getExternalNode(i);
342
343 Event tipEvent = (Event)unitTreelet.getNodeAttribute(tip, "Event");
344
345 if(tipEvent.type == EventType.INFECTION){
346 FlexibleNode subtreeRoot = eventToSubtreeRoot.get(tipEvent);
347
348 FlexibleNode firstSubtreeSplit = subtreeRoot.getChild(0);
349
350 subtreeRoot.removeChild(firstSubtreeSplit);
351 tip.addChild(firstSubtreeSplit);
352
353 }
354 }
355
356 return (FlexibleNode)unitTreelet.getRoot();
357 }
358
359 private FlexibleNode simulateCoalescent(ArrayList<SimpleNode> nodes, DemographicFunction demogFunct,
360 double maxHeight){
361
362 double earliestNodeHeight = Double.NEGATIVE_INFINITY;
363
364 for(SimpleNode node : nodes){
365 if(node.getHeight()>earliestNodeHeight){
366 earliestNodeHeight = node.getHeight();
367 }
368 }
369 double maxLastInterval = earliestNodeHeight;
370 double probNoCoalesenceInTime = Math.exp(demogFunct.getIntensity(maxLastInterval));
371
372 coalescentProbability *= (1-probNoCoalesenceInTime);
373
374
375
376 CoalescentSimulator simulator = new CoalescentSimulator();
377 SimpleNode root;
378
379 SimpleNode[] simResults;
380 int failCount = 0;
381
382 do {
383 simResults = simulator.simulateCoalescent(nodes.toArray(new SimpleNode[nodes.size()]),
384 demogFunct, -maxHeight, 0, true);
385 if(simResults.length>1){
386 failCount++;
387 System.out.println("Failed to coalesce lineages: "+failCount);
388 }
389 } while(simResults.length!=1);
390
391 root = simResults[0];
392
393 SimpleTree simpleTreelet = new SimpleTree(root);
394
395
396 for (int i=0; i<simpleTreelet.getNodeCount(); i++) {
397 SimpleNode node = (SimpleNode)simpleTreelet.getNode(i);
398 node.setHeight(node.getHeight() + maxHeight);
399 }
400
401 return new FlexibleNode(simpleTreelet, root, true);
402 }
403
404 private FlexibleTree makeWellBehavedTree(FlexibleTree tree){
405 FlexibleTree newPhylogeneticTree = new FlexibleTree(tree, false);
406
407 newPhylogeneticTree.beginTreeEdit();
408 for(int i=0; i<newPhylogeneticTree.getInternalNodeCount(); i++){
409 FlexibleNode node = (FlexibleNode)newPhylogeneticTree.getInternalNode(i);
410 if(newPhylogeneticTree.getChildCount(node)==1){
411 FlexibleNode parent = (FlexibleNode)newPhylogeneticTree.getParent(node);
412 FlexibleNode child = (FlexibleNode)newPhylogeneticTree.getChild(node, 0);
413 if(parent!=null){
414 double childHeight = newPhylogeneticTree.getNodeHeight(child);
415 newPhylogeneticTree.removeChild(parent, node);
416 newPhylogeneticTree.addChild(parent, child);
417 newPhylogeneticTree.setNodeHeight(child, childHeight);
418 } else {
419 child.setParent(null);
420 newPhylogeneticTree.setRoot(child);
421 }
422 }
423 }
424 newPhylogeneticTree.endTreeEdit();
425
426
427 return new FlexibleTree(newPhylogeneticTree, true);
428 }
429
430 private class InfectedUnit{
431 private String id;
432 private ArrayList<Event> childEvents;
433 private Event infectionEvent;
434 private InfectedUnit parent;
435
436 private InfectedUnit(String id){
437 this.id = id;
438 parent = null;
439 childEvents = new ArrayList<Event>();
440 }
441
442 private void addSamplingEvent(double time){
443 if(time < infectionEvent.time){
444 throw new RuntimeException("Adding an event to case "+id+" before its infection time");
445 }
446 childEvents.add(new Event(EventType.SAMPLE, time));
447 }
448
449 private void setInfectionEvent(double time, InfectedUnit infector){
450 setInfectionEvent(new Event(EventType.INFECTION, time, infector, this));
451 }
452
453 private void setInfectionEvent(Event event){
454 for(Event childEvent : childEvents){
455 if(event.time > childEvent.time){
456 throw new RuntimeException("Setting infection time for case "+id+" after an existing child event");
457 }
458 }
459
460 infectionEvent = event;
461 }
462
463 private void addChildInfectionEvent(double time, InfectedUnit infectee){
464 addInfectionEvent(new Event(EventType.INFECTION, time, this, infectee));
465 }
466
467 private void addInfectionEvent(Event event){
468 if(infectionEvent!=null && event.time < infectionEvent.time){
469 throw new RuntimeException("Adding an infection event to case "+id+" at "+event.time+" before its " +
470 "infection time at "+infectionEvent.time);
471 }
472 childEvents.add(event);
473 }
474
475 private void sortEvents(){
476 Collections.sort(childEvents);
477 Collections.reverse(childEvents);
478 }
479
480 }
481
482 private class Event implements Comparable<Event>{
483
484 private EventType type;
485 private double time;
486 private InfectedUnit infector;
487 private InfectedUnit infectee;
488
489
490 private Event(EventType type, double time){
491 this.type = type;
492 this.time = time;
493 }
494
495 private Event(EventType type, double time, InfectedUnit infector, InfectedUnit infectee){
496 this.type = type;
497 this.time = time;
498 this.infector = infector;
499 this.infectee = infectee;
500 }
501
502 public int compareTo(Event event) {
503 return Double.compare(time, event.time);
504 }
505 }
506
507 public static void printUsage(Arguments arguments) {
508
509 arguments.printUsage("virusTreeBuilder", "<infections-file-name> <sample-file-name> <output-file-name-root>");
510 }
511
512
513
514 public static void main(String[] args){
515
516 ModelType model = ModelType.CONSTANT;
517 double startNe = 1;
518 double growthRate = 0;
519 double t50 = 0;
520
521 Arguments arguments = new Arguments(
522 new Arguments.Option[]{
523 new Arguments.StringOption(DEMOGRAPHIC_MODEL, demographics, false, "The type of within-host" +
524 " demographic function to use, default = constant"),
525 new Arguments.RealOption(STARTING_POPULATION_SIZE,"The effective population size at time zero" +
526 " (used in all models), default = 1"),
527 new Arguments.RealOption(GROWTH_RATE,"The effective population size growth rate (used in" +
528 " exponential and logistic models), default = 0"),
529 new Arguments.RealOption(T50,"The time point, relative to the time of infection in backwards " +
530 "time, at which the population is equal to half its final asymptotic value, in the " +
531 "logistic model default = 0")
532 });
533
534
535 try {
536 arguments.parseArguments(args);
537 } catch (Arguments.ArgumentException ae) {
538 System.out.println(ae);
539 printUsage(arguments);
540 System.exit(1);
541 }
542
543 if (arguments.hasOption(HELP)) {
544 printUsage(arguments);
545 System.exit(0);
546 }
547
548 if (arguments.hasOption(DEMOGRAPHIC_MODEL)) {
549 String modelString = arguments.getStringOption(DEMOGRAPHIC_MODEL);
550 if(modelString.toLowerCase().startsWith("c")){
551 model = ModelType.CONSTANT;
552 } else if(modelString.toLowerCase().startsWith("e")){
553 model = ModelType.EXPONENTIAL;
554 } else if(modelString.toLowerCase().startsWith("l")){
555 model = ModelType.LOGISTIC;
556 } else {
557 progressStream.print("Unrecognised demographic model type");
558 System.exit(1);
559 }
560 }
561
562
563 if(arguments.hasOption(STARTING_POPULATION_SIZE)){
564 startNe = arguments.getRealOption(STARTING_POPULATION_SIZE);
565 }
566
567 if(arguments.hasOption(GROWTH_RATE) && model!=ModelType.CONSTANT){
568 growthRate = arguments.getRealOption(GROWTH_RATE);
569 }
570
571 if(arguments.hasOption(T50) && model==ModelType.LOGISTIC){
572 t50 = arguments.getRealOption(T50);
573 }
574
575 DemographicFunction demoFunction = null;
576
577 switch(model){
578 case CONSTANT: {
579 demoFunction = new ConstantPopulation(Units.Type.YEARS);
580 ((ConstantPopulation)demoFunction).setN0(startNe);
581 }
582 case EXPONENTIAL: {
583 demoFunction = new ExponentialGrowth(Units.Type.YEARS);
584 ((ExponentialGrowth)demoFunction).setN0(startNe);
585 ((ExponentialGrowth)demoFunction).setGrowthRate(growthRate);
586 }
587 case LOGISTIC: {
588 demoFunction = new LogisticGrowthN0(Units.Type.YEARS);
589 ((LogisticGrowthN0)demoFunction).setN0(startNe);
590 ((LogisticGrowthN0)demoFunction).setGrowthRate(growthRate);
591 ((LogisticGrowthN0)demoFunction).setT50(t50);
592 }
593 }
594
595 final String[] args2 = arguments.getLeftoverArguments();
596
597 if(args2.length!=3){
598 printUsage(arguments);
599 System.exit(1);
600 }
601
602 String infectionsFileName = args2[0];
603 String samplesFileName = args2[1];
604 String outputFileRoot = args2[2];
605
606
607 TransmissionTreeToVirusTree instance = new TransmissionTreeToVirusTree(samplesFileName,
608 infectionsFileName, demoFunction, outputFileRoot);
609
610 try{
611 instance.run();
612 } catch (IOException e){
613 e.printStackTrace();
614 }
615 }
616 }