Debian Codegraph @

src/dr/evomodel/treelikelihood/AncestralStateBeagleTreeLikelihood.java

raw symbols SCIP
1 /*
2 * AncestralStateBeagleTreeLikelihood.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.evomodel.treelikelihood;
27
28 import dr.evomodel.branchmodel.BranchModel;
29 import dr.evomodel.siteratemodel.SiteRateModel;
30 import dr.evolution.alignment.PatternList;
31 import dr.evolution.alignment.UncertainSiteList;
32 import dr.evolution.datatype.Codons;
33 import dr.evolution.datatype.DataType;
34 import dr.evolution.datatype.GeneralDataType;
35 import dr.evolution.tree.NodeRef;
36 import dr.evolution.tree.Tree;
37 import dr.evolution.tree.TreeTrait;
38 import dr.evolution.tree.TreeTraitProvider;
39 import dr.evomodel.branchratemodel.BranchRateModel;
40 import dr.evomodel.tree.TreeModel;
41 import dr.evomodel.tipstatesmodel.TipStatesModel;
42 import dr.inference.model.Model;
43 import dr.inference.model.Parameter;
44 import dr.math.MathUtils;
45
46 import java.util.Map;
47 import java.util.Set;
48
49 /**
50 * @author Marc Suchard
51 * @author Andrew Rambaut
52 */
53
54 public class AncestralStateBeagleTreeLikelihood extends BeagleTreeLikelihood implements TreeTraitProvider, AncestralStateTraitProvider {
55
56 // public AncestralStateBeagleTreeLikelihood(PatternList patternList, TreeModel treeModel,
57 // BranchSubstitutionModel branchSubstitutionModel, SiteRateModel siteRateModel,
58 // BranchRateModel branchRateModel, boolean useAmbiguities,
59 // PartialsRescalingScheme scalingScheme,
60 // DataType dataType,
61 // String tag,
62 // SubstitutionModel substModel) {
63 // this(patternList, treeModel, branchSubstitutionModel, siteRateModel, branchRateModel, useAmbiguities, scalingScheme,
64 // dataType, tag, substModel, false, true);
65 // }
66
67 public AncestralStateBeagleTreeLikelihood(PatternList patternList, TreeModel treeModel,
68 BranchModel branchModel,
69 SiteRateModel siteRateModel,
70 BranchRateModel branchRateModel,
71 TipStatesModel tipStatesModel,
72 boolean useAmbiguities,
73 PartialsRescalingScheme scalingScheme,
74 boolean delayRescalingUntilUnderflow,
75 Map<Set<String>, Parameter> partialsRestrictions,
76 final DataType dataType,
77 final String tag,
78 // SubstitutionModel substModel,
79 boolean useMAP,
80 boolean returnML) {
81
82 super(patternList, treeModel, branchModel, siteRateModel, branchRateModel, tipStatesModel, useAmbiguities, scalingScheme, delayRescalingUntilUnderflow,
83 partialsRestrictions);
84
85 this.dataType = dataType;
86 // this.tag = tag;
87
88 probabilities = new double[stateCount * stateCount * categoryCount];
89 partials = new double[stateCount * patternCount * categoryCount];
90 // rootPartials = new double[stateCount*patternCount];
91 // cumulativeScaleBuffers = new int[nodeCount][];
92 // scaleBufferIndex = getScaleBufferCount() - 1;
93
94 // Save tip states locally so these do not need to be transfers back
95
96 if (useAmbiguities()) {
97 tipPartials = new double[tipCount][];
98 } else {
99 tipStates = new int[tipCount][];
100 }
101
102 for (int i = 0; i < tipCount; i++) {
103 // Find the id of tip i in the patternList
104 String id = treeModel.getTaxonId(i);
105 int index = patternList.getTaxonIndex(id);
106 if (useAmbiguities()) {
107 tipPartials[i] = getPartials(patternList, index);
108 } else {
109 tipStates[i] = getStates(patternList, index);
110 }
111 }
112
113 reconstructedStates = new int[treeModel.getNodeCount()][patternCount];
114 storedReconstructedStates = new int[treeModel.getNodeCount()][patternCount];
115
116 this.useMAP = useMAP;
117 this.returnMarginalLogLikelihood = returnML;
118
119 treeTraits.addTrait(new TreeTrait.IA() {
120 public String getTraitName() {
121 return tag;
122 }
123
124 public Intent getIntent() {
125 return Intent.NODE;
126 }
127
128 public Class getTraitClass() {
129 return int[].class;
130 }
131
132 public int[] getTrait(Tree tree, NodeRef node) {
133 return getStatesForNode(tree, node);
134 }
135
136 public String getTraitString(Tree tree, NodeRef node) {
137 return formattedState(getStatesForNode(tree, node), dataType);
138 }
139 });
140
141 }
142
143 private double[] getPartials(PatternList patternList, int sequenceIndex) {
144 double[] partials = new double[patternCount * stateCount];
145
146 boolean[] stateSet;
147
148 int v = 0;
149 for (int i = 0; i < patternCount; i++) {
150
151
152 if (patternList instanceof UncertainSiteList) {
153 ((UncertainSiteList) patternList).fillPartials(sequenceIndex, i, partials, v);
154 v += stateCount;
155 // TODO Add this functionality to SimpleSiteList to avoid if statement here
156 } else {
157
158 int state = patternList.getPatternState(sequenceIndex, i);
159 stateSet = dataType.getStateSet(state);
160
161 for (int j = 0; j < stateCount; j++) {
162 if (stateSet[j]) {
163 partials[v] = 1.0;
164 } else {
165 partials[v] = 0.0;
166 }
167 v++;
168 }
169 }
170 } // TODO Note code duplication with BTL, refactor when debugged
171
172 return partials;
173 }
174
175 private int[] getStates(PatternList patternList,
176 int sequenceIndex) {
177
178 int[] states = new int[patternCount];
179 for (int i = 0; i < patternCount; i++) {
180 states[i] = patternList.getPatternState(sequenceIndex, i);
181 }
182 return states;
183 }
184
185 public BranchModel getBranchModel() {
186 return branchModel;
187 }
188
189 protected Helper treeTraits = new Helper();
190
191 public TreeTrait[] getTreeTraits() {
192 return treeTraits.getTreeTraits();
193 }
194
195 public TreeTrait getTreeTrait(String key) {
196 return treeTraits.getTreeTrait(key);
197 }
198
199 protected void handleModelChangedEvent(Model model, Object object, int index) {
200 super.handleModelChangedEvent(model, object, index);
201 fireModelChanged(model);
202 }
203
204 public int[] getStatesForNode(Tree tree, NodeRef node) {
205 if (tree != treeModel) {
206 throw new RuntimeException("Can only reconstruct states on treeModel given to constructor");
207 }
208
209 if (!likelihoodKnown) {
210 calculateLogLikelihood();
211 likelihoodKnown = true;
212 }
213
214 if (!areStatesRedrawn) {
215 redrawAncestralStates();
216 }
217 return reconstructedStates[node.getNumber()];
218 }
219
220 @Override
221 protected int getScaleBufferCount() {
222 return internalNodeCount + 2;
223 }
224
225 private int drawChoice(double[] measure) {
226 if (useMAP) {
227 double max = measure[0];
228 int choice = 0;
229 for (int i = 1; i < measure.length; i++) {
230 if (measure[i] > max) {
231 max = measure[i];
232 choice = i;
233 }
234 }
235 return choice;
236 } else {
237 return MathUtils.randomChoicePDF(measure);
238 }
239 }
240
241 public void makeDirty() {
242 super.makeDirty();
243 areStatesRedrawn = false;
244 }
245
246 public void redrawAncestralStates() {
247 // Sample states
248 jointLogLikelihood = 0;
249 traverseSample(treeModel, treeModel.getRoot(), null, null);
250 areStatesRedrawn = true;
251 }
252
253 // protected double calculateLogLikelihood() {
254 // areStatesRedrawn = false;
255 // return super.calculateLogLikelihood();
256 // }
257
258 protected double calculateLogLikelihood() {
259 areStatesRedrawn = false;
260 double marginalLogLikelihood = super.calculateLogLikelihood();
261 if (returnMarginalLogLikelihood) {
262 return marginalLogLikelihood;
263 }
264 // redraw states and return joint density of drawn states
265 redrawAncestralStates();
266 return jointLogLikelihood;
267 }
268
269 public String formattedState(int[] state) {
270 return formattedState(state, dataType);
271 }
272
273 private static String formattedState(int[] state, DataType dataType) {
274 StringBuffer sb = new StringBuffer();
275 sb.append("\"");
276 if (dataType instanceof GeneralDataType) {
277 boolean first = true;
278 for (int i : state) {
279 if (!first) {
280 sb.append(" ");
281 } else {
282 first = false;
283 }
284
285 sb.append(dataType.getCode(i));
286 }
287
288 } else {
289 for (int i : state) {
290 if (dataType.getClass().equals(Codons.class)) {
291 sb.append(dataType.getTriplet(i));
292 } else {
293 sb.append(dataType.getChar(i));
294 }
295 }
296 }
297 sb.append("\"");
298 return sb.toString();
299 }
300
301 protected void getMatrix(int branchIndex, double[] probabilities) {
302 beagle.getTransitionMatrix(substitutionModelDelegate.getMatrixIndex(branchIndex), probabilities);
303 // NB: It may be faster to compute matrices in BEAST via substitutionModel
304 }
305
306 public void setTipStates(int tipNum, int[] states) {
307 System.arraycopy(states, 0, tipStates[tipNum], 0, states.length);
308 beagle.setTipStates(tipNum, states);
309 makeDirty();
310 }
311
312 // public void getTipPartials(int tipNum, double[] partials) {
313 // System.arraycopy(tipPartials[tipNum], 0, partials, 0, partials.length);
314 // }
315
316 public void getTipStates(int tipNum, int[] states) {
317 // Saved locally to reduce BEAGLE library access
318 System.arraycopy(tipStates[tipNum], 0, states, 0, states.length);
319 }
320
321 // public int traverseCollectScaleBuffers(TreeModel tree, NodeRef node) {
322 //
323 // if (true) // Currently do nothing
324 // return 0;
325 //
326 // return 0;
327 //
328 // int nodeNum = node.getNumber();
329 //
330 // NodeRef child0 = tree.getChild(node,0);
331 // NodeRef child1 = tree.getChild(node,1);
332 //
333 // int len0 = traverseCollectScaleBuffers(tree,child0);
334 // int len1 = traverseCollectScaleBuffers(tree,child1);
335 // int thisLen = len0 + len1 + 1;
336 // int offset = 0;
337 //
338 // int[] scaleBuffer = new int[thisLen];
339 // if (len0 > 0) {
340 // System.arraycopy(cumulativeScaleBuffers[child0.getNumber()],0,scaleBuffer,offset,len0);
341 // offset += len0;
342 // }
343 // if (len1 > 0) {
344 // System.arraycopy(cumulativeScaleBuffers[child1.getNumber()],0,scaleBuffer,offset,len1);
345 // offset += len1;
346 // }
347 // scaleBuffer[offset] = scaleBufferHelper.getOffsetIndex(nodeNum - tipCount);
348 // cumulativeScaleBuffers[nodeNum] = scaleBuffer;
349 //
350 // return thisLen;
351 // }
352
353 public void storeState() {
354
355 super.storeState();
356
357 if (areStatesRedrawn) {
358 for (int i = 0; i < reconstructedStates.length; i++) {
359 System.arraycopy(reconstructedStates[i], 0, storedReconstructedStates[i], 0, reconstructedStates[i].length);
360 }
361 }
362 // TODO MAS: I do not understand why these are NOT necessary
363
364 storedAreStatesRedrawn = areStatesRedrawn;
365 storedJointLogLikelihood = jointLogLikelihood;
366 }
367
368 public void restoreState() {
369
370 super.restoreState();
371
372 int[][] temp = reconstructedStates;
373 reconstructedStates = storedReconstructedStates;
374 storedReconstructedStates = temp;
375
376 areStatesRedrawn = storedAreStatesRedrawn;
377 jointLogLikelihood = storedJointLogLikelihood;
378 }
379
380 public void traverseSample(TreeModel tree, NodeRef node, int[] parentState, int[] rateCategory) {
381
382 int nodeNum = node.getNumber();
383
384 NodeRef parent = tree.getParent(node);
385
386 // This function assumes that all partial likelihoods have already been calculated
387 // If the node is internal, then sample its state given the state of its parent (pre-order traversal).
388
389 double[] conditionalProbabilities = new double[stateCount];
390 int[] state = new int[patternCount];
391
392 if (!tree.isExternal(node)) {
393
394 if (parent == null) {
395
396 // This is the root node
397 getPartials(nodeNum, partials);
398
399 boolean sampleCategory = categoryCount > 1;
400 double[] posteriorWeightedCategory = null;
401 double[] priorWeightedCategory = null;
402
403 if (sampleCategory) {
404 rateCategory = new int[patternCount];
405 posteriorWeightedCategory = new double[categoryCount];
406 priorWeightedCategory = siteRateModel.getCategoryProportions();
407 }
408
409 for (int j = 0; j < patternCount; j++) {
410
411 // Sample across-site-rate-variation, if it exists
412 if (sampleCategory) {
413 for (int r = 0; r < categoryCount; r++) {
414 posteriorWeightedCategory[r] = 0;
415 for (int k = 0; k < stateCount; k++) {
416 posteriorWeightedCategory[r] += partials[r * stateCount * patternCount +
417 j * stateCount + k];
418 }
419 posteriorWeightedCategory[r] *= priorWeightedCategory[r];
420 }
421 rateCategory[j] = drawChoice(posteriorWeightedCategory);
422 }
423
424 // Sample root character state
425 int partialsIndex = (rateCategory == null ? 0 : rateCategory[j]) * stateCount * patternCount;
426 System.arraycopy(partials, partialsIndex + j * stateCount, conditionalProbabilities, 0, stateCount);
427
428 double[] frequencies = substitutionModelDelegate.getRootStateFrequencies(); // TODO May have more than one set of frequencies
429 for (int i = 0; i < stateCount; i++) {
430 conditionalProbabilities[i] *= frequencies[i];
431 }
432 try {
433 state[j] = drawChoice(conditionalProbabilities);
434 } catch (Error e) {
435 System.err.println(e.toString());
436 System.err.println("Please report error to Marc");
437 state[j] = 0;
438 }
439 reconstructedStates[nodeNum][j] = state[j];
440
441 if (!returnMarginalLogLikelihood) {
442 jointLogLikelihood += Math.log(frequencies[state[j]]);
443 }
444 }
445
446 if (sampleCategory) {
447 if (this.rateCategory == null) {
448 this.rateCategory = new int[patternCount];
449 }
450 System.arraycopy(rateCategory, 0, this.rateCategory, 0, patternCount);
451 }
452
453 } else {
454
455 // This is an internal node, but not the root
456 double[] partialLikelihood = new double[stateCount * patternCount * categoryCount];
457 getPartials(nodeNum, partialLikelihood);
458
459 // Sibon says that this actually works now
460 // if (categoryCount > 1)
461 // throw new RuntimeException("Reconstruction not implemented for multiple categories yet.");
462
463 getMatrix(nodeNum, probabilities);
464
465 for (int j = 0; j < patternCount; j++) {
466
467 int parentIndex = parentState[j] * stateCount;
468 int childIndex = j * stateCount;
469
470 int category = rateCategory == null ? 0 : rateCategory[j];
471 int matrixIndex = category * stateCount * stateCount;
472 int partialIndex = category * stateCount * patternCount;
473
474 for (int i = 0; i < stateCount; i++)
475 conditionalProbabilities[i] = partialLikelihood[partialIndex + childIndex + i]
476 * probabilities[matrixIndex + parentIndex + i];
477
478 state[j] = drawChoice(conditionalProbabilities);
479 reconstructedStates[nodeNum][j] = state[j];
480
481 if (!returnMarginalLogLikelihood) {
482 double contrib = probabilities[parentIndex + state[j]];
483 jointLogLikelihood += Math.log(contrib);
484 }
485 }
486
487 hookCalculation(tree, parent, node, parentState, state, probabilities, rateCategory);
488 }
489
490 // Traverse down the two child nodes
491 NodeRef child1 = tree.getChild(node, 0);
492 traverseSample(tree, child1, state, rateCategory);
493
494 NodeRef child2 = tree.getChild(node, 1);
495 traverseSample(tree, child2, state, rateCategory);
496 } else {
497
498 // This is an external leaf
499
500 if (useAmbiguities()) {
501
502 getMatrix(nodeNum, probabilities);
503 double[] partials = tipPartials[nodeNum];
504
505 for (int j = 0; j < patternCount; j++) {
506 final int parentIndex = parentState[j] * stateCount;
507 int category = rateCategory == null ? 0 : rateCategory[j];
508 int matrixIndex = category * stateCount * stateCount;
509
510 System.arraycopy(probabilities, parentIndex + matrixIndex, conditionalProbabilities, 0, stateCount);
511 for (int k = 0; k < stateCount; ++k) {
512 conditionalProbabilities[k] *= partials[j * stateCount + k];
513 }
514 reconstructedStates[nodeNum][j] = drawChoice(conditionalProbabilities);
515
516 if (!returnMarginalLogLikelihood) {
517 double contrib = probabilities[parentIndex + reconstructedStates[nodeNum][j]];
518 jointLogLikelihood += Math.log(contrib);
519 }
520 }
521
522 } else {
523
524 getTipStates(nodeNum, reconstructedStates[nodeNum]);
525
526 // Check for ambiguity codes and sample them
527
528 for (int j = 0; j < patternCount; j++) {
529
530 final int thisState = reconstructedStates[nodeNum][j];
531
532 if (dataType.isAmbiguousState(thisState)) {
533
534 final int parentIndex = parentState[j] * stateCount;
535 int category = rateCategory == null ? 0 : rateCategory[j];
536 int matrixIndex = category * stateCount * stateCount;
537
538 getMatrix(nodeNum, probabilities);
539 System.arraycopy(probabilities, parentIndex + matrixIndex, conditionalProbabilities, 0, stateCount);
540
541 if (useAmbiguities && !dataType.isUnknownState(thisState)) { // Not completely unknown
542 boolean[] stateSet = dataType.getStateSet(thisState);
543
544 for (int k = 0; k < stateCount; k++) {
545 if (!stateSet[k]) {
546 conditionalProbabilities[k] = 0.0;
547 }
548 }
549 }
550 reconstructedStates[nodeNum][j] = drawChoice(conditionalProbabilities);
551 }
552
553 if (!returnMarginalLogLikelihood) {
554 final int parentIndex = parentState[j] * stateCount;
555 getMatrix(nodeNum, probabilities);
556 if (!returnMarginalLogLikelihood) {
557 double contrib = probabilities[parentIndex + reconstructedStates[nodeNum][j]];
558 jointLogLikelihood += Math.log(contrib);
559 }
560 }
561 }
562 }
563
564 hookCalculation(tree, parent, node, parentState, reconstructedStates[nodeNum], null, rateCategory);
565 }
566 }
567
568 protected void hookCalculation(Tree tree, NodeRef parentNode, NodeRef childNode,
569 int[] parentStates, int[] childStates,
570 double[] probabilities, int[] rateCategory) {
571 // Do nothing
572 }
573
574 private final DataType dataType;
575 private int[][] reconstructedStates;
576 private int[][] storedReconstructedStates;
577
578 // private final String tag;
579 protected boolean areStatesRedrawn = false;
580 protected boolean storedAreStatesRedrawn = false;
581
582 private boolean useMAP = false;
583 private boolean returnMarginalLogLikelihood = true;
584
585 private double jointLogLikelihood;
586 private double storedJointLogLikelihood;
587
588 private int[][] tipStates;
589 private double[][] tipPartials;
590
591 private double[] probabilities;
592 private double[] partials;
593
594 protected int[] rateCategory = null;
595 // private double[] rootPartials;
596 // private int[][] cumulativeScaleBuffers;
597 // private int scaleBufferIndex;
598
599 }