Debian Codegraph @

src/dr/oldevomodel/treelikelihood/TreeLikelihood.java

raw symbols SCIP
1 /*
2 * TreeLikelihood.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.AscertainedSitePatterns;
29 import dr.evolution.alignment.PatternList;
30 import dr.evolution.alignment.SitePatterns;
31 import dr.evolution.datatype.DataType;
32 import dr.evolution.tree.NodeRef;
33 import dr.evolution.tree.Tree;
34 import dr.evolution.util.Taxon;
35 import dr.evolution.util.TaxonList;
36 import dr.evomodel.branchratemodel.BranchRateModel;
37 import dr.evomodel.branchratemodel.DefaultBranchRateModel;
38 import dr.evomodel.tree.TreeChangedEvent;
39 import dr.oldevomodel.sitemodel.SiteModel;
40 import dr.oldevomodel.substmodel.FrequencyModel;
41 import dr.evomodel.tipstatesmodel.TipStatesModel;
42 import dr.evomodel.tree.TreeModel;
43 import dr.oldevomodelxml.treelikelihood.TreeLikelihoodParser;
44 import dr.inference.model.Model;
45 import dr.inference.model.Statistic;
46
47 import java.util.logging.Logger;
48
49 /**
50 * TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree.
51 *
52 * @author Andrew Rambaut
53 * @author Alexei Drummond
54 * @version $Id: TreeLikelihood.java,v 1.31 2006/08/30 16:02:42 rambaut Exp $
55 */
56
57 @Deprecated // Switching to BEAGLE
58 public class TreeLikelihood extends AbstractTreeLikelihood {
59 private static final boolean DEBUG = false;
60
61 /**
62 * Constructor.
63 */
64 public TreeLikelihood(PatternList patternList,
65 TreeModel treeModel,
66 SiteModel siteModel,
67 BranchRateModel branchRateModel,
68 TipStatesModel tipStatesModel,
69 boolean useAmbiguities,
70 boolean allowMissingTaxa,
71 boolean storePartials,
72 boolean forceJavaCore,
73 boolean forceRescaling) {
74
75 super(TreeLikelihoodParser.TREE_LIKELIHOOD, patternList, treeModel);
76
77 this.storePartials = storePartials;
78
79 try {
80 this.siteModel = siteModel;
81 addModel(siteModel);
82
83 this.frequencyModel = siteModel.getFrequencyModel();
84 addModel(frequencyModel);
85
86 this.tipStatesModel = tipStatesModel;
87
88 integrateAcrossCategories = siteModel.integrateAcrossCategories();
89
90 this.categoryCount = siteModel.getCategoryCount();
91
92 final Logger logger = Logger.getLogger("dr.evomodel");
93 String coreName = "Java general";
94 if (integrateAcrossCategories) {
95
96 final DataType dataType = patternList.getDataType();
97
98 if (dataType instanceof dr.evolution.datatype.Nucleotides) {
99
100 if (!forceJavaCore && NativeNucleotideLikelihoodCore.isAvailable()) {
101 coreName = "native nucleotide";
102 likelihoodCore = new NativeNucleotideLikelihoodCore();
103 } else {
104 coreName = "Java nucleotide";
105 likelihoodCore = new NucleotideLikelihoodCore();
106 }
107
108 } else if (dataType instanceof dr.evolution.datatype.AminoAcids) {
109 if (!forceJavaCore && NativeAminoAcidLikelihoodCore.isAvailable()) {
110 coreName = "native amino acid";
111 likelihoodCore = new NativeAminoAcidLikelihoodCore();
112 } else {
113 coreName = "Java amino acid";
114 likelihoodCore = new AminoAcidLikelihoodCore();
115 }
116
117 // The codon core was out of date and did nothing more than the general core...
118 } else if (dataType instanceof dr.evolution.datatype.Codons) {
119 if (!forceJavaCore && NativeGeneralLikelihoodCore.isAvailable()) {
120 coreName = "native general";
121 likelihoodCore = new NativeGeneralLikelihoodCore(patternList.getStateCount());
122 } else {
123 coreName = "Java general";
124 likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
125 }
126 useAmbiguities = true;
127 } else {
128 if (!forceJavaCore && NativeGeneralLikelihoodCore.isAvailable()) {
129 coreName = "native general";
130 likelihoodCore = new NativeGeneralLikelihoodCore(patternList.getStateCount());
131 } else {
132 coreName = "Java general";
133 likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
134 }
135 }
136 } else {
137 likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
138 }
139 {
140 final String id = getId();
141 logger.info("TreeLikelihood(" + ((id != null) ? id : treeModel.getId()) + ") using " + coreName + " likelihood core");
142
143 logger.info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood.");
144 logger.info(" With " + patternList.getPatternCount() + " unique site patterns.");
145 }
146
147 if (branchRateModel != null) {
148 this.branchRateModel = branchRateModel;
149 logger.info("Branch rate model used: " + branchRateModel.getModelName());
150 } else {
151 this.branchRateModel = new DefaultBranchRateModel();
152 }
153 addModel(this.branchRateModel);
154
155 probabilities = new double[stateCount * stateCount];
156
157 likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories);
158
159 int extNodeCount = treeModel.getExternalNodeCount();
160 int intNodeCount = treeModel.getInternalNodeCount();
161
162 if (tipStatesModel != null) {
163 tipStatesModel.setTree(treeModel);
164
165 tipPartials = new double[patternCount * stateCount];
166
167 for (int i = 0; i < extNodeCount; i++) {
168 // Find the id of tip i in the patternList
169 String id = treeModel.getTaxonId(i);
170 int index = patternList.getTaxonIndex(id);
171
172 if (index == -1) {
173 throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
174 ", is not found in patternList, " + patternList.getId());
175 }
176
177 tipStatesModel.setStates(patternList, index, i, id);
178 likelihoodCore.createNodePartials(i);
179 }
180
181 addModel(tipStatesModel);
182 } else {
183 for (int i = 0; i < extNodeCount; i++) {
184 // Find the id of tip i in the patternList
185 String id = treeModel.getTaxonId(i);
186 int index = patternList.getTaxonIndex(id);
187
188 if (index == -1) {
189 if (!allowMissingTaxa) {
190 throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
191 ", is not found in patternList, " + patternList.getId());
192 }
193 if (useAmbiguities) {
194 setMissingPartials(likelihoodCore, i);
195 } else {
196 setMissingStates(likelihoodCore, i);
197 }
198 } else {
199 if (useAmbiguities) {
200 setPartials(likelihoodCore, patternList, categoryCount, index, i);
201 } else {
202 setStates(likelihoodCore, patternList, index, i);
203 }
204 }
205 }
206 }
207 for (int i = 0; i < intNodeCount; i++) {
208 likelihoodCore.createNodePartials(extNodeCount + i);
209 }
210
211 if (forceRescaling) {
212 likelihoodCore.setUseScaling(true);
213 logger.info(" Forcing use of partials rescaling.");
214 }
215
216 } catch (TaxonList.MissingTaxonException mte) {
217 throw new RuntimeException(mte.toString());
218 }
219
220 addStatistic(new SiteLikelihoodsStatistic());
221 }
222
223 public final LikelihoodCore getLikelihoodCore() {
224 return likelihoodCore;
225 }
226
227 // **************************************************************
228 // ModelListener IMPLEMENTATION
229 // **************************************************************
230
231 /**
232 * Handles model changed events from the submodels.
233 */
234 protected void handleModelChangedEvent(Model model, Object object, int index) {
235
236 if (model == treeModel) {
237 if (object instanceof TreeChangedEvent) {
238
239 if (((TreeChangedEvent) object).isNodeChanged()) {
240 // If a node event occurs the node and its two child nodes
241 // are flagged for updating (this will result in everything
242 // above being updated as well. Node events occur when a node
243 // is added to a branch, removed from a branch or its height or
244 // rate changes.
245 updateNodeAndChildren(((TreeChangedEvent) object).getNode());
246
247 } else if (((TreeChangedEvent) object).isTreeChanged()) {
248 // Full tree events result in a complete updating of the tree likelihood
249 updateAllNodes();
250 } else {
251 // Other event types are ignored (probably trait changes).
252 //System.err.println("Another tree event has occured (possibly a trait change).");
253 }
254 }
255
256 } else if (model == branchRateModel) {
257 if (index == -1) {
258 updateAllNodes();
259 } else {
260 if (DEBUG) {
261 if (index >= treeModel.getNodeCount()) {
262 throw new IllegalArgumentException("Node index out of bounds");
263 }
264 }
265 updateNode(treeModel.getNode(index));
266 }
267
268 } else if (model == frequencyModel) {
269
270 updateAllNodes();
271
272 } else if (model == tipStatesModel) {
273 if(object instanceof Taxon)
274 {
275 for(int i=0; i<treeModel.getNodeCount(); i++)
276 if(treeModel.getNodeTaxon(treeModel.getNode(i))!=null && treeModel.getNodeTaxon(treeModel.getNode(i)).getId().equalsIgnoreCase(((Taxon)object).getId()))
277 updateNode(treeModel.getNode(i));
278 }else
279 updateAllNodes();
280
281 } else if (model instanceof SiteModel) {
282
283 updateAllNodes();
284
285 } else {
286
287 throw new RuntimeException("Unknown componentChangedEvent");
288 }
289
290 super.handleModelChangedEvent(model, object, index);
291 }
292
293 // **************************************************************
294 // Model IMPLEMENTATION
295 // **************************************************************
296
297 /**
298 * Stores the additional state other than model components
299 */
300 protected void storeState() {
301
302 if (storePartials) {
303 likelihoodCore.storeState();
304 }
305 super.storeState();
306
307 }
308
309 /**
310 * Restore the additional stored state
311 */
312 protected void restoreState() {
313
314 if (storePartials) {
315 likelihoodCore.restoreState();
316 } else {
317 updateAllNodes();
318 }
319
320 super.restoreState();
321
322 }
323
324 // **************************************************************
325 // Likelihood IMPLEMENTATION
326 // **************************************************************
327
328 /**
329 * Calculate the log likelihood of the current state.
330 *
331 * @return the log likelihood.
332 */
333 protected double calculateLogLikelihood() {
334
335 if (patternLogLikelihoods == null) {
336 patternLogLikelihoods = new double[patternCount];
337 }
338
339 if (!integrateAcrossCategories) {
340 if (siteCategories == null) {
341 siteCategories = new int[patternCount];
342 }
343 for (int i = 0; i < patternCount; i++) {
344 siteCategories[i] = siteModel.getCategoryOfSite(i);
345 }
346 }
347
348 if (tipStatesModel != null) {
349 int extNodeCount = treeModel.getExternalNodeCount();
350 for (int index = 0; index < extNodeCount; index++) {
351 if (updateNode[index]) {
352 likelihoodCore.setNodePartialsForUpdate(index);
353 tipStatesModel.getTipPartials(index, tipPartials);
354 likelihoodCore.setCurrentNodePartials(index, tipPartials);
355 }
356 }
357 }
358
359
360 final NodeRef root = treeModel.getRoot();
361 traverse(treeModel, root);
362
363 double logL = 0.0;
364 double ascertainmentCorrection = getAscertainmentCorrection(patternLogLikelihoods);
365 for (int i = 0; i < patternCount; i++) {
366 logL += (patternLogLikelihoods[i] - ascertainmentCorrection) * patternWeights[i];
367 }
368
369 if (logL == Double.NEGATIVE_INFINITY) {
370 Logger.getLogger("dr.evomodel").info("TreeLikelihood, " + this.getId() + ", turning on partial likelihood scaling to avoid precision loss");
371
372 // We probably had an underflow... turn on scaling
373 likelihoodCore.setUseScaling(true);
374
375 // and try again...
376 updateAllNodes();
377 updateAllPatterns();
378 traverse(treeModel, root);
379
380 logL = 0.0;
381 ascertainmentCorrection = getAscertainmentCorrection(patternLogLikelihoods);
382 for (int i = 0; i < patternCount; i++) {
383 logL += (patternLogLikelihoods[i] - ascertainmentCorrection) * patternWeights[i];
384 }
385 }
386
387 //********************************************************************
388 // after traverse all nodes and patterns have been updated --
389 //so change flags to reflect this.
390 for (int i = 0; i < nodeCount; i++) {
391 updateNode[i] = false;
392 }
393 //********************************************************************
394
395 return logL;
396 }
397
398 public double[] getPatternLogLikelihoods() {
399 getLogLikelihood(); // Ensure likelihood is up-to-date
400 double ascertainmentCorrection = getAscertainmentCorrection(patternLogLikelihoods);
401 double[] out = new double[patternCount];
402 for (int i = 0; i < patternCount; i++) {
403 if (patternWeights[i] > 0) {
404 out[i] = (patternLogLikelihoods[i] - ascertainmentCorrection) * patternWeights[i];
405 } else {
406 out[i] = Double.NEGATIVE_INFINITY;
407 }
408 }
409 return out;
410 }
411
412 /* Calculate ascertainment correction if working off of AscertainedSitePatterns
413 @param patternLogProbs log pattern probabilities
414 @return the log total probability for a pattern.
415 */
416 protected double getAscertainmentCorrection(double[] patternLogProbs) {
417 if (patternList instanceof AscertainedSitePatterns) {
418 return ((AscertainedSitePatterns) patternList).getAscertainmentCorrection(patternLogProbs);
419 } else {
420 return 0.0;
421 }
422 }
423
424 /**
425 * Check whether the scaling is still required. If the sum of all the logScalingFactors
426 * is zero then we simply turn off the useScaling flag. This will speed up the likelihood
427 * calculations when scaling is not required.
428 */
429 public void checkScaling() {
430 // if (useScaling) {
431 // if (scalingCheckCount % 1000 == 0) {
432 // double totalScalingFactor = 0.0;
433 // for (int i = 0; i < nodeCount; i++) {
434 // for (int j = 0; j < patternCount; j++) {
435 // totalScalingFactor += scalingFactors[currentPartialsIndices[i]][i][j];
436 // }
437 // }
438 // useScaling = totalScalingFactor < 0.0;
439 // Logger.getLogger("dr.evomodel").info("LikelihoodCore total log scaling factor: " + totalScalingFactor);
440 // if (!useScaling) {
441 // Logger.getLogger("dr.evomodel").info("LikelihoodCore scaling turned off.");
442 // }
443 // }
444 // scalingCheckCount++;
445 // }
446 }
447
448
449 /**
450 * Traverse the tree calculating partial likelihoods.
451 *
452 * @return whether the partials for this node were recalculated.
453 */
454 protected boolean traverse(Tree tree, NodeRef node) {
455
456 boolean update = false;
457
458 int nodeNum = node.getNumber();
459
460 NodeRef parent = tree.getParent(node);
461
462 // First update the transition probability matrix(ices) for this branch
463 if (parent != null && updateNode[nodeNum]) {
464
465 final double branchRate = branchRateModel.getBranchRate(tree, node);
466
467 // Get the operational time of the branch
468 final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
469
470 if (branchTime < 0.0) {
471 throw new RuntimeException("Negative branch length: " + branchTime);
472 }
473
474 likelihoodCore.setNodeMatrixForUpdate(nodeNum);
475
476 for (int i = 0; i < categoryCount; i++) {
477
478 double branchLength = siteModel.getRateForCategory(i) * branchTime;
479 siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities);
480 likelihoodCore.setNodeMatrix(nodeNum, i, probabilities);
481 }
482
483 update = true;
484 }
485
486 // If the node is internal, update the partial likelihoods.
487 if (!tree.isExternal(node)) {
488
489 // Traverse down the two child nodes
490 NodeRef child1 = tree.getChild(node, 0);
491 final boolean update1 = traverse(tree, child1);
492
493 NodeRef child2 = tree.getChild(node, 1);
494 final boolean update2 = traverse(tree, child2);
495
496 // If either child node was updated then update this node too
497 if (update1 || update2) {
498
499 final int childNum1 = child1.getNumber();
500 final int childNum2 = child2.getNumber();
501
502 likelihoodCore.setNodePartialsForUpdate(nodeNum);
503
504 if (integrateAcrossCategories) {
505 likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum);
506 } else {
507 likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum, siteCategories);
508 }
509
510 if (COUNT_TOTAL_OPERATIONS) {
511 totalOperationCount ++;
512 }
513
514 if (parent == null) {
515 // No parent this is the root of the tree -
516 // calculate the pattern likelihoods
517 double[] frequencies = frequencyModel.getFrequencies();
518
519 double[] partials = getRootPartials();
520
521 likelihoodCore.calculateLogLikelihoods(partials, frequencies, patternLogLikelihoods);
522 }
523
524 update = true;
525 }
526 }
527
528 return update;
529
530 }
531
532 public final double[] getRootPartials() {
533 if (rootPartials == null) {
534 rootPartials = new double[patternCount * stateCount];
535 }
536
537 int nodeNum = treeModel.getRoot().getNumber();
538 if (integrateAcrossCategories) {
539
540 // moved this call to here, because non-integrating siteModels don't need to support it - AD
541 double[] proportions = siteModel.getCategoryProportions();
542 likelihoodCore.integratePartials(nodeNum, proportions, rootPartials);
543 } else {
544 likelihoodCore.getPartials(nodeNum, rootPartials);
545 }
546
547 return rootPartials;
548 }
549
550 /**
551 * the root partial likelihoods (a temporary array that is used
552 * to fetch the partials - it should not be examined directly -
553 * use getRootPartials() instead).
554 */
555 private double[] rootPartials = null;
556
557 public class SiteLikelihoodsStatistic extends Statistic.Abstract {
558
559 public SiteLikelihoodsStatistic() {
560 super("siteLikelihoods");
561 }
562
563 public int getDimension() {
564 if (patternList instanceof SitePatterns) {
565 return ((SitePatterns)patternList).getSiteCount();
566 } else {
567 return patternList.getPatternCount();
568 }
569 }
570
571 public String getDimensionName(int dim) {
572 return getTreeModel().getId() + "site-" + dim;
573 }
574
575 public double getStatisticValue(int i) {
576
577 if (patternList instanceof SitePatterns) {
578 int index = ((SitePatterns)patternList).getPatternIndex(i);
579 if( index >= 0 ) {
580 return patternLogLikelihoods[index] / patternWeights[index];
581 } else {
582 return 0.0;
583 }
584 } else {
585 return patternList.getPatternCount();
586 }
587 }
588
589 }
590
591 // **************************************************************
592 // INSTANCE VARIABLES
593 // **************************************************************
594
595 /**
596 * the frequency model for these sites
597 */
598 protected final FrequencyModel frequencyModel;
599
600 /**
601 * the site model for these sites
602 */
603 protected final SiteModel siteModel;
604
605 /**
606 * the branch rate model
607 */
608 protected final BranchRateModel branchRateModel;
609
610 /**
611 * the tip partials model
612 */
613 private final TipStatesModel tipStatesModel;
614
615 private final boolean storePartials;
616
617 protected final boolean integrateAcrossCategories;
618
619 /**
620 * the categories for each site
621 */
622 protected int[] siteCategories = null;
623
624
625 /**
626 * the pattern likelihoods
627 */
628 protected double[] patternLogLikelihoods = null;
629
630 /**
631 * the number of rate categories
632 */
633 protected int categoryCount;
634
635 /**
636 * an array used to transfer transition probabilities
637 */
638 protected double[] probabilities;
639
640
641 /**
642 * an array used to transfer tip partials
643 */
644 protected double[] tipPartials;
645
646 /**
647 * the LikelihoodCore
648 */
649 protected LikelihoodCore likelihoodCore;
650 }