Debian Codegraph @

src/dr/oldevomodel/treelikelihood/PurifyingGammaTreeLikelihood.java

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