Debian Codegraph @

src/dr/app/tools/TreeSummary.java

raw symbols SCIP
1 /*
2 * TreeSummary.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.beast.BeastVersion;
29 import dr.app.util.Arguments;
30 import dr.evolution.io.Importer;
31 import dr.evolution.io.NexusImporter;
32 import dr.evolution.io.TreeImporter;
33 import dr.evolution.tree.*;
34 import dr.evolution.util.Taxon;
35 import dr.evolution.util.TaxonList;
36 import dr.util.Version;
37
38 import java.io.FileOutputStream;
39 import java.io.FileReader;
40 import java.io.IOException;
41 import java.io.PrintStream;
42 import java.util.*;
43
44 /**
45 * @author Andrew Rambaut
46 */
47 public class TreeSummary {
48
49 private final static Version version = new BeastVersion();
50
51 // Messages to stderr, output to stdout
52 private static PrintStream progressStream = System.err;
53
54 /**
55 * Burnin can be specified as the number of trees or the number of states
56 * (one or other should be zero).
57 * @param burninTrees
58 * @param burninStates
59 * @param posteriorLimit
60 * @param inputFileName
61 * @param outputFileName
62 * @throws java.io.IOException
63 */
64 public TreeSummary(final int burninTrees,
65 final int burninStates,
66 double posteriorLimit,
67 boolean createSummaryTree,
68 boolean createCladeMap,
69 String inputFileName,
70 String outputFileName
71 ) throws IOException {
72
73 this.posteriorLimit = posteriorLimit;
74
75 CladeSystem cladeSystem = new CladeSystem();
76
77 int burnin = -1;
78
79 totalTrees = 10000;
80 totalTreesUsed = 0;
81
82 progressStream.println("Reading trees (bar assumes 10,000 trees)...");
83 progressStream.println("0 25 50 75 100");
84 progressStream.println("|--------------|--------------|--------------|--------------|");
85
86 int stepSize = totalTrees / 60;
87 if (stepSize < 1) stepSize = 1;
88
89 cladeSystem = new CladeSystem();
90 FileReader fileReader = new FileReader(inputFileName);
91 TreeImporter importer = new NexusImporter(fileReader);
92 try {
93 totalTrees = 0;
94 while (importer.hasTree()) {
95 Tree tree = importer.importNextTree();
96
97 int state = Integer.MAX_VALUE;
98
99 if (burninStates > 0) {
100 // if burnin has been specified in states, try to parse it out...
101 String name = tree.getId().trim();
102
103 if (name != null && name.length() > 0 && name.startsWith("STATE_")) {
104 state = Integer.parseInt(name.split("_")[1]);
105 }
106 }
107
108 if (totalTrees >= burninTrees && state >= burninStates) {
109 // if either of the two burnin thresholds have been reached...
110
111 if (burnin < 0) {
112 // if this is the first time this point has been reached,
113 // record the number of trees this represents for future use...
114 burnin = totalTrees;
115 }
116
117 cladeSystem.add(tree, true);
118
119 totalTreesUsed += 1;
120 }
121
122 if (totalTrees > 0 && totalTrees % stepSize == 0) {
123 progressStream.print("*");
124 progressStream.flush();
125 }
126 totalTrees++;
127 }
128
129 } catch (Importer.ImportException e) {
130 System.err.println("Error Parsing Input Tree: " + e.getMessage());
131 return;
132 }
133 fileReader.close();
134 progressStream.println();
135 progressStream.println();
136
137 if (totalTrees < 1) {
138 System.err.println("No trees");
139 return;
140 }
141 if (totalTreesUsed <= 1) {
142 if (burnin > 0) {
143 System.err.println("No trees to use: burnin too high");
144 return;
145 }
146 }
147 cladeSystem.calculateCladeCredibilities(totalTreesUsed);
148
149 progressStream.println("Total trees read: " + totalTrees);
150 if (burninTrees > 0) {
151 progressStream.println("Ignoring first " + burninTrees + " trees" +
152 (burninStates > 0 ? " (" + burninStates + " states)." : "." ));
153 } else if (burninStates > 0) {
154 progressStream.println("Ignoring first " + burninStates + " states (" + burnin + " trees).");
155 }
156
157 progressStream.println("Total unique clades: " + cladeSystem.getCladeMap().keySet().size());
158 progressStream.println();
159
160 if (createCladeMap) {
161
162 Map<BitSet, Integer> cladeCountMap = cladeSystem.getCladeCounts();
163
164 System.out.println("No.\tSize\tCred\tMembers");
165 int n = 1;
166 for (BitSet bits : cladeCountMap.keySet()) {
167 System.out.print(n);
168 System.out.print("\t");
169 System.out.print(bits.cardinality());
170 System.out.print("\t");
171 System.out.print(cladeSystem.getCladeCredibility(bits));
172 System.out.print("\t");
173 System.out.println(cladeSystem.getCladeString(bits));
174 n++;
175 }
176 System.out.println();
177
178
179 progressStream.println("Reading trees...");
180 progressStream.println("0 25 50 75 100");
181 progressStream.println("|--------------|--------------|--------------|--------------|");
182
183 stepSize = totalTrees / 60;
184
185 fileReader = new FileReader(inputFileName);
186 importer = new NexusImporter(fileReader);
187 final PrintStream stream = outputFileName != null ?
188 new PrintStream(new FileOutputStream(outputFileName)) :
189 System.out;
190
191 stream.print("Clade");
192 n = 1;
193 for (BitSet bits : cladeCountMap.keySet()) {
194 stream.print("\t");
195 stream.print(n);
196 n++;
197 }
198 stream.println();
199
200 stream.print("State");
201 for (BitSet bits : cladeCountMap.keySet()) {
202 stream.print("\t");
203 stream.print(cladeSystem.getCladeCredibility(bits));
204 }
205 stream.println();
206
207 try {
208 totalTrees = 0;
209 while (importer.hasTree()) {
210 Tree tree = importer.importNextTree();
211
212 int state = totalTrees;
213
214 if (burninStates > 0) {
215 // if burnin has been specified in states, try to parse it out...
216 String name = tree.getId().trim();
217
218 if (name != null && name.length() > 0 && name.startsWith("STATE_")) {
219 state = Integer.parseInt(name.split("_")[1]);
220 }
221 }
222
223 if (totalTrees >= burninTrees && state >= burninStates) {
224 // if either of the two burnin thresholds have been reached...
225
226 if (burnin < 0) {
227 // if this is the first time this point has been reached,
228 // record the number of trees this represents for future use...
229 burnin = totalTrees;
230 }
231
232 stream.print(state);
233
234 Set<BitSet> cladeSet = cladeSystem.getCladeSet(tree);
235
236 for (BitSet bits : cladeCountMap.keySet()) {
237 stream.print("\t");
238 stream.print(cladeSet.contains(bits) ? "1" : "0");
239 }
240 stream.println();
241
242 totalTreesUsed += 1;
243 }
244
245 if (totalTrees > 0 && totalTrees % stepSize == 0) {
246 progressStream.print("*");
247 progressStream.flush();
248 }
249 totalTrees++;
250 }
251
252 } catch (Importer.ImportException e) {
253 System.err.println("Error Parsing Input Tree: " + e.getMessage());
254 return;
255 }
256 fileReader.close();
257 stream.close();
258 progressStream.println();
259 progressStream.println();
260 }
261 if (createSummaryTree) {
262 progressStream.println("Finding summary tree...");
263
264 // MutableTree targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName /*, false*/));
265
266 Tree consensusTree = buildConsensusTree(cladeSystem);
267
268 progressStream.println("Writing consensus tree....");
269
270 try {
271 final PrintStream stream = outputFileName != null ?
272 new PrintStream(new FileOutputStream(outputFileName)) :
273 System.out;
274
275 new NexusExporter(stream).exportTree(consensusTree);
276 } catch (Exception e) {
277 System.err.println("Error writing consensus tree file: " + e.getMessage());
278 return;
279 }
280 }
281
282 }
283
284 private Tree buildConsensusTree(CladeSystem cladeSystem) {
285 List<BitSet> bitSets = new ArrayList<BitSet>(cladeSystem.getCladeMap().keySet());
286
287 Collections.sort(bitSets, new Comparator<BitSet>() {
288 @Override
289 public int compare(BitSet b1, BitSet b2) {
290 return b1.cardinality() - b2.cardinality();
291 }
292 });
293
294 SimpleNode root = null;
295
296 for (int i = 0; i < bitSets.size(); i++) {
297 BitSet key1 = bitSets.get(i);
298 CladeSystem.Clade clade1 = cladeSystem.getCladeMap().get(key1);
299
300 if (key1.cardinality() == 1) {
301 Taxon taxon = cladeSystem.getTaxon(key1.nextSetBit(0));
302 clade1.node = new SimpleNode();
303 clade1.node.setTaxon(taxon);
304
305 clade1.node.setAttribute("clade", clade1);
306 }
307
308 if (clade1.credibility >= posteriorLimit) {
309
310 for (int j = i + 1; j < bitSets.size(); j++) {
311 BitSet key2 = bitSets.get(j);
312 if (isSubSet(key1, key2) && cladeSystem.getCladeCredibility(key2) >= posteriorLimit) {
313 // the clades are ordered by size so this is the smallest clade for which
314 // clade1 is a subset and has high credibility.
315 CladeSystem.Clade clade2 = cladeSystem.getCladeMap().get(key2);
316 if (clade2.node == null) {
317 clade2.node = new SimpleNode();
318 }
319 if (clade1.node == null) {
320 throw new RuntimeException("null node");
321 }
322 clade2.node.addChild(clade1.node);
323
324 clade2.node.setAttribute("credibility", clade2.credibility);
325 clade2.node.setAttribute("clade", clade2);
326
327 if (key2.cardinality() == cladeSystem.taxonList.getTaxonCount()) {
328 root = clade2.node;
329 }
330 break;
331 }
332
333 }
334 }
335 }
336 SimpleTree tree = new SimpleTree(root);
337
338 return tree;
339 }
340
341 private Tree summarizeTrees(int burnin, Tree consensusTree, CladeSystem cladeSystem, String inputFileName)
342 throws IOException {
343
344 progressStream.println("Analyzing " + totalTreesUsed + " trees...");
345 progressStream.println("0 25 50 75 100");
346 progressStream.println("|--------------|--------------|--------------|--------------|");
347
348 int stepSize = totalTrees / 60;
349 if (stepSize < 1) stepSize = 1;
350
351 int counter = 0;
352 int bestTreeNumber = 0;
353 TreeImporter importer = new NexusImporter(new FileReader(inputFileName));
354
355 try {
356 while (importer.hasTree()) {
357 Tree tree = importer.importNextTree();
358
359 if (counter >= burnin) {
360 cladeSystem.addSubTrees(tree);
361 }
362 if (counter > 0 && counter % stepSize == 0) {
363 progressStream.print("*");
364 progressStream.flush();
365 }
366 counter++;
367 }
368 } catch (Importer.ImportException e) {
369 System.err.println("Error Parsing Input Tree: " + e.getMessage());
370 return null;
371 }
372
373 Tree bestTree = cladeSystem.getBestTree(consensusTree);
374
375 return bestTree;
376 }
377
378 private class CladeSystem {
379
380 public CladeSystem() {
381 }
382
383 public CladeSystem(TaxonList taxonList) {
384 this.taxonList = taxonList;
385 }
386
387 /**
388 * adds all the clades in the tree
389 */
390 public void add(Tree tree, boolean includeTips) {
391 if (taxonList == null) {
392 taxonList = tree;
393 }
394
395 // Recurse over the tree and add all the clades (or increment their
396 // frequency if already present). The root clade is added too (for
397 // annotation purposes).
398 addClades(tree, tree.getRoot(), includeTips);
399 }
400
401 private BitSet addClades(Tree tree, NodeRef node, boolean includeTips) {
402
403 BitSet bits = new BitSet();
404
405 if (tree.isExternal(node)) {
406
407 int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
408 bits.set(index);
409
410 if (includeTips) {
411 addClade(bits);
412 }
413
414 } else {
415
416 for (int i = 0; i < tree.getChildCount(node); i++) {
417
418 NodeRef node1 = tree.getChild(node, i);
419
420 bits.or(addClades(tree, node1, includeTips));
421 }
422
423 addClade(bits);
424 }
425
426 return bits;
427 }
428
429 private void addClade(BitSet bits) {
430 Clade clade = cladeMap.get(bits);
431 if (clade == null) {
432 clade = new Clade(bits);
433 cladeMap.put(bits, clade);
434 }
435 clade.setCount(clade.getCount() + 1);
436 }
437
438 public void addSubTrees(Tree tree) {
439 addSubTrees(tree, tree.getRoot());
440 }
441
442 private BitSet addSubTrees(Tree tree, NodeRef node) {
443
444 BitSet bits = new BitSet();
445
446 if (tree.isExternal(node)) {
447
448 int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
449 bits.set(index);
450
451 } else {
452
453 for (int i = 0; i < tree.getChildCount(node); i++) {
454
455 NodeRef node1 = tree.getChild(node, i);
456
457 BitSet bits2 = addSubTrees(tree, node1);
458
459 bits.or(bits2);
460 }
461
462 Clade clade = cladeMap.get(bits);
463
464 if (clade.credibility >= posteriorLimit) {
465 if (clade.conditionalCladeSystem == null) {
466 clade.conditionalCladeSystem = new CladeSystem(taxonList);
467 }
468 clade.conditionalCladeSystem.addClades(tree, node, false);
469 }
470 }
471
472 return bits;
473 }
474
475 public Map<BitSet, Clade> getCladeMap() {
476 return cladeMap;
477 }
478
479 public void calculateCladeCredibilities(int totalTreesUsed) {
480 for (Clade clade : cladeMap.values()) {
481
482 if (clade.getCount() > totalTreesUsed) {
483
484 throw new AssertionError("clade.getCount=(" + clade.getCount() +
485 ") should be <= totalTreesUsed = (" + totalTreesUsed + ")");
486 }
487
488 clade.setCredibility(((double) clade.getCount()) / (double) totalTreesUsed);
489
490 if (clade.conditionalCladeSystem != null) {
491 clade.conditionalCladeSystem.calculateCladeCredibilities(totalTreesUsed);
492 }
493 }
494 }
495
496 public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) {
497
498 double logCladeCredibility = 0.0;
499
500 if (tree.isExternal(node)) {
501
502 int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
503 bits.set(index);
504 } else {
505
506 BitSet bits2 = new BitSet();
507 for (int i = 0; i < tree.getChildCount(node); i++) {
508
509 NodeRef node1 = tree.getChild(node, i);
510
511 logCladeCredibility += getLogCladeCredibility(tree, node1, bits2);
512 }
513
514 logCladeCredibility += Math.log(getCladeCredibility(bits2));
515
516 if (bits != null) {
517 bits.or(bits2);
518 }
519 }
520
521 return logCladeCredibility;
522 }
523
524 private double getCladeCredibility(BitSet bits) {
525 Clade clade = cladeMap.get(bits);
526 if (clade == null) {
527 return 0.0;
528 }
529 return clade.getCredibility();
530 }
531
532 private int getCladeCount(BitSet bits) {
533 Clade clade = cladeMap.get(bits);
534 if (clade == null) {
535 return 0;
536 }
537 return clade.getCount();
538 }
539
540 public Tree getBestTree(Tree consensusTree) {
541 return new SimpleTree(getBestSubTree(consensusTree, consensusTree.getRoot()));
542 }
543
544 public SimpleNode getBestSubTree(Tree tree, NodeRef node) {
545 SimpleNode subTree = null;
546
547 if (tree.isExternal(node)) {
548 } else {
549
550 Clade clade = (Clade) tree.getNodeAttribute(node, "clade");
551 if (clade.conditionalCladeSystem != null) {
552 subTree = clade.conditionalCladeSystem.getBestSubTree(tree, node);
553 } else {
554
555 for (int i = 0; i < tree.getChildCount(node); i++) {
556
557 NodeRef child = tree.getChild(node, i);
558
559 SimpleNode newChild = getBestSubTree(tree, child);
560 }
561
562 }
563
564 }
565
566
567 return subTree;
568 }
569
570 public Taxon getTaxon(int index) {
571 return taxonList.getTaxon(index);
572 }
573
574 private BitSet getClades(Tree tree, NodeRef node, boolean includeTips, Set<BitSet> cladeSet) {
575
576 BitSet bits = new BitSet();
577
578 if (tree.isExternal(node)) {
579
580 int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
581 bits.set(index);
582
583 if (includeTips) {
584 cladeSet.add(bits);
585 }
586
587 } else {
588
589 for (int i = 0; i < tree.getChildCount(node); i++) {
590
591 NodeRef node1 = tree.getChild(node, i);
592
593 bits.or(getClades(tree, node1, includeTips, cladeSet));
594 }
595
596 cladeSet.add(bits);
597 }
598
599 return bits;
600 }
601
602 public Set<BitSet> getCladeSet(Tree tree) {
603 Set<BitSet> cladeSet = new HashSet<BitSet>();
604 getClades(tree, tree.getRoot(), false, cladeSet);
605 return cladeSet;
606 }
607
608 public Map<BitSet, Integer> getCladeCounts() {
609 Map<BitSet, Integer> countMap = new HashMap<BitSet, Integer>();
610
611 for (BitSet bits : cladeMap.keySet()) {
612 int count = getCladeCount(bits);
613 if (count > 1) {
614 countMap.put(bits, count);
615 }
616 }
617
618 return countMap;
619 }
620
621 public String getCladeString(BitSet bits) {
622 StringBuilder sb = new StringBuilder("{");
623 int index = bits.nextSetBit(0);
624 if (index != -1) {
625 sb.append(taxonList.getTaxon(index).getId());
626 index = bits.nextSetBit(index + 1);
627 }
628 while (index != -1) {
629 sb.append(",");
630 sb.append(taxonList.getTaxon(index).getId());
631 index = bits.nextSetBit(index + 1);
632 }
633 sb.append("}");
634 return sb.toString();
635 }
636
637 class Clade {
638 public Clade(BitSet bits) {
639 this.bits = bits;
640 count = 0;
641 credibility = 0.0;
642 }
643
644 public int getCount() {
645 return count;
646 }
647
648 public void setCount(int count) {
649 this.count = count;
650 }
651
652 public double getCredibility() {
653 return credibility;
654 }
655
656 public void setCredibility(double credibility) {
657 this.credibility = credibility;
658 }
659
660 public boolean equals(Object o) {
661 if (this == o) return true;
662 if (o == null || getClass() != o.getClass()) return false;
663
664 final Clade clade = (Clade) o;
665
666 return !(bits != null ? !bits.equals(clade.bits) : clade.bits != null);
667
668 }
669
670 public int hashCode() {
671 return (bits != null ? bits.hashCode() : 0);
672 }
673
674 public String toString() {
675 return "clade " + bits.toString();
676 }
677
678 int count;
679 double credibility;
680 BitSet bits;
681 SimpleNode node;
682 CladeSystem conditionalCladeSystem;
683 }
684
685 //
686 // Private stuff
687 //
688 TaxonList taxonList = null;
689 Map<BitSet, Clade> cladeMap = new HashMap<BitSet, Clade>();
690
691 Tree targetTree;
692 }
693
694 int totalTrees = 0;
695 int totalTreesUsed = 0;
696 double posteriorLimit = 0.0;
697
698 Set<String> attributeNames = new HashSet<String>();
699
700 public static void printTitle() {
701 progressStream.println();
702 centreLine("TreeSummary " + version.getVersionString() + ", " + version.getDateString(), 60);
703 centreLine("MCMC tree set summarizer", 60);
704 centreLine("by", 60);
705 centreLine("Andrew Rambaut", 60);
706 progressStream.println();
707 centreLine("Institute of Evolutionary Biology", 60);
708 centreLine("University of Edinburgh", 60);
709 centreLine("[email protected]", 60);
710 progressStream.println();
711 progressStream.println();
712 }
713
714 public static void centreLine(String line, int pageWidth) {
715 int n = pageWidth - line.length();
716 int n1 = n / 2;
717 for (int i = 0; i < n1; i++) {
718 progressStream.print(" ");
719 }
720 progressStream.println(line);
721 }
722
723
724 public static void printUsage(Arguments arguments) {
725
726 arguments.printUsage("treesummary", "<input-file-name> [<output-file-name>]");
727 progressStream.println();
728 progressStream.println(" Example: treesummary test.trees out.txt");
729 progressStream.println(" Example: treesummary -burnin 100 -heights mean test.trees out.txt");
730 progressStream.println();
731 }
732
733 //Main method
734 public static void main(String[] args) throws IOException {
735
736 // There is a major issue with languages that use the comma as a decimal separator.
737 // To ensure compatibility between programs in the package, enforce the US locale.
738 Locale.setDefault(Locale.US);
739
740 String inputFileName = null;
741 String outputFileName = null;
742
743 printTitle();
744
745 Arguments arguments = new Arguments(
746 new Arguments.Option[]{
747 new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"),
748 new Arguments.IntegerOption("burninTrees", "the number of trees to be considered as 'burn-in'"),
749 new Arguments.Option("clademap", "show states of all clades over chain length"),
750 new Arguments.RealOption("limit", "the minimum posterior probability for a subtree to be included"),
751 new Arguments.Option("help", "option to print this message")
752 });
753
754 try {
755 arguments.parseArguments(args);
756 } catch (Arguments.ArgumentException ae) {
757 progressStream.println(ae);
758 printUsage(arguments);
759 System.exit(1);
760 }
761
762 if (arguments.hasOption("help")) {
763 printUsage(arguments);
764 System.exit(0);
765 }
766
767 int burninStates = -1;
768 int burninTrees = -1;
769 if (arguments.hasOption("burnin")) {
770 burninStates = arguments.getIntegerOption("burnin");
771 }
772 if (arguments.hasOption("burninTrees")) {
773 burninTrees = arguments.getIntegerOption("burninTrees");
774 }
775
776 double posteriorLimit = 0.5;
777 if (arguments.hasOption("limit")) {
778 posteriorLimit = arguments.getRealOption("limit");
779 }
780
781 final String[] args2 = arguments.getLeftoverArguments();
782
783 boolean createCladeMap = false;
784 boolean createSummaryTree = true;
785
786 if (arguments.hasOption("clademap")) {
787 createCladeMap = true;
788 createSummaryTree = false;
789 }
790
791
792 switch (args2.length) {
793 case 2:
794 outputFileName = args2[1];
795 // fall to
796 case 1:
797 inputFileName = args2[0];
798 break;
799 default: {
800 System.err.println("Unknown option: " + args2[2]);
801 System.err.println();
802 printUsage(arguments);
803 System.exit(1);
804 }
805 }
806
807 new TreeSummary(burninTrees, burninStates, posteriorLimit, createSummaryTree, createCladeMap, inputFileName, outputFileName);
808
809 System.exit(0);
810 }
811
812 /**
813 * Is x a subset of y?
814 * @param x
815 * @param y
816 * @return
817 */
818 static boolean isSubSet(BitSet x, BitSet y) {
819 y = (BitSet) y.clone();
820 y.and(x);
821 return y.equals(x);
822 }
823
824 }
825