Debian Codegraph @

src/dr/evomodel/arg/likelihood/ARGLikelihood.java

raw symbols SCIP
1 /*
2 * ARGLikelihood.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 /*
27 * TreeLikelihood.java
28 *
29 * (c) 2002-2005 BEAST Development Core Team
30 *
31 * This package may be distributed under the
32 * Lesser Gnu Public Licence (LGPL)
33 */
34
35 package dr.evomodel.arg.likelihood;
36
37 import dr.evolution.alignment.PatternList;
38 import dr.evolution.tree.NodeRef;
39 import dr.evolution.tree.Tree;
40 import dr.evolution.util.TaxonList;
41 import dr.evomodel.arg.ARGModel;
42 import dr.evomodel.arg.ARGTree;
43 import dr.evomodel.arg.operators.ARGPartitioningOperator;
44 import dr.evomodel.branchratemodel.BranchRateModel;
45 import dr.evomodel.branchratemodel.DefaultBranchRateModel;
46 import dr.oldevomodel.sitemodel.SiteModel;
47 import dr.oldevomodel.substmodel.FrequencyModel;
48 import dr.evomodel.treelikelihood.*;
49 import dr.inference.model.Likelihood;
50 import dr.inference.model.Model;
51 import dr.inference.model.Parameter;
52 import dr.oldevomodel.treelikelihood.*;
53 import dr.xml.*;
54
55 import java.util.logging.Logger;
56 import java.util.*;
57
58 /**
59 * ARGLikelihood - implements a Likelihood Function for sequences on an ancestral recombination graph.
60 *
61 * @author Marc Suchard
62 * @version $Id: ARGLikelihood.java,v 1.3 2006/10/23 04:13:41 msuchard Exp $
63 */
64
65 public class ARGLikelihood extends AbstractARGLikelihood {
66
67 public static final String ARG_LIKELIHOOD = "argTreeLikelihood";
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 ARGLikelihood(PatternList patternList,
76 ARGModel treeModel,
77 SiteModel siteModel,
78 BranchRateModel branchRateModel,
79 boolean useAmbiguities,
80 boolean storePartials,
81 boolean useScaling) {
82
83 super(ARG_LIKELIHOOD, patternList, treeModel);
84
85 partition = treeModel.addLikelihoodCalculator(this);
86
87 this.storePartials = storePartials;
88 this.useAmbiguities = useAmbiguities;
89
90 try {
91 this.siteModel = siteModel;
92 addModel(siteModel);
93
94 this.frequencyModel = siteModel.getFrequencyModel();
95 addModel(frequencyModel);
96
97 integrateAcrossCategories = siteModel.integrateAcrossCategories();
98
99 this.categoryCount = siteModel.getCategoryCount();
100
101 if (integrateAcrossCategories) {
102 if (patternList.getDataType() instanceof dr.evolution.datatype.Nucleotides) {
103
104 if (NativeNucleotideLikelihoodCore.isAvailable()) {
105
106 Logger.getLogger("dr.evomodel").info("TreeLikelihood using native nucleotide likelihood core");
107 likelihoodCore = new NativeNucleotideLikelihoodCore();
108 } else {
109
110 Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java nucleotide likelihood core");
111 likelihoodCore = new NucleotideLikelihoodCore();
112 }
113
114 } else if (patternList.getDataType() instanceof dr.evolution.datatype.AminoAcids) {
115
116 if (NativeAminoAcidLikelihoodCore.isAvailable()) {
117 Logger.getLogger("dr.evomodel").info("TreeLikelihood using native amino acid likelihood core");
118 likelihoodCore = new NativeAminoAcidLikelihoodCore();
119 } else {
120 Logger.getLogger("dr.evomodel").info("TreeLikelihood using java likelihood core");
121 likelihoodCore = new AminoAcidLikelihoodCore();
122 }
123 } else if (patternList.getDataType() instanceof dr.evolution.datatype.Codons) {
124 Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java codon likelihood core");
125 // likelihoodCore = new CodonLikelihoodCore(patternList.getStateCount());
126 this.useAmbiguities = true;
127 throw new RuntimeException("Still need to merge codon likelihood core");
128 } else {
129 if (patternList.getDataType() instanceof dr.evolution.datatype.OldHiddenNucleotides &&
130 NativeCovarionLikelihoodCore.isAvailable()) {
131 Logger.getLogger("dr.evomodel").info("TreeLikelihood using native covarion likelihood core");
132 likelihoodCore = new NativeCovarionLikelihoodCore();
133 } else {
134 Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java general likelihood core");
135 likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
136 }
137
138 }
139 } else {
140
141 Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java general likelihood core");
142 likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
143 }
144 Logger.getLogger("dr.evomodel").info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood.");
145 Logger.getLogger("dr.evomodel").info(" Partial likelihood scaling " + (useScaling ? "on." : "off."));
146
147 if (branchRateModel != null) {
148 this.branchRateModel = branchRateModel;
149 Logger.getLogger("dr.evomodel").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, useScaling);
158 likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories);
159
160 int extNodeCount = treeModel.getExternalNodeCount();
161 int intNodeCount = treeModel.getInternalNodeCount();
162
163 for (int i = 0; i < extNodeCount; i++) {
164 // Find the id of tip i in the patternList
165 String id = treeModel.getTaxonId(i);
166 int index = patternList.getTaxonIndex(id);
167
168 // System.err.println("id = "+id+" index = "+index);
169
170 if (index == -1) {
171 throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
172 ", is not found in patternList, " + patternList.getId());
173 }
174
175 if (useAmbiguities) {
176 setPartials(likelihoodCore, patternList, categoryCount, index, i);
177 } else {
178 setStates(likelihoodCore, patternList, index, i);
179 }
180 }
181
182 // System.exit(-1);
183 for (int i = 0; i < intNodeCount; i++) {
184 likelihoodCore.createNodePartials(extNodeCount + i);
185 }
186 } catch (TaxonList.MissingTaxonException mte) {
187 throw new RuntimeException(mte.toString());
188 }
189
190 }
191
192 // **************************************************************
193 // ModelListener IMPLEMENTATION
194 // **************************************************************
195
196
197 private static final boolean NO_CACHING = false;
198
199 /**
200 * Handles model changed events from the submodels.
201 */
202 protected void handleModelChangedEvent(Model model, Object object, int index) {
203
204 if (NO_CACHING) {
205 reconstructTree = true;
206 updateAllNodes();
207 }
208
209 if (model == treeModel) {
210 if (object instanceof ARGModel.ARGTreeChangedEvent) {
211 ARGModel.ARGTreeChangedEvent event = (ARGModel.ARGTreeChangedEvent) object;
212 if (event.isSizeChanged() ) {
213 updateAllNodes(); // TODO Update only affected portion of tree
214 reconstructTree = true;
215 } else if (event.isNodeChanged()) {
216 // If a node event occurs the node and its two child nodes
217 // are flagged for updating (this will result in everything
218 // above being updated as well. Node events occur when a node
219 // is added to a branch, removed from a branch or its height or
220 // rate changes.
221
222 NodeRef treeNode = mapARGNodesToTreeNodes.get(event.getNode());
223 if ( treeNode != null ) {
224 if (event.isHeightChanged() || event.isRateChanged()) {
225 updateNodeAndChildren(treeNode);
226 } else {
227 reconstructTree = true;
228 // updateNodeAndChildren(treeNode); // TODO This doesn't work with sizeChange; why???
229 updateAllNodes();
230 }
231 }
232 } else if (event.isTreeChanged()) {
233 // Full tree events result in a complete updating of the tree likelihood
234 // These include adding and removing nodes
235 // TODO ARG rearrangements still call this; they should not
236 reconstructTree = true;
237 updateAllNodes();
238 } else {
239 // Other event types are ignored (probably trait changes).
240 throw new RuntimeException("Another tree event has occured (possibly a trait change).");
241 }
242 } else if (object instanceof ARGPartitioningOperator.PartitionChangedEvent) {
243 final boolean[] updatePartition = ((ARGPartitioningOperator.PartitionChangedEvent) object).getUpdatedPartitions();
244 if (updatePartition[partition]) {
245 reconstructTree = true;
246 updateAllNodes(); // TODO Probably does not affect entire tree; fix
247 }
248 } else if (object instanceof Parameter) {
249 // ignore, most of these are handled in isNodeChanged()
250 } else
251 throw new RuntimeException("Unexpected ARGModel update "+object.getClass());
252
253 } else if (model == branchRateModel) {
254 // TODO Only update affected branches
255 updateAllNodes();
256 } else if (model == frequencyModel) {
257 updateAllNodes();
258 } else if (model instanceof SiteModel) {
259 updateAllNodes();
260 } else {
261 throw new RuntimeException("Unknown componentChangedEvent");
262 }
263
264 super.handleModelChangedEvent(model, object, index);
265 }
266
267 // **************************************************************
268 // Model IMPLEMENTATION
269 // **************************************************************
270
271 /**
272 * Stores the additional state other than model components
273 */
274 protected void storeState() {
275
276 if (storePartials) {
277 likelihoodCore.storeState();
278 }
279 super.storeState();
280 }
281
282 /**
283 * Restore the additional stored state
284 */
285 protected void restoreState() {
286
287 if (storePartials) {
288 likelihoodCore.restoreState();
289 } else {
290 updateAllNodes();
291 }
292 reconstructTree = true; // currently the tree is not cached, because the ARG that generates it is cached
293 super.restoreState();
294 }
295
296 private int getUnusedInt(Map<NodeRef,Integer> inMap) {
297 Collection<Integer> intSet = inMap.values();
298 int i = tree.getExternalNodeCount();
299 while( intSet.contains(i) )
300 i++;
301 return i;
302 }
303
304
305 private Set<NodeRef> unsetNodes = null;
306
307 private void reconstructTree() {
308
309 oldTree = tree;
310 oldMapARGNodesToInts = mapARGNodesToInts;
311
312 tree = new ARGTree(treeModel, partition);
313 reconstructTree = false;
314 mapARGNodesToInts = new HashMap<NodeRef,Integer>(tree.getInternalNodeCount());
315 mapARGNodesToTreeNodes = tree.getMapping();
316
317 if (oldTree == null) {
318 // First initialization
319 for(int i=0; i<tree.getInternalNodeCount(); i++) {
320 NodeRef node = tree.getInternalNode(i);
321 mapARGNodesToInts.put(treeModel.getMirrorNode(node),node.getNumber());
322 }
323 } else {
324
325 // Need to renumber
326 if (unsetNodes == null)
327 unsetNodes = new HashSet<NodeRef>();
328 else
329 unsetNodes.clear();
330
331 // Copy over numbers for nodes that still exist in tree
332 for (int i = 0; i < tree.getInternalNodeCount(); i++) {
333 NodeRef newNode = tree.getInternalNode(i);
334 NodeRef argNode = treeModel.getMirrorNode(newNode);
335
336 if (oldMapARGNodesToInts.containsKey(argNode)) { // was in old tree
337
338 int oldNumber = oldMapARGNodesToInts.get(argNode);
339 treeModel.setNodeNumber(newNode,oldNumber);
340 mapARGNodesToInts.put(argNode,oldNumber);
341 } else // was not in old tree
342 unsetNodes.add(newNode);
343 }
344
345 // Set unused numbers for nodes that are new and mark for update
346 for (NodeRef node : unsetNodes) {
347 int newNumber = getUnusedInt(mapARGNodesToInts);
348 treeModel.setNodeNumber(node,newNumber);
349 mapARGNodesToInts.put(node,newNumber);
350 updateNode[newNumber] = true;
351 }
352 }
353 }
354
355 // **************************************************************
356 // Likelihood IMPLEMENTATION
357 // **************************************************************
358
359 /**
360 * Calculate the log likelihood of the current state.
361 *
362 * @return the log likelihood.
363 */
364 protected double calculateLogLikelihood() {
365
366 if (reconstructTree) {
367 reconstructTree();
368 }
369
370 NodeRef root = tree.getRoot();
371
372 if (rootPartials == null) {
373 rootPartials = new double[patternCount * stateCount];
374 }
375
376 if (patternLogLikelihoods == null) {
377 patternLogLikelihoods = new double[patternCount];
378 }
379
380 if (!integrateAcrossCategories) {
381 if (siteCategories == null) {
382 siteCategories = new int[patternCount];
383 }
384 for (int i = 0; i < patternCount; i++) {
385 siteCategories[i] = siteModel.getCategoryOfSite(i);
386 }
387 }
388
389 try {
390 traverse(tree, root);
391 } catch (NegativeBranchLengthException e) {
392 System.err.println("Negative branch length found, trying to return 0 likelihood");
393 return Double.NEGATIVE_INFINITY;
394 }
395
396 //********************************************************************
397 // after traverse all nodes and patterns have been updated --
398 //so change flags to reflect this.
399 for (int i = 0; i < nodeCount; i++) {
400 updateNode[i] = false;
401 }
402 //********************************************************************
403
404 double logL = 0.0;
405
406 for (int i = 0; i < patternCount; i++) {
407 // System.err.printf("Pattern %2d: %5.4f %5.4f\n",i,patternLogLikelihoods[i],patternWeights[i]);
408 logL += patternLogLikelihoods[i] * patternWeights[i];
409 }
410
411 return logL;
412 }
413
414 class NegativeBranchLengthException extends Exception {
415
416 }
417
418 /**
419 * Traverse the tree calculating partial likelihoods.
420 *
421 * @return whether the partials for this node were recalculated.
422 */
423 private boolean traverse(Tree tree, NodeRef node) throws NegativeBranchLengthException {
424
425 boolean update = false;
426
427 int nodeNum = node.getNumber();
428 // System.err.println(nodeNum);
429
430 NodeRef parent = tree.getParent(node);
431
432
433
434 // First update the transition probability matrix(ices) for this branch
435 if (parent != null && updateNode[nodeNum]) {
436
437
438 double branchRate = branchRateModel.getBranchRate(tree, node);
439
440 // Get the operational time of the branch
441 double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
442 if (branchTime < 0.0) {
443 if (!DEBUG) {
444 throw new RuntimeException("Negative branch length: " + branchTime);
445 } else{
446 throw new NegativeBranchLengthException();
447 }
448 }
449
450 for (int i = 0; i < categoryCount; i++) {
451 double branchLength = siteModel.getRateForCategory(i) * branchTime;
452 siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities);
453 likelihoodCore.setNodeMatrix(nodeNum, i, probabilities);
454 }
455
456 update = true;
457 }
458
459 // If the node is internal, update the partial likelihoods.
460 if (!tree.isExternal(node)) {
461
462 int nodeCount = tree.getChildCount(node);
463 if (nodeCount != 2)
464 throw new RuntimeException("binary trees only!");
465
466 // Traverse down the two child nodes
467 NodeRef child1 = tree.getChild(node, 0);
468 boolean update1 = traverse(tree, child1);
469
470 NodeRef child2 = tree.getChild(node, 1);
471 boolean update2 = traverse(tree, child2);
472
473 // If either child node was updated then update this node too
474 if (update1 || update2) {
475
476 int childNum1 = child1.getNumber();
477 int childNum2 = child2.getNumber();
478
479 if (integrateAcrossCategories) {
480 likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum);
481 } else {
482 likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum,
483 siteCategories);
484 }
485
486 if (parent == null) {
487 // No parent this is the root of the tree -
488 // calculate the pattern likelihoods
489 double[] frequencies = frequencyModel.getFrequencies();
490
491 if (integrateAcrossCategories) {
492
493 // moved this call to here, because non-integrating siteModels don't need to support it - AD
494 double[] proportions = siteModel.getCategoryProportions();
495 likelihoodCore.integratePartials(nodeNum, proportions, rootPartials);
496 } else {
497 likelihoodCore.getPartials(nodeNum, rootPartials);
498 }
499
500 likelihoodCore.calculateLogLikelihoods(rootPartials, frequencies, patternLogLikelihoods);
501 }
502
503 update = true;
504 }
505 }
506
507 return update;
508
509 }
510
511 /**
512 * The XML parser
513 */
514 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
515
516 public String getParserName() {
517 return ARG_LIKELIHOOD;
518 }
519
520 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
521
522 boolean useAmbiguities = false;
523 boolean storePartials = true;
524 boolean useScaling = false;
525 if (xo.hasAttribute(USE_AMBIGUITIES)) {
526 useAmbiguities = xo.getBooleanAttribute(USE_AMBIGUITIES);
527 }
528 if (xo.hasAttribute(STORE_PARTIALS)) {
529 storePartials = xo.getBooleanAttribute(STORE_PARTIALS);
530 }
531 if (xo.hasAttribute(USE_SCALING)) {
532 useScaling = xo.getBooleanAttribute(USE_SCALING);
533 }
534 PatternList patternList = (PatternList) xo.getChild(PatternList.class);
535 ARGModel treeModel = (ARGModel) xo.getChild(ARGModel.class);
536 SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class);
537
538 BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class);
539
540 return new ARGLikelihood(patternList, treeModel, siteModel, branchRateModel, useAmbiguities, storePartials, useScaling);
541 }
542
543 //************************************************************************
544 // AbstractXMLObjectParser implementation
545 //************************************************************************
546
547 public String getParserDescription() {
548 return "This element represents the likelihood of a patternlist on a tree given the site model.";
549 }
550
551 public Class getReturnType() {
552 return Likelihood.class;
553 }
554
555 public XMLSyntaxRule[] getSyntaxRules() {
556 return rules;
557 }
558
559 private final XMLSyntaxRule[] rules = {
560 AttributeRule.newBooleanRule(USE_AMBIGUITIES, true),
561 AttributeRule.newBooleanRule(STORE_PARTIALS, true),
562 AttributeRule.newBooleanRule(USE_SCALING, true),
563 new ElementRule(PatternList.class),
564 new ElementRule(ARGModel.class),
565 new ElementRule(SiteModel.class),
566 new ElementRule(BranchRateModel.class, true)
567 };
568 };
569
570 /**
571 * XML Serializer for parallelization
572 *
573 */
574
575 // public Element toXML() {
576 // Element likelihoodElement
577 // }
578
579 // **************************************************************
580 // INSTANCE VARIABLES
581 // **************************************************************
582
583 /**
584 * the frequency model for these sites
585 */
586 protected FrequencyModel frequencyModel = null;
587
588 /**
589 * the site model for these sites
590 */
591 protected SiteModel siteModel = null;
592
593 /**
594 * the branch rate model
595 */
596 protected BranchRateModel branchRateModel = null;
597
598 private boolean storePartials = false;
599
600 private boolean integrateAcrossCategories = false;
601
602 /**
603 * the categories for each site
604 */
605 protected int[] siteCategories = null;
606
607 /**
608 * the root partial likelihoods
609 */
610 protected double[] rootPartials = null;
611
612 /**
613 * the pattern likelihoods
614 */
615 protected double[] patternLogLikelihoods = null;
616
617 /**
618 * the number of rate categories
619 */
620 protected int categoryCount;
621
622 /**
623 * an array used to store transition probabilities
624 */
625 protected double[] probabilities;
626
627 /**
628 * the LikelihoodCore
629 */
630 protected LikelihoodCore likelihoodCore;
631
632 private boolean useAmbiguities;
633
634 private boolean reconstructTree = true;
635 private ARGTree tree = null;
636 private ARGTree oldTree;
637
638 private Map<NodeRef,Integer> mapARGNodesToInts = null;
639 private Map<NodeRef,Integer> oldMapARGNodesToInts;
640
641 private Map<NodeRef,NodeRef> mapARGNodesToTreeNodes = null;
642
643 private static final boolean DEBUG = true;
644 }