Debian Codegraph @

src/dr/evomodel/tree/WeightedMultiplicativeBinary.java

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