Debian Codegraph @

src/dr/oldevomodel/treelikelihood/PurifyingTreeLikelihood.java

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