Debian Codegraph @

src/dr/evomodel/operators/AbstractImportanceDistributionOperator.java

raw symbols SCIP
1 /*
2 * AbstractImportanceDistributionOperator.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.operators;
30
31 import dr.evolution.tree.Clade;
32 import dr.evolution.tree.MutableTree.InvalidTreeException;
33 import dr.evolution.tree.NodeRef;
34 import dr.evolution.tree.Tree;
35 import dr.evomodel.tree.AbstractCladeImportanceDistribution;
36 import dr.evomodel.tree.TreeModel;
37 import dr.inference.model.Likelihood;
38 import dr.inference.operators.*;
39 import dr.math.MathUtils;
40
41 import java.util.*;
42
43 /**
44 * @author Sebastian Hoehna
45 */
46 // Cleaning out untouched stuff. Can be resurrected if needed
47 @Deprecated
48 public abstract class AbstractImportanceDistributionOperator extends
49 SimpleMCMCOperator implements GeneralOperator {
50
51 private long transitions = 0;
52
53 private OperatorSchedule schedule;
54
55 protected TreeModel tree;
56
57 protected AbstractCladeImportanceDistribution probabilityEstimater;
58
59 private int sampleEvery;
60
61 private int samples;
62
63 private int sampleCount;
64
65 private Queue<NodeRef> internalNodes;
66
67 private Map<Integer, NodeRef> externalNodes;
68
69 private boolean burnin = false;
70
71 /**
72 *
73 */
74 public AbstractImportanceDistributionOperator(TreeModel tree, double weight) {
75 super();
76
77 this.tree = tree;
78
79 setWeight(weight);
80 this.samples = 10000;
81 this.sampleEvery = 10;
82
83 init();
84 }
85
86 /**
87 *
88 */
89 public AbstractImportanceDistributionOperator(TreeModel tree,
90 double weight, int samples, int sampleEvery) {
91 super();
92
93 this.tree = tree;
94 setWeight(weight);
95 this.samples = samples;
96 this.sampleEvery = sampleEvery;
97
98 init();
99 }
100
101 private void init() {
102 schedule = getOperatorSchedule(tree);
103 sampleCount = 0;
104 internalNodes = new LinkedList<NodeRef>();
105 externalNodes = new HashMap<Integer, NodeRef>();
106 fillExternalNodes(tree.getRoot());
107 }
108
109 /*
110 * (non-Javadoc)
111 *
112 * @see dr.inference.operators.AbstractImportanceSampler#doOperation()
113 */
114 public double doOperation() {
115 // dummy method
116 return 0.0;
117 }
118
119 /*
120 * (non-Javadoc)
121 *
122 * @see dr.inference.operators.AbstractImportanceSampler#doOperation()
123 */
124 public double doOperation(Likelihood likelihood) {
125 if (!burnin) {
126 if (sampleCount < samples * sampleEvery) {
127 sampleCount++;
128 if (sampleCount % sampleEvery == 0) {
129 probabilityEstimater.addTree(tree);
130 }
131 setAcceptCount(0);
132 setRejectCount(0);
133 setTransitions(0);
134
135 return doUnguidedOperation();
136
137 } else {
138 return doImportanceDistributionOperation(likelihood);
139 }
140 } else {
141
142 return doUnguidedOperation();
143
144 }
145 }
146
147 protected double doImportanceDistributionOperation(Likelihood likelihood) {
148 final NodeRef root = tree.getRoot();
149 BitSet all = new BitSet();
150 all.set(0, (tree.getNodeCount() + 1) / 2);
151 Clade rootClade = new Clade(all, tree.getNodeHeight(root));
152
153 internalNodes.clear();
154 fillInternalNodes(root);
155 // remove the root
156 internalNodes.poll();
157
158 externalNodes.clear();
159 fillExternalNodes(root);
160
161 double prob;
162 double back = probabilityEstimater.getTreeProbability(tree);
163
164 try {
165 tree.beginTreeEdit();
166
167 List<Clade> originalClades = new ArrayList<Clade>();
168 extractClades(tree, tree.getRoot(), originalClades, null);
169
170 double[] originalNodeHeights = getAbsoluteNodeHeights(originalClades);
171 Arrays.sort(originalNodeHeights);
172 back += getChanceForNodeHeights(originalNodeHeights);
173
174 prob = createTree(root, rootClade);
175
176 assignDummyHeights(root);
177
178 // assignCladeHeights(tree.getRoot(), originalClades, null);
179 // double[] originalNodeHeights = getAbsoluteNodeHeights(originalClades);
180 // Arrays.sort(originalNodeHeights);
181 // prob += setMissingNodeHeights(tree.getChild(tree.getRoot(),0));
182 // prob += setMissingNodeHeights(tree.getChild(tree.getRoot(),1));
183
184 prob += setNodeHeights(originalNodeHeights);
185
186 // List<Clade> newClades = new ArrayList<Clade>();
187 // extractClades(tree, tree.getRoot(), newClades, null);
188
189 tree.endTreeEdit();
190
191 tree.checkTreeIsValid();
192 } catch (InvalidTreeException e) {
193 throw new RuntimeException(e.getMessage());
194 }
195
196 tree.pushTreeChangedEvent(root);
197
198 return back - prob;
199 }
200
201 private void assignDummyHeights(NodeRef node) {
202 double rootHeight = tree.getNodeHeight(node) * tree.getInternalNodeCount();
203 tree.setNodeHeight(node, rootHeight);
204
205 int childcount = tree.getChildCount(node);
206 for (int i = 0; i < childcount; i++) {
207 NodeRef child = tree.getChild(node, i);
208 if (!tree.isExternal(child)) {
209 assignDummyHeights(child, rootHeight / 2.0);
210 }
211 }
212
213 }
214
215 private void assignDummyHeights(NodeRef node, double height) {
216 assert (!tree.isExternal(node));
217 tree.setNodeHeight(node, height);
218
219 int childcount = tree.getChildCount(node);
220 for (int i = 0; i < childcount; i++) {
221 NodeRef child = tree.getChild(node, i);
222 if (!tree.isExternal(child)) {
223 assignDummyHeights(child, height / 2.0);
224 }
225 }
226 }
227
228 private double createTree(NodeRef node, Clade c)
229 throws InvalidTreeException {
230 double prob = 0.0;
231 if (c.getSize() == 2) {
232 // this clade only contains two tips
233 // the split between them is trivial
234
235 int leftTipIndex = c.getBits().nextSetBit(0);
236 int rightTipIndex = c.getBits().nextSetBit(leftTipIndex + 1);
237 NodeRef leftTip = externalNodes.get(leftTipIndex);
238 NodeRef rightTip = externalNodes.get(rightTipIndex);
239
240 removeChildren(node);
241 NodeRef leftParent = tree.getParent(leftTip);
242 if (leftParent != null)
243 tree.removeChild(leftParent, leftTip);
244 NodeRef rightParent = tree.getParent(rightTip);
245 if (rightParent != null)
246 tree.removeChild(rightParent, rightTip);
247 tree.addChild(node, leftTip);
248 tree.addChild(node, rightTip);
249 } else {
250 Clade[] clades = new Clade[2];
251 prob = splitClade(c, clades);
252 NodeRef leftChild, rightChild;
253
254 if (clades[0].getSize() == 1) {
255 int tipIndex = clades[0].getBits().nextSetBit(0);
256 leftChild = externalNodes.get(tipIndex);
257 } else {
258 leftChild = internalNodes.poll();
259 // TODO set the node height for the new node
260 tree.setNodeHeight(leftChild, tree.getNodeHeight(node) * 0.5);
261 prob += createTree(leftChild, clades[0]);
262 }
263
264 if (clades[1].getSize() == 1) {
265 int tipIndex = clades[1].getBits().nextSetBit(0);
266 rightChild = externalNodes.get(tipIndex);
267 } else {
268 rightChild = internalNodes.poll();
269 // TODO set the node height for the new node
270 tree.setNodeHeight(rightChild, tree.getNodeHeight(node) * 0.5);
271 prob += createTree(rightChild, clades[1]);
272 }
273
274 removeChildren(node);
275 NodeRef leftParent = tree.getParent(leftChild);
276 if (leftParent != null)
277 tree.removeChild(leftParent, leftChild);
278 NodeRef rightParent = tree.getParent(rightChild);
279 if (rightParent != null)
280 tree.removeChild(rightParent, rightChild);
281 tree.addChild(node, leftChild);
282 tree.addChild(node, rightChild);
283 }
284
285 return prob;
286 }
287
288 /**
289 * @param parent
290 * @warning assumes strictly bifurcating trees
291 */
292 private void removeChildren(NodeRef parent) {
293 // assumes strictly bifurcating trees
294
295 NodeRef child = tree.getChild(parent, 0);
296 if (child != null) {
297 tree.removeChild(parent, child);
298 }
299
300 child = tree.getChild(parent, 1);
301 if (child != null) {
302 tree.removeChild(parent, child);
303 }
304 }
305
306 private double splitClade(Clade c, Clade[] children) {
307 return probabilityEstimater.splitClade(c, children);
308 }
309
310 /**
311 * Creates a list with all clades of the tree
312 *
313 * @param tree - the tree from which the clades are extracted
314 * @param node - the starting node. All clades below starting at this branch
315 * are added
316 * @param clades - the list in which the clades are stored
317 * @param bits - a bit set to which the current bits of the clades are added
318 */
319 private void extractClades(Tree tree, NodeRef node,
320 List<Clade> clades, BitSet bits) {
321
322 // create a new bit set for this clade
323 BitSet bits2 = new BitSet();
324
325 // check if the node is external
326 if (tree.isExternal(node)) {
327
328 // if so, the only taxon in the clade is I
329 int index = node.getNumber();
330 bits2.set(index);
331
332 } else {
333
334 // otherwise, call all children and add its taxon together to one
335 // clade
336 for (int i = 0; i < tree.getChildCount(node); i++) {
337 NodeRef child = tree.getChild(node, i);
338 extractClades(tree, child, clades, bits2);
339 }
340 // add my bit set to the list
341 clades.add(new Clade(bits2, tree.getNodeHeight(node)));
342 }
343
344 // add my bit set to the bit set I was given
345 // this is needed for adding all children clades together
346 if (bits != null) {
347 bits.or(bits2);
348 }
349 }
350
351 /**
352 * Creates a list with all clades of the tree
353 *
354 * @param node - the starting node. All clades below starting at this branch
355 * are added
356 * @param clades - the list in which the clades are stored
357 */
358 private void assignCladeHeights(NodeRef node,
359 HashMap<Clade, Double> clades, BitSet bits) {
360
361 // create a new bit set for this clade
362 BitSet bits2 = new BitSet();
363
364 // check if the node is external
365 if (tree.isExternal(node)) {
366
367 // if so, the only taxon in the clade is I
368 int index = node.getNumber();
369 bits2.set(index);
370
371 } else {
372
373 // otherwise, call all children and add its taxon together to one
374 // clade
375 for (int i = 0; i < tree.getChildCount(node); i++) {
376 NodeRef child = tree.getChild(node, i);
377 assignCladeHeights(child, clades, bits2);
378 }
379 Clade c = new Clade(bits2, tree.getNodeHeight(node));
380 if (clades.containsKey(c)) {
381 tree.setNodeHeight(node, clades.get(c));
382 clades.remove(c);
383 }
384 }
385
386 // add my bit set to the bit set I was given
387 // this is needed for adding all children clades together
388 if (bits != null) {
389 bits.or(bits2);
390 }
391 }
392
393 private double[] getRelativeNodeHeights(Tree tree) {
394 int count = tree.getInternalNodeCount();
395 double[] nodeHeights = new double[count];
396
397 for (int i = 0; i < count; i++) {
398 NodeRef node = tree.getInternalNode(i);
399 NodeRef parent = tree.getParent(node);
400 nodeHeights[i] = tree.getNodeHeight(node)
401 / tree.getNodeHeight(parent);
402 }
403
404 return nodeHeights;
405 }
406
407 private double[] getAbsoluteNodeHeights(Tree tree) {
408 int count = tree.getInternalNodeCount();
409 double[] nodeHeights = new double[count];
410
411 for (int i = 0; i < count; i++) {
412 NodeRef node = tree.getInternalNode(i);
413 nodeHeights[i] = tree.getNodeHeight(node);
414 }
415
416 return nodeHeights;
417 }
418
419 private double[] getAbsoluteNodeHeights(List<Clade> clades) {
420 double[] nodeHeights = new double[clades.size()];
421
422 int count = 0;
423 for (Clade c : clades) {
424 nodeHeights[count] = c.getHeight();
425 count++;
426 }
427
428 return nodeHeights;
429 }
430
431 private double getChanceForNodeHeights(double[] nodeHeights) {
432 return getChanceOfPermuation(nodeHeights);
433 // return getChanceOfUniformNodeHeights(tree.getRoot());
434 // return probabilityEstimater.getChanceForNodeHeights(tree, likelihood, prior);
435 }
436
437 private double getChanceOfUniformNodeHeights(NodeRef parent) {
438 double prob = 0.0;
439
440 NodeRef leftChild = tree.getChild(parent, 0);
441 NodeRef rightChild = tree.getChild(parent, 1);
442
443 if (!tree.isExternal(leftChild)) {
444 prob += Math.log(1.0 / tree.getNodeHeight(parent));
445 prob += getChanceOfUniformNodeHeights(leftChild);
446 }
447 if (!tree.isExternal(rightChild)) {
448 prob += Math.log(1.0 / tree.getNodeHeight(parent));
449 prob += getChanceOfUniformNodeHeights(rightChild);
450 }
451
452 return prob;
453 }
454
455 private double getChanceOfPermuation(double[] nodeHeights) {
456 List<NodeRef> nodes = new LinkedList<NodeRef>();
457
458 NodeRef root = tree.getRoot();
459
460 NodeRef leftChild = tree.getChild(root, 0);
461 NodeRef rightChild = tree.getChild(root, 1);
462
463 if (!tree.isExternal(leftChild)) {
464 nodes.add(leftChild);
465 }
466 if (!tree.isExternal(rightChild)) {
467 nodes.add(rightChild);
468 }
469
470 int pointer = nodeHeights.length - 2;
471 double prob = 0.0;
472 while (!nodes.isEmpty()) {
473 int index = getHighestNode(nodes);
474 prob += Math.log(1.0 / nodes.size());
475 NodeRef n = nodes.remove(index);
476 tree.setNodeHeight(n, nodeHeights[pointer]);
477 pointer--;
478 leftChild = tree.getChild(n, 0);
479 rightChild = tree.getChild(n, 1);
480
481 if (!tree.isExternal(leftChild)) {
482 nodes.add(leftChild);
483 }
484 if (!tree.isExternal(rightChild)) {
485 nodes.add(rightChild);
486 }
487 }
488
489 return prob;
490 }
491
492 private int getHighestNode(List<NodeRef> nodes) {
493 double maxHeight = 0;
494 int index = 0;
495
496 for (int i = 0; i < nodes.size(); i++) {
497 NodeRef n = nodes.get(i);
498 if (tree.getNodeHeight(n) > maxHeight) {
499 maxHeight = tree.getNodeHeight(n);
500 index = i;
501 }
502 }
503
504 return index;
505 }
506
507 private double setNodeHeights(double[] nodeHeights) {
508 // return setUniformNodeHeights(tree.getRoot());
509 return assignPermutedNodeHeights(nodeHeights);
510 // return probabilityEstimater.setNodeHeights(tree, likelihood, prior);
511 }
512
513 private double setUniformNodeHeights(NodeRef parent) {
514 double prob = 0.0;
515
516 NodeRef leftChild = tree.getChild(parent, 0);
517 NodeRef rightChild = tree.getChild(parent, 1);
518
519 if (!tree.isExternal(leftChild)) {
520 double max = tree.getNodeHeight(parent);
521 double height = max * MathUtils.nextDouble();
522 tree.setNodeHeight(leftChild, height);
523 prob += Math.log(1.0 / max);
524 prob += setUniformNodeHeights(leftChild);
525 }
526 if (!tree.isExternal(rightChild)) {
527 double max = tree.getNodeHeight(parent);
528 double height = max * MathUtils.nextDouble();
529 tree.setNodeHeight(rightChild, height);
530 prob += Math.log(1.0 / max);
531 prob += setUniformNodeHeights(rightChild);
532 }
533
534 return prob;
535 }
536
537 private double assignPermutedNodeHeights(double[] nodeHeights) {
538 List<NodeRef> nodes = new LinkedList<NodeRef>();
539
540 NodeRef root = tree.getRoot();
541
542 NodeRef leftChild = tree.getChild(root, 0);
543 NodeRef rightChild = tree.getChild(root, 1);
544
545 if (!tree.isExternal(leftChild)) {
546 nodes.add(leftChild);
547 }
548 if (!tree.isExternal(rightChild)) {
549 nodes.add(rightChild);
550 }
551
552 int pointer = nodeHeights.length - 2;
553 double prob = 0.0;
554 while (!nodes.isEmpty()) {
555 int index = MathUtils.nextInt(nodes.size());
556 prob += Math.log(1.0 / nodes.size());
557 NodeRef n = nodes.remove(index);
558 tree.setNodeHeight(n, nodeHeights[pointer]);
559 pointer--;
560 leftChild = tree.getChild(n, 0);
561 rightChild = tree.getChild(n, 1);
562
563 if (!tree.isExternal(leftChild)) {
564 nodes.add(leftChild);
565 }
566 if (!tree.isExternal(rightChild)) {
567 nodes.add(rightChild);
568 }
569 }
570
571 return prob;
572 }
573
574 private double setMissingNodeHeights(NodeRef node) {
575 double prob = 0.0;
576
577 // check if the node is external
578 if (!tree.isExternal(node)) {
579
580 // otherwise, call all children and add its taxon together to one
581 // clade
582 for (int i = 0; i < tree.getChildCount(node); i++) {
583 NodeRef child = tree.getChild(node, i);
584 setMissingNodeHeights(child);
585 }
586 double min = getMinNodeHeight(node);
587 double max = getMaxNodeHeight(node);
588 if (max <= min) {
589 max = tree.getNodeHeight(tree.getRoot());
590 }
591 prob += Math.log(1.0 / (max - min));
592 double height = min + MathUtils.nextDouble() * (max - min);
593 tree.setNodeHeight(node, height);
594 }
595
596 return prob;
597 }
598
599 private double getMinNodeHeight(NodeRef node) {
600 double min = Double.MAX_VALUE;
601 for (int i = 0; i < tree.getChildCount(node); i++) {
602 NodeRef child = tree.getChild(node, i);
603 double height = tree.getNodeHeight(child);
604 if (height < min) {
605 min = height;
606 }
607 }
608 return min;
609 }
610
611 private double getMaxNodeHeight(NodeRef node) {
612 return tree.getNodeHeight(tree.getParent(node));
613 }
614
615 private void fillInternalNodes(NodeRef node) {
616 if (!tree.isExternal(node)) {
617 internalNodes.add(node);
618 int childCount = tree.getChildCount(node);
619 for (int i = 0; i < childCount; i++) {
620 fillInternalNodes(tree.getChild(node, i));
621 }
622 }
623 }
624
625 private void fillExternalNodes(NodeRef node) {
626 if (!tree.isExternal(node)) {
627 int childCount = tree.getChildCount(node);
628 for (int i = 0; i < childCount; i++) {
629 fillExternalNodes(tree.getChild(node, i));
630 }
631 } else {
632 Integer i = node.getNumber();
633 externalNodes.put(i, node);
634 }
635 }
636
637 private OperatorSchedule getOperatorSchedule(TreeModel treeModel) {
638
639 ExchangeOperator narrowExchange = new ExchangeOperator(
640 ExchangeOperator.NARROW, treeModel, 10);
641 ExchangeOperator wideExchange = new ExchangeOperator(
642 ExchangeOperator.WIDE, treeModel, 3);
643 SubtreeSlideOperator subtreeSlide = new SubtreeSlideOperator(treeModel,
644 10.0, 1.0, true, false, false, false, AdaptationMode.ADAPTATION_ON, AdaptableMCMCOperator.DEFAULT_ADAPTATION_TARGET);
645 NNI nni = new NNI(treeModel, 10.0);
646 WilsonBalding wilsonBalding = new WilsonBalding(treeModel, 3.0);
647 FNPR fnpr = new FNPR(treeModel, 5.0);
648
649 OperatorSchedule schedule = new SimpleOperatorSchedule();
650 schedule.addOperator(narrowExchange);
651 schedule.addOperator(wideExchange);
652 schedule.addOperator(subtreeSlide);
653 schedule.addOperator(nni);
654 schedule.addOperator(wilsonBalding);
655 schedule.addOperator(fnpr);
656
657 return schedule;
658 }
659
660 protected double doUnguidedOperation() {
661 int index = schedule.getNextOperatorIndex();
662 SimpleMCMCOperator operator = (SimpleMCMCOperator) schedule
663 .getOperator(index);
664
665 return operator.doOperation();
666 }
667
668 /**
669 * @return the number of transitions since last call to reset().
670 */
671 public long getTransitions() {
672 return transitions;
673 }
674
675 /**
676 * Set the number of transitions since last call to reset(). This is used to
677 * restore the state of the operator
678 */
679 public void setTransitions(int transitions) {
680 this.transitions = transitions;
681 }
682
683 public double getTransistionProbability() {
684 long accepted = getAcceptCount();
685 long rejected = getRejectCount();
686 long transition = getTransitions();
687 return (double) transition / (double) (accepted + rejected);
688 }
689
690 public void reset() {
691 super.reset();
692 transitions = 0;
693 }
694
695 public double getMinimumAcceptanceLevel() {
696 return 0.50;
697 }
698
699 public double getMaximumAcceptanceLevel() {
700 return 1.0;
701 }
702
703 public double getMinimumGoodAcceptanceLevel() {
704 return 0.75;
705 }
706
707 public double getMaximumGoodAcceptanceLevel() {
708 return 1.0;
709 }
710
711 /*
712 * (non-Javadoc)
713 *
714 * @see dr.inference.operators.SimpleMCMCOperator#getOperatorName()
715 */
716 @Override
717 public abstract String getOperatorName();
718
719 /*
720 * (non-Javadoc)
721 *
722 * @see dr.inference.operators.MCMCOperator#getPerformanceSuggestion()
723 */
724 public abstract String getPerformanceSuggestion();
725
726 }