Debian Codegraph @

src/dr/oldevomodel/treelikelihood/AncestralStateTreeLikelihood.java

raw symbols SCIP
1 /*
2 * AncestralStateTreeLikelihood.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.datatype.DataType;
30 import dr.evolution.datatype.GeneralDataType;
31 import dr.evolution.tree.NodeRef;
32 import dr.evolution.tree.Tree;
33 import dr.evolution.tree.TreeTrait;
34 import dr.evolution.tree.TreeTraitProvider;
35 import dr.evomodel.branchratemodel.BranchRateModel;
36 import dr.oldevomodel.sitemodel.SiteModel;
37 import dr.evomodel.tree.TreeModel;
38 import dr.inference.model.Model;
39 import dr.math.MathUtils;
40
41 import java.util.logging.Logger;
42
43 /**
44 * @author Marc A. Suchard
45 */
46 @Deprecated // Switching to BEAGLE
47 public class AncestralStateTreeLikelihood extends TreeLikelihood implements TreeTraitProvider {
48 public static final String STATES_KEY = "states";
49
50 // private boolean useExtraReconstructedStates = false;
51
52
53 /**
54 * Constructor.
55 * Now also takes a DataType so that ancestral states are printed using data codes
56 *
57 * @param patternList -
58 * @param treeModel -
59 * @param siteModel -
60 * @param branchRateModel -
61 * @param useAmbiguities -
62 * @param storePartials -
63 * @param dataType - need to provide the data-type, so that corrent data characters can be returned
64 * @param tag - string label for reconstruction characters in tree log
65 * @param forceRescaling -
66 * @param useMAP - perform maximum aposteriori reconstruction
67 * @param returnML - report integrate likelihood of tip data
68 */
69 public AncestralStateTreeLikelihood(PatternList patternList, TreeModel treeModel,
70 SiteModel siteModel, BranchRateModel branchRateModel,
71 boolean useAmbiguities, boolean storePartials,
72 final DataType dataType,
73 final String tag,
74 boolean forceRescaling,
75 boolean useMAP,
76 boolean returnML) {
77 super(patternList, treeModel, siteModel, branchRateModel, null, useAmbiguities, false, storePartials,
78 false, forceRescaling);
79 this.dataType = dataType;
80 this.tag = tag;
81
82 reconstructedStates = new int[treeModel.getNodeCount()][patternCount];
83 storedReconstructedStates = new int[treeModel.getNodeCount()][patternCount];
84
85 this.useMAP = useMAP;
86 this.returnMarginalLogLikelihood = returnML;
87
88 treeTraits.addTrait(STATES_KEY, new TreeTrait.IA() {
89 public String getTraitName() {
90 return tag;
91 }
92
93 public Intent getIntent() {
94 return Intent.NODE;
95 }
96
97 public int[] getTrait(Tree tree, NodeRef node) {
98 return getStatesForNode(tree,node);
99 }
100
101 public String getTraitString(Tree tree, NodeRef node) {
102 return formattedState(getStatesForNode(tree,node), dataType);
103 }
104 });
105
106 if (useAmbiguities) {
107 Logger.getLogger("dr.evomodel.treelikelihood").info("Ancestral reconstruction using ambiguities is currently "+
108 "not support without BEAGLE");
109 System.exit(-1);
110 }
111
112 }
113
114 public AncestralStateTreeLikelihood(PatternList patternList, TreeModel treeModel,
115 SiteModel siteModel, BranchRateModel branchRateModel,
116 boolean useAmbiguities, boolean storePartials,
117 DataType dataType,
118 String tag,
119 boolean forceRescaling) {
120 this(patternList, treeModel, siteModel, branchRateModel, useAmbiguities,
121 storePartials, dataType, tag, forceRescaling, false, true);
122 }
123
124 public void storeState() {
125
126 super.storeState();
127
128 for (int i = 0; i < reconstructedStates.length; i++) {
129 System.arraycopy(reconstructedStates[i], 0, storedReconstructedStates[i], 0, reconstructedStates[i].length);
130 }
131
132 storedAreStatesRedrawn = areStatesRedrawn;
133 storedJointLogLikelihood = jointLogLikelihood;
134 }
135
136 public void restoreState() {
137
138 super.restoreState();
139
140 int[][] temp = reconstructedStates;
141 reconstructedStates = storedReconstructedStates;
142 storedReconstructedStates = temp;
143
144 areStatesRedrawn = storedAreStatesRedrawn;
145 jointLogLikelihood = storedJointLogLikelihood;
146 }
147
148 public DataType getDataType() {
149 return dataType;
150 }
151
152 public int[] getStatesForNode(Tree tree, NodeRef node) {
153 if (tree != treeModel) {
154 throw new RuntimeException("Can only reconstruct states on treeModel given to constructor");
155 }
156
157 if (!likelihoodKnown) {
158 calculateLogLikelihood();
159 likelihoodKnown = true;
160 }
161
162 if (!areStatesRedrawn) {
163 redrawAncestralStates();
164 }
165 return reconstructedStates[node.getNumber()];
166 }
167
168
169 public void redrawAncestralStates() {
170 jointLogLikelihood = 0;
171 traverseSample(treeModel, treeModel.getRoot(), null);
172 areStatesRedrawn = true;
173 }
174
175 // private boolean checkConditioning = true;
176
177
178 protected void handleModelChangedEvent(Model model, Object object, int index) {
179 super.handleModelChangedEvent(model, object, index);
180 fireModelChanged(model);
181
182 }
183
184 protected double calculateLogLikelihood() {
185
186 areStatesRedrawn = false;
187 double marginalLogLikelihood = super.calculateLogLikelihood();
188 if (returnMarginalLogLikelihood) {
189 return marginalLogLikelihood;
190 }
191 // redraw states and return joint density of drawn states
192 redrawAncestralStates();
193 return jointLogLikelihood;
194 }
195
196 protected TreeTraitProvider.Helper treeTraits = new Helper();
197
198 public TreeTrait[] getTreeTraits() {
199 return treeTraits.getTreeTraits();
200 }
201
202 public TreeTrait getTreeTrait(String key) {
203 return treeTraits.getTreeTrait(key);
204 }
205
206
207 private static String formattedState(int[] state, DataType dataType) {
208 StringBuffer sb = new StringBuffer();
209 sb.append("\"");
210 if (dataType instanceof GeneralDataType) {
211 boolean first = true;
212 for (int i : state) {
213 if (!first) {
214 sb.append(" ");
215 } else {
216 first = false;
217 }
218
219 sb.append(dataType.getCode(i));
220 }
221
222 } else {
223 for (int i : state) {
224 sb.append(dataType.getChar(i));
225 }
226 }
227 sb.append("\"");
228 return sb.toString();
229 }
230
231 private int drawChoice(double[] measure) {
232 if (useMAP) {
233 double max = measure[0];
234 int choice = 0;
235 for (int i = 1; i < measure.length; i++) {
236 if (measure[i] > max) {
237 max = measure[i];
238 choice = i;
239 }
240 }
241 return choice;
242 } else {
243 return MathUtils.randomChoicePDF(measure);
244 }
245 }
246
247 /**
248 * Traverse (pre-order) the tree sampling the internal node states.
249 *
250 * @param tree - TreeModel on which to perform sampling
251 * @param node - current node
252 * @param parentState - character state of the parent node to 'node'
253 */
254 public void traverseSample(TreeModel tree, NodeRef node, int[] parentState) {
255
256 int nodeNum = node.getNumber();
257
258 NodeRef parent = tree.getParent(node);
259
260 // This function assumes that all partial likelihoods have already been calculated
261 // If the node is internal, then sample its state given the state of its parent (pre-order traversal).
262
263 double[] conditionalProbabilities = new double[stateCount];
264 int[] state = new int[patternCount];
265
266 if (!tree.isExternal(node)) {
267
268 if (parent == null) {
269
270 double[] rootPartials = getRootPartials();
271
272 // This is the root node
273 for (int j = 0; j < patternCount; j++) {
274
275 System.arraycopy(rootPartials, j * stateCount, conditionalProbabilities, 0, stateCount);
276 double[] frequencies = frequencyModel.getFrequencies();
277 for (int i = 0; i < stateCount; i++) {
278 conditionalProbabilities[i] *= frequencies[i];
279 }
280 try {
281 state[j] = drawChoice(conditionalProbabilities);
282 } catch (Error e) {
283 System.err.println(e.toString());
284 System.err.println("Please report error to Marc");
285 state[j] = 0;
286 }
287 reconstructedStates[nodeNum][j] = state[j];
288
289 //System.out.println("Pr(j) = " + frequencies[state[j]]);
290 jointLogLikelihood += Math.log(frequencies[state[j]]);
291 }
292
293 } else {
294
295 // This is an internal node, but not the root
296 double[] partialLikelihood = new double[stateCount * patternCount];
297 if (categoryCount > 1)
298 throw new RuntimeException("Reconstruction not implemented for multiple categories yet.");
299
300 likelihoodCore.getPartials(nodeNum, partialLikelihood);
301
302 // final double branchRate = branchRateModel.getBranchRate(tree, node);
303 //
304 // // Get the operational time of the branch
305 // final double branchTime = branchRate * ( tree.getNodeHeight(parent) - tree.getNodeHeight(node) );
306 //
307 // for (int i = 0; i < categoryCount; i++) {
308 //
309 // siteModel.getTransitionProbabilitiesForCategory(i, branchTime, probabilities);
310 //
311 // }
312 //
313
314
315
316
317 ((AbstractLikelihoodCore) likelihoodCore).getNodeMatrix(nodeNum, 0, probabilities);
318
319
320 for (int j = 0; j < patternCount; j++) {
321
322 int parentIndex = parentState[j] * stateCount;
323 int childIndex = j * stateCount;
324
325 for (int i = 0; i < stateCount; i++) {
326 conditionalProbabilities[i] = partialLikelihood[childIndex + i] * probabilities[parentIndex + i];
327 }
328
329 state[j] = drawChoice(conditionalProbabilities);
330 reconstructedStates[nodeNum][j] = state[j];
331
332 double contrib = probabilities[parentIndex + state[j]];
333 //System.out.println("Pr(" + parentState[j] + ", " + state[j] + ") = " + contrib);
334 jointLogLikelihood += Math.log(contrib);
335 }
336 }
337
338 // Traverse down the two child nodes
339 NodeRef child1 = tree.getChild(node, 0);
340 traverseSample(tree, child1, state);
341
342 NodeRef child2 = tree.getChild(node, 1);
343 traverseSample(tree, child2, state);
344 } else {
345
346 // This is an external leaf
347
348 ((AbstractLikelihoodCore) likelihoodCore).getNodeStates(nodeNum, reconstructedStates[nodeNum]);
349
350 // Check for ambiguity codes and sample them
351
352 for (int j = 0; j < patternCount; j++) {
353
354 final int thisState = reconstructedStates[nodeNum][j];
355 final int parentIndex = parentState[j] * stateCount;
356 ((AbstractLikelihoodCore) likelihoodCore).getNodeMatrix(nodeNum, 0, probabilities);
357 if (dataType.isAmbiguousState(thisState)) {
358
359 System.arraycopy(probabilities, parentIndex, conditionalProbabilities, 0, stateCount);
360 reconstructedStates[nodeNum][j] = drawChoice(conditionalProbabilities);
361 }
362
363 double contrib = probabilities[parentIndex + reconstructedStates[nodeNum][j]];
364 //System.out.println("Pr(" + parentState[j] + ", " + reconstructedStates[nodeNum][j] + ") = " + contrib);
365 jointLogLikelihood += Math.log(contrib);
366 }
367 }
368 }
369
370 private DataType dataType;
371 private int[][] reconstructedStates;
372 private int[][] storedReconstructedStates;
373
374 private String tag;
375 private boolean areStatesRedrawn = false;
376 private boolean storedAreStatesRedrawn = false;
377
378 private boolean useMAP = false;
379 private boolean returnMarginalLogLikelihood = true;
380
381 private double jointLogLikelihood;
382 private double storedJointLogLikelihood;
383
384
385 }