Debian Codegraph @

src/dr/evolution/continuous/ContinuousTraitLikelihood.java

raw symbols SCIP
1 /*
2 * ContinuousTraitLikelihood.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.evolution.continuous;
27
28 import dr.evolution.io.NewickImporter;
29 import dr.evolution.tree.*;
30 import dr.matrix.Matrix;
31 import dr.matrix.MutableMatrix;
32 import dr.geo.math.SphericalPolarCoordinates;
33
34 import java.io.StringReader;
35
36
37 /**
38 * Calculates the likelihood of a trait and tree.
39 *
40 * @version $Id: ContinuousTraitLikelihood.java,v 1.8 2006/06/18 16:20:58 alexei Exp $
41 *
42 * @author Alexei Drummond
43 */
44 public class ContinuousTraitLikelihood {
45
46 /**
47 * Calculates the likelihood of the traits on the given tree.
48 * @param tree this is the tree on which to calculate the continuous attributes likelihood
49 */
50 public double calculateLikelihood(MutableTree tree, String[] attributes, Contrastable[] mles, double kappa) {
51
52 ContrastedTraitNode contrastNode = new ContrastedTraitNode(tree, tree.getRoot(), attributes);
53 contrastNode.calculateContrasts(kappa);
54
55 for (int i =0; i < mles.length; i++) {
56 mles[i] = contrastNode.getTraitValue(i);
57 }
58
59 return calculateTraitsLikelihood(contrastNode);
60 }
61
62 /**
63 * Calculates the likelihood of the contrasted node
64 * @param contrastNode this is the node that the likelihood is calculated for
65 */
66 private double calculateTraitsLikelihood(ContrastedTraitNode contrastNode) {
67
68 int count = contrastNode.getTraitCount();
69
70 if (count == 1) return calculateSingleTraitLikelihood(contrastNode);
71
72 return calculateMultipleTraitsLikelihood(contrastNode, count);
73 }
74
75
76 /**
77 * Calculates the likelihood of the contrasted node
78 * @param contrastNode this is the node that the likelihood is calculated for
79 */
80 private double calculateMultipleTraitsLikelihood(ContrastedTraitNode contrastNode, int traitCount) {
81
82 SimpleTree contrastTree = new SimpleTree(contrastNode);
83
84 double[][] w = new double[traitCount][traitCount];
85 for (int j =0; j < traitCount; j++) {
86 for (int k = j; k < traitCount; k++) {
87 double wjk = 0.0;
88 for (int i = 0; i < contrastTree.getInternalNodeCount(); i++) {
89 ContrastedTraitNode ctNode = (ContrastedTraitNode)contrastTree.getInternalNode(i);
90
91 wjk += (ctNode.contrast[j] * ctNode.contrast[k]) / ctNode.contrastVariance;
92 }
93
94
95 //System.out.println("w["+j+"]["+k+"]="+wjk);
96 wjk /= (double)contrastTree.getInternalNodeCount();
97 w[j][k] = wjk;
98 w[k][j] = wjk;
99 }
100 }
101
102 MutableMatrix answer = Matrix.Util.createMutableMatrix(new double[1][1]);
103 MutableMatrix temp = Matrix.Util.createMutableMatrix(w);
104 double detW = 0.0;
105 try {
106 detW = Matrix.Util.det(temp);
107 } catch (Matrix.NotSquareException nse) { nse.printStackTrace(System.out); }
108
109 //System.out.println("W matrix");
110 //System.out.println(temp);
111
112 //System.out.println("|W|=" + detW);
113
114 MutableMatrix invW = Matrix.Util.createMutableMatrix(w);
115 try {
116 Matrix.Util.invert(invW);
117 } catch (Matrix.NotSquareException nse) { nse.printStackTrace(System.out); }
118
119 //System.out.println("inverse of W matrix");
120 //System.out.println(invW);
121
122 double logL = 0.0;
123 int n = contrastTree.getInternalNodeCount() + 1;
124
125 for (int i =0; i < contrastTree.getInternalNodeCount(); i++) {
126 ContrastedTraitNode ctNode = (ContrastedTraitNode)contrastTree.getInternalNode(i);
127 double[] contrasts = ctNode.getTraitContrasts();
128
129 Matrix uT = Matrix.Util.createRowVector(contrasts);
130 Matrix u = Matrix.Util.createColumnVector(contrasts);
131
132 try {
133 Matrix.Util.product(invW, u, temp);
134 Matrix.Util.product(uT, temp, answer);
135 } catch (Matrix.WrongDimensionException wde) { wde.printStackTrace(System.out); }
136
137 logL += answer.getElement(0,0) / ctNode.getContrastVariance();
138 logL += traitCount * Math.log(ctNode.getContrastVariance());
139 }
140
141 // root variance
142 logL += traitCount * Math.log(contrastNode.getNodeVariance());
143 logL += n * Math.log(detW);
144 logL += n * traitCount * Math.log(2*Math.PI);
145 logL = -logL / 2.0;
146
147 //System.out.println("root node variance = " + contrastNode.getNodeVariance());
148
149 return logL;
150 }
151
152 /**
153 * Calculate the likelihood of a single continuous trait on the given tree.
154 */
155 private double calculateSingleTraitLikelihood(ContrastedTraitNode contrastNode) {
156
157 SimpleTree contrastTree = new SimpleTree(contrastNode);
158
159 double s2 = 0.0;
160 double sssContrast = 0.0;
161 double slogCV = 0.0;
162 for (int i = 0; i < contrastTree.getInternalNodeCount(); i++) {
163 ContrastedTraitNode ctNode = (ContrastedTraitNode)contrastTree.getInternalNode(i);
164 double contrast = ctNode.getTraitContrasts()[0];
165 double cv = ctNode.getContrastVariance();
166 sssContrast += (contrast * contrast) / cv;
167 slogCV += Math.log(cv);
168 if (ctNode.isRoot()) {
169 slogCV += Math.log(ctNode.getNodeVariance());
170 }
171 }
172
173 double tl = 0.0;
174 for (int i = 0; i < contrastTree.getNodeCount(); i++) {
175 NodeRef node = contrastTree.getNode(i);
176 if (!contrastTree.isRoot(node)) {
177 tl += contrastTree.getBranchLength(node);
178 }
179 }
180
181 s2 = sssContrast / contrastTree.getInternalNodeCount();
182
183 int n = contrastTree.getInternalNodeCount() + 1;
184
185 double logL = n * Math.log(2.0*Math.PI*s2);
186 logL += slogCV;
187
188 logL += sssContrast / s2;
189 logL = -logL / 2.0;
190
191 return logL;
192 }
193
194 class ContrastedTraitNode extends SimpleNode {
195
196 public ContrastedTraitNode(MutableTree tree, NodeRef node, String[] attributeNames) {
197
198 init(tree, node, attributeNames.length);
199
200 if (!tree.isExternal(node)) {
201
202 if (tree.getChildCount(node) != 2) { throw new IllegalArgumentException("Tree must be strictly bifurcating!"); }
203
204 addChild(new ContrastedTraitNode(tree, tree.getChild(node, 0), attributeNames));
205 addChild(new ContrastedTraitNode(tree, tree.getChild(node, 1), attributeNames));
206 } else {
207 for (int i =0; i < attributeNames.length; i++) {
208 Object obj = tree.getNodeTaxon(node).getAttribute(attributeNames[i]);
209
210 if (obj == null) throw new IllegalArgumentException("attribute " + attributeNames[i] + " does not exist in " + tree.getTaxonId(node.getNumber()));
211
212 if (obj instanceof Number) {
213 traitValue[i] = new Continuous(((Number)obj).doubleValue());
214 } else if (obj instanceof String) {
215 traitValue[i] = new Continuous(Double.parseDouble((String)obj));
216 } else if (obj instanceof Continuous) {
217 traitValue[i] = (Continuous)obj;
218 } else if (obj instanceof SphericalPolarCoordinates) {
219 traitValue[i] = (SphericalPolarCoordinates)obj;
220 }
221
222 tree.setNodeAttribute(node,attributeNames[i], traitValue[i]);
223 }
224 }
225
226 this.traitNames = attributeNames;
227 }
228
229 private void init(MutableTree tree, NodeRef node, int traitCount) {
230 setHeight(tree.getNodeHeight(node));
231 setRate(tree.getNodeRate(node));
232 setId(tree.getTaxonId(node.getNumber()));
233 setNumber(node.getNumber());
234 setTaxon(tree.getNodeTaxon(node));
235
236 contrast = new double[traitCount];
237 contrastVariance = 0.0;
238 traitValue = new Contrastable[traitCount];
239 nodeVariance = 0.0;
240 this.tree = tree;
241 this.node = node;
242 }
243
244 public double[] getTraitContrasts() {
245 return contrast;
246 }
247
248 public double getContrastVariance() { return contrastVariance; }
249
250 public double getNodeVariance() { return nodeVariance; }
251
252 public Contrastable getTraitValue(int traitIndex) {
253
254 return traitValue[traitIndex];
255 }
256
257
258 public int getTraitCount() { return traitValue.length; }
259
260 /**
261 * Recursively calculate the contrast information for the continuous trait nodes.
262 */
263 private void calculateContrasts(double kappa) {
264 if (!isExternal()) {
265
266 ContrastedTraitNode left = (ContrastedTraitNode)getChild(0);
267 ContrastedTraitNode right = (ContrastedTraitNode)getChild(1);
268
269 left.calculateContrasts(kappa);
270 right.calculateContrasts(kappa);
271
272 double leftNodeBranchVariance = left.nodeVariance + Math.pow(getHeight() - left.getHeight(),kappa);
273 double rightNodeBranchVariance = right.nodeVariance + Math.pow(getHeight() - right.getHeight(), kappa);
274
275 // calculate the contrast variances
276 contrastVariance = leftNodeBranchVariance + rightNodeBranchVariance;
277
278 // estimate the variance of the tree value at this node
279 nodeVariance = (leftNodeBranchVariance * rightNodeBranchVariance) / (leftNodeBranchVariance + rightNodeBranchVariance);
280
281 // calculate the weights for each child
282 double invVarLeft = 1.0 / leftNodeBranchVariance;
283 double invVarRight = 1.0 / rightNodeBranchVariance;
284
285 // estimate the contrasts for each trait
286 for (int i = 0; i < getTraitCount(); i++) {
287 // calculate the contrast
288 contrast[i] = left.traitValue[i].getDifference(right.traitValue[i]);
289 //left.traitValue[i] - right.traitValue[i];
290
291 // estimate the variance weighted mean of the two child observations of the ith trait
292 traitValue[i] = left.traitValue[i].getWeightedMean(invVarLeft, left.traitValue[i], invVarRight, right.traitValue[i]);
293 //traitValue[i] = (invVarLeft * left.traitValue[i] + invVarRight * right.traitValue[i]) / (invVarLeft + invVarRight);
294
295 tree.setNodeAttribute(node, traitNames[i], traitValue[i]);
296 }
297 }
298 }
299
300 // the contrast for each trait at this node.
301 private double[] contrast;
302
303 // the contrast variance at this node.
304 private double contrastVariance;
305
306 // the trait value at this node.
307 private Contrastable[] traitValue;
308
309 // the tree variance at this node.
310 private double nodeVariance;
311
312 // the original tree
313 private MutableTree tree;
314 private NodeRef node;
315
316 private String[] traitNames;
317
318 // @todo find out what should be done with this variable
319 // the sum of the log of the contrast variances below this node
320 // private double slContrastVariance = 0;
321 }
322
323 public static void main(String[] args) throws Exception {
324
325 String testTree = "((A:1, B:1):1,(C:1, D:1):1);";
326
327 NewickImporter newickImporter = new NewickImporter(new StringReader(testTree));
328
329 MutableTree tree = (MutableTree)newickImporter.importTree(null);
330
331 tree.setTaxonAttribute(0, "U1", new Continuous(1.10));
332 tree.setTaxonAttribute(1, "U1", new Continuous(1.95));
333 tree.setTaxonAttribute(2, "U1", new Continuous(3.15));
334 tree.setTaxonAttribute(3, "U1", new Continuous(4.39));
335
336 tree.setTaxonAttribute(0, "U2", new Continuous(5.2));
337 tree.setTaxonAttribute(1, "U2", new Continuous(3.8));
338 tree.setTaxonAttribute(2, "U2", new Continuous(3.1));
339 tree.setTaxonAttribute(3, "U2", new Continuous(1.95));
340
341 ContinuousTraitLikelihood ctLikelihood = new ContinuousTraitLikelihood();
342
343 Contrastable[] mles = new Contrastable[2];
344 double logL = ctLikelihood.calculateLikelihood(tree, new String[] {"U1", "U2"}, mles, 1.0);
345
346
347 System.out.println("logL = " + logL);
348 System.out.println("mle(trait1) = " + mles[0]);
349 System.out.println("mle(trait2) = " + mles[1]);
350
351 Contrastable[] mle = new Contrastable[1];
352 System.out.println("logL (trait1) = " + ctLikelihood.calculateLikelihood(tree, new String[] {"U1"}, mle, 1.0));
353 System.out.println("mle(trait1) = " + mle[0]);
354 System.out.println("logL (trait2) = " + ctLikelihood.calculateLikelihood(tree, new String[] {"U2"}, mle, 1.0));
355 System.out.println("mle(trait2) = " + mle[0]);
356
357
358 }
359 }