Debian Codegraph @

src/dr/evomodel/tree/ConditionalCladeFrequency.java

raw symbols SCIP
1 /*
2 * ConditionalCladeFrequency.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 /**
27 *
28 */
29 package dr.evomodel.tree;
30
31 import dr.evolution.io.Importer;
32 import dr.evolution.io.NewickImporter;
33 import dr.evolution.io.NexusImporter;
34 import dr.evolution.io.TreeTrace;
35 import dr.evolution.tree.Clade;
36 import dr.evolution.tree.NodeRef;
37 import dr.evolution.tree.SimpleTree;
38 import dr.evolution.tree.Tree;
39 import dr.inference.model.Likelihood;
40 import dr.math.MathUtils;
41
42 import java.io.BufferedReader;
43 import java.io.IOException;
44 import java.io.Reader;
45 import java.util.*;
46
47 /**
48 * @author Sebastian Hoehna
49 * <p/>
50 * This class calculates the conditional clade probabilities for a set of trees.
51 * It can be used to estimate the marginal posterior for a given tree.
52 */
53 public class ConditionalCladeFrequency extends
54 AbstractCladeImportanceDistribution {
55
56 private double EPSILON;
57
58 private long samples = 0;
59
60 private HashMap<BitSet, Clade> cladeProbabilities;
61
62 private HashMap<BitSet, HashMap<BitSet, Clade>> cladeCoProbabilities;
63
64 private TreeTrace[] traces;
65
66 private int burnin;
67
68 /**
69 * @param epsilon - the default number of occurences for each clade which wasn't
70 * observed to guarantee non-zero probabilities
71 */
72 public ConditionalCladeFrequency(Tree tree, double epsilon) {
73
74 // initializing global variables
75 cladeProbabilities = new HashMap<BitSet, Clade>();
76 cladeCoProbabilities = new HashMap<BitSet, HashMap<BitSet, Clade>>();
77
78 // setting global variables
79 EPSILON = epsilon;
80 }
81
82 /**
83 * @param traces - samples of trees in a tree traces array.
84 * @param epsilon - the default number of occurences for each clade which wasn't
85 * observed to guarantee non-zero probabilities
86 * @param burnIn - number of trees discarded from the trace
87 * @param verbose - hide the runtime status and outputs
88 */
89 public ConditionalCladeFrequency(TreeTrace[] traces, double epsilon,
90 int burnIn, boolean verbose) {
91
92 // initializing global variables
93 cladeProbabilities = new HashMap<BitSet, Clade>();
94 cladeCoProbabilities = new HashMap<BitSet, HashMap<BitSet, Clade>>();
95
96 // setting global variables
97 EPSILON = epsilon;
98 this.traces = traces;
99
100 // calculates the burn-in to 10% if it was set out of the boundaries
101 int minMaxState = Integer.MAX_VALUE;
102 for (TreeTrace trace : traces) {
103 if (trace.getMaximumState() < minMaxState) {
104 minMaxState = trace.getMaximumState();
105 }
106 }
107
108 if (burnIn < 0 || burnIn >= minMaxState) {
109 this.burnin = minMaxState / (10 * traces[0].getStepSize());
110 if (verbose)
111 System.out
112 .println("WARNING: Burn-in larger than total number of states - using 10% of smallest trace");
113 } else {
114 this.burnin = burnIn;
115 }
116
117 // analyzing the whole trace -> reading the trees
118 analyzeTrace(verbose);
119 }
120
121 /**
122 * Actually analyzes the trace given the burn-in. Each tree from the trace
123 * is read and the conditional clade frequencies incremented.
124 *
125 * @param verbose if true then progress is logged to stdout
126 */
127 public void analyzeTrace(boolean verbose) {
128
129 if (verbose) {
130 if (traces.length > 1)
131 System.out.println("Combining " + traces.length + " traces.");
132 }
133
134 // get first tree to extract the taxon
135 Tree tree = getTree(0);
136 // taxonMap = getTaxonMap(tree);
137
138 // read every tree from the trace
139 for (TreeTrace trace : traces) {
140 // do some output stuff
141 int treeCount = trace.getTreeCount(burnin * trace.getStepSize());
142 double stepSize = treeCount / 60.0;
143 int counter = 1;
144
145 if (verbose) {
146 System.out.println("Analyzing " + treeCount + " trees...");
147 System.out
148 .println("0 25 50 75 100");
149 System.out
150 .println("|--------------|--------------|--------------|--------------|");
151 System.out.print("*");
152 }
153 for (int i = 1; i < treeCount; i++) {
154 // get the next tree
155 tree = trace.getTree(i, burnin * trace.getStepSize());
156
157 // add the tree and its clades to the frequencies
158 addTree(tree);
159
160 // some more output stuff
161 if (i >= (int) Math.round(counter * stepSize) && counter <= 60) {
162 if (verbose) {
163 System.out.print("*");
164 System.out.flush();
165 }
166 counter += 1;
167 }
168 }
169 if (verbose) {
170 System.out.println("*");
171 }
172 }
173 }
174
175 /**
176 * Creates the report. The estimated posterior of the given tree is printed.
177 *
178 * @throws IOException if general I/O error occurs
179 */
180 public void report(Reader r) throws IOException, Importer.ImportException {
181
182 System.err.println("making report");
183
184 ArrayList<Tree> referenceTrees = new ArrayList<Tree>();
185
186 BufferedReader reader = new BufferedReader(r);
187 String line = reader.readLine();
188
189 if (line.toUpperCase().startsWith("#NEXUS")) {
190 NexusImporter importer = new NexusImporter(reader);
191 Tree[] trees = importer.importTrees(null);
192
193 for (Tree tree : trees) {
194 referenceTrees.add(tree);
195
196 SimpleTree sTree = new SimpleTree(tree);
197 System.out.println("Estimated marginal posterior by condiational clade frequencies:");
198 System.out.println(getTreeProbability(sTree) + "\t\t" + sTree);
199 }
200 } else {
201 throw new RuntimeException("Could not read reference tree. Only Nexus format is supported.");
202 }
203
204 System.out.flush();
205 }
206
207 /**
208 * Calculates the probability of a given tree.
209 *
210 * @param tree - the tree to be analyzed
211 * @return estimated posterior probability in log
212 */
213 public double getTreeProbability(Tree tree) {
214
215 double prob = 0.0;
216
217 List<Clade> clades = new ArrayList<Clade>();
218 List<Clade> parentClades = new ArrayList<Clade>();
219 // get clades contained in the tree
220 getNonComplementaryClades(tree, tree.getRoot(), parentClades, clades);
221
222 int size = clades.size();
223 // for every clade multiply its conditional clade probability to the tree probability
224 for (int i = 0; i < size; i++) {
225 Clade c = clades.get(i);
226
227 // get the bits of the clade
228 Clade parent = parentClades.get(i);
229
230 // set the occurrences to epsilon
231 double tmp = EPSILON;
232 double parentOccurrences = 0.0;
233 BitSet parentBits = parent.getBits();
234 if (cladeProbabilities.containsKey(parentBits)) {
235 // if we observed this clade in the trace, add the occurrences to epsilon
236 parentOccurrences += cladeProbabilities.get(parentBits)
237 .getSampleCount();
238 }
239
240 if (cladeCoProbabilities.containsKey(parentBits)) {
241 // if we observed the parent clade
242 HashMap<BitSet, Clade> conditionalProbs = cladeCoProbabilities
243 .get(parentBits);
244
245 BitSet bits = c.getBits();
246 if (conditionalProbs.containsKey(bits)) {
247 // if we observed this conditional clade in the trace, add the occurrences to epsilon
248 tmp += conditionalProbs.get(bits).getSampleCount();
249 }
250 }
251 // add epsilon for each clade
252 final double splits = Math.pow(2, parent.getSize() - 1) - 1;
253 parentOccurrences += EPSILON * splits;
254
255 // multiply the conditional clade probability to the tree
256 // probability
257 prob += Math.log(tmp / parentOccurrences);
258
259 }
260
261 return prob;
262 }
263
264 /**
265 * Calculates the probability of a given tree.
266 *
267 * @param tree - the tree to be analyzed
268 * @return estimated posterior probability in log
269 */
270 public double getTreeProbability(Tree tree,
271 HashMap<String, Integer> taxonMap) {
272 double prob = 0.0;
273
274 List<Clade> clades = new ArrayList<Clade>();
275 List<Clade> parentClades = new ArrayList<Clade>();
276 // get clades contained in the tree
277 getNonComplementaryClades(tree, tree.getRoot(), parentClades, clades,
278 taxonMap);
279
280 int size = clades.size();
281 // for every clade multiply its conditional clade probability to the
282 // tree probability
283 for (int i = 0; i < size; i++) {
284 Clade c = clades.get(i);
285
286 // get the bits of the clade
287 Clade parent = parentClades.get(i);
288
289 // set the occurrences to epsilon
290 double tmp = EPSILON;
291 double parentOccurrences = 0.0;
292 BitSet parentBits = parent.getBits();
293 if (cladeProbabilities.containsKey(parentBits)) {
294 // if we observed this clade in the trace, add the
295 // occurrences
296 // to epsilon
297 parentOccurrences += cladeProbabilities.get(parentBits)
298 .getSampleCount();
299 }
300
301 if (cladeCoProbabilities.containsKey(parentBits)) {
302 // if we observed the parent clade
303 HashMap<BitSet, Clade> conditionalProbs = cladeCoProbabilities
304 .get(parentBits);
305
306 BitSet bits = c.getBits();
307 if (conditionalProbs.containsKey(bits)) {
308 // if we observed this conditional clade in the trace,
309 // add
310 // the occurrences to epsilon
311 tmp += conditionalProbs.get(bits).getSampleCount();
312 }
313 }
314 // add epsilon for each clade
315 final double splits = Math.pow(2, parent.getSize() - 1) - 1;
316 parentOccurrences += EPSILON * splits;
317
318 // multiply the conditional clade probability to the tree
319 // probability
320 prob += Math.log(tmp / parentOccurrences);
321
322 }
323
324 return prob;
325 }
326
327 public double splitClade(Clade parent, Clade[] children) {
328 // the number of all possible clades is 2^n with n the number of tips
329 // reduced by 2 because we wont consider the clades with all or no tips
330 // contained
331 // divide this number by 2 because every clade has a matching clade to
332 // form the split
333 // #splits = 2^(n-1) - 1
334 final double splits = Math.pow(2, parent.getSize() - 1) - 1;
335
336 double prob = 0;
337
338 if (cladeCoProbabilities.containsKey(parent.getBits())) {
339 HashMap<BitSet, Clade> childClades = cladeCoProbabilities
340 .get(parent.getBits());
341 double noChildClades = 0.0;
342
343 double sum = 0.0;
344 Set<BitSet> keys = childClades.keySet();
345 for (BitSet child : keys) {
346 Clade tmp = childClades.get(child);
347 if (parent.getSize() > tmp.getSize() + 1) {
348 sum += (tmp.getSampleCount() + EPSILON) / 2.0;
349 noChildClades += 0.5;
350 } else {
351 sum += (tmp.getSampleCount() + EPSILON);
352 noChildClades += 1.0;
353 }
354 }
355
356 // add epsilon for each not observed clade
357 sum += EPSILON * (splits - noChildClades);
358
359 // roulette wheel
360 double randomNumber = MathUtils.nextDouble() * sum;
361 for (BitSet child : keys) {
362 Clade tmp = childClades.get(child);
363 if (parent.getSize() > tmp.getSize() + 1) {
364 randomNumber -= (tmp.getSampleCount() + EPSILON) / 2.0;
365 } else {
366 randomNumber -= (tmp.getSampleCount() + EPSILON);
367 }
368 if (randomNumber < 0) {
369 children[0] = tmp;
370 prob = (tmp.getSampleCount() + EPSILON) / sum;
371 break;
372 }
373 }
374
375 if (randomNumber >= 0) {
376 // randomNumber /= EPSILON;
377 prob = EPSILON / sum;
378 BitSet newChild;
379 BitSet inverseBits;
380 do {
381 do {
382 newChild = (BitSet) parent.getBits().clone();
383 int index = -1;
384 do {
385 index = newChild.nextSetBit(index + 1);
386 if (index > -1 && MathUtils.nextBoolean()) {
387 newChild.clear(index);
388 }
389 } while (index > -1);
390 } while (newChild.cardinality() == 0
391 || newChild.cardinality() == parent.getSize());
392 inverseBits = (BitSet) newChild.clone();
393 inverseBits.xor(parent.getBits());
394 } while (childClades.containsKey(newChild)
395 || childClades.containsKey(inverseBits));
396
397 Clade randomClade = new Clade(newChild, 0.9999 * parent
398 .getHeight());
399 children[0] = randomClade;
400
401 BitSet secondChild = (BitSet) children[0].getBits().clone();
402 secondChild.xor(parent.getBits());
403 children[1] = new Clade(secondChild, 0.9999 * parent
404 .getHeight());
405 } else {
406 BitSet secondChild = (BitSet) children[0].getBits().clone();
407 secondChild.xor(parent.getBits());
408 children[1] = childClades.get(secondChild);
409 if (children[1] == null) {
410 children[1] = new Clade(secondChild, 0.9999 * parent
411 .getHeight());
412 }
413 }
414
415 } else {
416 prob = 1.0 / splits;
417
418 BitSet newChild;
419 do {
420 newChild = (BitSet) parent.getBits().clone();
421 int index = -1;
422 do {
423 index = newChild.nextSetBit(index + 1);
424 if (index > -1 && MathUtils.nextBoolean()) {
425 newChild.clear(index);
426 }
427 } while (index > -1);
428 } while (newChild.cardinality() == 0
429 || newChild.cardinality() == parent.getSize());
430 Clade randomClade = new Clade(newChild, 0.9999 * parent.getHeight());
431 // randomClade.addSample();
432 randomClade.addHeight(0.9999 * parent.getHeight());
433 children[0] = randomClade;
434 BitSet secondChild = (BitSet) children[0].getBits().clone();
435 secondChild.xor(parent.getBits());
436 children[1] = new Clade(secondChild, 0.9999 * parent.getHeight());
437 // children[1].addSample();
438 randomClade.addHeight(0.9999 * parent.getHeight());
439 }
440
441 return Math.log(prob);
442
443 }
444
445 public double getChanceForNodeHeights(TreeModel tree, Likelihood likelihood) {
446 double prob = 0.0;
447 NodeRef node = tree.getRoot();
448 Clade currentClade = getClade(tree, node);
449
450 int childcount = tree.getChildCount(node);
451 for (int i = 0; i < childcount; i++) {
452 NodeRef child = tree.getChild(node, i);
453 if (!tree.isExternal(child)) {
454 // prob += getChanceForNodeheights(tree, child, currentClade,
455 // likelihood, prior);
456 }
457 }
458
459 return prob;
460 }
461
462 public double setNodeHeights(TreeModel tree, Likelihood likelihood) {
463 double prob = 0.0;
464 NodeRef node = tree.getRoot();
465 Clade currentClade = getClade(tree, node);
466
467 int childcount = tree.getChildCount(node);
468 for (int i = 0; i < childcount; i++) {
469 NodeRef child = tree.getChild(node, i);
470 if (!tree.isExternal(child)) {
471 // prob += setNodeHeights(tree, child, currentClade, likelihood,
472 // prior);
473 }
474 }
475
476 return prob;
477 }
478
479 /**
480 * get the i'th tree of the trace
481 *
482 * @param index
483 * @return the i'th tree of the trace
484 */
485 public final Tree getTree(int index) {
486
487 int oldTreeCount = 0;
488 int newTreeCount = 0;
489 for (TreeTrace trace : traces) {
490 newTreeCount += trace.getTreeCount(burnin * trace.getStepSize());
491
492 if (index < newTreeCount) {
493 return trace.getTree(index - oldTreeCount, burnin
494 * trace.getStepSize());
495 }
496 oldTreeCount = newTreeCount;
497 }
498 throw new RuntimeException("Couldn't find tree " + index);
499 }
500
501 /**
502 * increments the number of occurrences for all conditional clades
503 *
504 * @param tree - the tree to be added
505 */
506 public void addTree(Tree tree) {
507
508 samples++;
509
510 List<Clade> clades = new ArrayList<Clade>();
511 List<Clade> parentClades = new ArrayList<Clade>();
512 // get clades contained in the tree
513 getClades(tree, tree.getRoot(), parentClades, clades);
514 // add the clade containing all taxa as well so that it get counted
515 clades.add(parentClades.get(parentClades.size() - 1));
516 parentClades.add(clades.get(clades.size() - 1));
517
518 int size = clades.size();
519 // for every clade multiply its conditional clade probability to the
520 // tree probability
521 for (int i = 0; i < size; i++) {
522 Clade c = clades.get(i);
523
524 // get the bits of the clade
525 Clade parent = parentClades.get(i);
526
527 HashMap<BitSet, Clade> coFreqs;
528 // increment the clade occurrences
529 if (cladeProbabilities.containsKey(c.getBits())) {
530 Clade tmp = cladeProbabilities.get(c.getBits());
531 // tmp.addSample();
532 tmp.addHeight(c.getHeight());
533 // add the amount to the current occurences
534 // frequency += cladeProbabilities.get(c);
535 } else {
536 // just to set the first value of the height value list
537 // c.addSample();
538 c.addHeight(c.getHeight());
539 cladeProbabilities.put(c.getBits(), c);
540 }
541
542 // increment the conditional clade occurrences
543 if (!parent.equals(c)) {
544 if (cladeCoProbabilities.containsKey(parent.getBits())) {
545 coFreqs = cladeCoProbabilities.get(parent.getBits());
546 } else {
547 // if it's the first time we observe the parent then we need
548 // a new list for its conditional clades
549 coFreqs = new HashMap<BitSet, Clade>();
550 cladeCoProbabilities.put(parent.getBits(), coFreqs);
551 }
552
553 // add the previous observed occurrences for this conditional
554 // clade
555 if (coFreqs.containsKey(c.getBits())) {
556 Clade tmp = coFreqs.get(c.getBits());
557 tmp.addHeight(c.getHeight());
558 // coFrequency += coFreqs.get(c.getBits());
559 } else {
560 // TODO check this code, especially if the cloning is needed
561 // and not just the clade could be added
562 Clade tmp = new Clade((BitSet) c.getBits().clone(), c.getHeight());
563 tmp.addHeight(c.getHeight());
564 coFreqs.put(c.getBits(), tmp);
565 }
566 }
567 }
568 }
569
570 /**
571 * increments the number of occurrences for all conditional clades
572 *
573 * @param tree - the tree to be added
574 */
575 public void addTree(Tree tree, HashMap<String, Integer> taxonMap) {
576
577 samples++;
578
579 List<Clade> clades = new ArrayList<Clade>();
580 List<Clade> parentClades = new ArrayList<Clade>();
581 // get clades contained in the tree
582 getClades(tree, tree.getRoot(), parentClades, clades, taxonMap);
583 // add the clade containing all taxa as well so that it get counted
584 clades.add(parentClades.get(parentClades.size() - 1));
585 parentClades.add(clades.get(clades.size() - 1));
586
587 int size = clades.size();
588 // for every clade multiply its conditional clade probability to the
589 // tree probability
590 for (int i = 0; i < size; i++) {
591 Clade c = clades.get(i);
592
593 // get the bits of the clade
594 Clade parent = parentClades.get(i);
595
596 HashMap<BitSet, Clade> coFreqs;
597 // increment the clade occurrences
598 if (cladeProbabilities.containsKey(c.getBits())) {
599 Clade tmp = cladeProbabilities.get(c.getBits());
600 // tmp.addSample();
601 tmp.addHeight(c.getHeight());
602 // add the amount to the current occurences
603 // frequency += cladeProbabilities.get(c);
604 } else {
605 // just to set the first value of the height value list
606 // c.addSample();
607 c.addHeight(c.getHeight());
608 cladeProbabilities.put(c.getBits(), c);
609 }
610
611 // increment the conditional clade occurrences
612 if (!parent.equals(c)) {
613 if (cladeCoProbabilities.containsKey(parent.getBits())) {
614 coFreqs = cladeCoProbabilities.get(parent.getBits());
615 } else {
616 // if it's the first time we observe the parent then we need
617 // a new list for its conditional clades
618 coFreqs = new HashMap<BitSet, Clade>();
619 cladeCoProbabilities.put(parent.getBits(), coFreqs);
620 }
621
622 // add the previous observed occurrences for this conditional
623 // clade
624 if (coFreqs.containsKey(c.getBits())) {
625 Clade tmp = coFreqs.get(c.getBits());
626 tmp.addHeight(c.getHeight());
627 // coFrequency += coFreqs.get(c.getBits());
628 } else {
629 // TODO check this code, especially if the cloning is needed
630 // and not just the clade could be added
631 Clade tmp = new Clade((BitSet) c.getBits().clone(), c
632 .getHeight());
633 tmp.addHeight(c.getHeight());
634 coFreqs.put(c.getBits(), tmp);
635 }
636 }
637 }
638 }
639
640 /**
641 * @param reader the readers to be analyzed
642 * @param burnin the burnin in states
643 * @param verbose true if progress should be logged to stdout
644 * @return an analyses of the trees in a log file.
645 * @throws java.io.IOException if general I/O error occurs
646 */
647 public static ConditionalCladeFrequency analyzeLogFile(Reader[] reader,
648 double e, int burnin, boolean verbose) throws IOException {
649
650 TreeTrace[] trace = new TreeTrace[reader.length];
651 for (int i = 0; i < reader.length; i++) {
652 try {
653 trace[i] = TreeTrace.loadTreeTrace(reader[i]);
654 } catch (Importer.ImportException ie) {
655 throw new RuntimeException(ie.toString());
656 }
657 reader[i].close();
658
659 }
660
661 return new ConditionalCladeFrequency(trace, e, burnin, verbose);
662 }
663 }