Debian Codegraph @

src/dr/oldevomodel/treelikelihood/AdvancedTreeLikelihood.java

raw symbols SCIP
1 /*
2 * AdvancedTreeLikelihood.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.oldevomodel.treelikelihood;
27
28 import dr.evolution.alignment.PatternList;
29 import dr.evolution.tree.NodeRef;
30 import dr.evolution.tree.Tree;
31 import dr.evolution.tree.TreeUtils;
32 import dr.evolution.util.Taxon;
33 import dr.evolution.util.TaxonList;
34 import dr.evomodel.branchratemodel.BranchRateModel;
35 import dr.evomodel.branchratemodel.DefaultBranchRateModel;
36 import dr.evomodel.tree.TreeChangedEvent;
37 import dr.oldevomodel.sitemodel.SiteModel;
38 import dr.oldevomodel.substmodel.FrequencyModel;
39 import dr.evomodel.tree.TreeModel;
40 import dr.inference.model.Likelihood;
41 import dr.inference.model.Model;
42 import dr.inference.model.Parameter;
43 import dr.inference.model.Variable;
44 import dr.xml.*;
45
46 import java.util.ArrayList;
47 import java.util.HashSet;
48 import java.util.Set;
49 import java.util.logging.Logger;
50
51 /**
52 * AdvancedTreeLikelihood - implements a Likelihood Function for sequences on a tree.
53 * This one has some advanced models such as multiple site models for different clades.
54 * This only makes sense if those clades are being constrained to remain monophyletic.
55 *
56 * @author Andrew Rambaut
57 * @version $Id: AdvancedTreeLikelihood.java,v 1.11 2006/01/10 16:48:27 rambaut Exp $
58 */
59
60 @Deprecated // Switching to BEAGLE
61 public class AdvancedTreeLikelihood extends AbstractTreeLikelihood {
62
63 public static final String ADVANCED_TREE_LIKELIHOOD = "advancedTreeLikelihood";
64 public static final String CLADE = "clade";
65 public static final String INCLUDE_STEM = "includeStem";
66 public static final String TIPS = "tips";
67 public static final String DELTA = "delta";
68 public static final String USE_AMBIGUITIES = "useAmbiguities";
69 public static final String STORE_PARTIALS = "storePartials";
70 public static final String USE_SCALING = "useScaling";
71
72 /**
73 * Constructor.
74 */
75 public AdvancedTreeLikelihood(PatternList patternList,
76 TreeModel treeModel,
77 SiteModel siteModel,
78 BranchRateModel branchRateModel,
79 boolean useAmbiguities,
80 boolean useScaling) {
81
82 super(ADVANCED_TREE_LIKELIHOOD, patternList, treeModel);
83
84 try {
85 this.siteModel = siteModel;
86 addModel(siteModel);
87
88 this.frequencyModel = siteModel.getFrequencyModel();
89 addModel(frequencyModel);
90
91 if (!siteModel.integrateAcrossCategories()) {
92 throw new RuntimeException("AdvancedTreeLikelihood can only use SiteModels that require integration across categories");
93 }
94
95 this.categoryCount = siteModel.getCategoryCount();
96
97 if (patternList.getDataType() instanceof dr.evolution.datatype.Nucleotides) {
98
99 if (NativeNucleotideLikelihoodCore.isAvailable()) {
100
101 Logger.getLogger("dr.evomodel").info("AdvancedTreeLikelihood using native nucleotide likelihood core.");
102 likelihoodCore = new NativeNucleotideLikelihoodCore();
103 } else {
104
105 Logger.getLogger("dr.evomodel").info("AdvancedTreeLikelihood Java nucleotide likelihood core.");
106 likelihoodCore = new NucleotideLikelihoodCore();
107 }
108
109 } else if (patternList.getDataType() instanceof dr.evolution.datatype.AminoAcids) {
110 Logger.getLogger("dr.evomodel").info("AdvancedTreeLikelihood Java amino acid likelihood core.");
111 likelihoodCore = new AminoAcidLikelihoodCore();
112 } else if (patternList.getDataType() instanceof dr.evolution.datatype.Codons) {
113 Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java general likelihood core");
114 likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
115 useAmbiguities = true;
116 } else {
117 Logger.getLogger("dr.evomodel").info("AdvancedTreeLikelihood using Java general likelihood core");
118 likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
119 }
120 // likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
121 Logger.getLogger("dr.evomodel").info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood.");
122 Logger.getLogger("dr.evomodel").info(" Partial likelihood scaling " + (useScaling ? "on." : "off."));
123
124 if (branchRateModel != null) {
125 this.branchRateModel = branchRateModel;
126 Logger.getLogger("dr.evomodel").info("Branch rate model used: " + branchRateModel.getModelName());
127 } else {
128 this.branchRateModel = new DefaultBranchRateModel();
129 }
130 addModel(this.branchRateModel);
131
132 probabilities = new double[stateCount * stateCount];
133
134 likelihoodCore.initialize(nodeCount, patternCount, categoryCount, true);
135
136 int extNodeCount = treeModel.getExternalNodeCount();
137 int intNodeCount = treeModel.getInternalNodeCount();
138
139 for (int i = 0; i < extNodeCount; i++) {
140 // Find the id of tip i in the patternList
141 String id = treeModel.getTaxonId(i);
142 int index = patternList.getTaxonIndex(id);
143
144 if (index == -1) {
145 throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
146 ", is not found in patternList, " + patternList.getId());
147 }
148
149 if (useAmbiguities) {
150 setPartials(likelihoodCore, patternList, categoryCount, index, i);
151 } else {
152 setStates(likelihoodCore, patternList, index, i);
153 }
154 }
155
156 for (int i = 0; i < intNodeCount; i++) {
157 likelihoodCore.createNodePartials(extNodeCount + i);
158 }
159 } catch (TaxonList.MissingTaxonException mte) {
160 throw new RuntimeException(mte.toString());
161 }
162
163 }
164
165 /**
166 * Add an additional siteModel for a clade in the tree.
167 */
168 public void addCladeSiteModel(SiteModel siteModel,
169 TaxonList taxonList,
170 boolean includeStem) throws TreeUtils.MissingTaxonException {
171 Logger.getLogger("dr.evomodel").info("SiteModel added for clade.");
172 cladeSiteModels.add(new Clade(siteModel, taxonList, includeStem));
173 addModel(siteModel);
174 commonAncestorsKnown = true;
175 }
176
177 /**
178 * Add an additional siteModel for the tips of the tree.
179 */
180 public void addTipsSiteModel(SiteModel siteModel) {
181 Logger.getLogger("dr.evomodel").info("SiteModel added for tips.");
182 tipsSiteModel = siteModel;
183 addModel(siteModel);
184 }
185
186 private void addDeltaParameter(Parameter deltaParameter, TaxonList taxa) {
187 this.deltaParameter = deltaParameter;
188 this.deltaTips = new HashSet<Integer>();
189
190 if (taxa != null) {
191 boolean first = true;
192 StringBuffer sb = new StringBuffer("Delta parameter added for tips: {");
193 for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
194 NodeRef node = treeModel.getExternalNode(i);
195 Taxon taxon = treeModel.getNodeTaxon(node);
196 if (taxa.getTaxonIndex(taxon) != -1) {
197 if (!first) {
198 sb.append(", ");
199 } else {
200 first = false;
201 }
202 sb.append(taxon.getId());
203 deltaTips.add(node.getNumber());
204 }
205 }
206 sb.append("}");
207
208 Logger.getLogger("dr.evomodel").info(sb.toString());
209 } else {
210 Logger.getLogger("dr.evomodel").info("Delta parameter added for all tips.");
211 }
212
213 addVariable(deltaParameter);
214 }
215
216 // **************************************************************
217 // VariableListener IMPLEMENTATION
218 // **************************************************************
219
220 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
221 // deltaParameter has changed...
222 updateAllNodes();
223 super.handleVariableChangedEvent(variable, index, type);
224 }
225
226 // **************************************************************
227 // ModelListener IMPLEMENTATION
228 // **************************************************************
229
230 /**
231 * Handles model changed events from the submodels.
232 */
233 protected void handleModelChangedEvent(Model model, Object object, int index) {
234
235 if (model == treeModel) {
236 if (object instanceof TreeChangedEvent) {
237
238 if (((TreeChangedEvent) object).isNodeChanged()) {
239
240 updateNodeAndChildren(((TreeChangedEvent) object).getNode());
241
242 } else {
243 updateAllNodes();
244
245 commonAncestorsKnown = false;
246
247 }
248 }
249
250 } else if (model == branchRateModel) {
251 updateAllNodes();
252
253 } else if (model == frequencyModel) {
254
255 updateAllNodes();
256
257 } else if (model instanceof SiteModel) {
258
259 if (model == siteModel) {
260
261 updateAllNodes();
262
263 } else if (model == tipsSiteModel) {
264
265 updateAllNodes();
266
267 } else {
268
269 // find the siteModel in the additional siteModel list
270 NodeRef node = null;
271 for (int i = 0, n = cladeSiteModels.size(); i < n; i++) {
272 Clade clade = cladeSiteModels.get(i);
273
274 if (!commonAncestorsKnown) {
275 clade.findMRCA();
276 }
277
278 if (clade.getSiteModel() == model) {
279 node = treeModel.getNode(clade.getNode());
280 }
281 }
282 commonAncestorsKnown = true;
283
284 updateNodeAndDescendents(node);
285 }
286
287 } else {
288
289 throw new RuntimeException("Unknown componentChangedEvent");
290 }
291
292 super.handleModelChangedEvent(model, object, index);
293 }
294
295 // **************************************************************
296 // Model IMPLEMENTATION
297 // **************************************************************
298
299 /**
300 * Stores the additional state other than model components
301 */
302 protected void storeState() {
303
304 if (storePartials) {
305 likelihoodCore.storeState();
306 }
307 super.storeState();
308
309 }
310
311 /**
312 * Restore the additional stored state
313 */
314 protected void restoreState() {
315
316 if (storePartials) {
317 likelihoodCore.restoreState();
318 } else {
319 updateAllNodes();
320 }
321
322 super.restoreState();
323
324 }
325
326 // **************************************************************
327 // Likelihood IMPLEMENTATION
328 // **************************************************************
329
330 /**
331 * Calculate the log likelihood of the current state.
332 *
333 * @return the log likelihood.
334 */
335 protected double calculateLogLikelihood() {
336
337 NodeRef root = treeModel.getRoot();
338
339 if (rootPartials == null) {
340 rootPartials = new double[patternCount * stateCount];
341 }
342
343 if (patternLogLikelihoods == null) {
344 patternLogLikelihoods = new double[patternCount];
345 }
346
347 if (!commonAncestorsKnown) {
348 for (int i = 0, n = cladeSiteModels.size(); i < n; i++) {
349 (cladeSiteModels.get(i)).findMRCA();
350 }
351 commonAncestorsKnown = true;
352 }
353
354 traverse(treeModel, root, siteModel);
355
356 //********************************************************************
357 // after traverse all nodes and patterns have been updated --
358 //so change flags to reflect this.
359 for (int i = 0; i < nodeCount; i++) {
360 updateNode[i] = false;
361 }
362 //********************************************************************
363
364 double logL = 0.0;
365
366 for (int i = 0; i < patternCount; i++) {
367 logL += patternLogLikelihoods[i] * patternWeights[i];
368 }
369
370 return logL;
371 }
372
373 /**
374 * Traverse the tree calculating partial likelihoods.
375 *
376 * @return whether the partials for this node were recalculated.
377 */
378 private boolean traverse(Tree tree, NodeRef node, SiteModel currentSiteModel) {
379
380 boolean update = false;
381
382 int nodeNum = node.getNumber();
383
384 SiteModel nextSiteModel = currentSiteModel;
385
386 if (tipsSiteModel != null && tree.isExternal(node)) {
387 currentSiteModel = tipsSiteModel;
388 } else {
389 for (int i = 0, n = cladeSiteModels.size(); i < n; i++) {
390 Clade clade = cladeSiteModels.get(i);
391 if (clade.getNode() == nodeNum) {
392 nextSiteModel = clade.getSiteModel();
393
394 if (clade.includeStem()) {
395 currentSiteModel = nextSiteModel;
396 }
397 break;
398 }
399 }
400 }
401
402 NodeRef parent = tree.getParent(node);
403
404 // First update the transition probability matrix(ices) for this branch
405 if (parent != null && updateNode[nodeNum]) {
406
407 double branchRate = branchRateModel.getBranchRate(tree, node);
408
409 // Get the operational time of the branch
410 double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
411 if (branchTime < 0.0) {
412 throw new RuntimeException("Negative branch length: " + branchTime);
413 }
414
415 likelihoodCore.setNodeMatrixForUpdate(nodeNum);
416
417 if (tree.isExternal(node) && deltaParameter != null &&
418 (deltaTips.size() == 0 || deltaTips.contains(new Integer(node.getNumber())))) {
419 branchTime += deltaParameter.getParameterValue(0);
420 }
421
422 for (int i = 0; i < categoryCount; i++) {
423 double branchLength = currentSiteModel.getRateForCategory(i) * branchTime;
424 currentSiteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities);
425 likelihoodCore.setNodeMatrix(nodeNum, i, probabilities);
426 }
427
428 update = true;
429 }
430
431 // If the node is internal, update the partial likelihoods.
432 if (!tree.isExternal(node)) {
433
434 int nodeCount = tree.getChildCount(node);
435 if (nodeCount != 2)
436 throw new RuntimeException("binary trees only!");
437
438 // Traverse down the two child nodes
439 NodeRef child1 = tree.getChild(node, 0);
440 boolean update1 = traverse(tree, child1, nextSiteModel);
441
442 NodeRef child2 = tree.getChild(node, 1);
443 boolean update2 = traverse(tree, child2, nextSiteModel);
444
445 // If either child node was updated then update this node too
446 if (update1 || update2) {
447
448 int childNum1 = child1.getNumber();
449 int childNum2 = child2.getNumber();
450
451 likelihoodCore.setNodePartialsForUpdate(nodeNum);
452
453 likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum);
454
455 if (parent == null) {
456 // No parent this is the root of the tree -
457 // calculate the pattern likelihoods
458 double[] frequencies = frequencyModel.getFrequencies();
459 double[] proportions = currentSiteModel.getCategoryProportions();
460
461 likelihoodCore.integratePartials(nodeNum, proportions, rootPartials);
462 likelihoodCore.calculateLogLikelihoods(rootPartials, frequencies, patternLogLikelihoods);
463 }
464
465 update = true;
466 }
467 }
468
469 return update;
470
471 }
472
473 /**
474 * The XML parser
475 */
476 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
477
478 public String getParserName() {
479 return ADVANCED_TREE_LIKELIHOOD;
480 }
481
482 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
483
484 boolean useAmbiguities = xo.getAttribute(USE_AMBIGUITIES, false);
485 boolean useScaling = xo.getAttribute(USE_SCALING, false);
486
487 PatternList patternList = (PatternList) xo.getChild(PatternList.class);
488 TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
489 SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class);
490
491 BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class);
492
493 AdvancedTreeLikelihood treeLikelihood = new AdvancedTreeLikelihood(patternList, treeModel, siteModel,
494 branchRateModel, useAmbiguities,
495 useScaling);
496
497 if (xo.hasChildNamed(TIPS)) {
498 SiteModel siteModel2 = (SiteModel) xo.getElementFirstChild(TIPS);
499 treeLikelihood.addTipsSiteModel(siteModel2);
500 }
501
502 XMLObject xoc = (XMLObject) xo.getChild(DELTA);
503 if (xoc != null) {
504 Parameter deltaParameter = (Parameter) xoc.getChild(Parameter.class);
505 TaxonList taxa = (TaxonList) xoc.getChild(TaxonList.class);
506 treeLikelihood.addDeltaParameter(deltaParameter, taxa);
507 }
508
509 for (int i = 0; i < xo.getChildCount(); i++) {
510 if (xo.getChild(i) instanceof XMLObject) {
511
512 xoc = (XMLObject) xo.getChild(i);
513 if (xoc.getName().equals(CLADE)) {
514
515 SiteModel siteModel2 = (SiteModel) xoc.getChild(SiteModel.class);
516 TaxonList taxonList = (TaxonList) xoc.getChild(TaxonList.class);
517
518 boolean includeStem = false;
519
520 if (xoc.hasAttribute(INCLUDE_STEM)) {
521 includeStem = xoc.getBooleanAttribute(INCLUDE_STEM);
522
523 if (taxonList.getTaxonCount() == 1 && !includeStem) {
524 throw new XMLParseException("The site model is only applied to 1 taxon and therefore must include the stem branch");
525 }
526 } else if (taxonList.getTaxonCount() == 1) {
527 includeStem = true;
528 }
529
530 try {
531
532 treeLikelihood.addCladeSiteModel(siteModel2, taxonList, includeStem);
533
534 } catch (TreeUtils.MissingTaxonException mte) {
535 throw new XMLParseException("Taxon, " + mte + ", in " + getParserName() + " was not found in the tree.");
536 }
537 }
538
539 }
540 }
541
542 return treeLikelihood;
543 }
544
545 //************************************************************************
546 // AbstractXMLObjectParser implementation
547 //************************************************************************
548
549 public String getParserDescription() {
550 return "This element represents the likelihood of a patternlist on a tree given the site model.";
551 }
552
553 public Class getReturnType() {
554 return Likelihood.class;
555 }
556
557 public XMLSyntaxRule[] getSyntaxRules() {
558 return rules;
559 }
560
561 private final XMLSyntaxRule[] rules = {
562 AttributeRule.newBooleanRule(USE_AMBIGUITIES, true),
563 // AttributeRule.newBooleanRule(STORE_PARTIALS, true),
564 AttributeRule.newBooleanRule(USE_SCALING, true),
565 new ElementRule(TIPS, SiteModel.class, "A siteModel that will be applied only to the tips.", 0, 1),
566 new ElementRule(DELTA,
567 new XMLSyntaxRule[]{
568 new ElementRule(TaxonList.class, "A set of taxa to which to apply the delta model to", 0, 1),
569 new ElementRule(Parameter.class, "A parameter that specifies the amount of extra substitutions per site at each tip.", 0, 1),
570 }, true),
571 new ElementRule(CLADE,
572 new XMLSyntaxRule[]{
573 AttributeRule.newBooleanRule(INCLUDE_STEM, true, "determines whether or not the stem branch above this clade is included in the siteModel."),
574 new ElementRule(TaxonList.class, "A set of taxa which defines a clade to apply a different site model to"),
575 new ElementRule(SiteModel.class, "A siteModel that will be applied only to this clade")
576 }, 0, Integer.MAX_VALUE),
577 new ElementRule(PatternList.class),
578 new ElementRule(TreeModel.class),
579 new ElementRule(SiteModel.class),
580 new ElementRule(BranchRateModel.class, true)
581 };
582 };
583
584 private class Clade {
585 Clade(SiteModel siteModel, TaxonList taxonList, boolean includeStem) throws TreeUtils.MissingTaxonException {
586 this.siteModel = siteModel;
587 this.leafSet = TreeUtils.getLeavesForTaxa(treeModel, taxonList);
588 this.includeStem = includeStem;
589 if (taxonList.getTaxonCount() == 1) {
590 this.includeStem = true;
591 }
592
593 findMRCA();
594 }
595
596 void findMRCA() {
597 node = TreeUtils.getCommonAncestorNode(treeModel, leafSet).getNumber();
598 }
599
600 int getNode() {
601 return node;
602 }
603
604 boolean includeStem() {
605 return includeStem;
606 }
607
608 SiteModel getSiteModel() {
609 return this.siteModel;
610 }
611
612 SiteModel siteModel;
613 Set<String> leafSet;
614 int node;
615 boolean includeStem;
616 }
617
618 // **************************************************************
619 // INSTANCE VARIABLES
620 // **************************************************************
621
622 /**
623 * the frequency model for these sites
624 */
625 protected FrequencyModel frequencyModel = null;
626
627 /**
628 * the site model for these sites
629 */
630 protected SiteModel siteModel = null;
631
632 /**
633 * the branch rate model
634 */
635 protected BranchRateModel branchRateModel = null;
636
637 private final boolean storePartials = false;
638
639
640 /**
641 * the site model for the tips
642 */
643 protected SiteModel tipsSiteModel = null;
644
645 protected Parameter deltaParameter = null;
646 protected Set<Integer> deltaTips = null;
647
648 /**
649 * the site models for specific clades
650 */
651 protected ArrayList<Clade> cladeSiteModels = new ArrayList<Clade>();
652
653 private boolean commonAncestorsKnown = true;
654
655 /**
656 * the root partial likelihoods
657 */
658 protected double[] rootPartials = null;
659
660 /**
661 * the pattern likelihoods
662 */
663 protected double[] patternLogLikelihoods = null;
664
665 /**
666 * the number of rate categories
667 */
668 protected int categoryCount;
669
670 /**
671 * an array used to store transition probabilities
672 */
673 protected double[] probabilities;
674
675 /**
676 * the LikelihoodCore
677 */
678 protected LikelihoodCore likelihoodCore;
679 }