| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
package dr.evomodel.continuous; |
| 27 |
|
| 28 |
import dr.evolution.tree.MutableTreeModel; |
| 29 |
import dr.evolution.tree.TreeUtils; |
| 30 |
import dr.evomodel.treelikelihood.MarkovJumpsBeagleTreeLikelihood; |
| 31 |
import dr.app.util.Arguments; |
| 32 |
import dr.evolution.tree.NodeRef; |
| 33 |
import dr.evolution.tree.Tree; |
| 34 |
import dr.evolution.util.TaxonList; |
| 35 |
import dr.evomodel.branchratemodel.BranchRateModel; |
| 36 |
import dr.evomodel.tree.TreeStatistic; |
| 37 |
import dr.geo.KMLCoordinates; |
| 38 |
import dr.geo.Polygon2D; |
| 39 |
import dr.geo.contouring.ContourMaker; |
| 40 |
import dr.geo.contouring.ContourPath; |
| 41 |
import dr.geo.contouring.ContourWithSynder; |
| 42 |
import dr.geo.math.SphericalPolarCoordinates; |
| 43 |
import dr.inference.model.Statistic; |
| 44 |
import dr.math.distributions.MultivariateNormalDistribution; |
| 45 |
import dr.stats.DiscreteStatistics; |
| 46 |
import dr.stats.Regression; |
| 47 |
import dr.xml.*; |
| 48 |
import org.jdom.Element; |
| 49 |
import org.apache.commons.math.stat.ranking.NaturalRanking; |
| 50 |
|
| 51 |
import java.util.*; |
| 52 |
|
| 53 |
import static java.lang.Double.NaN; |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
public class ContinuousDiffusionStatistic extends Statistic.Abstract { |
| 61 |
|
| 62 |
public static final String CONTINUOUS_DIFFUSION_STATISTIC = "continuousDiffusionStatistic"; |
| 63 |
public static final String DIFFUSION_RATE_STATISTIC = "diffusionRateStatistic"; |
| 64 |
public static final String TREE_DISPERSION_STATISTIC = "treeDispersionStatistic"; |
| 65 |
|
| 66 |
public static final String USE_GREATCIRCLEDISTANCES = "greatCircleDistance"; |
| 67 |
public static final String MODE = "mode"; |
| 68 |
public static final String MEDIAN = "median"; |
| 69 |
public static final String AVERAGE = "average"; |
| 70 |
public static final String WEIGHTED_AVERAGE = "weightedAverage"; |
| 71 |
public static final String COEFFICIENT_OF_VARIATION = "coefficientOfVariation"; |
| 72 |
public static final String SPEARMAN = "spearman"; |
| 73 |
public static final String CORRELATION_COEFFICIENT = "correlationCoefficient"; |
| 74 |
public static final String DISTANCE_TIME_CORRELATION = "distanceTimeCorrelation"; |
| 75 |
public static final String R_SQUARED = "Rsquared"; |
| 76 |
public static final String STATISTIC = "statistic"; |
| 77 |
public static final String TRAIT = "trait"; |
| 78 |
public static final String TRAIT2DAREA = "trait2Darea"; |
| 79 |
public static final String DIMENSION = "dimension"; |
| 80 |
public static final String DIFFUSION_TIME = "diffusionTime"; |
| 81 |
public static final String DIFFUSION_DISTANCE = "diffusionDistance"; |
| 82 |
public static final String DIFFUSION_RATE = "diffusionRate"; |
| 83 |
public static final String WAVEFRONT_DISTANCE = "wavefrontDistance"; |
| 84 |
public static final String WAVEFRONT_DISTANCE_PHYLO = "wavefrontDistancePhylo"; |
| 85 |
public static final String WAVEFRONT_RATE = "wavefrontRate"; |
| 86 |
public static final String DIFFUSION_COEFFICIENT = "diffusionCoefficient"; |
| 87 |
public static final String HEIGHT_UPPER = "heightUpper"; |
| 88 |
public static final String HEIGHT_LOWER = "heightLower"; |
| 89 |
public static final String HEIGHT_LOWER_SERIE = "heightLowerSerie"; |
| 90 |
public static final String CUMULATIVE = "cumulative"; |
| 91 |
public static final String DISCRETE_STATE = "discreteState"; |
| 92 |
public static final Integer SITE = 0; |
| 93 |
public static final Integer NUMBER_OF_HISTORY_ENTRIES = 3; |
| 94 |
public static final String NOISE = "noise"; |
| 95 |
public static final String TAXA = "taxa"; |
| 96 |
public static final String BRANCHSET = "branchSet"; |
| 97 |
public static final String ALL = "all"; |
| 98 |
public static final String CLADE = "clade"; |
| 99 |
public static final String BACKBONE = "backbone"; |
| 100 |
public static final String BACKBONE_TIME = "backboneTime"; |
| 101 |
|
| 102 |
public ContinuousDiffusionStatistic(String name, List<AbstractMultivariateTraitLikelihood> traitLikelihoods, |
| 103 |
boolean greatCircleDistances, Mode mode, |
| 104 |
summaryStatistic statistic, double heightUpper, double heightLower, |
| 105 |
double[] lowerHeights, boolean cumulative, boolean trueNoise, int dimension, |
| 106 |
TaxonList taxonList, BranchSet branchset, Double backboneTime, |
| 107 |
String stateString, MarkovJumpsBeagleTreeLikelihood markovJumpLikelihood) { |
| 108 |
super(name); |
| 109 |
this.traitLikelihoods = traitLikelihoods; |
| 110 |
this.useGreatCircleDistances = greatCircleDistances; |
| 111 |
summaryMode = mode; |
| 112 |
summaryStat = statistic; |
| 113 |
this.heightUpper = heightUpper; |
| 114 |
|
| 115 |
if (lowerHeights == null){ |
| 116 |
heightLowers = new double[]{heightLower}; |
| 117 |
} else { |
| 118 |
heightLowers = extractUnique(lowerHeights); |
| 119 |
Arrays.sort(heightLowers); |
| 120 |
reverse(heightLowers); |
| 121 |
} |
| 122 |
this.cumulative = cumulative; |
| 123 |
this.trueNoise = trueNoise; |
| 124 |
|
| 125 |
this.dimension = dimension; |
| 126 |
|
| 127 |
this.taxonList = taxonList; |
| 128 |
this.branchset = branchset; |
| 129 |
this.backboneTime = backboneTime; |
| 130 |
|
| 131 |
this.stateString = stateString; |
| 132 |
|
| 133 |
this.markovJumpLikelihood = markovJumpLikelihood; |
| 134 |
} |
| 135 |
|
| 136 |
public int getDimension() { |
| 137 |
return heightLowers.length; |
| 138 |
} |
| 139 |
|
| 140 |
public double getStatisticValue(int dim) { |
| 141 |
|
| 142 |
double treeLength = 0; |
| 143 |
double treeDistance = 0; |
| 144 |
double totalMaxDistanceFromRoot = 0; |
| 145 |
double maxDistanceFromRootCumulative = 0; |
| 146 |
double maxBranchDistanceFromRoot = 0; |
| 147 |
double maxDistanceOverTimeFromRootWA = 0; |
| 148 |
double maxBranchDistanceOverTimeFromRootWA = 0; |
| 149 |
List<Double> rates = new ArrayList<Double>(); |
| 150 |
List<Double> distances = new ArrayList<Double>(); |
| 151 |
List<Double> times = new ArrayList<Double>(); |
| 152 |
List<Double> traits = new ArrayList<Double>(); |
| 153 |
List<double[]> traits2D = new ArrayList<double[]>(); |
| 154 |
|
| 155 |
List<Double> diffusionCoefficients = new ArrayList<Double>(); |
| 156 |
double waDiffusionCoefficient = 0; |
| 157 |
|
| 158 |
double lowerHeight = heightLowers[dim]; |
| 159 |
double upperHeight = Double.MAX_VALUE; |
| 160 |
if (heightLowers.length == 1){ |
| 161 |
upperHeight = heightUpper; |
| 162 |
} else { |
| 163 |
if (dim > 0) { |
| 164 |
if (!cumulative) { |
| 165 |
upperHeight = heightLowers[dim -1]; |
| 166 |
} |
| 167 |
} |
| 168 |
} |
| 169 |
|
| 170 |
for (AbstractMultivariateTraitLikelihood traitLikelihood : traitLikelihoods) { |
| 171 |
MutableTreeModel tree = traitLikelihood.getTreeModel(); |
| 172 |
BranchRateModel branchRates = traitLikelihood.getBranchRateModel(); |
| 173 |
|
| 174 |
String traitName = traitLikelihood.getTraitName(); |
| 175 |
|
| 176 |
for (int i = 0; i < tree.getNodeCount(); i++) { |
| 177 |
NodeRef node = tree.getNode(i); |
| 178 |
|
| 179 |
if (node != tree.getRoot()) { |
| 180 |
|
| 181 |
NodeRef parentNode = tree.getParent(node); |
| 182 |
|
| 183 |
boolean testNode = true; |
| 184 |
if (branchset.equals(BranchSet.CLADE)){ |
| 185 |
try{ |
| 186 |
testNode = inClade(tree, node, taxonList); |
| 187 |
} catch (TreeUtils.MissingTaxonException mte) { |
| 188 |
throw new RuntimeException(mte.toString()); |
| 189 |
} |
| 190 |
} else if (branchset.equals(BranchSet.BACKBONE)) { |
| 191 |
if (backboneTime > 0) { |
| 192 |
testNode = onAncestralPathTime(tree, node, backboneTime); |
| 193 |
} else { |
| 194 |
try{ |
| 195 |
testNode = onAncestralPathTaxa(tree, node, taxonList); |
| 196 |
} catch (TreeUtils.MissingTaxonException mte) { |
| 197 |
throw new RuntimeException(mte.toString()); |
| 198 |
} |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
if (testNode){ |
| 203 |
|
| 204 |
if ((tree.getNodeHeight(parentNode) > lowerHeight) && (tree.getNodeHeight(node) < upperHeight)) { |
| 205 |
|
| 206 |
double[] trait = traitLikelihood.getTraitForNode(tree, node, traitName); |
| 207 |
double[] parentTrait = traitLikelihood.getTraitForNode(tree, parentNode, traitName); |
| 208 |
|
| 209 |
double[] traitUp = parentTrait; |
| 210 |
double[] traitLow = trait; |
| 211 |
|
| 212 |
double timeUp = tree.getNodeHeight(parentNode); |
| 213 |
double timeLow = tree.getNodeHeight(node); |
| 214 |
|
| 215 |
double rate = (branchRates != null ? branchRates.getBranchRate(tree, node) : 1.0); |
| 216 |
|
| 217 |
MultivariateDiffusionModel diffModel = traitLikelihood.diffusionModel; |
| 218 |
double[] precision = diffModel.getPrecisionParameter().getParameterValues(); |
| 219 |
|
| 220 |
History history = null; |
| 221 |
if (stateString != null) { |
| 222 |
history = setUpHistory(markovJumpLikelihood.getHistoryForNode(tree, node, SITE), markovJumpLikelihood.getStatesForNode(tree, node)[SITE], markovJumpLikelihood.getStatesForNode(tree, parentNode)[SITE], timeLow, timeUp); |
| 223 |
} |
| 224 |
|
| 225 |
if (tree.getNodeHeight(parentNode) > upperHeight) { |
| 226 |
timeUp = upperHeight; |
| 227 |
traitUp = imputeValue(trait, parentTrait, upperHeight, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, trueNoise); |
| 228 |
if (stateString != null) { |
| 229 |
history.truncateUpper(timeUp); |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
if (tree.getNodeHeight(node) < lowerHeight) { |
| 234 |
timeLow = lowerHeight; |
| 235 |
traitLow = imputeValue(trait, parentTrait, lowerHeight, tree.getNodeHeight(node), tree.getNodeHeight(parentNode), precision, rate, trueNoise); |
| 236 |
if (stateString != null) { |
| 237 |
history.truncateLower(timeLow); |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
if (dimension > traitLow.length) { |
| 242 |
System.err.println("specified trait dimension for continuous trait summary, " + dimension + ", is > dimensionality of trait, " + traitLow.length + ". No trait summarized."); |
| 243 |
} else { |
| 244 |
traits.add(traitLow[(dimension - 1)]); |
| 245 |
} |
| 246 |
|
| 247 |
if (traitLow.length == 2){ |
| 248 |
traits2D.add(traitLow); |
| 249 |
} |
| 250 |
|
| 251 |
double time; |
| 252 |
if (stateString != null) { |
| 253 |
if (!history.returnMismatch()){ |
| 254 |
time = history.getStateTime(stateString); |
| 255 |
} else { |
| 256 |
time = NaN; |
| 257 |
} |
| 258 |
|
| 259 |
} else { |
| 260 |
time = timeUp - timeLow; |
| 261 |
} |
| 262 |
treeLength += time; |
| 263 |
times.add(time); |
| 264 |
|
| 265 |
|
| 266 |
if (stateString != null) { |
| 267 |
history.setTraitsforHeights(traitUp, traitLow, precision, rate, trueNoise); |
| 268 |
} |
| 269 |
|
| 270 |
double[] rootTrait = traitLikelihood.getTraitForNode(tree, tree.getRoot(), traitName); |
| 271 |
double timeFromRoot = (tree.getNodeHeight(tree.getRoot()) - timeLow); |
| 272 |
|
| 273 |
if (useGreatCircleDistances && (trait.length == 2)) { |
| 274 |
double distance; |
| 275 |
if (stateString != null) { |
| 276 |
if (!history.returnMismatch()){ |
| 277 |
distance = history.getStateGreatCircleDistance(stateString); |
| 278 |
} else { |
| 279 |
distance = NaN; |
| 280 |
} |
| 281 |
} else { |
| 282 |
distance = getGreatCircleDistance(traitLow, traitUp); |
| 283 |
} |
| 284 |
distances.add(distance); |
| 285 |
|
| 286 |
if (time > 0) { |
| 287 |
treeDistance += distance; |
| 288 |
double dc = Math.pow(distance, 2) / (4 * time); |
| 289 |
diffusionCoefficients.add(dc); |
| 290 |
waDiffusionCoefficient += (dc * time); |
| 291 |
rates.add(distance / time); |
| 292 |
} |
| 293 |
|
| 294 |
SphericalPolarCoordinates rootCoord = new SphericalPolarCoordinates(rootTrait[0], rootTrait[1]); |
| 295 |
double tempDistanceFromRootLow = rootCoord.distance(new SphericalPolarCoordinates(traitUp[0], traitUp[1])); |
| 296 |
|
| 297 |
|
| 298 |
if (tempDistanceFromRootLow > totalMaxDistanceFromRoot) { |
| 299 |
totalMaxDistanceFromRoot = tempDistanceFromRootLow; |
| 300 |
if (stateString != null) { |
| 301 |
double[] stateTimeDistance = getStateTimeAndDistanceFromRoot(tree, node, timeLow, traitLikelihood, traitName, traitLow, precision, branchRates, true); |
| 302 |
if (stateTimeDistance[0] > 0) { |
| 303 |
if (!history.returnMismatch()){ |
| 304 |
maxDistanceFromRootCumulative = tempDistanceFromRootLow * (stateTimeDistance[0] / timeFromRoot); |
| 305 |
maxDistanceOverTimeFromRootWA = maxDistanceFromRootCumulative / stateTimeDistance[0]; |
| 306 |
maxBranchDistanceFromRoot = stateTimeDistance[1]; |
| 307 |
maxBranchDistanceOverTimeFromRootWA = stateTimeDistance[1] / stateTimeDistance[0]; |
| 308 |
} else { |
| 309 |
maxDistanceFromRootCumulative = NaN; |
| 310 |
maxDistanceOverTimeFromRootWA = NaN; |
| 311 |
maxBranchDistanceFromRoot = NaN; |
| 312 |
maxBranchDistanceOverTimeFromRootWA = NaN; |
| 313 |
} |
| 314 |
} |
| 315 |
} else { |
| 316 |
maxDistanceFromRootCumulative = tempDistanceFromRootLow; |
| 317 |
maxDistanceOverTimeFromRootWA = tempDistanceFromRootLow / timeFromRoot; |
| 318 |
double[] timeDistance = getTimeAndDistanceFromRoot(tree, node, timeLow, traitLikelihood, traitName, traitLow, true); |
| 319 |
maxBranchDistanceFromRoot = timeDistance[1]; |
| 320 |
maxBranchDistanceOverTimeFromRootWA = timeDistance[1] / timeDistance[0]; |
| 321 |
|
| 322 |
} |
| 323 |
|
| 324 |
if (timeUp == upperHeight) { |
| 325 |
if (time > 0) { |
| 326 |
maxDistanceFromRootCumulative = distance; |
| 327 |
maxDistanceOverTimeFromRootWA = distance / time; |
| 328 |
maxBranchDistanceFromRoot = distance; |
| 329 |
maxBranchDistanceOverTimeFromRootWA = distance / time; |
| 330 |
} |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
} else { |
| 335 |
double distance; |
| 336 |
if (stateString != null) { |
| 337 |
if (!history.returnMismatch()){ |
| 338 |
distance = history.getStateNativeDistance(stateString); |
| 339 |
} else { |
| 340 |
distance = NaN; |
| 341 |
} |
| 342 |
} else { |
| 343 |
distance = getNativeDistance(traitLow, traitUp); |
| 344 |
} |
| 345 |
distances.add(distance); |
| 346 |
|
| 347 |
if (time > 0) { |
| 348 |
treeDistance += distance; |
| 349 |
double dc = Math.pow(distance, 2) / (4 * time); |
| 350 |
diffusionCoefficients.add(dc); |
| 351 |
waDiffusionCoefficient += dc * time; |
| 352 |
rates.add(distance / time); |
| 353 |
} |
| 354 |
|
| 355 |
double tempDistanceFromRoot = getNativeDistance(traitLow, rootTrait); |
| 356 |
if (tempDistanceFromRoot > totalMaxDistanceFromRoot) { |
| 357 |
totalMaxDistanceFromRoot = tempDistanceFromRoot; |
| 358 |
if (stateString != null) { |
| 359 |
double[] stateTimeDistance = getStateTimeAndDistanceFromRoot(tree, node, timeLow, traitLikelihood, traitName, traitLow, precision, branchRates, false); |
| 360 |
if (stateTimeDistance[0] > 0) { |
| 361 |
if (!history.returnMismatch()){ |
| 362 |
maxDistanceFromRootCumulative = tempDistanceFromRoot * (stateTimeDistance[0] / timeFromRoot); |
| 363 |
maxDistanceOverTimeFromRootWA = maxDistanceFromRootCumulative / stateTimeDistance[0]; |
| 364 |
maxBranchDistanceFromRoot = stateTimeDistance[1]; |
| 365 |
maxBranchDistanceOverTimeFromRootWA = stateTimeDistance[1] / stateTimeDistance[0]; |
| 366 |
} else { |
| 367 |
maxDistanceFromRootCumulative = NaN; |
| 368 |
maxDistanceOverTimeFromRootWA = NaN; |
| 369 |
maxBranchDistanceFromRoot = NaN; |
| 370 |
maxBranchDistanceOverTimeFromRootWA = NaN; |
| 371 |
} |
| 372 |
} |
| 373 |
} else { |
| 374 |
maxDistanceFromRootCumulative = tempDistanceFromRoot; |
| 375 |
maxDistanceOverTimeFromRootWA = tempDistanceFromRoot / timeFromRoot; |
| 376 |
double[] timeDistance = getTimeAndDistanceFromRoot(tree, node, timeLow, traitLikelihood, traitName, traitLow, false); |
| 377 |
maxBranchDistanceFromRoot = timeDistance[1]; |
| 378 |
maxBranchDistanceOverTimeFromRootWA = timeDistance[1] / timeDistance[0]; |
| 379 |
} |
| 380 |
|
| 381 |
if (timeUp == upperHeight) { |
| 382 |
if (time > 0) { |
| 383 |
maxDistanceFromRootCumulative = distance; |
| 384 |
maxDistanceOverTimeFromRootWA = distance / time; |
| 385 |
maxBranchDistanceFromRoot = distance; |
| 386 |
maxBranchDistanceOverTimeFromRootWA = distance / time; |
| 387 |
} |
| 388 |
} |
| 389 |
} |
| 390 |
} |
| 391 |
} |
| 392 |
} |
| 393 |
} |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
if (summaryStat == summaryStatistic.DIFFUSION_RATE){ |
| 398 |
if (summaryMode == Mode.AVERAGE) { |
| 399 |
return DiscreteStatistics.mean(toArray(rates)); |
| 400 |
} else if (summaryMode == Mode.MEDIAN) { |
| 401 |
return DiscreteStatistics.median(toArray(rates)); |
| 402 |
} else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) { |
| 403 |
final double mean = DiscreteStatistics.mean(toArray(rates)); |
| 404 |
return Math.sqrt(DiscreteStatistics.variance(toArray(rates), mean)) / mean; |
| 405 |
|
| 406 |
} else { |
| 407 |
return treeDistance / treeLength; |
| 408 |
} |
| 409 |
} else if (summaryStat == summaryStatistic.TRAIT) { |
| 410 |
if (summaryMode == Mode.MEDIAN) { |
| 411 |
return DiscreteStatistics.median(toArray(traits)); |
| 412 |
} else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) { |
| 413 |
|
| 414 |
final double mean = DiscreteStatistics.mean(toArray(traits)); |
| 415 |
return Math.sqrt(DiscreteStatistics.variance(toArray(traits), mean)) / mean; |
| 416 |
|
| 417 |
} else { |
| 418 |
return DiscreteStatistics.mean(toArray(traits)); |
| 419 |
} |
| 420 |
} else if (summaryStat == summaryStatistic.TRAIT2DAREA) { |
| 421 |
double area = getAreaFrom2Dtraits(traits2D, 0.99); |
| 422 |
return area; |
| 423 |
} else if (summaryStat == summaryStatistic.DIFFUSION_COEFFICIENT) { |
| 424 |
if (summaryMode == Mode.AVERAGE) { |
| 425 |
return DiscreteStatistics.mean(toArray(diffusionCoefficients)); |
| 426 |
} else if (summaryMode == Mode.MEDIAN) { |
| 427 |
return DiscreteStatistics.median(toArray(diffusionCoefficients)); |
| 428 |
} else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) { |
| 429 |
|
| 430 |
final double mean = DiscreteStatistics.mean(toArray(diffusionCoefficients)); |
| 431 |
return Math.sqrt(DiscreteStatistics.variance(toArray(diffusionCoefficients), mean)) / mean; |
| 432 |
} else { |
| 433 |
return waDiffusionCoefficient / treeLength; |
| 434 |
} |
| 435 |
|
| 436 |
|
| 437 |
} else if (summaryStat == summaryStatistic.WAVEFRONT_DISTANCE) { |
| 438 |
return maxDistanceFromRootCumulative; |
| 439 |
|
| 440 |
} else if (summaryStat == summaryStatistic.WAVEFRONT_DISTANCE_PHYLO) { |
| 441 |
return maxBranchDistanceFromRoot; |
| 442 |
|
| 443 |
} else if (summaryStat == summaryStatistic.WAVEFRONT_RATE) { |
| 444 |
return maxDistanceOverTimeFromRootWA; |
| 445 |
|
| 446 |
} else if (summaryStat == summaryStatistic.DIFFUSION_DISTANCE) { |
| 447 |
return treeDistance; |
| 448 |
|
| 449 |
} else if (summaryStat == summaryStatistic.DISTANCE_TIME_CORRELATION) { |
| 450 |
if (summaryMode == Mode.SPEARMAN) { |
| 451 |
return getSpearmanRho(convertDoubles(times),convertDoubles(distances)); |
| 452 |
} else if (summaryMode == Mode.R_SQUARED) { |
| 453 |
Regression r = new Regression(convertDoubles(times), convertDoubles(distances)); |
| 454 |
return r.getRSquared(); |
| 455 |
} else { |
| 456 |
Regression r = new Regression(convertDoubles(times),convertDoubles(distances)); |
| 457 |
return r.getCorrelationCoefficient(); |
| 458 |
} |
| 459 |
} else { |
| 460 |
return treeLength; |
| 461 |
} |
| 462 |
} |
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
private double getNativeDistance(double[] location1, double[] location2) { |
| 469 |
int traitDimension = location1.length; |
| 470 |
double sum = 0; |
| 471 |
for (int i = 0; i < traitDimension; i++) { |
| 472 |
sum += Math.pow((location2[i] - location1[i]),2); |
| 473 |
} |
| 474 |
return Math.sqrt(sum); |
| 475 |
} |
| 476 |
|
| 477 |
public double getGreatCircleDistance(double[] loc1, double[] loc2){ |
| 478 |
SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(loc1[0], loc1[1]); |
| 479 |
SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(loc2[0], loc2[1]); |
| 480 |
return coord1.distance(coord2); |
| 481 |
} |
| 482 |
|
| 483 |
private double[] toArray(List<Double> list) { |
| 484 |
double[] returnArray = new double[list.size()]; |
| 485 |
for (int i = 0; i < list.size(); i++) { |
| 486 |
returnArray[i] = Double.valueOf(list.get(i).toString()); |
| 487 |
} |
| 488 |
return returnArray; |
| 489 |
} |
| 490 |
|
| 491 |
private double[] imputeValue(double[] nodeValue, double[] parentValue, double time, double nodeHeight, double parentHeight, double[] precisionArray, double rate, boolean trueNoise) { |
| 492 |
|
| 493 |
final double scaledTimeChild = (time - nodeHeight) * rate; |
| 494 |
final double scaledTimeParent = (parentHeight - time) * rate; |
| 495 |
final double scaledWeightTotal = 1.0 / scaledTimeChild + 1.0 / scaledTimeParent; |
| 496 |
final int dim = nodeValue.length; |
| 497 |
|
| 498 |
double[][] precision = new double[dim][dim]; |
| 499 |
int counter = 0; |
| 500 |
for (int a = 0; a < dim; a++){ |
| 501 |
for (int b = 0; b < dim; b++){ |
| 502 |
precision[a][b] = precisionArray[counter]; |
| 503 |
counter++ ; |
| 504 |
} |
| 505 |
} |
| 506 |
|
| 507 |
if (scaledTimeChild == 0) |
| 508 |
return nodeValue; |
| 509 |
|
| 510 |
if (scaledTimeParent == 0) |
| 511 |
return parentValue; |
| 512 |
|
| 513 |
|
| 514 |
double[] mean = new double[dim]; |
| 515 |
double[][] scaledPrecision = new double[dim][dim]; |
| 516 |
|
| 517 |
for (int i = 0; i < dim; i++) { |
| 518 |
mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal; |
| 519 |
if (trueNoise) { |
| 520 |
for (int j = i; j < dim; j++) |
| 521 |
scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal; |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
if (trueNoise) { |
| 528 |
mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, scaledPrecision); |
| 529 |
} |
| 530 |
|
| 531 |
|
| 532 |
double[] result = new double[dim]; |
| 533 |
for (int i = 0; i < dim; i++) |
| 534 |
result[i] = mean[i]; |
| 535 |
return result; |
| 536 |
} |
| 537 |
|
| 538 |
public static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException { |
| 539 |
|
| 540 |
List<Double> returnList = new ArrayList<Double>(); |
| 541 |
StringTokenizer st = new StringTokenizer(inString, ","); |
| 542 |
while (st.hasMoreTokens()) { |
| 543 |
try { |
| 544 |
returnList.add(Double.parseDouble(st.nextToken())); |
| 545 |
} catch (NumberFormatException e) { |
| 546 |
throw new Arguments.ArgumentException(); |
| 547 |
} |
| 548 |
|
| 549 |
} |
| 550 |
|
| 551 |
if (returnList.size() > 0) { |
| 552 |
double[] doubleArray = new double[returnList.size()]; |
| 553 |
for (int i = 0; i < doubleArray.length; i++) |
| 554 |
doubleArray[i] = returnList.get(i); |
| 555 |
|
| 556 |
return doubleArray; |
| 557 |
} |
| 558 |
return null; |
| 559 |
} |
| 560 |
|
| 561 |
@Override |
| 562 |
public String getDimensionName(int dim) { |
| 563 |
if (getDimension() == 1) { |
| 564 |
return getStatisticName(); |
| 565 |
} else { |
| 566 |
return getStatisticName() +".height"+ heightLowers[dim]; |
| 567 |
} |
| 568 |
} |
| 569 |
|
| 570 |
public static void reverse(double[] array) { |
| 571 |
if (array == null) { |
| 572 |
return; |
| 573 |
} |
| 574 |
int i = 0; |
| 575 |
int j = array.length - 1; |
| 576 |
double tmp; |
| 577 |
while (j > i) { |
| 578 |
tmp = array[j]; |
| 579 |
array[j] = array[i]; |
| 580 |
array[i] = tmp; |
| 581 |
j--; |
| 582 |
i++; |
| 583 |
} |
| 584 |
} |
| 585 |
|
| 586 |
public static double[] extractUnique(double[] array){ |
| 587 |
Set<Double> tmp = new LinkedHashSet<Double>(); |
| 588 |
for (Double each : array) { |
| 589 |
tmp.add(each); |
| 590 |
} |
| 591 |
double [] output = new double[tmp.size()]; |
| 592 |
int i = 0; |
| 593 |
for (Double each : tmp) { |
| 594 |
output[i++] = each; |
| 595 |
} |
| 596 |
return output; |
| 597 |
} |
| 598 |
|
| 599 |
public History setUpHistory(String historyString, int nodeState, int parentNodeState, double timeLow, double timeUp){ |
| 600 |
double[] heights; |
| 601 |
String[] states; |
| 602 |
boolean mismatch = false; |
| 603 |
if (historyString.equals("{}")){ |
| 604 |
heights = new double[]{timeUp,timeLow}; |
| 605 |
states = new String[]{getState(nodeState)}; |
| 606 |
|
| 607 |
} else { |
| 608 |
List<String> returnList = new ArrayList<String>(); |
| 609 |
StringTokenizer st = new StringTokenizer(historyString, "},{"); |
| 610 |
while (st.hasMoreTokens()) { |
| 611 |
String test = st.nextToken(); |
| 612 |
|
| 613 |
returnList.add(test); |
| 614 |
|
| 615 |
} |
| 616 |
|
| 617 |
int numberOfJumps = returnList.size()/NUMBER_OF_HISTORY_ENTRIES; |
| 618 |
String[][] jumpStrings = new String[numberOfJumps][NUMBER_OF_HISTORY_ENTRIES]; |
| 619 |
for (int a = 0; a < numberOfJumps; a++){ |
| 620 |
jumpStrings[a][0] = returnList.get(a*NUMBER_OF_HISTORY_ENTRIES); |
| 621 |
jumpStrings[a][1] = returnList.get(a*NUMBER_OF_HISTORY_ENTRIES + 1); |
| 622 |
jumpStrings[a][2] = returnList.get(a*NUMBER_OF_HISTORY_ENTRIES + 2); |
| 623 |
} |
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
heights = new double[numberOfJumps+2]; |
| 628 |
states = new String[numberOfJumps+1]; |
| 629 |
for (int b = 0; b < numberOfJumps; b++){ |
| 630 |
states[b] = jumpStrings[b][1]; |
| 631 |
heights[b + 1] = Double.valueOf(jumpStrings[b][0]); |
| 632 |
} |
| 633 |
|
| 634 |
|
| 635 |
if (!jumpStrings[0][1].equals(getState(parentNodeState))){ |
| 636 |
|
| 637 |
System.err.println("mismatch in jump history and parent node state, continuous diffusion statistic will return NaN"); |
| 638 |
mismatch = true; |
| 639 |
|
| 640 |
} |
| 641 |
|
| 642 |
|
| 643 |
states[numberOfJumps] = jumpStrings[numberOfJumps-1][2]; |
| 644 |
if (!jumpStrings[numberOfJumps-1][2].equals(getState(nodeState))){ |
| 645 |
|
| 646 |
|
| 647 |
|
| 648 |
System.err.println("mismatch in jump history and node state, continuous diffusion statistic will return NaN"); |
| 649 |
mismatch = true; |
| 650 |
|
| 651 |
} |
| 652 |
|
| 653 |
heights[0] = timeUp; |
| 654 |
heights[numberOfJumps+1] = timeLow; |
| 655 |
|
| 656 |
} |
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
return new History(heights,states,mismatch); |
| 663 |
} |
| 664 |
|
| 665 |
private String getState(int stateInt){ |
| 666 |
String returnString = null; |
| 667 |
try{ |
| 668 |
returnString = markovJumpLikelihood.formattedState(new int[] {stateInt}).replaceAll("\"",""); |
| 669 |
} catch (IndexOutOfBoundsException iobe) { |
| 670 |
System.err.println("no state found for int = "+stateInt+"..."); |
| 671 |
System.exit(-1); |
| 672 |
} |
| 673 |
return returnString; |
| 674 |
} |
| 675 |
|
| 676 |
public double[] getStateTimeAndDistanceFromRoot(MutableTreeModel tree, NodeRef node, double timeLow, AbstractMultivariateTraitLikelihood traitLikelihood, String traitName, double[] traitLow, double[] precision, BranchRateModel branchRates, boolean useGreatCircleDistance){ |
| 677 |
|
| 678 |
NodeRef nodeOfInterest = node; |
| 679 |
|
| 680 |
double[] timeDistance = new double[]{0,0}; |
| 681 |
|
| 682 |
double[] rootTrait = traitLikelihood.getTraitForNode(tree, tree.getRoot(), traitName); |
| 683 |
|
| 684 |
int counter = 0; |
| 685 |
while (nodeOfInterest != tree.getRoot()){ |
| 686 |
NodeRef parentNode = tree.getParent(nodeOfInterest); |
| 687 |
History history = setUpHistory(markovJumpLikelihood.getHistoryForNode(tree,nodeOfInterest,SITE),markovJumpLikelihood.getStatesForNode(tree,nodeOfInterest)[SITE],markovJumpLikelihood.getStatesForNode(tree,parentNode)[SITE],tree.getNodeHeight(nodeOfInterest),tree.getNodeHeight(parentNode)); |
| 688 |
if (counter == 0){ |
| 689 |
if (timeLow > tree.getNodeHeight(nodeOfInterest)){ |
| 690 |
history.truncateLower(timeLow); |
| 691 |
} |
| 692 |
} |
| 693 |
double rate = (branchRates != null ? branchRates.getBranchRate(tree, nodeOfInterest) : 1.0); |
| 694 |
double[] parentTrait = traitLikelihood.getTraitForNode(tree, parentNode, traitName); |
| 695 |
double[] nodeTrait = traitLow; |
| 696 |
if (counter > 0){ |
| 697 |
nodeTrait = traitLikelihood.getTraitForNode(tree, nodeOfInterest, traitName); |
| 698 |
} |
| 699 |
history.setTraitsforHeights(parentTrait, nodeTrait, precision, rate, trueNoise); |
| 700 |
|
| 701 |
timeDistance[0] += history.getStateTime(stateString); |
| 702 |
|
| 703 |
if (useGreatCircleDistance){ |
| 704 |
timeDistance[1] += history.getStateDifferenceInGreatCircleDistanceFromRoot(stateString,rootTrait); |
| 705 |
} else { |
| 706 |
timeDistance[1] += history.getStateDifferenceInNativeDistanceFromRoot(stateString,rootTrait); |
| 707 |
} |
| 708 |
|
| 709 |
nodeOfInterest = tree.getParent(nodeOfInterest); |
| 710 |
counter++; |
| 711 |
} |
| 712 |
|
| 713 |
return timeDistance; |
| 714 |
} |
| 715 |
|
| 716 |
public double[] getTimeAndDistanceFromRoot(MutableTreeModel tree, NodeRef node, double timeLow, AbstractMultivariateTraitLikelihood traitLikelihood, String traitName, double[] traitLow, boolean useGreatCircleDistance){ |
| 717 |
|
| 718 |
NodeRef nodeOfInterest = node; |
| 719 |
double[] timeDistance = new double[]{0,0}; |
| 720 |
|
| 721 |
double[] rootTrait = traitLikelihood.getTraitForNode(tree, tree.getRoot(), traitName); |
| 722 |
|
| 723 |
int counter = 0; |
| 724 |
while (nodeOfInterest != tree.getRoot()){ |
| 725 |
NodeRef parentNode = tree.getParent(nodeOfInterest); |
| 726 |
double[] parentTrait = traitLikelihood.getTraitForNode(tree, parentNode, traitName); |
| 727 |
double[] nodeTrait = traitLow; |
| 728 |
double nodeHeight = timeLow; |
| 729 |
if (counter > 0){ |
| 730 |
nodeTrait = traitLikelihood.getTraitForNode(tree, nodeOfInterest, traitName); |
| 731 |
nodeHeight = tree.getNodeHeight(nodeOfInterest); |
| 732 |
} |
| 733 |
|
| 734 |
timeDistance[0] += tree.getNodeHeight(parentNode) - nodeHeight; |
| 735 |
|
| 736 |
if (useGreatCircleDistance){ |
| 737 |
timeDistance[1] += getGreatCircleDistance(nodeTrait, rootTrait) - getGreatCircleDistance(parentTrait, rootTrait); |
| 738 |
} else { |
| 739 |
timeDistance[1] += getNativeDistance(nodeTrait,rootTrait) - getNativeDistance(parentTrait,rootTrait); |
| 740 |
} |
| 741 |
|
| 742 |
nodeOfInterest = tree.getParent(nodeOfInterest); |
| 743 |
counter++; |
| 744 |
} |
| 745 |
|
| 746 |
return timeDistance; |
| 747 |
} |
| 748 |
|
| 749 |
|
| 750 |
public boolean inClade(MutableTreeModel tree, NodeRef node, TaxonList taxonList) throws TreeUtils.MissingTaxonException { |
| 751 |
|
| 752 |
Set leafSubSet; |
| 753 |
leafSubSet = TreeUtils.getLeavesForTaxa(tree, taxonList); |
| 754 |
NodeRef mrca = TreeUtils.getCommonAncestorNode(tree, leafSubSet); |
| 755 |
Set mrcaLeafSet = TreeUtils.getDescendantLeaves(tree,mrca); |
| 756 |
|
| 757 |
Set nodeLeafSet = TreeUtils.getDescendantLeaves(tree,node); |
| 758 |
|
| 759 |
if (!nodeLeafSet.isEmpty()){ |
| 760 |
nodeLeafSet.removeAll(mrcaLeafSet); |
| 761 |
} |
| 762 |
|
| 763 |
if (nodeLeafSet.isEmpty()){ |
| 764 |
return true; |
| 765 |
} else { |
| 766 |
|
| 767 |
} |
| 768 |
return false; |
| 769 |
} |
| 770 |
private static boolean onAncestralPathTaxa(Tree tree, NodeRef node, TaxonList taxonList) throws TreeUtils.MissingTaxonException { |
| 771 |
|
| 772 |
if (tree.isExternal(node)) return false; |
| 773 |
|
| 774 |
Set leafSet = TreeUtils.getDescendantLeaves(tree, node); |
| 775 |
int size = leafSet.size(); |
| 776 |
|
| 777 |
Set targetSet = TreeUtils.getLeavesForTaxa(tree, taxonList); |
| 778 |
leafSet.retainAll(targetSet); |
| 779 |
|
| 780 |
if (leafSet.size() > 0) { |
| 781 |
|
| 782 |
|
| 783 |
if (leafSet.size() == size) { |
| 784 |
|
| 785 |
Set superLeafSet = TreeUtils.getDescendantLeaves(tree, tree.getParent(node)); |
| 786 |
superLeafSet.removeAll(targetSet); |
| 787 |
|
| 788 |
|
| 789 |
return (superLeafSet.size() > 0); |
| 790 |
|
| 791 |
} else return true; |
| 792 |
|
| 793 |
} else return false; |
| 794 |
} |
| 795 |
|
| 796 |
|
| 797 |
private static boolean onAncestralPathTime(Tree tree, NodeRef node, double time) { |
| 798 |
|
| 799 |
double maxDescendentTime = 0; |
| 800 |
|
| 801 |
Set leafSet = TreeUtils.getExternalNodes(tree, node); |
| 802 |
Set nodeSet = TreeUtils.getExternalNodes(tree, node); |
| 803 |
|
| 804 |
Iterator iter = leafSet.iterator(); |
| 805 |
|
| 806 |
while (iter.hasNext()) { |
| 807 |
|
| 808 |
NodeRef currentNode = (NodeRef)iter.next(); |
| 809 |
|
| 810 |
while (tree.getNodeHeight(node) > tree.getNodeHeight(currentNode)) { |
| 811 |
|
| 812 |
if (!nodeSet.contains(currentNode)) { |
| 813 |
|
| 814 |
nodeSet.add(currentNode); |
| 815 |
} |
| 816 |
currentNode = tree.getParent(currentNode); |
| 817 |
} |
| 818 |
} |
| 819 |
|
| 820 |
Iterator nodeIter = nodeSet.iterator(); |
| 821 |
|
| 822 |
while (nodeIter.hasNext()) { |
| 823 |
NodeRef testNode = (NodeRef)nodeIter.next(); |
| 824 |
maxDescendentTime += tree.getBranchLength(testNode); |
| 825 |
} |
| 826 |
|
| 827 |
if (maxDescendentTime > time){ |
| 828 |
return true; |
| 829 |
} else { |
| 830 |
return false; |
| 831 |
} |
| 832 |
} |
| 833 |
|
| 834 |
private static double getAreaFrom2Dtraits(List<double[]> traits2D, double hpdValue){ |
| 835 |
|
| 836 |
boolean bandwidthlimit = true; |
| 837 |
|
| 838 |
double totalArea = 0; |
| 839 |
double[][] y = new double[2][traits2D.size()]; |
| 840 |
for (int a=0; a<traits2D.size(); a++){ |
| 841 |
double[] trait = traits2D.get(a); |
| 842 |
y[0][a]= trait[0]; |
| 843 |
y[1][a]= trait[1]; |
| 844 |
|
| 845 |
} |
| 846 |
|
| 847 |
ContourMaker contourMaker; |
| 848 |
contourMaker = new ContourWithSynder(y[0], y[1], bandwidthlimit); |
| 849 |
|
| 850 |
ContourPath[] paths = contourMaker.getContourPaths(hpdValue); |
| 851 |
int pathCounter = 1; |
| 852 |
for (ContourPath path : paths) { |
| 853 |
KMLCoordinates coords = new KMLCoordinates(path.getAllX(), path.getAllY()); |
| 854 |
Element testElement = new Element("test"); |
| 855 |
testElement.addContent(coords.toXML()); |
| 856 |
Polygon2D testPolygon = new Polygon2D(testElement); |
| 857 |
totalArea += testPolygon.calculateArea(); |
| 858 |
|
| 859 |
} |
| 860 |
|
| 861 |
return totalArea; |
| 862 |
} |
| 863 |
|
| 864 |
private static double[] convertDoubles(List<Double> doubles) { |
| 865 |
double[] ret = new double[doubles.size()]; |
| 866 |
Iterator<Double> iterator = doubles.iterator(); |
| 867 |
int i = 0; |
| 868 |
while(iterator.hasNext()) |
| 869 |
{ |
| 870 |
ret[i] = iterator.next(); |
| 871 |
i++; |
| 872 |
} |
| 873 |
return ret; |
| 874 |
} |
| 875 |
|
| 876 |
private static double getSpearmanRho(double[] data1, double[] data2){ |
| 877 |
|
| 878 |
double data1Ranks[] = new NaturalRanking().rank(data1); |
| 879 |
double data2Ranks[] = new NaturalRanking().rank(data2); |
| 880 |
|
| 881 |
int counter = 0; |
| 882 |
double d_i = 0; |
| 883 |
while(counter < data1Ranks.length){ |
| 884 |
d_i += Math.pow(data1Ranks[counter] - data2Ranks[counter], 2); |
| 885 |
counter ++; |
| 886 |
} |
| 887 |
return (1 - (6*d_i)/(data1Ranks.length*(Math.pow(data1Ranks.length,2) - 1))); |
| 888 |
} |
| 889 |
|
| 890 |
|
| 891 |
|
| 892 |
|
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
|
| 905 |
|
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
|
| 913 |
enum Mode { |
| 914 |
AVERAGE, |
| 915 |
WEIGHTED_AVERAGE, |
| 916 |
MEDIAN, |
| 917 |
COEFFICIENT_OF_VARIATION, |
| 918 |
SPEARMAN, |
| 919 |
CORRELATION_COEFFICIENT, |
| 920 |
R_SQUARED |
| 921 |
} |
| 922 |
|
| 923 |
enum summaryStatistic { |
| 924 |
TRAIT, |
| 925 |
TRAIT2DAREA, |
| 926 |
DIFFUSION_TIME, |
| 927 |
DIFFUSION_DISTANCE, |
| 928 |
DIFFUSION_RATE, |
| 929 |
DIFFUSION_COEFFICIENT, |
| 930 |
WAVEFRONT_DISTANCE, |
| 931 |
WAVEFRONT_DISTANCE_PHYLO, |
| 932 |
WAVEFRONT_RATE, |
| 933 |
DISTANCE_TIME_CORRELATION |
| 934 |
} |
| 935 |
|
| 936 |
enum BranchSet { |
| 937 |
ALL, |
| 938 |
CLADE, |
| 939 |
BACKBONE, |
| 940 |
} |
| 941 |
|
| 942 |
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { |
| 943 |
|
| 944 |
public String getParserName() { |
| 945 |
return CONTINUOUS_DIFFUSION_STATISTIC; |
| 946 |
} |
| 947 |
|
| 948 |
@Override |
| 949 |
public String[] getParserNames() { |
| 950 |
return new String[]{getParserName(), DIFFUSION_RATE_STATISTIC, TREE_DISPERSION_STATISTIC}; |
| 951 |
} |
| 952 |
|
| 953 |
public Object parseXMLObject(XMLObject xo) throws XMLParseException { |
| 954 |
|
| 955 |
String name = xo.getAttribute(NAME, xo.getId()); |
| 956 |
|
| 957 |
boolean greatCircleDistances = xo.getAttribute(USE_GREATCIRCLEDISTANCES, false); |
| 958 |
Mode statMode; |
| 959 |
String mode = xo.getAttribute(MODE, WEIGHTED_AVERAGE); |
| 960 |
|
| 961 |
if (mode.equals(AVERAGE)) { |
| 962 |
statMode = Mode.AVERAGE; |
| 963 |
} else if (mode.equals(MEDIAN)) { |
| 964 |
statMode = Mode.MEDIAN; |
| 965 |
} else if (mode.equals(COEFFICIENT_OF_VARIATION)) { |
| 966 |
statMode = Mode.COEFFICIENT_OF_VARIATION; |
| 967 |
} else if (mode.equals(WEIGHTED_AVERAGE)) { |
| 968 |
statMode = Mode.WEIGHTED_AVERAGE; |
| 969 |
} else if (mode.equals(SPEARMAN)) { |
| 970 |
statMode = Mode.SPEARMAN; |
| 971 |
} else if (mode.equals(CORRELATION_COEFFICIENT)) { |
| 972 |
statMode = Mode.CORRELATION_COEFFICIENT; |
| 973 |
} else if (mode.equals(R_SQUARED)) { |
| 974 |
statMode = Mode.R_SQUARED; |
| 975 |
} else { |
| 976 |
System.err.println("Unknown mode: "+mode+". Reverting to weighted average for "+name); |
| 977 |
statMode = Mode.WEIGHTED_AVERAGE; |
| 978 |
} |
| 979 |
|
| 980 |
final double upperHeight = xo.getAttribute(HEIGHT_UPPER, Double.MAX_VALUE); |
| 981 |
final double lowerHeight = xo.getAttribute(HEIGHT_LOWER, 0.0); |
| 982 |
|
| 983 |
double[] lowerHeights = null; |
| 984 |
if (xo.hasAttribute(HEIGHT_LOWER_SERIE)){ |
| 985 |
String lowerHeightsString = xo.getStringAttribute(HEIGHT_LOWER_SERIE); |
| 986 |
try { |
| 987 |
lowerHeights = parseVariableLengthDoubleArray(lowerHeightsString); |
| 988 |
} catch (Arguments.ArgumentException e) { |
| 989 |
System.err.println(name+": error reading " + HEIGHT_LOWER_SERIE); |
| 990 |
System.exit(1); |
| 991 |
} |
| 992 |
} |
| 993 |
|
| 994 |
boolean cumulative = xo.getAttribute(CUMULATIVE, false); |
| 995 |
|
| 996 |
boolean trueNoise = xo.getAttribute(NOISE, false); |
| 997 |
|
| 998 |
|
| 999 |
summaryStatistic summaryStat; |
| 1000 |
String statistic = xo.getAttribute(STATISTIC, DIFFUSION_RATE); |
| 1001 |
int dimension = 1; |
| 1002 |
if (statistic.equals(DIFFUSION_RATE)) { |
| 1003 |
summaryStat = summaryStatistic.DIFFUSION_RATE; |
| 1004 |
if (mode.equals(SPEARMAN) || mode.equals(R_SQUARED) || mode.equals(CORRELATION_COEFFICIENT)){ |
| 1005 |
System.err.println(name+": mode = "+mode+" ignored for "+DIFFUSION_TIME+", reverting to weighted average mode"); |
| 1006 |
statMode = Mode.WEIGHTED_AVERAGE; |
| 1007 |
} |
| 1008 |
} else if (statistic.equals(DIFFUSION_TIME)) { |
| 1009 |
summaryStat = summaryStatistic.DIFFUSION_TIME; |
| 1010 |
if (!mode.equals(WEIGHTED_AVERAGE)) { |
| 1011 |
System.err.println(name+": mode = "+mode+" ignored for "+DIFFUSION_TIME); |
| 1012 |
} |
| 1013 |
} else if (statistic.equals(DIFFUSION_DISTANCE)) { |
| 1014 |
summaryStat = summaryStatistic.DIFFUSION_DISTANCE; |
| 1015 |
if (!mode.equals(WEIGHTED_AVERAGE)) { |
| 1016 |
System.err.println(name+": mode = "+mode+" ignored for "+DIFFUSION_DISTANCE); |
| 1017 |
} |
| 1018 |
} else if (statistic.equals(DISTANCE_TIME_CORRELATION)) { |
| 1019 |
summaryStat = summaryStatistic.DISTANCE_TIME_CORRELATION; |
| 1020 |
if (mode.equals(AVERAGE) || mode.equals(WEIGHTED_AVERAGE) || mode.equals(COEFFICIENT_OF_VARIATION) || mode.equals(MEDIAN)){ |
| 1021 |
System.err.println(name+": mode = "+mode+" ignored for "+DISTANCE_TIME_CORRELATION+", reverting to correlation coefficient mode"); |
| 1022 |
statMode = Mode.CORRELATION_COEFFICIENT; |
| 1023 |
} |
| 1024 |
} else if (statistic.equals(WAVEFRONT_DISTANCE)) { |
| 1025 |
summaryStat = summaryStatistic.WAVEFRONT_DISTANCE; |
| 1026 |
if (!mode.equals(WEIGHTED_AVERAGE)) { |
| 1027 |
System.err.println(name + ": mode = " + mode + " ignored for " + WAVEFRONT_DISTANCE); |
| 1028 |
} |
| 1029 |
} else if (statistic.equals(WAVEFRONT_DISTANCE_PHYLO)) { |
| 1030 |
summaryStat = summaryStatistic.WAVEFRONT_DISTANCE_PHYLO; |
| 1031 |
if (!mode.equals(WEIGHTED_AVERAGE)) { |
| 1032 |
System.err.println(name + ": mode = " + mode + " ignored for " + WAVEFRONT_DISTANCE); |
| 1033 |
} |
| 1034 |
} else if (statistic.equals(TRAIT)) { |
| 1035 |
summaryStat = summaryStatistic.TRAIT; |
| 1036 |
if (mode.equals(WEIGHTED_AVERAGE)) { |
| 1037 |
System.err.println(name + ": mode = " + mode + " ignored for " + TRAIT + ", resorting to " + AVERAGE); |
| 1038 |
statMode = Mode.AVERAGE; |
| 1039 |
} |
| 1040 |
if (upperHeight < Double.MAX_VALUE) { |
| 1041 |
System.err.println(name + ": only " + HEIGHT_LOWER + " or " + HEIGHT_LOWER_SERIE + " are relevant for " + TRAIT); |
| 1042 |
} |
| 1043 |
dimension = xo.getAttribute(DIMENSION, 1); |
| 1044 |
if (dimension == 0) { |
| 1045 |
System.err.println(name + ": trait dimensions start from 1. Setting dimension to 1"); |
| 1046 |
dimension = 1; |
| 1047 |
} |
| 1048 |
if (cumulative) { |
| 1049 |
System.err.println(name + ": " + CUMULATIVE + " is ignored for " + TRAIT); |
| 1050 |
} |
| 1051 |
if (greatCircleDistances) { |
| 1052 |
System.err.println(name + ": " + USE_GREATCIRCLEDISTANCES + " is ignored for " + TRAIT); |
| 1053 |
} |
| 1054 |
} else if (statistic.equals(TRAIT2DAREA)) { |
| 1055 |
summaryStat = summaryStatistic.TRAIT2DAREA; |
| 1056 |
dimension = xo.getAttribute(DIMENSION, 2); |
| 1057 |
if (dimension != 2){ |
| 1058 |
System.err.println(name + ": trait dimension ("+dimension+") is not 2. Cannot calculate 2D area for the traits, 0's will be returned"); |
| 1059 |
} |
| 1060 |
} else if (statistic.equals(WAVEFRONT_RATE)) { |
| 1061 |
summaryStat = summaryStatistic.WAVEFRONT_RATE; |
| 1062 |
} else if (statistic.equals(DIFFUSION_COEFFICIENT)) { |
| 1063 |
summaryStat = summaryStatistic.DIFFUSION_COEFFICIENT; |
| 1064 |
} else if (statistic.equals(DISTANCE_TIME_CORRELATION)) { |
| 1065 |
summaryStat = summaryStatistic.DISTANCE_TIME_CORRELATION; |
| 1066 |
} else { |
| 1067 |
System.err.println(name+": unknown statistic: "+statistic+". Reverting to diffusion rate."); |
| 1068 |
summaryStat = summaryStatistic.DIFFUSION_RATE; |
| 1069 |
} |
| 1070 |
|
| 1071 |
BranchSet branchset; |
| 1072 |
String branchMode = xo.getAttribute(BRANCHSET, ALL); |
| 1073 |
if (branchMode.equals(CLADE)) { |
| 1074 |
branchset = BranchSet.CLADE; |
| 1075 |
} else if (branchMode.equals(BACKBONE)) { |
| 1076 |
branchset = BranchSet.BACKBONE; |
| 1077 |
} else if (branchMode.equals(ALL)) { |
| 1078 |
branchset = BranchSet.ALL; |
| 1079 |
} else { |
| 1080 |
System.err.println(name+": unknown branchset: "+branchMode+". Reverting to all branches."); |
| 1081 |
branchset = BranchSet.ALL; |
| 1082 |
} |
| 1083 |
|
| 1084 |
TaxonList taxonList = null; |
| 1085 |
double backboneTime = 0; |
| 1086 |
if (branchset.equals(BranchSet.CLADE)){ |
| 1087 |
taxonList = (TaxonList) xo.getChild(TaxonList.class); |
| 1088 |
if (taxonList==null){ |
| 1089 |
System.err.println("empty taxon list in continuousDiffusionStatistic despite 'clade' branchSet attribute"); |
| 1090 |
} |
| 1091 |
} else if (branchset.equals(BranchSet.BACKBONE)){ |
| 1092 |
taxonList = (TaxonList) xo.getChild(TaxonList.class); |
| 1093 |
if (xo.hasAttribute(BACKBONE_TIME)){ |
| 1094 |
backboneTime = xo.getAttribute(BACKBONE_TIME, 0.0); |
| 1095 |
if (taxonList!=null){ |
| 1096 |
System.err.println("both backbone time and taxon list provided for backbone definition in continuousDiffusionStatistic. Ignoring taxon list..."); |
| 1097 |
} |
| 1098 |
} else if (taxonList==null){ |
| 1099 |
System.err.println("empty taxon list and no backboneTime in continuousDiffusionStatistic despite 'backbone' branchSet attribute. Ignoring 'backbone' branchSet..."); |
| 1100 |
} |
| 1101 |
} else if (branchset.equals(BranchSet.ALL)){ |
| 1102 |
taxonList = (TaxonList) xo.getChild(TaxonList.class); |
| 1103 |
if (taxonList!=null){ |
| 1104 |
System.err.println("taxon list provided in continuousDiffusionStatistic but no 'clade' or 'backbone' branchSet attribute?? Ignoring taxon list..."); |
| 1105 |
} |
| 1106 |
if (xo.hasAttribute(BACKBONE_TIME)){ |
| 1107 |
System.err.println("backoneTime provided in continuousDiffusionStatistic but no 'backbone' branchSet attribute?? Ignoring backboneTime list..."); |
| 1108 |
} |
| 1109 |
} |
| 1110 |
|
| 1111 |
|
| 1112 |
String stateString = null; |
| 1113 |
if (xo.hasAttribute(DISCRETE_STATE)){ |
| 1114 |
stateString = xo.getStringAttribute(DISCRETE_STATE); |
| 1115 |
} |
| 1116 |
|
| 1117 |
List<AbstractMultivariateTraitLikelihood> traitLikelihoods = new ArrayList<AbstractMultivariateTraitLikelihood>(); |
| 1118 |
MarkovJumpsBeagleTreeLikelihood mjtl = null; |
| 1119 |
|
| 1120 |
for (int i = 0; i < xo.getChildCount(); i++) { |
| 1121 |
|
| 1122 |
if (xo.getChild(i) instanceof AbstractMultivariateTraitLikelihood) { |
| 1123 |
AbstractMultivariateTraitLikelihood amtl = (AbstractMultivariateTraitLikelihood) xo.getChild(i); |
| 1124 |
traitLikelihoods.add(amtl); |
| 1125 |
} |
| 1126 |
if (xo.getChild(i) instanceof MarkovJumpsBeagleTreeLikelihood) { |
| 1127 |
mjtl = (MarkovJumpsBeagleTreeLikelihood) xo.getChild(i); |
| 1128 |
} |
| 1129 |
} |
| 1130 |
|
| 1131 |
if (stateString == null && mjtl != null) { |
| 1132 |
System.err.println(name+": markovJumpsTreeLikelihood specified for state-specific summaries but no state string.. ignoring markovJumpsTreeLikelihood"); |
| 1133 |
mjtl = null; |
| 1134 |
} else if (stateString != null && mjtl == null){ |
| 1135 |
System.err.println(name+": state number provided for state-specific summaries but no markovJumpsTreeLikelihood specified.. ignoring state"); |
| 1136 |
stateString = null; |
| 1137 |
} else if (stateString != null && mjtl != null) { |
| 1138 |
if (statistic.equals(TRAIT)){ |
| 1139 |
System.err.println(name+": ignoring state-specific summary (for "+stateString+") for " + TRAIT+", resorting to overall summary"); |
| 1140 |
} else { |
| 1141 |
int stateInt = -1; |
| 1142 |
int counter = 0; |
| 1143 |
try{ |
| 1144 |
while (stateInt < 0) { |
| 1145 |
if (stateString.equalsIgnoreCase((mjtl.formattedState(new int[] {counter})).replaceAll("\"",""))) { |
| 1146 |
stateInt = counter; |
| 1147 |
System.out.println(name+": summarizing continuous diffusion statistic for state "+mjtl.formattedState(new int[] {counter})); |
| 1148 |
} |
| 1149 |
counter ++; |
| 1150 |
} |
| 1151 |
} catch (IndexOutOfBoundsException iobe) { |
| 1152 |
int states[] = new int[counter]; |
| 1153 |
for (int a = 0; a < states.length; a++){ |
| 1154 |
states[a] = a; |
| 1155 |
} |
| 1156 |
System.err.println(name+": state "+stateString+" not found among "+mjtl.formattedState(states)+ "... ignoring state"); |
| 1157 |
mjtl = null; |
| 1158 |
stateString = null; |
| 1159 |
} |
| 1160 |
} |
| 1161 |
} |
| 1162 |
|
| 1163 |
|
| 1164 |
|
| 1165 |
return new ContinuousDiffusionStatistic(name, traitLikelihoods, greatCircleDistances, statMode, summaryStat, upperHeight, lowerHeight, lowerHeights, cumulative, trueNoise, dimension, taxonList, branchset, backboneTime, stateString, mjtl); |
| 1166 |
} |
| 1167 |
|
| 1168 |
|
| 1169 |
|
| 1170 |
|
| 1171 |
|
| 1172 |
public String getParserDescription() { |
| 1173 |
return "A statistic that returns the average of the branch diffusion rates"; |
| 1174 |
} |
| 1175 |
|
| 1176 |
public Class getReturnType() { |
| 1177 |
return TreeStatistic.class; |
| 1178 |
} |
| 1179 |
|
| 1180 |
public XMLSyntaxRule[] getSyntaxRules() { |
| 1181 |
return rules; |
| 1182 |
} |
| 1183 |
|
| 1184 |
private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ |
| 1185 |
AttributeRule.newStringRule(NAME, true), |
| 1186 |
AttributeRule.newBooleanRule(USE_GREATCIRCLEDISTANCES, true), |
| 1187 |
AttributeRule.newStringRule(MODE, true), |
| 1188 |
AttributeRule.newStringRule(STATISTIC,true), |
| 1189 |
AttributeRule.newStringRule(DISCRETE_STATE,true), |
| 1190 |
AttributeRule.newDoubleRule(HEIGHT_UPPER, true), |
| 1191 |
AttributeRule.newDoubleRule(HEIGHT_LOWER, true), |
| 1192 |
AttributeRule.newStringRule(HEIGHT_LOWER_SERIE, true), |
| 1193 |
AttributeRule.newDoubleRule(DIMENSION, true), |
| 1194 |
AttributeRule.newBooleanRule(CUMULATIVE, true), |
| 1195 |
AttributeRule.newBooleanRule(NOISE, true), |
| 1196 |
AttributeRule.newStringRule(BRANCHSET, true), |
| 1197 |
new ElementRule(TaxonList.class,true), |
| 1198 |
new ElementRule(AbstractMultivariateTraitLikelihood.class, 1, Integer.MAX_VALUE), |
| 1199 |
new ElementRule(MarkovJumpsBeagleTreeLikelihood.class, true) |
| 1200 |
}; |
| 1201 |
}; |
| 1202 |
|
| 1203 |
private boolean useGreatCircleDistances; |
| 1204 |
private List<AbstractMultivariateTraitLikelihood> traitLikelihoods; |
| 1205 |
private MarkovJumpsBeagleTreeLikelihood markovJumpLikelihood; |
| 1206 |
|
| 1207 |
private String stateString; |
| 1208 |
private Mode summaryMode; |
| 1209 |
private summaryStatistic summaryStat; |
| 1210 |
private double heightUpper; |
| 1211 |
private double[] heightLowers; |
| 1212 |
private boolean cumulative; |
| 1213 |
private boolean trueNoise; |
| 1214 |
private int dimension; |
| 1215 |
private TaxonList taxonList; |
| 1216 |
private BranchSet branchset; |
| 1217 |
private double backboneTime; |
| 1218 |
|
| 1219 |
private class History { |
| 1220 |
|
| 1221 |
private double[] historyHeights; |
| 1222 |
private String[] historyStates; |
| 1223 |
private double[][] historyTraits; |
| 1224 |
private boolean mismatch; |
| 1225 |
|
| 1226 |
public History(double historyHeights[], String historyStates[], boolean mismatch) { |
| 1227 |
this.historyHeights = historyHeights; |
| 1228 |
this.historyStates = historyStates; |
| 1229 |
this.mismatch = mismatch; |
| 1230 |
} |
| 1231 |
|
| 1232 |
public void truncateUpper(double time) { |
| 1233 |
int cutFrom = -1; |
| 1234 |
for (int a = 0; a < (historyHeights.length - 1); a++) { |
| 1235 |
if ((time < historyHeights[a]) && (time > historyHeights[a+1])) { |
| 1236 |
cutFrom = a; |
| 1237 |
} |
| 1238 |
} |
| 1239 |
|
| 1240 |
if (cutFrom < 0){ |
| 1241 |
System.err.println("no upper truncation of discrete trait history on branch possible"); |
| 1242 |
System.exit(0); |
| 1243 |
} |
| 1244 |
|
| 1245 |
double[] tempHeights = new double[historyHeights.length - cutFrom]; |
| 1246 |
String[] tempStates = new String[historyStates.length - cutFrom]; |
| 1247 |
|
| 1248 |
tempHeights = Arrays.copyOfRange(historyHeights, cutFrom, historyHeights.length); |
| 1249 |
tempHeights[0] = time; |
| 1250 |
|
| 1251 |
tempStates = Arrays.copyOfRange(historyStates, cutFrom, historyStates.length); |
| 1252 |
|
| 1253 |
historyHeights = tempHeights; |
| 1254 |
historyStates = tempStates; |
| 1255 |
} |
| 1256 |
|
| 1257 |
public void truncateLower (double time) { |
| 1258 |
int cutTo = -1; |
| 1259 |
|
| 1260 |
for (int a = (historyHeights.length - 1); a > 0; a--) { |
| 1261 |
if ((time > historyHeights[a]) && (time < historyHeights[a - 1])) { |
| 1262 |
cutTo = a; |
| 1263 |
} |
| 1264 |
} |
| 1265 |
|
| 1266 |
if (cutTo < 0){ |
| 1267 |
System.err.println("no lower truncation of discrete trait history on branch possible"); |
| 1268 |
System.exit(0); |
| 1269 |
} |
| 1270 |
|
| 1271 |
double[] tempHeights = new double[cutTo + 1]; |
| 1272 |
String[] tempStates = new String[cutTo]; |
| 1273 |
|
| 1274 |
tempHeights = Arrays.copyOfRange(historyHeights, 0, cutTo + 1); |
| 1275 |
tempHeights[(tempHeights.length-1)] = time; |
| 1276 |
|
| 1277 |
tempStates = Arrays.copyOfRange(historyStates, 0, cutTo); |
| 1278 |
|
| 1279 |
historyHeights = tempHeights; |
| 1280 |
historyStates = tempStates; |
| 1281 |
} |
| 1282 |
|
| 1283 |
public double getStateTime(String state){ |
| 1284 |
double time = 0; |
| 1285 |
for (int x = 0; x < historyStates.length; x++){ |
| 1286 |
if (state.equals(historyStates[x])){ |
| 1287 |
time += (historyHeights[x] - historyHeights[x+1]); |
| 1288 |
} |
| 1289 |
} |
| 1290 |
return time; |
| 1291 |
} |
| 1292 |
|
| 1293 |
public boolean returnMismatch(){ |
| 1294 |
return mismatch; |
| 1295 |
} |
| 1296 |
|
| 1297 |
private void setTraitsforHeights(double[] traitUp, double[] traitLow, double[] precisionArray, double rate, boolean trueNoise){ |
| 1298 |
historyTraits = new double[historyHeights.length][2]; |
| 1299 |
for (int x = 0; x < historyHeights.length; x++){ |
| 1300 |
if(x == 0){ |
| 1301 |
historyTraits[x] = traitUp; |
| 1302 |
} else if (x == (historyTraits.length -1)) { |
| 1303 |
historyTraits[x] = traitLow; |
| 1304 |
} else { |
| 1305 |
historyTraits[x] = imputeValue(traitUp, traitLow, historyHeights[x], historyHeights[(historyHeights.length -1)], historyHeights[0], precisionArray, rate, trueNoise); |
| 1306 |
} |
| 1307 |
|
| 1308 |
} |
| 1309 |
} |
| 1310 |
|
| 1311 |
public double getStateGreatCircleDistance(String state){ |
| 1312 |
double distance = 0; |
| 1313 |
for (int x = 0; x < historyStates.length; x++){ |
| 1314 |
if (state.equals(historyStates[x])){ |
| 1315 |
distance += getGreatCircleDistance(historyTraits[x],historyTraits[x+1]); |
| 1316 |
} |
| 1317 |
} |
| 1318 |
return distance; |
| 1319 |
} |
| 1320 |
|
| 1321 |
public double getStateDifferenceInGreatCircleDistanceFromRoot(String state, double[] rootTrait){ |
| 1322 |
double distance = 0; |
| 1323 |
for (int x = 0; x < historyStates.length; x++){ |
| 1324 |
if (state.equals(historyStates[x])){ |
| 1325 |
distance += (getGreatCircleDistance(historyTraits[x+1],rootTrait) - getGreatCircleDistance(historyTraits[x],rootTrait)); |
| 1326 |
} |
| 1327 |
} |
| 1328 |
return distance; |
| 1329 |
} |
| 1330 |
|
| 1331 |
public double getStateNativeDistance(String state){ |
| 1332 |
double distance = 0; |
| 1333 |
for (int x = 0; x < historyStates.length; x++){ |
| 1334 |
if (state.equals(historyStates[x])){ |
| 1335 |
distance += getNativeDistance(historyTraits[x],historyTraits[x+1]); |
| 1336 |
} |
| 1337 |
} |
| 1338 |
return distance; |
| 1339 |
} |
| 1340 |
|
| 1341 |
public double getStateDifferenceInNativeDistanceFromRoot(String state, double[] rootTrait){ |
| 1342 |
double distance = 0; |
| 1343 |
for (int x = 0; x < historyStates.length; x++){ |
| 1344 |
if (state.equals(historyStates[x])){ |
| 1345 |
distance += (getNativeDistance(historyTraits[x+1],rootTrait) - getNativeDistance(historyTraits[x],rootTrait)); |
| 1346 |
} |
| 1347 |
} |
| 1348 |
return distance; |
| 1349 |
} |
| 1350 |
|
| 1351 |
} |
| 1352 |
|
| 1353 |
} |
| 1354 |
|