Debian Codegraph @

src/dr/oldevomodel/treelikelihood/PrecisionTestTreeLikelihood.java

raw symbols SCIP
1 /*
2 * PrecisionTestTreeLikelihood.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.util.TaxonList;
32 import dr.evomodel.branchratemodel.BranchRateModel;
33 import dr.evomodel.branchratemodel.DefaultBranchRateModel;
34 import dr.evomodel.tree.TreeChangedEvent;
35 import dr.oldevomodel.sitemodel.SiteModel;
36 import dr.oldevomodel.substmodel.FrequencyModel;
37 import dr.evomodel.tree.TreeModel;
38 import dr.inference.model.Likelihood;
39 import dr.inference.model.Model;
40 import dr.xml.*;
41
42 import java.math.BigDecimal;
43 import java.util.logging.Logger;
44
45 /**
46 * TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree.
47 *
48 * @author Andrew Rambaut
49 * @author Alexei Drummond
50 * @version $Id: TreeLikelihood.java,v 1.31 2006/08/30 16:02:42 rambaut Exp $
51 */
52
53 @Deprecated // Switching to BEAGLE
54 public class PrecisionTestTreeLikelihood extends AbstractTreeLikelihood {
55
56 public static final String TREE_LIKELIHOOD = "precisionTestTreeLikelihood";
57 public static final String USE_AMBIGUITIES = "useAmbiguities";
58 public static final String ALLOW_MISSING_TAXA = "allowMissingTaxa";
59 public static final String STORE_PARTIALS = "storePartials";
60 public static final String USE_SCALING = "useScaling";
61 public static final String FORCE_JAVA_CORE = "forceJavaCore";
62
63 /**
64 * Constructor.
65 */
66 public PrecisionTestTreeLikelihood(PatternList patternList,
67 TreeModel treeModel,
68 SiteModel siteModel,
69 BranchRateModel branchRateModel,
70 boolean useAmbiguities,
71 boolean allowMissingTaxa,
72 boolean storePartials) {
73
74 super(TREE_LIKELIHOOD, patternList, treeModel);
75
76 this.storePartials = storePartials;
77
78 try {
79 this.siteModel = siteModel;
80 addModel(siteModel);
81
82 this.frequencyModel = siteModel.getFrequencyModel();
83 addModel(frequencyModel);
84
85 this.categoryCount = siteModel.getCategoryCount();
86
87 final Logger logger = Logger.getLogger("dr.evomodel");
88 String coreName = "Java general";
89 likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
90 precisionLikelihoodCore = new ArbitraryPrecisionLikelihoodCore(patternList.getStateCount(), 20);
91
92 logger.info("PrecisionTestTreeLikelihood using " + coreName + " likelihood core");
93
94 logger.info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood.");
95
96 if (branchRateModel != null) {
97 this.branchRateModel = branchRateModel;
98 logger.info("Branch rate model used: " + branchRateModel.getModelName());
99 } else {
100 this.branchRateModel = new DefaultBranchRateModel();
101 }
102 addModel(this.branchRateModel);
103
104 probabilities = new double[stateCount * stateCount];
105
106 likelihoodCore.initialize(nodeCount, patternCount, categoryCount, true);
107 precisionLikelihoodCore.initialize(nodeCount, patternCount, categoryCount, true);
108
109 int extNodeCount = treeModel.getExternalNodeCount();
110 int intNodeCount = treeModel.getInternalNodeCount();
111
112 for (int i = 0; i < extNodeCount; i++) {
113 // Find the id of tip i in the patternList
114 String id = treeModel.getTaxonId(i);
115 int index = patternList.getTaxonIndex(id);
116
117 if (index == -1) {
118 if (!allowMissingTaxa) {
119 throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
120 ", is not found in patternList, " + patternList.getId());
121 }
122 if (useAmbiguities) {
123 setMissingPartials(likelihoodCore, i);
124 setMissingPartials(precisionLikelihoodCore, i);
125 } else {
126 setMissingStates(likelihoodCore, i);
127 setMissingStates(precisionLikelihoodCore, i);
128 }
129 } else {
130 if (useAmbiguities) {
131 setPartials(likelihoodCore, patternList, categoryCount, index, i);
132 setPartials(precisionLikelihoodCore, patternList, categoryCount, index, i);
133 } else {
134 setStates(likelihoodCore, patternList, index, i);
135 setStates(precisionLikelihoodCore, patternList, index, i);
136 }
137 }
138 }
139
140 for (int i = 0; i < intNodeCount; i++) {
141 likelihoodCore.createNodePartials(extNodeCount + i);
142 precisionLikelihoodCore.createNodePartials(extNodeCount + i);
143 }
144 } catch (TaxonList.MissingTaxonException mte) {
145 throw new RuntimeException(mte.toString());
146 }
147 }
148
149 // **************************************************************
150 // ModelListener IMPLEMENTATION
151 // **************************************************************
152
153 /**
154 * Handles model changed events from the submodels.
155 */
156 protected void handleModelChangedEvent(Model model, Object object, int index) {
157
158 if (model == treeModel) {
159 if (object instanceof TreeChangedEvent) {
160
161 if (((TreeChangedEvent) object).isNodeChanged()) {
162 // If a node event occurs the node and its two child nodes
163 // are flagged for updating (this will result in everything
164 // above being updated as well. Node events occur when a node
165 // is added to a branch, removed from a branch or its height or
166 // rate changes.
167 updateNodeAndChildren(((TreeChangedEvent) object).getNode());
168
169 } else if (((TreeChangedEvent) object).isTreeChanged()) {
170 // Full tree events result in a complete updating of the tree likelihood
171 // Currently this event type is not used.
172 System.err.println("Full tree update event - these events currently aren't used\n" +
173 "so either this is in error or a new feature is using them so remove this message.");
174 updateAllNodes();
175 } else {
176 // Other event types are ignored (probably trait changes).
177 //System.err.println("Another tree event has occured (possibly a trait change).");
178 }
179 }
180
181 } else if (model == branchRateModel) {
182 if (index == -1) {
183 updateAllNodes();
184 } else {
185 updateNode(treeModel.getNode(index));
186 }
187
188 } else if (model == frequencyModel) {
189
190 updateAllNodes();
191
192 } else if (model instanceof SiteModel) {
193
194 updateAllNodes();
195
196 } else {
197
198 throw new RuntimeException("Unknown componentChangedEvent");
199 }
200
201 super.handleModelChangedEvent(model, object, index);
202 }
203
204 // **************************************************************
205 // Model IMPLEMENTATION
206 // **************************************************************
207
208 /**
209 * Stores the additional state other than model components
210 */
211 protected void storeState() {
212
213 if (storePartials) {
214 likelihoodCore.storeState();
215 precisionLikelihoodCore.storeState();
216 }
217 super.storeState();
218
219 }
220
221 /**
222 * Restore the additional stored state
223 */
224 protected void restoreState() {
225
226 if (storePartials) {
227 likelihoodCore.restoreState();
228 precisionLikelihoodCore.restoreState();
229 } else {
230 updateAllNodes();
231 }
232
233 super.restoreState();
234
235 }
236
237 // **************************************************************
238 // Likelihood IMPLEMENTATION
239 // **************************************************************
240
241 /**
242 * Calculate the log likelihood of the current state.
243 *
244 * @return the log likelihood.
245 */
246 protected double calculateLogLikelihood() {
247
248 if (patternLogLikelihoods == null) {
249 patternLogLikelihoods = new double[patternCount];
250 }
251
252 if (precisionPatternLogLikelihoods == null) {
253 precisionPatternLogLikelihoods = new double[patternCount];
254 }
255
256 final NodeRef root = treeModel.getRoot();
257 traverse(treeModel, root);
258
259 double logL = 0.0;
260
261 for (int i = 0; i < patternCount; i++) {
262 logL += patternLogLikelihoods[i] * patternWeights[i];
263 }
264
265 double precisionLogL = 0.0;
266
267 for (int i = 0; i < patternCount; i++) {
268 precisionLogL += precisionPatternLogLikelihoods[i] * patternWeights[i];
269 }
270
271 if (Math.abs(logL - precisionLogL) > 1.0E-5) {
272 System.out.println("logL = " + logL + " precision logL = " + precisionLogL);
273 }
274
275 if (logL == Double.NEGATIVE_INFINITY) {
276 // We probably had an underflow... turn on scaling
277 likelihoodCore.setUseScaling(true);
278
279 // and try again...
280 updateAllNodes();
281 updateAllPatterns();
282 traverse(treeModel, root);
283
284 logL = 0.0;
285 for (int i = 0; i < patternCount; i++) {
286 logL += patternLogLikelihoods[i] * patternWeights[i];
287 }
288
289 if (Math.abs(logL - precisionLogL) > 1.0E-5) {
290 System.out.println("scaled logL = " + logL + " precision logL = " + precisionLogL);
291 }
292
293 }
294
295 //********************************************************************
296 // after traverse all nodes and patterns have been updated --
297 //so change flags to reflect this.
298 for (int i = 0; i < nodeCount; i++) {
299 updateNode[i] = false;
300 }
301 //********************************************************************
302
303 return logL;
304 }
305
306 /**
307 * Traverse the tree calculating partial likelihoods.
308 *
309 * @return whether the partials for this node were recalculated.
310 */
311 private boolean traverse(Tree tree, NodeRef node) {
312
313 boolean update = false;
314
315 int nodeNum = node.getNumber();
316
317 NodeRef parent = tree.getParent(node);
318
319 // First update the transition probability matrix(ices) for this branch
320 if (parent != null && updateNode[nodeNum]) {
321
322 final double branchRate = branchRateModel.getBranchRate(tree, node);
323
324 // Get the operational time of the branch
325 final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
326
327 if (branchTime < 0.0) {
328 throw new RuntimeException("Negative branch length: " + branchTime);
329 }
330
331 likelihoodCore.setNodeMatrixForUpdate(nodeNum);
332 precisionLikelihoodCore.setNodeMatrixForUpdate(nodeNum);
333
334 for (int i = 0; i < categoryCount; i++) {
335
336 double branchLength = siteModel.getRateForCategory(i) * branchTime;
337 siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities);
338 likelihoodCore.setNodeMatrix(nodeNum, i, probabilities);
339 precisionLikelihoodCore.setNodeMatrix(nodeNum, i, probabilities);
340 }
341
342 update = true;
343 }
344
345 // If the node is internal, update the partial likelihoods.
346 if (!tree.isExternal(node)) {
347
348 // Traverse down the two child nodes
349 NodeRef child1 = tree.getChild(node, 0);
350 final boolean update1 = traverse(tree, child1);
351
352 NodeRef child2 = tree.getChild(node, 1);
353 final boolean update2 = traverse(tree, child2);
354
355 // If either child node was updated then update this node too
356 if (update1 || update2) {
357
358 final int childNum1 = child1.getNumber();
359 final int childNum2 = child2.getNumber();
360
361 likelihoodCore.setNodePartialsForUpdate(nodeNum);
362 precisionLikelihoodCore.setNodePartialsForUpdate(nodeNum);
363
364 likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum);
365 precisionLikelihoodCore.calculatePartials(childNum1, childNum2, nodeNum);
366
367 if (parent == null) {
368 // No parent this is the root of the tree -
369 // calculate the pattern likelihoods
370 double[] frequencies = frequencyModel.getFrequencies();
371
372 double[] partials = getRootPartials();
373 likelihoodCore.calculateLogLikelihoods(partials, frequencies, patternLogLikelihoods);
374
375 BigDecimal[] precisionPartials = getPrecisionRootPartials();
376 precisionLikelihoodCore.calculateLogLikelihoods(precisionPartials, frequencies, precisionPatternLogLikelihoods);
377 }
378
379 update = true;
380 }
381 }
382
383 return update;
384
385 }
386
387 public final double[] getRootPartials() {
388 if (rootPartials == null) {
389 rootPartials = new double[patternCount * stateCount];
390 }
391
392 int nodeNum = treeModel.getRoot().getNumber();
393 // moved this call to here, because non-integrating siteModels don't need to support it - AD
394 double[] proportions = siteModel.getCategoryProportions();
395 likelihoodCore.integratePartials(nodeNum, proportions, rootPartials);
396
397 return rootPartials;
398 }
399
400 private double[] rootPartials = null;
401
402 public final BigDecimal[] getPrecisionRootPartials() {
403 if (precisionRootPartials == null) {
404 precisionRootPartials = new BigDecimal[patternCount * stateCount];
405 }
406
407 int nodeNum = treeModel.getRoot().getNumber();
408 // moved this call to here, because non-integrating siteModels don't need to support it - AD
409 double[] proportions = siteModel.getCategoryProportions();
410 precisionLikelihoodCore.integratePartials(nodeNum, proportions, precisionRootPartials);
411
412 return precisionRootPartials;
413 }
414
415 private BigDecimal[] precisionRootPartials = null;
416
417 /**
418 * The XML parser
419 */
420 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
421
422 public String getParserName() {
423 return TREE_LIKELIHOOD;
424 }
425
426 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
427
428 boolean useAmbiguities = xo.getAttribute(USE_AMBIGUITIES, false);
429 boolean allowMissingTaxa = xo.getAttribute(ALLOW_MISSING_TAXA, false);
430 boolean storePartials = xo.getAttribute(STORE_PARTIALS, true);
431
432 PatternList patternList = (PatternList) xo.getChild(PatternList.class);
433 TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
434 SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class);
435
436 BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class);
437
438 return new PrecisionTestTreeLikelihood(
439 patternList,
440 treeModel,
441 siteModel,
442 branchRateModel,
443 useAmbiguities, allowMissingTaxa, storePartials);
444 }
445
446 //************************************************************************
447 // AbstractXMLObjectParser implementation
448 //************************************************************************
449
450 public String getParserDescription() {
451 return "This element represents the likelihood of a patternlist on a tree given the site model.";
452 }
453
454 public Class getReturnType() {
455 return Likelihood.class;
456 }
457
458 public XMLSyntaxRule[] getSyntaxRules() {
459 return rules;
460 }
461
462 private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
463 AttributeRule.newBooleanRule(USE_AMBIGUITIES, true),
464 AttributeRule.newBooleanRule(ALLOW_MISSING_TAXA, true),
465 AttributeRule.newBooleanRule(STORE_PARTIALS, true),
466 new ElementRule(PatternList.class),
467 new ElementRule(TreeModel.class),
468 new ElementRule(SiteModel.class),
469 new ElementRule(BranchRateModel.class, true),
470 };
471 };
472
473 // **************************************************************
474 // INSTANCE VARIABLES
475 // **************************************************************
476
477 /**
478 * the frequency model for these sites
479 */
480 protected final FrequencyModel frequencyModel;
481
482 /**
483 * the site model for these sites
484 */
485 protected final SiteModel siteModel;
486
487 /**
488 * the branch rate model
489 */
490 protected final BranchRateModel branchRateModel;
491
492 private final boolean storePartials;
493
494 /**
495 * the categories for each site
496 */
497 protected int[] siteCategories = null;
498
499
500 /**
501 * the pattern likelihoods
502 */
503 protected double[] patternLogLikelihoods = null;
504 /**
505 * the pattern likelihoods
506 */
507 protected double[] precisionPatternLogLikelihoods = null;
508
509 /**
510 * the number of rate categories
511 */
512 protected int categoryCount;
513
514 /**
515 * an array used to store transition probabilities
516 */
517 protected double[] probabilities;
518
519 /**
520 * the LikelihoodCore
521 */
522 protected LikelihoodCore likelihoodCore;
523 protected ArbitraryPrecisionLikelihoodCore precisionLikelihoodCore;
524 }