Debian Codegraph @

src/dr/evomodel/continuous/DiffusionRateStatistic.java

raw symbols SCIP
1 /*
2 * DiffusionRateStatistic.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.continuous;
27
28 import dr.app.util.Arguments;
29 import dr.evolution.tree.MutableTreeModel;
30 import dr.evolution.tree.NodeRef;
31 import dr.evomodel.branchratemodel.BranchRateModel;
32 import dr.evomodel.tree.TreeStatistic;
33 import dr.geo.math.SphericalPolarCoordinates;
34 import dr.inference.model.Statistic;
35 import dr.math.distributions.MultivariateNormalDistribution;
36 import dr.stats.DiscreteStatistics;
37 import dr.xml.*;
38
39 import java.util.*;
40
41 /**
42 * @author Marc Suchard
43 * @author Philippe Lemey
44 * @author Andrew Rambaut
45 */
46 @Deprecated
47 public class DiffusionRateStatistic extends Statistic.Abstract {
48
49 public static final String DIFFUSION_RATE_STATISTIC = "diffusionRateStatistic";
50 public static final String TREE_DISPERSION_STATISTIC = "treeDispersionStatistic";
51 public static final String BOOLEAN_DIS_OPTION = "greatCircleDistance";
52 public static final String MODE = "mode";
53 public static final String MEDIAN = "median";
54 public static final String AVERAGE = "average"; // average over all branches
55 public static final String WEIGHTED_AVERAGE = "weightedAverage"; // weighted average (=total distance/total time)
56 public static final String COEFFICIENT_OF_VARIATION = "coefficientOfVariation"; // weighted average (=total distance/total time)
57 public static final String STATISTIC = "statistic";
58 public static final String DIFFUSION_RATE = "diffusionRate"; // weighted average (=total distance/total time)
59 public static final String WAVEFRONT_DISTANCE = "wavefrontDistance"; // weighted average (=total distance/total time)
60 public static final String WAVEFRONT_RATE = "wavefrontRate"; // weighted average (=total distance/total time)
61 public static final String DIFFUSION_COEFFICIENT = "diffusionCoefficient";
62 // public static final String DIFFUSIONCOEFFICIENT = "diffusionCoefficient"; // weighted average (=total distance/total time)
63 // public static final String BOOLEAN_DC_OPTION = "diffusionCoefficient";
64 public static final String HEIGHT_UPPER = "heightUpper";
65 public static final String HEIGHT_LOWER = "heightLower";
66 public static final String HEIGHT_LOWER_SERIE = "heightLowerSerie";
67 public static final String CUMULATIVE = "cumulative";
68
69 public DiffusionRateStatistic(String name, List<AbstractMultivariateTraitLikelihood> traitLikelihoods,
70 boolean option, Mode mode,
71 summaryStatistic statistic, double heightUpper, double heightLower,
72 double[] lowerHeights, boolean cumulative) {
73 super(name);
74 this.traitLikelihoods = traitLikelihoods;
75 this.useGreatCircleDistances = option;
76 summaryMode = mode;
77 summaryStat = statistic;
78 this.heightUpper = heightUpper;
79
80 if (lowerHeights == null){
81 heightLowers = new double[]{heightLower};
82 } else {
83 heightLowers = extractUnique(lowerHeights);
84 Arrays.sort(heightLowers);
85 reverse(heightLowers);
86 }
87 this.cumulative = cumulative;
88 }
89
90 public int getDimension() {
91 return heightLowers.length;
92 }
93
94 public double getStatisticValue(int dim) {
95
96 String traitName = traitLikelihoods.get(0).getTraitName();
97
98 double treelength = 0;
99 double treeDistance = 0;
100 double maxDistanceFromRoot = 0;
101 double maxDistanceOverTimeFromRoot = 0;
102
103 //double[] rates = null;
104 List<Double> rates = new ArrayList<Double>();
105 //double[] diffusionCoefficients = null;
106 List<Double> diffusionCoefficients = new ArrayList<Double>();
107 double waDiffusionCoefficient = 0;
108
109 double lowerHeight = heightLowers[dim];
110 double upperHeight = Double.MAX_VALUE;
111 if (heightLowers.length == 1){
112 upperHeight = heightUpper;
113 } else {
114 if (dim > 0) {
115 if (!cumulative) {
116 upperHeight = heightLowers[dim -1];
117 }
118 }
119 }
120
121 // System.out.println("dim = "+dim+", heightLower = "+lowerHeight+", heightUpper = "+upperHeight);
122
123 for (AbstractMultivariateTraitLikelihood traitLikelihood : traitLikelihoods) {
124 MutableTreeModel tree = traitLikelihood.getTreeModel();
125 BranchRateModel branchRates = traitLikelihood.getBranchRateModel();
126
127 for (int i = 0; i < tree.getNodeCount(); i++) {
128 NodeRef node = tree.getNode(i);
129
130 if (node != tree.getRoot()) {
131
132 NodeRef parentNode = tree.getParent(node);
133 if ((tree.getNodeHeight(parentNode) > lowerHeight) && (tree.getNodeHeight(node) < upperHeight)) {
134
135 double[] trait = traitLikelihood.getTraitForNode(tree, node, traitName);
136 double[] parentTrait = traitLikelihood.getTraitForNode(tree, parentNode, traitName);
137
138 double[] traitUp = parentTrait;
139 double[] traitLow = trait;
140
141 double timeUp = tree.getNodeHeight(parentNode);
142 double timeLow = tree.getNodeHeight(node);
143
144 double rate = (branchRates != null ? branchRates.getBranchRate(tree, node) : 1.0);
145
146 MultivariateDiffusionModel diffModel = traitLikelihood.diffusionModel;
147 double[] precision = diffModel.getPrecisionParameter().getParameterValues();
148
149 if (tree.getNodeHeight(parentNode) > upperHeight) {
150 timeUp = upperHeight;
151 //TODO: implement TrueNoise??
152 traitUp = imputeValue(trait, parentTrait, upperHeight, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, false);
153 }
154
155 if (tree.getNodeHeight(node) < lowerHeight) {
156 timeLow = lowerHeight;
157 traitLow = imputeValue(trait, parentTrait, lowerHeight, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, false);
158 }
159
160 double time = timeUp - timeLow;
161 treelength += time;
162
163 double[] rootTrait = traitLikelihood.getTraitForNode(tree, tree.getRoot(), traitName);
164
165 if (useGreatCircleDistances && (trait.length == 2)) { // Great Circle distance
166 SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(traitLow[0], traitLow[1]);
167 SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(traitUp[0], traitUp[1]);
168 double distance = coord1.distance(coord2);
169 treeDistance += distance;
170 double dc = Math.pow(distance,2)/(4*time);
171 diffusionCoefficients.add(dc);
172 waDiffusionCoefficient += dc*time;
173 rates.add(distance/time);
174
175 SphericalPolarCoordinates rootCoord = new SphericalPolarCoordinates(rootTrait[0], rootTrait[1]);
176 double tempDistanceFromRoot = rootCoord.distance(coord2);
177 if (tempDistanceFromRoot > maxDistanceFromRoot){
178 maxDistanceFromRoot = tempDistanceFromRoot;
179 maxDistanceOverTimeFromRoot = tempDistanceFromRoot/(tree.getNodeHeight(tree.getRoot()) - timeLow);
180 //distance between traitLow and traitUp for maxDistanceFromRoot
181 if (timeUp == upperHeight) {
182 maxDistanceFromRoot = distance;
183 maxDistanceOverTimeFromRoot = distance/time;
184 }
185 }
186
187
188 } else {
189 double distance = getNativeDistance(traitLow, traitUp);
190 treeDistance += distance;
191 double dc = Math.pow(distance,2)/(4*time);
192 diffusionCoefficients.add(dc);
193 waDiffusionCoefficient += dc*time;
194 rates.add(distance/time);
195
196 double tempDistanceFromRoot = getNativeDistance(traitLow, rootTrait);
197 if (tempDistanceFromRoot > maxDistanceFromRoot){
198 maxDistanceFromRoot = tempDistanceFromRoot;
199 maxDistanceOverTimeFromRoot = tempDistanceFromRoot/(tree.getNodeHeight(tree.getRoot()) - timeLow);
200 //distance between traitLow and traitUp for maxDistanceFromRoot
201 if (timeUp == upperHeight) {
202 maxDistanceFromRoot = distance;
203 maxDistanceOverTimeFromRoot = distance/time;
204 }
205 }
206
207
208
209
210 }
211 }
212 }
213 }
214 }
215
216 if (summaryStat == summaryStatistic.DIFFUSION_RATE){
217 if (summaryMode == Mode.AVERAGE) {
218 return DiscreteStatistics.mean(toArray(rates));
219 } else if (summaryMode == Mode.MEDIAN) {
220 return DiscreteStatistics.median(toArray(rates));
221 } else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) {
222 // don't compute mean twice
223 final double mean = DiscreteStatistics.mean(toArray(rates));
224 return Math.sqrt(DiscreteStatistics.variance(toArray(rates), mean)) / mean;
225 } else {
226 return treeDistance / treelength;
227 }
228 } else if (summaryStat == summaryStatistic.DIFFUSION_COEFFICIENT) {
229 if (summaryMode == Mode.AVERAGE) {
230 return DiscreteStatistics.mean(toArray(diffusionCoefficients));
231 } else if (summaryMode == Mode.MEDIAN) {
232 return DiscreteStatistics.median(toArray(diffusionCoefficients));
233 } else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) {
234 // don't compute mean twice
235 final double mean = DiscreteStatistics.mean(toArray(diffusionCoefficients));
236 return Math.sqrt(DiscreteStatistics.variance(toArray(diffusionCoefficients), mean)) / mean;
237 } else {
238 return waDiffusionCoefficient/treelength;
239 }
240 } else if (summaryStat == summaryStatistic.WAVEFRONT_DISTANCE) {
241 return maxDistanceFromRoot;
242 } else {
243 return maxDistanceOverTimeFromRoot;
244 }
245 }
246
247 // private double getNativeDistance(double[] location1, double[] location2) {
248 // return Math.sqrt(Math.pow((location2[0] - location1[0]), 2.0) + Math.pow((location2[1] - location1[1]), 2.0));
249 // }
250
251 private double getNativeDistance(double[] location1, double[] location2) {
252 int traitDimension = location1.length;
253 double sum = 0;
254 for (int i = 0; i < traitDimension; i++) {
255 sum += Math.pow((location2[i] - location1[i]),2);
256 // System.out.println(sum);
257 }
258 return Math.sqrt(sum);
259 }
260
261 private double[] toArray(List<Double> list) {
262 double[] returnArray = new double[list.size()];
263 for (int i = 0; i < list.size(); i++) {
264 returnArray[i] = Double.valueOf(list.get(i).toString());
265 }
266 return returnArray;
267 }
268
269 private double[] imputeValue(double[] nodeValue, double[] parentValue, double time, double nodeHeight, double parentHeight, double[] precisionArray, double rate, boolean trueNoise) {
270
271 final double scaledTimeChild = (time - nodeHeight) * rate;
272 final double scaledTimeParent = (parentHeight - time) * rate;
273 final double scaledWeightTotal = 1.0 / scaledTimeChild + 1.0 / scaledTimeParent;
274 final int dim = nodeValue.length;
275
276 double[][] precision = new double[dim][dim];
277 int counter = 0;
278 for (int a = 0; a < dim; a++){
279 for (int b = 0; b < dim; b++){
280 precision[a][b] = precisionArray[counter];
281 counter++ ;
282 }
283 }
284
285 if (scaledTimeChild == 0)
286 return nodeValue;
287
288 if (scaledTimeParent == 0)
289 return parentValue;
290
291 // Find mean value, weighted average
292 double[] mean = new double[dim];
293 double[][] scaledPrecision = new double[dim][dim];
294
295 for (int i = 0; i < dim; i++) {
296 mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal;
297 if (trueNoise) {
298 for (int j = i; j < dim; j++)
299 scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal;
300 }
301 }
302
303 // System.out.print(time+"\t"+nodeHeight+"\t"+parentHeight+"\t"+scaledTimeChild+"\t"+scaledTimeParent+"\t"+scaledWeightTotal+"\t"+mean[0]+"\t"+mean[1]+"\t"+scaledPrecision[0][0]+"\t"+scaledPrecision[0][1]+"\t"+scaledPrecision[1][0]+"\t"+scaledPrecision[1][1]);
304
305 if (trueNoise) {
306 mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, scaledPrecision);
307 }
308 // System.out.println("\t"+mean[0]+"\t"+mean[1]+"\r");
309
310 double[] result = new double[dim];
311 for (int i = 0; i < dim; i++)
312 result[i] = mean[i];
313 return result;
314 }
315
316 public static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException {
317
318 List<Double> returnList = new ArrayList<Double>();
319 StringTokenizer st = new StringTokenizer(inString, ",");
320 while (st.hasMoreTokens()) {
321 try {
322 returnList.add(Double.parseDouble(st.nextToken()));
323 } catch (NumberFormatException e) {
324 throw new Arguments.ArgumentException();
325 }
326
327 }
328
329 if (returnList.size() > 0) {
330 double[] doubleArray = new double[returnList.size()];
331 for (int i = 0; i < doubleArray.length; i++)
332 doubleArray[i] = returnList.get(i);
333
334 return doubleArray;
335 }
336 return null;
337 }
338
339 @Override
340 public String getDimensionName(int dim) {
341 if (getDimension() == 1) {
342 return getStatisticName();
343 } else {
344 return getStatisticName() +".height"+ heightLowers[dim];
345 }
346 }
347
348 public static void reverse(double[] array) {
349 if (array == null) {
350 return;
351 }
352 int i = 0;
353 int j = array.length - 1;
354 double tmp;
355 while (j > i) {
356 tmp = array[j];
357 array[j] = array[i];
358 array[i] = tmp;
359 j--;
360 i++;
361 }
362 }
363
364 public static double[] extractUnique(double[] array){
365 Set<Double> tmp = new LinkedHashSet<Double>();
366 for (Double each : array) {
367 tmp.add(each);
368 }
369 double [] output = new double[tmp.size()];
370 int i = 0;
371 for (Double each : tmp) {
372 output[i++] = each;
373 }
374 return output;
375 }
376
377 enum Mode {
378 AVERAGE,
379 WEIGHTED_AVERAGE,
380 MEDIAN,
381 COEFFICIENT_OF_VARIATION
382 }
383
384 enum summaryStatistic {
385 DIFFUSION_RATE,
386 DIFFUSION_COEFFICIENT,
387 WAVEFRONT_DISTANCE,
388 WAVEFRONT_RATE,
389 }
390
391 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
392
393 public String getParserName() {
394 return DIFFUSION_RATE_STATISTIC;
395 }
396
397 @Override
398 public String[] getParserNames() {
399 return new String[]{getParserName(), TREE_DISPERSION_STATISTIC};
400 }
401
402 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
403
404 String name = xo.getAttribute(NAME, xo.getId());
405
406 boolean option = xo.getAttribute(BOOLEAN_DIS_OPTION, true); // Default value is true
407 Mode averageMode;
408 String mode = xo.getAttribute(MODE, WEIGHTED_AVERAGE);
409
410 if (mode.equals(AVERAGE)) {
411 averageMode = Mode.AVERAGE;
412 } else if (mode.equals(MEDIAN)) {
413 averageMode = Mode.MEDIAN;
414 } else if (mode.equals(COEFFICIENT_OF_VARIATION)) {
415 averageMode = Mode.COEFFICIENT_OF_VARIATION;
416 } else if (mode.equals(WEIGHTED_AVERAGE)) {
417 averageMode = Mode.WEIGHTED_AVERAGE;
418 } else {
419 System.err.println("Unknown mode: "+mode+". Reverting to weighted average");
420 averageMode = Mode.WEIGHTED_AVERAGE;
421 }
422
423 // boolean diffCoeff = xo.getAttribute(BOOLEAN_DC_OPTION, false); // Default value is false
424 summaryStatistic summaryStat;
425 String statistic = xo.getAttribute(STATISTIC, DIFFUSION_RATE);
426 if (statistic.equals(DIFFUSION_RATE)) {
427 summaryStat = summaryStatistic.DIFFUSION_RATE;
428 } else if (statistic.equals(WAVEFRONT_DISTANCE)) {
429 summaryStat = summaryStatistic.WAVEFRONT_DISTANCE;
430 } else if (statistic.equals(WAVEFRONT_RATE)) {
431 summaryStat = summaryStatistic.WAVEFRONT_RATE;
432 } else if (statistic.equals(DIFFUSION_COEFFICIENT)) {
433 summaryStat = summaryStatistic.DIFFUSION_COEFFICIENT;
434 } else {
435 System.err.println("Unknown statistic: "+statistic+". Reverting to diffusion rate");
436 summaryStat = summaryStatistic.DIFFUSION_COEFFICIENT;
437 }
438
439 final double upperHeight = xo.getAttribute(HEIGHT_UPPER, Double.MAX_VALUE);
440 final double lowerHeight = xo.getAttribute(HEIGHT_LOWER, 0.0);
441
442 double[] lowerHeights = null;
443 if (xo.hasAttribute(HEIGHT_LOWER_SERIE)){
444 String lowerHeightsString = xo.getStringAttribute(HEIGHT_LOWER_SERIE);
445 try {
446 lowerHeights = parseVariableLengthDoubleArray(lowerHeightsString);
447 } catch (Arguments.ArgumentException e) {
448 System.err.println("Error reading " + HEIGHT_LOWER_SERIE);
449 System.exit(1);
450 }
451 }
452
453 boolean cumulative = xo.getAttribute(CUMULATIVE, false);
454
455 List<AbstractMultivariateTraitLikelihood> traitLikelihoods = new ArrayList<AbstractMultivariateTraitLikelihood>();
456
457 for (int i = 0; i < xo.getChildCount(); i++) {
458 if (xo.getChild(i) instanceof AbstractMultivariateTraitLikelihood) {
459 AbstractMultivariateTraitLikelihood amtl = (AbstractMultivariateTraitLikelihood) xo.getChild(i);
460 traitLikelihoods.add(amtl);
461 }
462 }
463
464 return new DiffusionRateStatistic(name, traitLikelihoods, option, averageMode, summaryStat, upperHeight, lowerHeight, lowerHeights, cumulative);
465 }
466
467 //************************************************************************
468 // AbstractXMLObjectParser implementation
469 //************************************************************************
470
471 public String getParserDescription() {
472 return "A statistic that returns the average of the branch diffusion rates";
473 }
474
475 public Class getReturnType() {
476 return TreeStatistic.class;
477 }
478
479 public XMLSyntaxRule[] getSyntaxRules() {
480 return rules;
481 }
482
483 private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
484 AttributeRule.newStringRule(NAME, true),
485 AttributeRule.newBooleanRule(BOOLEAN_DIS_OPTION, true),
486 AttributeRule.newStringRule(MODE, true),
487 AttributeRule.newStringRule(STATISTIC,true),
488 AttributeRule.newDoubleRule(HEIGHT_UPPER, true),
489 AttributeRule.newDoubleRule(HEIGHT_LOWER, true),
490 AttributeRule.newStringRule(HEIGHT_LOWER_SERIE,true),
491 AttributeRule.newBooleanRule(CUMULATIVE, true),
492 new ElementRule(AbstractMultivariateTraitLikelihood.class, 1, Integer.MAX_VALUE),
493 };
494 };
495
496 private boolean useGreatCircleDistances;
497 private List<AbstractMultivariateTraitLikelihood> traitLikelihoods;
498 private Mode summaryMode;
499 private summaryStatistic summaryStat;
500 private double heightUpper;
501 private double[] heightLowers;
502 private boolean cumulative;
503
504 }
505