| 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.app.tools; |
| 27 |
|
| 28 |
import dr.app.beast.BeastVersion; |
| 29 |
import dr.app.util.Arguments; |
| 30 |
import dr.evolution.io.Importer; |
| 31 |
import dr.evolution.io.NewickImporter; |
| 32 |
import dr.evolution.io.NexusImporter; |
| 33 |
import dr.evolution.io.TreeImporter; |
| 34 |
import dr.evolution.tree.NodeRef; |
| 35 |
import dr.evolution.tree.Tree; |
| 36 |
import dr.evolution.tree.TreeUtils; |
| 37 |
import dr.geo.color.ChannelColorScheme; |
| 38 |
import dr.geo.color.ColorScheme; |
| 39 |
import dr.geo.math.SphericalPolarCoordinates; |
| 40 |
import dr.math.distributions.MultivariateNormalDistribution; |
| 41 |
import dr.util.TIFFWriter; |
| 42 |
import dr.util.Version; |
| 43 |
|
| 44 |
import javax.imageio.ImageIO; |
| 45 |
import java.io.*; |
| 46 |
import java.util.*; |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
public class Branch2dRateToGrid { |
| 56 |
|
| 57 |
public static final boolean GREATCIRCLEDISTANCE = true; |
| 58 |
public static final String PRECISION_STRING = "precision"; |
| 59 |
public static final String BURNIN = "burnin"; |
| 60 |
public static final String SKIP = "skip"; |
| 61 |
public static final String RATE_ATTRIBUTE = "rateAttribute"; |
| 62 |
public static final String TRAIT = "trait"; |
| 63 |
public static final String HELP = "help"; |
| 64 |
public static final String TRAIT_NOISE = "traitNoise"; |
| 65 |
public static final String RATE_NOISE = "rateNoise"; |
| 66 |
public static final String FORMAT = "format"; |
| 67 |
public static final String NORMALIZATION = "normalization"; |
| 68 |
public static final String LATMAX = "latmax"; |
| 69 |
public static final String LATMIN = "latmin"; |
| 70 |
public static final String LONGMAX = "longmax"; |
| 71 |
public static final String LONGMIN = "longmin"; |
| 72 |
public static final String[] falseTrue = {"false", "true"}; |
| 73 |
public static final String GRIDXCELLS = "gridXcells"; |
| 74 |
public static final String GRIDYCELLS = "gridYcells"; |
| 75 |
public static final String MAXPATHLENGTH = "maxPathLength"; |
| 76 |
public static final String sep = "\t"; |
| 77 |
|
| 78 |
public static final String SLICE_TIMES = "sliceTimes"; |
| 79 |
public static final String SLICE_HEIGHTS = "sliceHeights"; |
| 80 |
public static final String SLICE_FILE_HEIGHTS = "sliceFileHeights"; |
| 81 |
public static final String SLICE_FILE_TIMES = "sliceFileTimes"; |
| 82 |
public static final String SLICE_COUNT = "sliceCount"; |
| 83 |
public static final String START_TIME = "startTime"; |
| 84 |
public static final String STDEVS = "stdevs"; |
| 85 |
public static final String CUTOFF = "cutoff"; |
| 86 |
public static final String DISCRETE_TRAIT_NAME = "discreteTraitName"; |
| 87 |
public static final String DISCRETE_TRAIT_STATES = "discreteTraitStates"; |
| 88 |
public static final String HISTORY_ANNOTATION = "history"; |
| 89 |
|
| 90 |
|
| 91 |
public Branch2dRateToGrid(String treeFileName, int burnin, int skipEvery, |
| 92 |
String traitString, boolean traitNoise, boolean rateNoise, String rateString, double maxPathLength, Normalization normalize, |
| 93 |
double latMin, double latMax, double longMin, double longMax, int gridXcells, int gridYcells, double[] sliceHeights, boolean getStdevs, |
| 94 |
double posteriorCutoff, String discreteTrait, String[] discreteTraitStates, String historyAnnotation) { |
| 95 |
|
| 96 |
|
| 97 |
this.latMin = latMin; |
| 98 |
this.latMax = latMax; |
| 99 |
this.longMin = longMin; |
| 100 |
this.longMax = longMax; |
| 101 |
this.gridXcells = gridXcells; |
| 102 |
this.gridYcells = gridYcells; |
| 103 |
|
| 104 |
cellXWidth = (longMax - longMin) / gridXcells; |
| 105 |
cellYHeight = (latMax - latMin) / gridYcells; |
| 106 |
|
| 107 |
rateAttributeString = rateString; |
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
sliceCount = sliceHeights.length; |
| 112 |
|
| 113 |
if (sliceCount > 1) { |
| 114 |
sliceHeights = extractUnique(sliceHeights); |
| 115 |
Arrays.sort(sliceHeights); |
| 116 |
reverse(sliceHeights); |
| 117 |
} |
| 118 |
|
| 119 |
this.sliceHeights = sliceHeights; |
| 120 |
this.getStdevs = getStdevs; |
| 121 |
|
| 122 |
if (discreteTrait != null) { |
| 123 |
this.discreteTrait = discreteTrait; |
| 124 |
this.discreteTraitStates = discreteTraitStates; |
| 125 |
this.historyAnnotation = historyAnnotation; |
| 126 |
summarizeByDiscreteTrait = true; |
| 127 |
} |
| 128 |
|
| 129 |
densities = new double[sliceCount][gridXcells][gridYcells]; |
| 130 |
if (summarizeByDiscreteTrait) { |
| 131 |
densitiesByDTrait = new double[sliceCount][discreteTraitStates.length][gridXcells][gridYcells]; |
| 132 |
} |
| 133 |
rates = new double[sliceCount][gridXcells][gridYcells]; |
| 134 |
if (getStdevs) { |
| 135 |
stdevs = new double[sliceCount][gridXcells][gridYcells]; |
| 136 |
} |
| 137 |
|
| 138 |
this.posteriorCutoff = posteriorCutoff; |
| 139 |
|
| 140 |
try { |
| 141 |
readAndAnalyzeTrees(treeFileName, burnin, skipEvery, traitString, traitNoise, rateNoise, maxPathLength, normalize, false); |
| 142 |
summarizeMeanRates(); |
| 143 |
if (getStdevs) { |
| 144 |
|
| 145 |
readAndAnalyzeTrees(treeFileName, burnin, skipEvery, traitString, traitNoise, rateNoise, maxPathLength, normalize, true); |
| 146 |
summarizeStdevs(); |
| 147 |
} |
| 148 |
} catch (IOException e) { |
| 149 |
System.err.println("Error reading file: " + treeFileName); |
| 150 |
System.exit(-1); |
| 151 |
} catch (Importer.ImportException e) { |
| 152 |
System.err.println("Error parsing trees in file: " + treeFileName); |
| 153 |
System.exit(-1); |
| 154 |
} |
| 155 |
|
| 156 |
progressStream.println(treesRead + " trees read."); |
| 157 |
progressStream.println(treesAnalyzed + " trees analyzed."); |
| 158 |
|
| 159 |
} |
| 160 |
|
| 161 |
|
| 162 |
private void readAndAnalyzeTrees(String treeFileName, int burnin, int skipEvery, |
| 163 |
String traitString, boolean traitNoise, boolean rateNoise, double maxPathLength, Normalization normalize, |
| 164 |
boolean getStdev) |
| 165 |
throws IOException, Importer.ImportException { |
| 166 |
|
| 167 |
int totalTrees = 10000; |
| 168 |
int totalStars = 0; |
| 169 |
|
| 170 |
if (!printedBar) { |
| 171 |
progressStream.println("Reading and analyzing trees (bar assumes 10,000 trees)..."); |
| 172 |
progressStream.println("0 25 50 75 100"); |
| 173 |
progressStream.println("|--------------|--------------|--------------|--------------|"); |
| 174 |
printedBar = true; |
| 175 |
} |
| 176 |
|
| 177 |
if (getStdev) { |
| 178 |
progressStream.println("summarizing standard deviations"); |
| 179 |
} |
| 180 |
|
| 181 |
int stepSize = totalTrees / 60; |
| 182 |
if (stepSize < 1) stepSize = 1; |
| 183 |
|
| 184 |
BufferedReader reader1 = new BufferedReader(new FileReader(treeFileName)); |
| 185 |
|
| 186 |
String line1 = reader1.readLine(); |
| 187 |
TreeImporter importer1; |
| 188 |
if (line1.toUpperCase().startsWith("#NEXUS")) { |
| 189 |
importer1 = new NexusImporter(new FileReader(treeFileName)); |
| 190 |
} else { |
| 191 |
importer1 = new NewickImporter(new FileReader(treeFileName)); |
| 192 |
} |
| 193 |
totalTrees = 0; |
| 194 |
|
| 195 |
while (importer1.hasTree()) { |
| 196 |
Tree treeTime = importer1.importNextTree(); |
| 197 |
if (totalTrees % skipEvery == 0) { |
| 198 |
treesRead++; |
| 199 |
if (totalTrees >= burnin) { |
| 200 |
analyzeTree(treeTime, traitString, traitNoise, rateNoise, maxPathLength, normalize, getStdev); |
| 201 |
} |
| 202 |
} |
| 203 |
if (totalTrees > 0 && totalTrees % stepSize == 0) { |
| 204 |
progressStream.print("*"); |
| 205 |
totalStars++; |
| 206 |
if (totalStars % 61 == 0) |
| 207 |
progressStream.print("\n"); |
| 208 |
progressStream.flush(); |
| 209 |
} |
| 210 |
totalTrees++; |
| 211 |
} |
| 212 |
progressStream.print("\n"); |
| 213 |
} |
| 214 |
|
| 215 |
private void analyzeTree(Tree treeTime, String traitString, boolean traitNoise, boolean rateNoise, double maxPathLength, Normalization normalize, boolean getStdev) { |
| 216 |
|
| 217 |
double[][] precision = null; |
| 218 |
|
| 219 |
Object o = treeTime.getAttribute(PRECISION_STRING); |
| 220 |
double treeNormalization = 1; |
| 221 |
if (normalize == Normalization.LENGTH) { |
| 222 |
treeNormalization = TreeUtils.getTreeLength(treeTime, treeTime.getRoot()); |
| 223 |
} else if (normalize == Normalization.HEIGHT) { |
| 224 |
treeNormalization = treeTime.getNodeHeight(treeTime.getRoot()); |
| 225 |
} |
| 226 |
|
| 227 |
if (o != null) { |
| 228 |
Object[] array = (Object[]) o; |
| 229 |
int dim = (int) Math.sqrt(1 + 8 * array.length) / 2; |
| 230 |
precision = new double[dim][dim]; |
| 231 |
int c = 0; |
| 232 |
for (int i = 0; i < dim; i++) { |
| 233 |
for (int j = i; j < dim; j++) { |
| 234 |
precision[j][i] = precision[i][j] = ((Double) array[c++]) * treeNormalization; |
| 235 |
} |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
treeLengths.add(TreeUtils.getTreeLength(treeTime, treeTime.getRoot())); |
| 240 |
|
| 241 |
for (int x = 0; x < treeTime.getNodeCount(); x++) { |
| 242 |
|
| 243 |
NodeRef node = treeTime.getNode(x); |
| 244 |
|
| 245 |
if (!(treeTime.isRoot(node))) { |
| 246 |
|
| 247 |
double nodeHeight = treeTime.getNodeHeight(node); |
| 248 |
double parentHeight = treeTime.getNodeHeight(treeTime.getParent(node)); |
| 249 |
Object tmpNodeTrait = treeTime.getNodeAttribute(node, traitString); |
| 250 |
if (tmpNodeTrait == null) { |
| 251 |
System.err.println("Trait '" + traitString + "' not found on branch."); |
| 252 |
System.exit(-1); |
| 253 |
} |
| 254 |
Trait nodeTrait = new Trait(tmpNodeTrait); |
| 255 |
|
| 256 |
Object tmpParentNodeTrait = treeTime.getNodeAttribute(treeTime.getParent(node), traitString); |
| 257 |
if (tmpParentNodeTrait == null) { |
| 258 |
System.err.println("Trait '" + traitString + "' not found on branch."); |
| 259 |
System.exit(-1); |
| 260 |
} |
| 261 |
Trait parentNodeTrait = new Trait(tmpParentNodeTrait); |
| 262 |
|
| 263 |
double rate = 1; |
| 264 |
if (!rateNoise) { |
| 265 |
if (GREATCIRCLEDISTANCE) { |
| 266 |
rate = getGeographicalDistance(nodeTrait.getValue(), parentNodeTrait.getValue()) / (parentHeight - nodeHeight); |
| 267 |
} else { |
| 268 |
rate = getNativeDistance(nodeTrait.getValue(), parentNodeTrait.getValue()) / (parentHeight - nodeHeight); |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
|
| 273 |
History history = null; |
| 274 |
if (summarizeByDiscreteTrait) { |
| 275 |
Object historyObject = treeTime.getNodeAttribute(node, historyAnnotation); |
| 276 |
String nodeState = ((String) treeTime.getNodeAttribute(node, discreteTrait)).replaceAll("\"", ""); |
| 277 |
String parentNodeState = ((String) treeTime.getNodeAttribute(treeTime.getParent(node), discreteTrait)).replaceAll("\"", ""); |
| 278 |
|
| 279 |
if (!parentNodeState.equals(nodeState)) { |
| 280 |
if (historyObject instanceof Object[]) { |
| 281 |
Object[] histories = (Object[]) historyObject; |
| 282 |
history = setUpHistory(histories, nodeState, parentNodeState, nodeHeight, parentHeight); |
| 283 |
} else { |
| 284 |
System.err.println("History '" + historyAnnotation + "' not found on a branch that has different node and parent node states."); |
| 285 |
System.exit(-1); |
| 286 |
} |
| 287 |
} else { |
| 288 |
history = setUpHistory(nodeState, nodeHeight, parentHeight); |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
|
| 293 |
boolean inSliceInterval = false; |
| 294 |
|
| 295 |
for (int i = 0; i < sliceCount; i++) { |
| 296 |
double heightAbove = Double.MAX_VALUE; |
| 297 |
if (i > 0) { |
| 298 |
heightAbove = sliceHeights[i - 1]; |
| 299 |
} |
| 300 |
|
| 301 |
|
| 302 |
if ((nodeHeight > sliceHeights[i]) && (parentHeight < heightAbove)) { |
| 303 |
inSliceInterval = true; |
| 304 |
} |
| 305 |
if ((parentHeight > heightAbove) && (nodeHeight < heightAbove)) { |
| 306 |
inSliceInterval = true; |
| 307 |
|
| 308 |
Double rateAttribute = (Double) treeTime.getNodeAttribute(node, rateAttributeString); |
| 309 |
double diffusionRate = 1.0; |
| 310 |
if (rateAttribute != null) { |
| 311 |
diffusionRate = rateAttribute; |
| 312 |
if (outputRateWarning) { |
| 313 |
progressStream.println("Warning: using " + rateAttributeString + " as rate attribute during imputation!"); |
| 314 |
outputRateWarning = false; |
| 315 |
} |
| 316 |
} |
| 317 |
if (traitNoise && precision == null) { |
| 318 |
progressStream.println("Error: not precision available for imputation with correct noise!"); |
| 319 |
System.exit(-1); |
| 320 |
} |
| 321 |
parentNodeTrait = imputeValue(nodeTrait, parentNodeTrait, heightAbove, nodeHeight, parentHeight, precision, diffusionRate, traitNoise); |
| 322 |
parentHeight = heightAbove; |
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
|
| 329 |
} |
| 330 |
if ((nodeHeight < sliceHeights[i]) && (parentHeight > sliceHeights[i])) { |
| 331 |
inSliceInterval = true; |
| 332 |
|
| 333 |
Double rateAttribute = (Double) treeTime.getNodeAttribute(node, rateAttributeString); |
| 334 |
double diffusionRate = 1.0; |
| 335 |
if (rateAttribute != null) { |
| 336 |
diffusionRate = rateAttribute; |
| 337 |
if (outputRateWarning) { |
| 338 |
progressStream.println("Warning: using " + rateAttributeString + " as rate attribute during imputation!"); |
| 339 |
outputRateWarning = false; |
| 340 |
} |
| 341 |
} |
| 342 |
if (traitNoise && precision == null) { |
| 343 |
progressStream.println("Error: no precision available for imputation with correct noise!"); |
| 344 |
System.exit(-1); |
| 345 |
} |
| 346 |
nodeTrait = imputeValue(nodeTrait, parentNodeTrait, heightAbove, nodeHeight, parentHeight, precision, diffusionRate, traitNoise); |
| 347 |
nodeHeight = sliceHeights[i]; |
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
} |
| 354 |
|
| 355 |
|
| 356 |
if ((isInGrid(nodeTrait.getValue())) && (isInGrid(parentNodeTrait.getValue())) && inSliceInterval) { |
| 357 |
|
| 358 |
|
| 359 |
double branchLength = parentHeight - nodeHeight; |
| 360 |
while (branchLength > maxPathLength) { |
| 361 |
|
| 362 |
Double rateAttribute = (Double) treeTime.getNodeAttribute(node, rateAttributeString); |
| 363 |
double diffusionRate = 1.0; |
| 364 |
if (rateAttribute != null) { |
| 365 |
diffusionRate = rateAttribute; |
| 366 |
if (outputRateWarning) { |
| 367 |
progressStream.println("Warning: using " + rateAttributeString + " as rate attribute during imputation!"); |
| 368 |
outputRateWarning = false; |
| 369 |
} |
| 370 |
} |
| 371 |
if (traitNoise && precision == null) { |
| 372 |
progressStream.println("Error: no precision available for imputation with correct noise!"); |
| 373 |
System.exit(-1); |
| 374 |
} |
| 375 |
|
| 376 |
double imputeTime = parentHeight - maxPathLength; |
| 377 |
Trait intermediateTrait = imputeValue(nodeTrait, parentNodeTrait, imputeTime, nodeHeight, parentHeight, precision, diffusionRate, traitNoise); |
| 378 |
|
| 379 |
if ((isInGrid(intermediateTrait.getValue())) && (isInGrid(parentNodeTrait.getValue()))) { |
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
int[] nodeGridCell = getCellforPoint(intermediateTrait.getValue()); |
| 387 |
int[] parentNodeGridCell = getCellforPoint(parentNodeTrait.getValue()); |
| 388 |
|
| 389 |
if (rateNoise) { |
| 390 |
if (precision == null) { |
| 391 |
progressStream.println("Error: no precision available for imputation with correct noise!"); |
| 392 |
System.exit(-1); |
| 393 |
} |
| 394 |
if (GREATCIRCLEDISTANCE) { |
| 395 |
rate = getGeographicalDistance(intermediateTrait.getValue(), parentNodeTrait.getValue()) / (parentHeight - imputeTime); |
| 396 |
} else { |
| 397 |
rate = getNativeDistance(intermediateTrait.getValue(), parentNodeTrait.getValue()) / (parentHeight - imputeTime); |
| 398 |
} |
| 399 |
} |
| 400 |
|
| 401 |
if (!getStdev) { |
| 402 |
addDensityAndRate(parentNodeGridCell[0], parentNodeGridCell[1], nodeGridCell[0], nodeGridCell[1], i, rate, history, parentHeight, nodeHeight); |
| 403 |
} else { |
| 404 |
addStdev(parentNodeGridCell[0], parentNodeGridCell[1], nodeGridCell[0], nodeGridCell[1], i, rate); |
| 405 |
} |
| 406 |
|
| 407 |
branchLength = branchLength - maxPathLength; |
| 408 |
parentHeight = parentHeight - maxPathLength; |
| 409 |
parentNodeTrait = intermediateTrait; |
| 410 |
} |
| 411 |
} |
| 412 |
|
| 413 |
int[] nodeGridCell = getCellforPoint(nodeTrait.getValue()); |
| 414 |
int[] parentNodeGridCell = getCellforPoint(parentNodeTrait.getValue()); |
| 415 |
|
| 416 |
if (rateNoise) { |
| 417 |
if (precision == null) { |
| 418 |
progressStream.println("Error: no precision available for imputation with correct noise!"); |
| 419 |
System.exit(-1); |
| 420 |
} |
| 421 |
if (GREATCIRCLEDISTANCE) { |
| 422 |
rate = getGeographicalDistance(nodeTrait.getValue(), parentNodeTrait.getValue()) / (parentHeight - nodeHeight); |
| 423 |
} else { |
| 424 |
rate = getNativeDistance(nodeTrait.getValue(), parentNodeTrait.getValue()) / (parentHeight - nodeHeight); |
| 425 |
} |
| 426 |
} |
| 427 |
|
| 428 |
if (!getStdev) { |
| 429 |
addDensityAndRate(parentNodeGridCell[0], parentNodeGridCell[1], nodeGridCell[0], nodeGridCell[1], i, rate, history, parentHeight, nodeHeight); |
| 430 |
} else { |
| 431 |
addStdev(parentNodeGridCell[0], parentNodeGridCell[1], nodeGridCell[0], nodeGridCell[1], i, rate); |
| 432 |
} |
| 433 |
|
| 434 |
} |
| 435 |
} |
| 436 |
} |
| 437 |
} |
| 438 |
treesAnalyzed++; |
| 439 |
} |
| 440 |
|
| 441 |
private int[] getCellforPoint(double[] location) { |
| 442 |
|
| 443 |
int[] cell = new int[2]; |
| 444 |
cell[0] = (int) Math.floor((location[1] - longMin) / cellXWidth); |
| 445 |
cell[1] = gridYcells - (int) Math.ceil((location[0] - latMin) / cellYHeight); |
| 446 |
return cell; |
| 447 |
} |
| 448 |
|
| 449 |
public void addDensityAndRate(int x, int y, int x2, int y2, int slice, double rate) { |
| 450 |
int w = x2 - x; |
| 451 |
int h = y2 - y; |
| 452 |
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0; |
| 453 |
if (w < 0) dx1 = -1; |
| 454 |
else if (w > 0) dx1 = 1; |
| 455 |
if (h < 0) dy1 = -1; |
| 456 |
else if (h > 0) dy1 = 1; |
| 457 |
if (w < 0) dx2 = -1; |
| 458 |
else if (w > 0) dx2 = 1; |
| 459 |
int longest = Math.abs(w); |
| 460 |
int shortest = Math.abs(h); |
| 461 |
if (!(longest > shortest)) { |
| 462 |
longest = Math.abs(h); |
| 463 |
shortest = Math.abs(w); |
| 464 |
if (h < 0) dy2 = -1; |
| 465 |
else if (h > 0) dy2 = 1; |
| 466 |
dx2 = 0; |
| 467 |
} |
| 468 |
int numerator = longest >> 1; |
| 469 |
for (int i = 0; i <= longest; i++) { |
| 470 |
|
| 471 |
densities[slice][x][y]++; |
| 472 |
rates[slice][x][y] = +rate; |
| 473 |
numerator += shortest; |
| 474 |
if (!(numerator < longest)) { |
| 475 |
numerator -= longest; |
| 476 |
x += dx1; |
| 477 |
y += dy1; |
| 478 |
} else { |
| 479 |
x += dx2; |
| 480 |
y += dy2; |
| 481 |
} |
| 482 |
} |
| 483 |
} |
| 484 |
|
| 485 |
public void addDensityAndRate(int x, int y, int x2, int y2, int slice, double rate, History history, double parentHeight, double nodeHeight) { |
| 486 |
int w = x2 - x; |
| 487 |
int h = y2 - y; |
| 488 |
double branchLength = parentHeight - nodeHeight; |
| 489 |
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0; |
| 490 |
if (w < 0) dx1 = -1; |
| 491 |
else if (w > 0) dx1 = 1; |
| 492 |
if (h < 0) dy1 = -1; |
| 493 |
else if (h > 0) dy1 = 1; |
| 494 |
if (w < 0) dx2 = -1; |
| 495 |
else if (w > 0) dx2 = 1; |
| 496 |
int longest = Math.abs(w); |
| 497 |
int shortest = Math.abs(h); |
| 498 |
if (!(longest > shortest)) { |
| 499 |
longest = Math.abs(h); |
| 500 |
shortest = Math.abs(w); |
| 501 |
if (h < 0) dy2 = -1; |
| 502 |
else if (h > 0) dy2 = 1; |
| 503 |
dx2 = 0; |
| 504 |
} |
| 505 |
int numerator = longest >> 1; |
| 506 |
for (int i = 0; i <= longest; i++) { |
| 507 |
|
| 508 |
if (history != null) { |
| 509 |
double height = parentHeight; |
| 510 |
if (longest > 0) { |
| 511 |
height -= (branchLength / longest) * i; |
| 512 |
} |
| 513 |
double[] test = history.getHeights(); |
| 514 |
if (height < test[test.length - 1]) { |
| 515 |
|
| 516 |
height = test[test.length - 1]; |
| 517 |
} |
| 518 |
|
| 519 |
String state = history.getStateForHeight(height); |
| 520 |
int stateInt = getIntForState(state); |
| 521 |
if (stateInt >= 0) { |
| 522 |
densitiesByDTrait[slice][stateInt][x][y]++; |
| 523 |
} |
| 524 |
} |
| 525 |
|
| 526 |
densities[slice][x][y]++; |
| 527 |
rates[slice][x][y] =+ rate; |
| 528 |
|
| 529 |
numerator += shortest; |
| 530 |
if (!(numerator < longest)) { |
| 531 |
numerator -= longest; |
| 532 |
x += dx1; |
| 533 |
y += dy1; |
| 534 |
} else { |
| 535 |
x += dx2; |
| 536 |
y += dy2; |
| 537 |
} |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
public void addStdev(int x, int y, int x2, int y2, int slice, double rate) { |
| 542 |
int w = x2 - x; |
| 543 |
int h = y2 - y; |
| 544 |
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0; |
| 545 |
if (w < 0) dx1 = -1; |
| 546 |
else if (w > 0) dx1 = 1; |
| 547 |
if (h < 0) dy1 = -1; |
| 548 |
else if (h > 0) dy1 = 1; |
| 549 |
if (w < 0) dx2 = -1; |
| 550 |
else if (w > 0) dx2 = 1; |
| 551 |
int longest = Math.abs(w); |
| 552 |
int shortest = Math.abs(h); |
| 553 |
if (!(longest > shortest)) { |
| 554 |
longest = Math.abs(h); |
| 555 |
shortest = Math.abs(w); |
| 556 |
if (h < 0) dy2 = -1; |
| 557 |
else if (h > 0) dy2 = 1; |
| 558 |
dx2 = 0; |
| 559 |
} |
| 560 |
int numerator = longest >> 1; |
| 561 |
for (int i = 0; i <= longest; i++) { |
| 562 |
|
| 563 |
|
| 564 |
stdevs[slice][x][y] = +Math.pow((rate - rates[slice][x][y]), 2); |
| 565 |
numerator += shortest; |
| 566 |
if (!(numerator < longest)) { |
| 567 |
numerator -= longest; |
| 568 |
x += dx1; |
| 569 |
y += dy1; |
| 570 |
} else { |
| 571 |
x += dx2; |
| 572 |
y += dy2; |
| 573 |
} |
| 574 |
} |
| 575 |
} |
| 576 |
|
| 577 |
private static double getNativeDistance(double[] location1, double[] location2) { |
| 578 |
return Math.sqrt(Math.pow((location2[0] - location1[0]), 2.0) + Math.pow((location2[1] - location1[1]), 2.0)); |
| 579 |
} |
| 580 |
|
| 581 |
private static double getGeographicalDistance(double[] location1, double[] location2) { |
| 582 |
if (location1.length == 1) { |
| 583 |
|
| 584 |
return getKilometerGreatCircleDistance(new double[]{location1[0], 0.0}, new double[]{location2[0], 0.0}); |
| 585 |
} else if (location1.length == 2) { |
| 586 |
return getKilometerGreatCircleDistance(location1, location2); |
| 587 |
} |
| 588 |
throw new RuntimeException("Distances can only be calculated for longitude and latitude (or just latitude)"); |
| 589 |
} |
| 590 |
|
| 591 |
private static double getKilometerGreatCircleDistance(double[] location1, double[] location2) { |
| 592 |
SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(location1[0], location1[1]); |
| 593 |
SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(location2[0], location2[1]); |
| 594 |
return (coord1.distance(coord2)); |
| 595 |
} |
| 596 |
|
| 597 |
private Trait imputeValue(Trait nodeTrait, Trait parentTrait, double time, double nodeHeight, double parentHeight, double[][] precision, double rate, boolean trueNoise) { |
| 598 |
if (!nodeTrait.isNumber()) { |
| 599 |
System.err.println("Can only impute numbers!"); |
| 600 |
System.exit(-1); |
| 601 |
} |
| 602 |
|
| 603 |
int dim = nodeTrait.getDim(); |
| 604 |
double[] nodeValue = nodeTrait.getValue(); |
| 605 |
double[] parentValue = parentTrait.getValue(); |
| 606 |
|
| 607 |
final double scaledTimeChild = (time - nodeHeight) * rate; |
| 608 |
final double scaledTimeParent = (parentHeight - time) * rate; |
| 609 |
final double scaledWeightTotal = 1.0 / scaledTimeChild + 1.0 / scaledTimeParent; |
| 610 |
|
| 611 |
if (scaledTimeChild == 0) |
| 612 |
return nodeTrait; |
| 613 |
|
| 614 |
if (scaledTimeParent == 0) |
| 615 |
return parentTrait; |
| 616 |
|
| 617 |
|
| 618 |
double[] mean = new double[dim]; |
| 619 |
double[][] scaledPrecision = new double[dim][dim]; |
| 620 |
|
| 621 |
for (int i = 0; i < dim; i++) { |
| 622 |
mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal; |
| 623 |
if (trueNoise) { |
| 624 |
for (int j = i; j < dim; j++) |
| 625 |
scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal; |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
if (trueNoise) { |
| 632 |
mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, scaledPrecision); |
| 633 |
} |
| 634 |
|
| 635 |
|
| 636 |
Object[] result = new Object[dim]; |
| 637 |
for (int i = 0; i < dim; i++) |
| 638 |
result[i] = mean[i]; |
| 639 |
return new Trait(result); |
| 640 |
} |
| 641 |
|
| 642 |
private double[] imputeValue(double[] nodeValue, double[] parentValue, double time, double nodeHeight, double parentHeight, double[] precisionArray, double rate, boolean trueNoise) { |
| 643 |
|
| 644 |
final double scaledTimeChild = (time - nodeHeight) * rate; |
| 645 |
final double scaledTimeParent = (parentHeight - time) * rate; |
| 646 |
final double scaledWeightTotal = 1.0 / scaledTimeChild + 1.0 / scaledTimeParent; |
| 647 |
final int dim = nodeValue.length; |
| 648 |
|
| 649 |
double[][] precision = new double[dim][dim]; |
| 650 |
int counter = 0; |
| 651 |
for (int a = 0; a < dim; a++) { |
| 652 |
for (int b = 0; b < dim; b++) { |
| 653 |
precision[a][b] = precisionArray[counter]; |
| 654 |
counter++; |
| 655 |
} |
| 656 |
} |
| 657 |
|
| 658 |
if (scaledTimeChild == 0) |
| 659 |
return nodeValue; |
| 660 |
|
| 661 |
if (scaledTimeParent == 0) |
| 662 |
return parentValue; |
| 663 |
|
| 664 |
|
| 665 |
double[] mean = new double[dim]; |
| 666 |
double[][] scaledPrecision = new double[dim][dim]; |
| 667 |
|
| 668 |
for (int i = 0; i < dim; i++) { |
| 669 |
mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal; |
| 670 |
if (trueNoise) { |
| 671 |
for (int j = i; j < dim; j++) |
| 672 |
scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal; |
| 673 |
} |
| 674 |
} |
| 675 |
|
| 676 |
|
| 677 |
|
| 678 |
if (trueNoise) { |
| 679 |
mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, scaledPrecision); |
| 680 |
} |
| 681 |
|
| 682 |
|
| 683 |
double[] result = new double[dim]; |
| 684 |
for (int i = 0; i < dim; i++) |
| 685 |
result[i] = mean[i]; |
| 686 |
return result; |
| 687 |
} |
| 688 |
|
| 689 |
private boolean isInGrid(double[] point) { |
| 690 |
boolean in = false; |
| 691 |
if (((point[0] > latMin) && (point[0] < latMax)) && |
| 692 |
((point[1] > longMin) && (point[1] < longMax))) { |
| 693 |
in = true; |
| 694 |
} |
| 695 |
return in; |
| 696 |
} |
| 697 |
|
| 698 |
private int getIntForState(String state) { |
| 699 |
|
| 700 |
int returnInt = -1; |
| 701 |
|
| 702 |
for (int x = 0; x < discreteTraitStates.length; x++) { |
| 703 |
if (state.equals(discreteTraitStates[x])) { |
| 704 |
returnInt = x; |
| 705 |
} |
| 706 |
|
| 707 |
} |
| 708 |
|
| 709 |
|
| 710 |
|
| 711 |
return returnInt; |
| 712 |
} |
| 713 |
|
| 714 |
|
| 715 |
enum Normalization { |
| 716 |
LENGTH, |
| 717 |
HEIGHT, |
| 718 |
NONE |
| 719 |
} |
| 720 |
|
| 721 |
|
| 722 |
private String name(String pre, String post) { |
| 723 |
return pre + "." + post; |
| 724 |
} |
| 725 |
|
| 726 |
public void output(String outFileName) { |
| 727 |
|
| 728 |
resultsStream = System.out; |
| 729 |
|
| 730 |
if (outFileName != null) { |
| 731 |
try { |
| 732 |
resultsStream = new PrintStream(new File(outFileName)); |
| 733 |
} catch (IOException e) { |
| 734 |
System.err.println("Error opening file: " + outFileName); |
| 735 |
System.exit(-1); |
| 736 |
} |
| 737 |
} |
| 738 |
|
| 739 |
outputGridInfo(); |
| 740 |
resultsStream.print("\n"); |
| 741 |
|
| 742 |
if (posteriorCutoff > 0) { |
| 743 |
|
| 744 |
setPosteriorCutoff(); |
| 745 |
} |
| 746 |
|
| 747 |
double maxGridDensity = 0; |
| 748 |
if (sliceCount > 1) { |
| 749 |
for (int a = 0; a < sliceCount; a++) { |
| 750 |
double tempMax = getMaxMatrix(densities[a]); |
| 751 |
if (maxGridDensity < tempMax) { |
| 752 |
maxGridDensity = tempMax; |
| 753 |
} |
| 754 |
} |
| 755 |
} |
| 756 |
|
| 757 |
double maxGridDensityByDtrait = 0; |
| 758 |
if (summarizeByDiscreteTrait) { |
| 759 |
for (int a = 0; a < sliceCount; a++) { |
| 760 |
for (int b = 0; b < discreteTraitStates.length; b++) { |
| 761 |
double tempMax = getMaxMatrix(densitiesByDTrait[a][b]); |
| 762 |
if (maxGridDensityByDtrait < tempMax) { |
| 763 |
maxGridDensityByDtrait = tempMax; |
| 764 |
} |
| 765 |
} |
| 766 |
} |
| 767 |
} |
| 768 |
|
| 769 |
|
| 770 |
String writerNames[] = ImageIO.getWriterFormatNames(); |
| 771 |
for (String name : writerNames) { |
| 772 |
System.err.println("Available format:" + name); |
| 773 |
} |
| 774 |
|
| 775 |
String graphicsFormat = "png"; |
| 776 |
|
| 777 |
String suffix = ".worldFile"; |
| 778 |
if (graphicsFormat.equals("png")){ |
| 779 |
suffix = "pgw"; |
| 780 |
} |
| 781 |
|
| 782 |
for (int i = 0; i < sliceCount; i++) { |
| 783 |
|
| 784 |
String ratesFile = "gridRates"; |
| 785 |
String densityFile = "gridDensity"; |
| 786 |
String rateStdevFile = "gridRateStdevs"; |
| 787 |
|
| 788 |
if (sliceCount == 1) { |
| 789 |
|
| 790 |
resultsStream.print("grid rates:\n"); |
| 791 |
printGrid(transpose(rates[i])); |
| 792 |
resultsStream.print("\n"); |
| 793 |
|
| 794 |
resultsStream.print("grid densities:\n"); |
| 795 |
printGrid(transpose(densities[i])); |
| 796 |
resultsStream.print("\n"); |
| 797 |
|
| 798 |
if (getStdevs) { |
| 799 |
resultsStream.print("grid stdevs:\n"); |
| 800 |
printGrid(transpose(stdevs[i])); |
| 801 |
} |
| 802 |
resultsStream.print("\n"); |
| 803 |
|
| 804 |
|
| 805 |
|
| 806 |
|
| 807 |
|
| 808 |
|
| 809 |
|
| 810 |
|
| 811 |
|
| 812 |
|
| 813 |
writeAsAnyFormat(name(ratesFile, graphicsFormat), graphicsFormat, rates[i], true); |
| 814 |
writeAsAnyFormat(name(densityFile, graphicsFormat), graphicsFormat, densities[i], true); |
| 815 |
writeAsAnyFormat(name(rateStdevFile, graphicsFormat), graphicsFormat, stdevs[i], true); |
| 816 |
|
| 817 |
writeWorldFile(name(ratesFile, suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 818 |
writeWorldFile(name(densityFile, suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 819 |
writeWorldFile(name(rateStdevFile, suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 820 |
|
| 821 |
|
| 822 |
|
| 823 |
if (summarizeByDiscreteTrait) { |
| 824 |
for (int x = 0; x < discreteTraitStates.length; x++) { |
| 825 |
resultsStream.print("grid densities for discrete trait " + discreteTraitStates[x] + ":\n"); |
| 826 |
printGrid(transpose(densitiesByDTrait[i][x])); |
| 827 |
resultsStream.print("\n"); |
| 828 |
|
| 829 |
|
| 830 |
writeAsAnyFormat(name(densityFile + ".discreteTrait" + discreteTraitStates[x], graphicsFormat), |
| 831 |
graphicsFormat, |
| 832 |
densitiesByDTrait[i][x], true, maxGridDensityByDtrait); |
| 833 |
writeWorldFile(name(densityFile + ".discreteTrait" + discreteTraitStates[x], suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 834 |
} |
| 835 |
|
| 836 |
|
| 837 |
List<double[][]> channels = new ArrayList<double[][]>(); |
| 838 |
for (int x = 0; x < discreteTraitStates.length; ++x) { |
| 839 |
channels.add(densitiesByDTrait[i][x]); |
| 840 |
} |
| 841 |
writeAsAnyFormatMultiChannel(name("channel." + densityFile + ".discreteTraitAll", graphicsFormat), |
| 842 |
graphicsFormat, |
| 843 |
channels, true, maxGridDensityByDtrait, ChannelColorScheme.CHANNEL_RED_BLUE); |
| 844 |
writeWorldFile(name("channel." + densityFile + ".discreteTraitAll", suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 845 |
|
| 846 |
} |
| 847 |
|
| 848 |
} else { |
| 849 |
resultsStream.print("grid rates for slice height " + sliceHeights[i] + ":\n"); |
| 850 |
printGrid(transpose(rates[i])); |
| 851 |
resultsStream.print("\n"); |
| 852 |
|
| 853 |
resultsStream.print("grid densities for slice height " + sliceHeights[i] + ":\n"); |
| 854 |
printGrid(transpose(densities[i])); |
| 855 |
resultsStream.print("\n"); |
| 856 |
|
| 857 |
if (getStdevs){ |
| 858 |
resultsStream.print("grid rate stdevs for slice height " + sliceHeights[i] + ":\n"); |
| 859 |
printGrid(transpose(stdevs[i])); |
| 860 |
resultsStream.print("\n"); |
| 861 |
} |
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
|
| 866 |
writeAsAnyFormat(name(ratesFile + ".height" + sliceHeights[i], graphicsFormat), graphicsFormat, rates[i], true, maxGridDensity); |
| 867 |
writeAsAnyFormat(name(densityFile + ".height" + sliceHeights[i], graphicsFormat), graphicsFormat, densities[i], true, maxGridDensity); |
| 868 |
|
| 869 |
writeWorldFile(name(ratesFile + ".height" + sliceHeights[i], suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 870 |
writeWorldFile(name(densityFile + ".height" + sliceHeights[i], suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 871 |
|
| 872 |
if (getStdevs){ |
| 873 |
writeAsAnyFormat(name(rateStdevFile + ".height" + sliceHeights[i], graphicsFormat), graphicsFormat, stdevs[i], true, maxGridDensity); |
| 874 |
writeWorldFile(name(rateStdevFile + ".height" + sliceHeights[i], suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 875 |
} |
| 876 |
|
| 877 |
if (summarizeByDiscreteTrait) { |
| 878 |
for (int x = 0; x < discreteTraitStates.length; x++) { |
| 879 |
resultsStream.print("grid densities for slice height " + sliceHeights[i] + " and for discrete trait " + discreteTraitStates[x] + ":\n"); |
| 880 |
printGrid(transpose(densitiesByDTrait[i][x])); |
| 881 |
resultsStream.print("\n"); |
| 882 |
|
| 883 |
|
| 884 |
writeAsAnyFormat(name(densityFile + ".height" + sliceHeights[i] + ".discreteTrait" + discreteTraitStates[x], graphicsFormat), graphicsFormat, densitiesByDTrait[i][x], true, maxGridDensityByDtrait); |
| 885 |
writeWorldFile(name(densityFile + ".height" + sliceHeights[i] + ".discreteTrait" + discreteTraitStates[x], suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 886 |
} |
| 887 |
|
| 888 |
|
| 889 |
List<double[][]> channels = new ArrayList<double[][]>(); |
| 890 |
for (int x = 0; x < discreteTraitStates.length; ++x) { |
| 891 |
channels.add(densitiesByDTrait[i][x]); |
| 892 |
} |
| 893 |
writeAsAnyFormatMultiChannel(name("channel." + densityFile + ".height" + sliceHeights[i] + ".discreteTraitAll", graphicsFormat), |
| 894 |
graphicsFormat, |
| 895 |
channels, true, maxGridDensityByDtrait, ChannelColorScheme.CHANNEL_RED_BLUE); |
| 896 |
writeWorldFile(name("channel." + densityFile + ".height" + sliceHeights[i] + ".discreteTraitAll", suffix), cellXWidth, cellYHeight, 0, 0, longMin, latMax); |
| 897 |
|
| 898 |
} |
| 899 |
} |
| 900 |
} |
| 901 |
} |
| 902 |
|
| 903 |
private void outputGridInfo() { |
| 904 |
StringBuffer sb = new StringBuffer("# grid info\n"); |
| 905 |
sb.append("# lat min (Y)").append(sep).append(latMin); |
| 906 |
sb.append("\n"); |
| 907 |
sb.append("# lat max (Y)").append(sep).append(latMax); |
| 908 |
sb.append("\n"); |
| 909 |
sb.append("# long min (Y)").append(sep).append(longMin); |
| 910 |
sb.append("\n"); |
| 911 |
sb.append("# long max (Y)").append(sep).append(longMax); |
| 912 |
sb.append("\n"); |
| 913 |
sb.append("# number of X cells (long)").append(sep).append(gridXcells); |
| 914 |
sb.append("\n"); |
| 915 |
sb.append("# number of Y cells (lat)").append(sep).append(gridYcells); |
| 916 |
sb.append("\n"); |
| 917 |
sb.append("# X cell width (long)").append(sep).append(cellXWidth); |
| 918 |
sb.append("\n"); |
| 919 |
sb.append("# Y cell height (lat)").append(sep).append(cellYHeight); |
| 920 |
sb.append("\n"); |
| 921 |
if (posteriorCutoff > 0) { |
| 922 |
sb.append("# cut off for reporting grid values").append(sep).append(posteriorCutoff); |
| 923 |
sb.append("\n"); |
| 924 |
} |
| 925 |
resultsStream.print(sb); |
| 926 |
} |
| 927 |
|
| 928 |
private void printGrid(double array[][]) { |
| 929 |
|
| 930 |
StringBuffer sb = new StringBuffer(); |
| 931 |
for (int a = 0; a < array.length; a++) { |
| 932 |
for (int b = 0; b < array[0].length; b++) { |
| 933 |
sb.append(array[a][b]).append(sep); |
| 934 |
} |
| 935 |
sb.append("\n"); |
| 936 |
} |
| 937 |
resultsStream.print(sb); |
| 938 |
} |
| 939 |
|
| 940 |
public void writeAsTIFF(String fileName, double[][] matrix, boolean log) { |
| 941 |
|
| 942 |
|
| 943 |
|
| 944 |
double[][] mat = normalize(matrix, 255, log); |
| 945 |
try { |
| 946 |
DataOutputStream tiffOut = new DataOutputStream(new FileOutputStream(fileName)); |
| 947 |
TIFFWriter.writeDoubleArray(tiffOut, mat); |
| 948 |
tiffOut.close(); |
| 949 |
} catch (Exception e) { |
| 950 |
throw new RuntimeException(e.getMessage()); |
| 951 |
} |
| 952 |
} |
| 953 |
|
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
public void writeAsAnyFormat(String fileName, String format, double[][] matrix, boolean log) { |
| 958 |
double[][] mat = normalize(matrix, 255, log); |
| 959 |
try { |
| 960 |
TIFFWriter.writeDoubleArray(fileName, mat, format, ColorScheme.HEATMAP); |
| 961 |
} catch (Exception e) { |
| 962 |
throw new RuntimeException(e.getMessage()); |
| 963 |
} |
| 964 |
} |
| 965 |
|
| 966 |
public void writeAsTIFF(String fileName, double[][] matrix, boolean log, double maxValue) { |
| 967 |
|
| 968 |
|
| 969 |
|
| 970 |
double[][] mat = normalize(matrix, 255, log, maxValue); |
| 971 |
try { |
| 972 |
DataOutputStream tiffOut = new DataOutputStream(new FileOutputStream(fileName)); |
| 973 |
TIFFWriter.writeDoubleArray(tiffOut, mat); |
| 974 |
tiffOut.close(); |
| 975 |
} catch (Exception e) { |
| 976 |
throw new RuntimeException(e.getMessage()); |
| 977 |
} |
| 978 |
} |
| 979 |
|
| 980 |
public void writeAsAnyFormat(String fileName, String format, double[][] matrix, boolean log, double maxValue) { |
| 981 |
|
| 982 |
|
| 983 |
|
| 984 |
double[][] mat = normalize(matrix, 255, log, maxValue); |
| 985 |
try { |
| 986 |
TIFFWriter.writeDoubleArray(fileName, mat, format, |
| 987 |
|
| 988 |
|
| 989 |
ColorScheme.TRANPARENT0_HEATMAP |
| 990 |
); |
| 991 |
} catch (Exception e) { |
| 992 |
throw new RuntimeException(e.getMessage()); |
| 993 |
} |
| 994 |
} |
| 995 |
|
| 996 |
public void writeAsAnyFormatMultiChannel(String fileName, String format, List<double[][]> matrices, boolean log, double maxValue, |
| 997 |
ChannelColorScheme scheme) { |
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
List<double[][]> normalizedMatrix = new ArrayList<double[][]>(); |
| 1002 |
for (double[][] matrix : matrices) { |
| 1003 |
normalizedMatrix.add(normalize(matrix, 255, log, maxValue)); |
| 1004 |
} |
| 1005 |
|
| 1006 |
try { |
| 1007 |
TIFFWriter.writeDoubleArrayMultiChannel(fileName, normalizedMatrix, format, scheme); |
| 1008 |
} catch (Exception e) { |
| 1009 |
throw new RuntimeException(e.getMessage()); |
| 1010 |
} |
| 1011 |
} |
| 1012 |
|
| 1013 |
public void writeWorldFile(String fileName, double xDim, double yDim, double rot1, double rot2, double upperLeftLong, double upperLeftLat) { |
| 1014 |
|
| 1015 |
try { |
| 1016 |
PrintWriter outFile = new PrintWriter(new FileWriter(fileName), true); |
| 1017 |
|
| 1018 |
outFile.println(xDim); |
| 1019 |
outFile.println(rot1); |
| 1020 |
outFile.println(rot2); |
| 1021 |
outFile.println(-yDim); |
| 1022 |
outFile.println(upperLeftLong+(xDim/2.0)); |
| 1023 |
outFile.println(upperLeftLat-(yDim/2.0)); |
| 1024 |
|
| 1025 |
outFile.close(); |
| 1026 |
|
| 1027 |
} catch(IOException io) { |
| 1028 |
System.err.print("Error writing to file: " + fileName); |
| 1029 |
} |
| 1030 |
|
| 1031 |
} |
| 1032 |
|
| 1033 |
|
| 1034 |
private double sum(double[][] mat) { |
| 1035 |
double value = 0.0; |
| 1036 |
for (int i = 0; i < mat.length; ++i) { |
| 1037 |
for (int j = 0; j < mat[i].length; ++j) { |
| 1038 |
value += mat[i][j]; |
| 1039 |
} |
| 1040 |
} |
| 1041 |
return value; |
| 1042 |
} |
| 1043 |
|
| 1044 |
|
| 1045 |
|
| 1046 |
private double[][] normalize(double inputArray[][], double max, boolean log) { |
| 1047 |
|
| 1048 |
double[][] matrix = new double[inputArray.length][inputArray[0].length]; |
| 1049 |
|
| 1050 |
double maxValue = 0; |
| 1051 |
for (int i = 0; i < inputArray[0].length; i++) { |
| 1052 |
for (int j = 0; j < inputArray.length; j++) { |
| 1053 |
if (log) { |
| 1054 |
|
| 1055 |
if (inputArray[j][i] == 0) { |
| 1056 |
inputArray[j][i] = 1; |
| 1057 |
} |
| 1058 |
inputArray[j][i] = Math.log(inputArray[j][i]); |
| 1059 |
} |
| 1060 |
if (inputArray[j][i] > maxValue) { |
| 1061 |
maxValue = inputArray[j][i]; |
| 1062 |
} |
| 1063 |
} |
| 1064 |
} |
| 1065 |
|
| 1066 |
for (int i = 0; i < inputArray[0].length; i++) { |
| 1067 |
for (int j = 0; j < inputArray.length; j++) { |
| 1068 |
matrix[j][i] = ((double) inputArray[j][i] / maxValue) * max; |
| 1069 |
} |
| 1070 |
} |
| 1071 |
|
| 1072 |
return matrix; |
| 1073 |
|
| 1074 |
} |
| 1075 |
|
| 1076 |
|
| 1077 |
private double[][] normalize(double inputArray[][], double max, boolean log, double maxValue) { |
| 1078 |
|
| 1079 |
double[][] matrix = new double[inputArray.length][inputArray[0].length]; |
| 1080 |
|
| 1081 |
if (log) { |
| 1082 |
maxValue = Math.log(maxValue); |
| 1083 |
for (int i = 0; i < inputArray[0].length; i++) { |
| 1084 |
for (int j = 0; j < inputArray.length; j++) { |
| 1085 |
|
| 1086 |
if (inputArray[j][i] == 0) { |
| 1087 |
matrix[j][i] = 0; |
| 1088 |
} else { |
| 1089 |
matrix[j][i] = Math.log(inputArray[j][i]); |
| 1090 |
} |
| 1091 |
} |
| 1092 |
} |
| 1093 |
} |
| 1094 |
|
| 1095 |
|
| 1096 |
for (int i = 0; i < inputArray[0].length; i++) { |
| 1097 |
for (int j = 0; j < inputArray.length; j++) { |
| 1098 |
matrix[j][i] = ((double) matrix[j][i] / maxValue) * max; |
| 1099 |
} |
| 1100 |
} |
| 1101 |
|
| 1102 |
return matrix; |
| 1103 |
|
| 1104 |
} |
| 1105 |
|
| 1106 |
private double[][] toDoubleArray(int array[][]) { |
| 1107 |
|
| 1108 |
double[][] returnArray = new double[array.length][array[0].length]; |
| 1109 |
for (int a = 0; a < returnArray.length; a++) { |
| 1110 |
for (int b = 0; b < array[0].length; b++) { |
| 1111 |
returnArray[a][b] = array[a][b]; |
| 1112 |
} |
| 1113 |
} |
| 1114 |
return returnArray; |
| 1115 |
} |
| 1116 |
|
| 1117 |
public double[][] transpose(double[][] matrix) { |
| 1118 |
|
| 1119 |
double[][] transposeMatrix = new double[matrix[0].length][matrix.length]; |
| 1120 |
for (int i = 0; i < matrix.length; i++) { |
| 1121 |
for (int j = 0; j < matrix[0].length; j++) { |
| 1122 |
transposeMatrix[j][i] = matrix[i][j]; |
| 1123 |
} |
| 1124 |
|
| 1125 |
} |
| 1126 |
return transposeMatrix; |
| 1127 |
} |
| 1128 |
|
| 1129 |
private void summarizeMeanRates() { |
| 1130 |
for (int a = 0; a < rates.length; a++) { |
| 1131 |
for (int b = 0; b < rates[0].length; b++) { |
| 1132 |
for (int c = 0; c < rates[0][0].length; c++) { |
| 1133 |
rates[a][b][c] = rates[a][b][c] / densities[a][b][c]; |
| 1134 |
if (rates[a][b][c] == 0){ |
| 1135 |
rates[a][b][c] = Double.NaN; |
| 1136 |
} |
| 1137 |
} |
| 1138 |
} |
| 1139 |
} |
| 1140 |
} |
| 1141 |
|
| 1142 |
private void summarizeStdevs() { |
| 1143 |
for (int a = 0; a < stdevs.length; a++) { |
| 1144 |
for (int b = 0; b < stdevs[0].length; b++) { |
| 1145 |
for (int c = 0; c < stdevs[0][0].length; c++) { |
| 1146 |
stdevs[a][b][c] = Math.sqrt(stdevs[a][b][c] / densities[a][b][c]); |
| 1147 |
} |
| 1148 |
} |
| 1149 |
} |
| 1150 |
} |
| 1151 |
|
| 1152 |
private double[][] summarizRateStdevs(List<Double>[][] individualRates, double[][] meanRates) { |
| 1153 |
double[][] rateStdevs = new double[individualRates.length][individualRates[0].length]; |
| 1154 |
for (int i = 0; i < individualRates.length; i++) { |
| 1155 |
for (int j = 0; j < individualRates[0].length; j++) { |
| 1156 |
if (individualRates[i][j].isEmpty()) { |
| 1157 |
|
| 1158 |
rateStdevs[i][j] = Double.NaN; |
| 1159 |
} else { |
| 1160 |
List<Double> cellRates = individualRates[i][j]; |
| 1161 |
double sumOfSquaredDifferences = 0; |
| 1162 |
for (Double element : cellRates) { |
| 1163 |
sumOfSquaredDifferences += Math.pow((element - meanRates[i][j]), 2); |
| 1164 |
} |
| 1165 |
rateStdevs[i][j] = Math.sqrt(sumOfSquaredDifferences / (cellRates.size())); |
| 1166 |
} |
| 1167 |
|
| 1168 |
} |
| 1169 |
} |
| 1170 |
|
| 1171 |
return rateStdevs; |
| 1172 |
} |
| 1173 |
|
| 1174 |
public static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException { |
| 1175 |
|
| 1176 |
List<Double> returnList = new ArrayList<Double>(); |
| 1177 |
StringTokenizer st = new StringTokenizer(inString, ","); |
| 1178 |
while (st.hasMoreTokens()) { |
| 1179 |
try { |
| 1180 |
returnList.add(Double.parseDouble(st.nextToken())); |
| 1181 |
} catch (NumberFormatException e) { |
| 1182 |
throw new Arguments.ArgumentException(); |
| 1183 |
} |
| 1184 |
|
| 1185 |
} |
| 1186 |
|
| 1187 |
if (returnList.size() > 0) { |
| 1188 |
double[] doubleArray = new double[returnList.size()]; |
| 1189 |
for (int i = 0; i < doubleArray.length; i++) |
| 1190 |
doubleArray[i] = returnList.get(i); |
| 1191 |
|
| 1192 |
return doubleArray; |
| 1193 |
} |
| 1194 |
return null; |
| 1195 |
} |
| 1196 |
|
| 1197 |
private static String[] parseVariableLengthStringArray(String inString) { |
| 1198 |
|
| 1199 |
List<String> returnList = new ArrayList<String>(); |
| 1200 |
StringTokenizer st = new StringTokenizer(inString, ","); |
| 1201 |
while (st.hasMoreTokens()) { |
| 1202 |
returnList.add(st.nextToken()); |
| 1203 |
} |
| 1204 |
|
| 1205 |
if (returnList.size() > 0) { |
| 1206 |
String[] stringArray = new String[returnList.size()]; |
| 1207 |
stringArray = returnList.toArray(stringArray); |
| 1208 |
return stringArray; |
| 1209 |
} |
| 1210 |
return null; |
| 1211 |
} |
| 1212 |
|
| 1213 |
public static void reverse(double[] array) { |
| 1214 |
if (array == null) { |
| 1215 |
return; |
| 1216 |
} |
| 1217 |
int i = 0; |
| 1218 |
int j = array.length - 1; |
| 1219 |
double tmp; |
| 1220 |
while (j > i) { |
| 1221 |
tmp = array[j]; |
| 1222 |
array[j] = array[i]; |
| 1223 |
array[i] = tmp; |
| 1224 |
j--; |
| 1225 |
i++; |
| 1226 |
} |
| 1227 |
} |
| 1228 |
|
| 1229 |
public static double[] extractUnique(double[] array) { |
| 1230 |
Set<Double> tmp = new LinkedHashSet<Double>(); |
| 1231 |
for (Double each : array) { |
| 1232 |
tmp.add(each); |
| 1233 |
} |
| 1234 |
double[] output = new double[tmp.size()]; |
| 1235 |
int i = 0; |
| 1236 |
for (Double each : tmp) { |
| 1237 |
output[i++] = each; |
| 1238 |
} |
| 1239 |
return output; |
| 1240 |
} |
| 1241 |
|
| 1242 |
|
| 1243 |
public static <T extends Enum<T>> String[] enumNamesToStringArray(T[] values) { |
| 1244 |
int i = 0; |
| 1245 |
String[] result = new String[values.length]; |
| 1246 |
for (T value : values) { |
| 1247 |
result[i++] = value.name(); |
| 1248 |
} |
| 1249 |
return result; |
| 1250 |
} |
| 1251 |
|
| 1252 |
public static double getMaxMatrix(double[][] gridDensities) { |
| 1253 |
double max = 0; |
| 1254 |
for (int x = 0; x < gridDensities.length; x++) { |
| 1255 |
for (int y = 0; y < gridDensities[0].length; y++) { |
| 1256 |
if (gridDensities[x][y] > max) { |
| 1257 |
max = gridDensities[x][y]; |
| 1258 |
} |
| 1259 |
} |
| 1260 |
|
| 1261 |
} |
| 1262 |
return max; |
| 1263 |
} |
| 1264 |
|
| 1265 |
private void setPosteriorCutoff() { |
| 1266 |
|
| 1267 |
|
| 1268 |
|
| 1269 |
|
| 1270 |
|
| 1271 |
|
| 1272 |
|
| 1273 |
|
| 1274 |
|
| 1275 |
|
| 1276 |
|
| 1277 |
|
| 1278 |
|
| 1279 |
for (int a = 0; a < densitiesByDTrait.length; a++) { |
| 1280 |
for (int b = 0; b < densitiesByDTrait[0].length; b++) { |
| 1281 |
for (int c = 0; c < densitiesByDTrait[0][0].length; c++) { |
| 1282 |
for (int d = 0; d < densitiesByDTrait[0][0][0].length; d++) { |
| 1283 |
if (summarizeByDiscreteTrait) { |
| 1284 |
if (densitiesByDTrait[a][b][c][d] < (posteriorCutoff * treesAnalyzed)) { |
| 1285 |
densitiesByDTrait[a][b][c][d] = 0; |
| 1286 |
} |
| 1287 |
} |
| 1288 |
if (densities[a][c][d] < (posteriorCutoff * treesAnalyzed)) { |
| 1289 |
densities[a][c][d] = 0; |
| 1290 |
rates[a][c][d] = Double.NaN; |
| 1291 |
if (getStdevs){ |
| 1292 |
stdevs[a][c][d] = Double.NaN; |
| 1293 |
} |
| 1294 |
} |
| 1295 |
} |
| 1296 |
} |
| 1297 |
} |
| 1298 |
} |
| 1299 |
} |
| 1300 |
|
| 1301 |
public History setUpHistory(String nodeState, double timeLow, double timeUp) { |
| 1302 |
double[] heights = new double[]{timeUp, timeLow}; |
| 1303 |
String[] states = new String[]{nodeState}; |
| 1304 |
return new History(heights, states); |
| 1305 |
} |
| 1306 |
|
| 1307 |
public History setUpHistory(Object[] historyObject, String nodeState, String parentNodeState, double timeLow, double timeUp) { |
| 1308 |
double[] heights; |
| 1309 |
String[] states; |
| 1310 |
|
| 1311 |
Object[] histories = (Object[]) historyObject; |
| 1312 |
|
| 1313 |
Object[] testHistory = (Object[]) histories[0]; |
| 1314 |
String[][] jumpStrings = new String[histories.length][testHistory.length]; |
| 1315 |
|
| 1316 |
|
| 1317 |
for (int q = 0; q < histories.length; q++) { |
| 1318 |
Object[] singleHistory = (Object[]) histories[q]; |
| 1319 |
for (int r = 0; r < singleHistory.length; r++) { |
| 1320 |
|
| 1321 |
jumpStrings[q][r] = singleHistory[r].toString(); |
| 1322 |
} |
| 1323 |
|
| 1324 |
} |
| 1325 |
|
| 1326 |
|
| 1327 |
|
| 1328 |
heights = new double[histories.length + 2]; |
| 1329 |
states = new String[histories.length + 1]; |
| 1330 |
for (int b = 0; b < histories.length; b++) { |
| 1331 |
states[b] = jumpStrings[b][1]; |
| 1332 |
heights[b + 1] = Double.valueOf(jumpStrings[b][0]); |
| 1333 |
} |
| 1334 |
|
| 1335 |
|
| 1336 |
if (!jumpStrings[0][1].equals(parentNodeState)) { |
| 1337 |
System.out.println(jumpStrings[0][1] + "\t" + parentNodeState); |
| 1338 |
System.err.println("mismatch in jump history and parent node state"); |
| 1339 |
System.exit(-1); |
| 1340 |
} |
| 1341 |
|
| 1342 |
|
| 1343 |
states[histories.length] = jumpStrings[histories.length - 1][2]; |
| 1344 |
if (!jumpStrings[histories.length - 1][2].equals(nodeState)) { |
| 1345 |
System.err.println("mismatch in jump history and node state"); |
| 1346 |
System.exit(-1); |
| 1347 |
} |
| 1348 |
|
| 1349 |
heights[0] = timeUp; |
| 1350 |
heights[histories.length + 1] = timeLow; |
| 1351 |
|
| 1352 |
|
| 1353 |
return new History(heights, states); |
| 1354 |
} |
| 1355 |
|
| 1356 |
private String getState(int stateInt) { |
| 1357 |
String returnString = null; |
| 1358 |
try { |
| 1359 |
|
| 1360 |
} catch (IndexOutOfBoundsException iobe) { |
| 1361 |
System.err.println("no state found for int = " + stateInt + "..."); |
| 1362 |
System.exit(-1); |
| 1363 |
} |
| 1364 |
return returnString; |
| 1365 |
} |
| 1366 |
|
| 1367 |
private int treesRead = 0; |
| 1368 |
private int treesAnalyzed = 0; |
| 1369 |
private double latMin; |
| 1370 |
private double latMax; |
| 1371 |
private double longMin; |
| 1372 |
private double longMax; |
| 1373 |
private int gridXcells; |
| 1374 |
private int gridYcells; |
| 1375 |
private double cellXWidth; |
| 1376 |
private double cellYHeight; |
| 1377 |
private String rateAttributeString = "rate"; |
| 1378 |
|
| 1379 |
|
| 1380 |
private ArrayList treeLengths = new ArrayList(); |
| 1381 |
private boolean outputRateWarning = true; |
| 1382 |
private double[][][] densities; |
| 1383 |
private double[][][][] densitiesByDTrait; |
| 1384 |
private double[][][] rates; |
| 1385 |
private double[][][] stdevs; |
| 1386 |
|
| 1387 |
|
| 1388 |
|
| 1389 |
|
| 1390 |
private int sliceCount; |
| 1391 |
private double[] sliceHeights; |
| 1392 |
|
| 1393 |
private boolean printedBar = false; |
| 1394 |
private boolean getStdevs = true; |
| 1395 |
private double posteriorCutoff; |
| 1396 |
private String discreteTrait; |
| 1397 |
private String[] discreteTraitStates; |
| 1398 |
private boolean summarizeByDiscreteTrait = false; |
| 1399 |
private String historyAnnotation; |
| 1400 |
|
| 1401 |
|
| 1402 |
private static PrintStream progressStream = System.err; |
| 1403 |
private PrintStream resultsStream; |
| 1404 |
|
| 1405 |
private final static Version version = new BeastVersion(); |
| 1406 |
|
| 1407 |
private static final String commandName = "Branch2dRateToGrid"; |
| 1408 |
|
| 1409 |
|
| 1410 |
public static void printUsage(Arguments arguments) { |
| 1411 |
|
| 1412 |
arguments.printUsage(commandName, "<input-file-name> [<output-file-name>]"); |
| 1413 |
progressStream.println(); |
| 1414 |
progressStream.println(" Example: " + commandName + " test.trees out.txt"); |
| 1415 |
progressStream.println(); |
| 1416 |
} |
| 1417 |
|
| 1418 |
public static void centreLine(String line, int pageWidth) { |
| 1419 |
int n = pageWidth - line.length(); |
| 1420 |
int n1 = n / 2; |
| 1421 |
for (int i = 0; i < n1; i++) { |
| 1422 |
progressStream.print(" "); |
| 1423 |
} |
| 1424 |
progressStream.println(line); |
| 1425 |
} |
| 1426 |
|
| 1427 |
public static void printTitle() { |
| 1428 |
progressStream.println(); |
| 1429 |
centreLine("branchGrid2Drate " + version.getVersionString() + ", " + version.getDateString(), 60); |
| 1430 |
centreLine("MCMC Output analysis", 60); |
| 1431 |
centreLine("by", 60); |
| 1432 |
centreLine("Philippe Lemey, Marc A. Suchard", 60); |
| 1433 |
progressStream.println(); |
| 1434 |
centreLine("Rega Institute for Medical Research", 60); |
| 1435 |
centreLine("KU Leuven", 60); |
| 1436 |
centreLine("[email protected]", 60); |
| 1437 |
progressStream.println(); |
| 1438 |
centreLine("Department of Biomathematics", 60); |
| 1439 |
centreLine("University of California, Los Angeles", 60); |
| 1440 |
centreLine("[email protected]", 60); |
| 1441 |
progressStream.println(); |
| 1442 |
progressStream.println(); |
| 1443 |
} |
| 1444 |
|
| 1445 |
|
| 1446 |
public static void main(String[] args) throws IOException { |
| 1447 |
|
| 1448 |
String inputFileName = null; |
| 1449 |
String outputFileName = null; |
| 1450 |
String traitName = "location"; |
| 1451 |
boolean trait2DNoise = true; |
| 1452 |
boolean rate2DNoise = false; |
| 1453 |
Normalization normalize = Normalization.LENGTH; |
| 1454 |
int burnin = -1; |
| 1455 |
int skipEvery = 1; |
| 1456 |
double latMax = 90; |
| 1457 |
double latMin = -90; |
| 1458 |
double longMax = 180; |
| 1459 |
double longMin = -180; |
| 1460 |
int gridXcells = 360; |
| 1461 |
int gridYcells = 180; |
| 1462 |
String rateString = "rate"; |
| 1463 |
double maxPathLength = Double.MAX_VALUE; |
| 1464 |
double posteriorCutoff = 0; |
| 1465 |
|
| 1466 |
double[] sliceHeights = null; |
| 1467 |
double mrsd = 0; |
| 1468 |
boolean getStdevs = true; |
| 1469 |
String discreteTraitName = null; |
| 1470 |
String[] discreteTraitStates = null; |
| 1471 |
String historyAnnotation = "history"; |
| 1472 |
|
| 1473 |
printTitle(); |
| 1474 |
|
| 1475 |
Arguments arguments = new Arguments( |
| 1476 |
new Arguments.Option[]{ |
| 1477 |
new Arguments.IntegerOption(BURNIN, "the number of states to be considered as 'burn-in' [default = 0]"), |
| 1478 |
new Arguments.IntegerOption(SKIP, "skip every i'th tree [default = 0]"), |
| 1479 |
new Arguments.StringOption(TRAIT, "trait_name", "specifies an attribute to use to summarize the 2D trait info [default = location]"), |
| 1480 |
new Arguments.StringOption(RATE_ATTRIBUTE, "rate_attribute", "specifies the trait rate attribute string [default=rate]"), |
| 1481 |
new Arguments.Option(HELP, "option to print this message"), |
| 1482 |
new Arguments.StringOption(TRAIT_NOISE, falseTrue, false, |
| 1483 |
"add true noise to 2D traits [default = true])"), |
| 1484 |
new Arguments.StringOption(RATE_NOISE, falseTrue, false, |
| 1485 |
"add true noise to rates [default = true])"), |
| 1486 |
new Arguments.StringOption(NORMALIZATION, enumNamesToStringArray(Normalization.values()), false, |
| 1487 |
"tree normalization [default = length"), |
| 1488 |
new Arguments.RealOption(LATMAX, "specifies the maximum latitude for the grid [default=90]"), |
| 1489 |
new Arguments.RealOption(LATMIN, "specifies the minimum latitude for the grid [default=-90]"), |
| 1490 |
new Arguments.RealOption(LONGMAX, "specifies the maximum longitude for the grid [default=180]"), |
| 1491 |
new Arguments.RealOption(LONGMIN, "specifies the minimum longitude for the grid [default=-180]"), |
| 1492 |
new Arguments.IntegerOption(GRIDXCELLS, "the number of cells along the x-axis (longitude) of the grid [default = 360]"), |
| 1493 |
new Arguments.IntegerOption(GRIDYCELLS, "the number of cells along the y-axis (latitude) of the grid [default = 180]"), |
| 1494 |
new Arguments.RealOption(MAXPATHLENGTH, "specifies the maximum (time) length a branch can go in one direction before adding Brownian noise to it [default=MAX_VALUE (no noise)]"), |
| 1495 |
new Arguments.StringOption(SLICE_TIMES, "slice_times", "specifies a slice time-list [default=none]"), |
| 1496 |
new Arguments.StringOption(SLICE_HEIGHTS, "slice_heights", "specifies a slice height-list [default=none]"), |
| 1497 |
new Arguments.StringOption(SLICE_FILE_HEIGHTS, "heights_file", "specifies a file with a slice heights-list, is overwritten by command-line specification of slice heights [default=none]"), |
| 1498 |
new Arguments.StringOption(SLICE_FILE_TIMES, "Times_file", "specifies a file with a slice Times-list, is overwritten by command-line specification of slice times [default=none]"), |
| 1499 |
new Arguments.StringOption(STDEVS, falseTrue, true, |
| 1500 |
"get standard deviations for the rates [default = true])"), |
| 1501 |
new Arguments.RealOption(CUTOFF, "specifies the posterior cut-off for summarize grid values [default=-0]"), |
| 1502 |
new Arguments.StringOption(DISCRETE_TRAIT_NAME, "discrete_traitName", "specifies the name for a discrete trait that is annotated to the tree nodes and by which states the grid needs to be summarized [default=none]"), |
| 1503 |
new Arguments.StringOption(DISCRETE_TRAIT_STATES, "discrete_traitStates", "specifies the state of a discrete trait by which the grid needs to be summarized [default=none]"), |
| 1504 |
new Arguments.StringOption(HISTORY_ANNOTATION, "history_annotation", "specifies the name for the history annotation for the discrete trait [default=history]"), |
| 1505 |
|
| 1506 |
} |
| 1507 |
); |
| 1508 |
|
| 1509 |
try { |
| 1510 |
arguments.parseArguments(args); |
| 1511 |
} catch (Arguments.ArgumentException ae) { |
| 1512 |
progressStream.println(ae); |
| 1513 |
printUsage(arguments); |
| 1514 |
System.exit(1); |
| 1515 |
} |
| 1516 |
|
| 1517 |
if (arguments.hasOption(HELP)) { |
| 1518 |
printUsage(arguments); |
| 1519 |
System.exit(0); |
| 1520 |
} |
| 1521 |
|
| 1522 |
try { |
| 1523 |
|
| 1524 |
if (arguments.hasOption(LATMAX)) { |
| 1525 |
latMax = arguments.getRealOption(LATMAX); |
| 1526 |
} |
| 1527 |
|
| 1528 |
if (arguments.hasOption(LATMIN)) { |
| 1529 |
latMin = arguments.getRealOption(LATMIN); |
| 1530 |
} |
| 1531 |
|
| 1532 |
if (arguments.hasOption(LONGMAX)) { |
| 1533 |
longMax = arguments.getRealOption(LONGMAX); |
| 1534 |
} |
| 1535 |
|
| 1536 |
if (arguments.hasOption(LONGMIN)) { |
| 1537 |
longMin = arguments.getRealOption(LONGMIN); |
| 1538 |
} |
| 1539 |
|
| 1540 |
if (arguments.hasOption(MAXPATHLENGTH)) { |
| 1541 |
maxPathLength = arguments.getRealOption(MAXPATHLENGTH); |
| 1542 |
} |
| 1543 |
|
| 1544 |
if (arguments.hasOption(GRIDXCELLS)) { |
| 1545 |
gridXcells = arguments.getIntegerOption(GRIDXCELLS); |
| 1546 |
} |
| 1547 |
|
| 1548 |
if (arguments.hasOption(GRIDYCELLS)) { |
| 1549 |
gridYcells = arguments.getIntegerOption(GRIDYCELLS); |
| 1550 |
} |
| 1551 |
|
| 1552 |
String traitRateString = arguments.getStringOption(RATE_ATTRIBUTE); |
| 1553 |
if (traitRateString != null) { |
| 1554 |
rateString = traitRateString; |
| 1555 |
} |
| 1556 |
|
| 1557 |
if (arguments.hasOption(BURNIN)) { |
| 1558 |
burnin = arguments.getIntegerOption(BURNIN); |
| 1559 |
System.err.println("Ignoring a burnin of " + burnin + " trees."); |
| 1560 |
} |
| 1561 |
|
| 1562 |
if (arguments.hasOption(SKIP)) { |
| 1563 |
skipEvery = arguments.getIntegerOption(SKIP); |
| 1564 |
System.err.println("Skipping every " + skipEvery + " trees."); |
| 1565 |
} |
| 1566 |
if (skipEvery < 1) { |
| 1567 |
System.err.println("Skipping every " + skipEvery + " is not possible, no trees will be skipped"); |
| 1568 |
skipEvery = 1; |
| 1569 |
} |
| 1570 |
|
| 1571 |
String traitString = arguments.getStringOption(TRAIT); |
| 1572 |
if (traitString != null) { |
| 1573 |
traitName = traitString; |
| 1574 |
} |
| 1575 |
|
| 1576 |
String trait2DnoiseString = arguments.getStringOption(TRAIT_NOISE); |
| 1577 |
if (trait2DnoiseString != null && trait2DnoiseString.compareToIgnoreCase("false") == 0) |
| 1578 |
trait2DNoise = false; |
| 1579 |
|
| 1580 |
String rate2DNoiseString = arguments.getStringOption(TRAIT_NOISE); |
| 1581 |
if (rate2DNoiseString != null && rate2DNoiseString.compareToIgnoreCase("true") == 0) |
| 1582 |
rate2DNoise = true; |
| 1583 |
|
| 1584 |
String normalizeString = arguments.getStringOption(NORMALIZATION); |
| 1585 |
if (normalizeString != null) { |
| 1586 |
try { |
| 1587 |
normalize = Normalization.valueOf(normalizeString.toUpperCase()); |
| 1588 |
} catch (IllegalArgumentException iae) { |
| 1589 |
System.err.println("Unrecognized normalization mode: " + normalizeString); |
| 1590 |
} |
| 1591 |
|
| 1592 |
} |
| 1593 |
|
| 1594 |
String sliceTimeString = arguments.getStringOption(SLICE_TIMES); |
| 1595 |
if (sliceTimeString != null) { |
| 1596 |
double[] sliceTimes = parseVariableLengthDoubleArray(sliceTimeString); |
| 1597 |
sliceHeights = new double[sliceTimes.length]; |
| 1598 |
for (int i = 0; i < sliceTimes.length; i++) { |
| 1599 |
if (mrsd == 0) { |
| 1600 |
sliceHeights[i] = sliceTimes[i]; |
| 1601 |
} else { |
| 1602 |
sliceHeights[i] = mrsd - sliceTimes[i]; |
| 1603 |
} |
| 1604 |
} |
| 1605 |
} |
| 1606 |
|
| 1607 |
String stdevString = arguments.getStringOption(STDEVS); |
| 1608 |
if (stdevString != null && stdevString.compareToIgnoreCase("false") == 0) |
| 1609 |
getStdevs = false; |
| 1610 |
|
| 1611 |
if (arguments.hasOption(CUTOFF)) { |
| 1612 |
posteriorCutoff = arguments.getRealOption(CUTOFF); |
| 1613 |
} |
| 1614 |
|
| 1615 |
String discreteTraitNameString = arguments.getStringOption(DISCRETE_TRAIT_NAME); |
| 1616 |
if (discreteTraitNameString != null) { |
| 1617 |
discreteTraitName = discreteTraitNameString; |
| 1618 |
if (!arguments.hasOption(DISCRETE_TRAIT_STATES)) { |
| 1619 |
System.err.print("a discrete trait name is specified (" + discreteTraitName + "), but no associated states of that trait are specified"); |
| 1620 |
System.exit(-1); |
| 1621 |
} |
| 1622 |
} |
| 1623 |
|
| 1624 |
String discreteTraitStatesString = arguments.getStringOption(DISCRETE_TRAIT_STATES); |
| 1625 |
if (discreteTraitStatesString != null) { |
| 1626 |
discreteTraitStates = parseVariableLengthStringArray(discreteTraitStatesString); |
| 1627 |
if (discreteTraitName == null) { |
| 1628 |
System.err.print("states for a discrete trait are specified, but no associated trait name for trait annotation is specified"); |
| 1629 |
System.exit(-1); |
| 1630 |
} |
| 1631 |
} |
| 1632 |
|
| 1633 |
String historyString = arguments.getStringOption(HISTORY_ANNOTATION); |
| 1634 |
if (historyString != null) { |
| 1635 |
historyAnnotation = historyString; |
| 1636 |
} |
| 1637 |
|
| 1638 |
|
| 1639 |
|
| 1640 |
|
| 1641 |
String sliceHeightString = arguments.getStringOption(SLICE_HEIGHTS); |
| 1642 |
if (sliceHeightString != null) { |
| 1643 |
if (sliceTimeString != null) { |
| 1644 |
progressStream.println("Either sliceTimes, sliceHeights, timesFile or sliceCount" + |
| 1645 |
"nt."); |
| 1646 |
System.exit(-1); |
| 1647 |
} |
| 1648 |
sliceHeights = parseVariableLengthDoubleArray(sliceHeightString); |
| 1649 |
} |
| 1650 |
|
| 1651 |
if (arguments.hasOption(SLICE_COUNT)) { |
| 1652 |
int sliceCount = arguments.getIntegerOption(SLICE_COUNT); |
| 1653 |
double startTime; |
| 1654 |
if (arguments.hasOption(START_TIME)) { |
| 1655 |
startTime = arguments.getRealOption(START_TIME); |
| 1656 |
} else { |
| 1657 |
progressStream.println("slice count specified, but no associated start time?"); |
| 1658 |
System.exit(-1); |
| 1659 |
startTime = 0; |
| 1660 |
} |
| 1661 |
double delta; |
| 1662 |
if (mrsd != 0) { |
| 1663 |
if (sliceCount == 1) { |
| 1664 |
delta = (mrsd - startTime); |
| 1665 |
} else { |
| 1666 |
delta = (mrsd - startTime) / (sliceCount - 1); |
| 1667 |
} |
| 1668 |
} else { |
| 1669 |
if (sliceCount == 1) { |
| 1670 |
delta = startTime; |
| 1671 |
} else { |
| 1672 |
delta = startTime / (sliceCount - 1); |
| 1673 |
} |
| 1674 |
} |
| 1675 |
sliceHeights = new double[sliceCount]; |
| 1676 |
|
| 1677 |
|
| 1678 |
|
| 1679 |
|
| 1680 |
|
| 1681 |
double height = 0; |
| 1682 |
for (int i = 0; i < sliceCount; i++) { |
| 1683 |
sliceHeights[i] = height; |
| 1684 |
height += delta; |
| 1685 |
} |
| 1686 |
} |
| 1687 |
|
| 1688 |
if ((sliceTimeString == null) && (sliceHeightString == null) && (!arguments.hasOption(SLICE_COUNT))) { |
| 1689 |
sliceHeights = new double[]{0}; |
| 1690 |
} |
| 1691 |
|
| 1692 |
} catch (Arguments.ArgumentException e) { |
| 1693 |
progressStream.println(e); |
| 1694 |
printUsage(arguments); |
| 1695 |
System.exit(-1); |
| 1696 |
} |
| 1697 |
|
| 1698 |
|
| 1699 |
final String[] args2 = arguments.getLeftoverArguments(); |
| 1700 |
|
| 1701 |
switch (args2.length) { |
| 1702 |
case 0: |
| 1703 |
printUsage(arguments); |
| 1704 |
System.exit(1); |
| 1705 |
case 2: |
| 1706 |
outputFileName = args2[1]; |
| 1707 |
|
| 1708 |
case 1: |
| 1709 |
inputFileName = args2[0]; |
| 1710 |
break; |
| 1711 |
default: { |
| 1712 |
System.err.println("Unknown option: " + args2[2]); |
| 1713 |
System.err.println(); |
| 1714 |
printUsage(arguments); |
| 1715 |
System.exit(1); |
| 1716 |
} |
| 1717 |
} |
| 1718 |
|
| 1719 |
Branch2dRateToGrid grid = new Branch2dRateToGrid(inputFileName, burnin, skipEvery, traitName, trait2DNoise, rate2DNoise, rateString, maxPathLength, normalize, latMin, latMax, longMin, longMax, gridXcells, gridYcells, sliceHeights, getStdevs, posteriorCutoff, discreteTraitName, discreteTraitStates, historyAnnotation); |
| 1720 |
grid.output(outputFileName); |
| 1721 |
|
| 1722 |
System.exit(0); |
| 1723 |
|
| 1724 |
} |
| 1725 |
|
| 1726 |
private class History { |
| 1727 |
|
| 1728 |
private double[] historyHeights; |
| 1729 |
private String[] historyStates; |
| 1730 |
private double[][] historyTraits; |
| 1731 |
|
| 1732 |
public History(double historyHeights[], String historyStates[]) { |
| 1733 |
this.historyHeights = historyHeights; |
| 1734 |
this.historyStates = historyStates; |
| 1735 |
} |
| 1736 |
|
| 1737 |
public String getStateForHeight(double height) { |
| 1738 |
String returnState = null; |
| 1739 |
if ((height > historyHeights[0]) || (height < historyHeights[(historyHeights.length - 1)])) { |
| 1740 |
System.err.print("height " + height + " is outside the history range!!"); |
| 1741 |
System.exit(-1); |
| 1742 |
} |
| 1743 |
for (int a = 0; a < (historyHeights.length - 1); a++) { |
| 1744 |
if ((height <= historyHeights[a]) && (height >= historyHeights[a + 1])) { |
| 1745 |
returnState = historyStates[a]; |
| 1746 |
} |
| 1747 |
} |
| 1748 |
|
| 1749 |
return returnState; |
| 1750 |
} |
| 1751 |
|
| 1752 |
public double[] getHeights() { |
| 1753 |
return historyHeights; |
| 1754 |
} |
| 1755 |
|
| 1756 |
public void truncateUpper(double time) { |
| 1757 |
int cutFrom = -1; |
| 1758 |
for (int a = 0; a < (historyHeights.length - 1); a++) { |
| 1759 |
if ((time < historyHeights[a]) && (time > historyHeights[a + 1])) { |
| 1760 |
cutFrom = a; |
| 1761 |
} |
| 1762 |
} |
| 1763 |
|
| 1764 |
if (cutFrom < 0) { |
| 1765 |
System.err.println("no upper truncation of discrete trait history on branch possible"); |
| 1766 |
System.exit(0); |
| 1767 |
} |
| 1768 |
|
| 1769 |
double[] tempHeights = new double[historyHeights.length - cutFrom]; |
| 1770 |
String[] tempStates = new String[historyStates.length - cutFrom]; |
| 1771 |
|
| 1772 |
tempHeights = Arrays.copyOfRange(historyHeights, cutFrom, historyHeights.length); |
| 1773 |
tempHeights[0] = time; |
| 1774 |
|
| 1775 |
tempStates = Arrays.copyOfRange(historyStates, cutFrom, historyStates.length); |
| 1776 |
|
| 1777 |
historyHeights = tempHeights; |
| 1778 |
historyStates = tempStates; |
| 1779 |
} |
| 1780 |
|
| 1781 |
public void truncateLower(double time) { |
| 1782 |
int cutTo = -1; |
| 1783 |
|
| 1784 |
for (int a = (historyHeights.length - 1); a > 0; a--) { |
| 1785 |
if ((time > historyHeights[a]) && (time < historyHeights[a - 1])) { |
| 1786 |
cutTo = a; |
| 1787 |
} |
| 1788 |
} |
| 1789 |
|
| 1790 |
if (cutTo < 0) { |
| 1791 |
System.err.println("no lower truncation of discrete trait history on branch possible"); |
| 1792 |
System.exit(0); |
| 1793 |
} |
| 1794 |
|
| 1795 |
double[] tempHeights = new double[cutTo + 1]; |
| 1796 |
String[] tempStates = new String[cutTo]; |
| 1797 |
|
| 1798 |
tempHeights = Arrays.copyOfRange(historyHeights, 0, cutTo + 1); |
| 1799 |
tempHeights[(tempHeights.length - 1)] = time; |
| 1800 |
|
| 1801 |
tempStates = Arrays.copyOfRange(historyStates, 0, cutTo); |
| 1802 |
|
| 1803 |
historyHeights = tempHeights; |
| 1804 |
historyStates = tempStates; |
| 1805 |
} |
| 1806 |
|
| 1807 |
public double getStateTime(String state) { |
| 1808 |
double time = 0; |
| 1809 |
for (int x = 0; x < historyStates.length; x++) { |
| 1810 |
if (state.equals(historyStates[x])) { |
| 1811 |
time += (historyHeights[x] - historyHeights[x + 1]); |
| 1812 |
} |
| 1813 |
} |
| 1814 |
return time; |
| 1815 |
} |
| 1816 |
|
| 1817 |
private void setTraitsforHeights(double[] traitUp, double[] traitLow, double[] precisionArray, double rate, boolean trueNoise) { |
| 1818 |
historyTraits = new double[historyHeights.length][2]; |
| 1819 |
for (int x = 0; x < historyHeights.length; x++) { |
| 1820 |
if (x == 0) { |
| 1821 |
historyTraits[x] = traitUp; |
| 1822 |
} else if (x == (historyTraits.length - 1)) { |
| 1823 |
historyTraits[x] = traitLow; |
| 1824 |
} else { |
| 1825 |
historyTraits[x] = imputeValue(traitUp, traitLow, historyHeights[x], historyHeights[(historyHeights.length - 1)], historyHeights[0], precisionArray, rate, trueNoise); |
| 1826 |
} |
| 1827 |
|
| 1828 |
} |
| 1829 |
} |
| 1830 |
|
| 1831 |
public double getStateGreatCircleDistance(String state) { |
| 1832 |
double distance = 0; |
| 1833 |
for (int x = 0; x < historyStates.length; x++) { |
| 1834 |
if (state.equals(historyStates[x])) { |
| 1835 |
distance += getKilometerGreatCircleDistance(historyTraits[x], historyTraits[x + 1]); |
| 1836 |
} |
| 1837 |
} |
| 1838 |
return distance; |
| 1839 |
} |
| 1840 |
|
| 1841 |
public double getStateDifferenceInGreatCircleDistanceFromRoot(String state, double[] rootTrait) { |
| 1842 |
double distance = 0; |
| 1843 |
for (int x = 0; x < historyStates.length; x++) { |
| 1844 |
if (state.equals(historyStates[x])) { |
| 1845 |
distance += (getKilometerGreatCircleDistance(historyTraits[x + 1], rootTrait) - getKilometerGreatCircleDistance(historyTraits[x], rootTrait)); |
| 1846 |
} |
| 1847 |
} |
| 1848 |
return distance; |
| 1849 |
} |
| 1850 |
|
| 1851 |
public double getStateNativeDistance(String state) { |
| 1852 |
double distance = 0; |
| 1853 |
for (int x = 0; x < historyStates.length; x++) { |
| 1854 |
if (state.equals(historyStates[x])) { |
| 1855 |
distance += getNativeDistance(historyTraits[x], historyTraits[x + 1]); |
| 1856 |
} |
| 1857 |
} |
| 1858 |
return distance; |
| 1859 |
} |
| 1860 |
|
| 1861 |
public double getStateDifferenceInNativeDistanceFromRoot(String state, double[] rootTrait) { |
| 1862 |
double distance = 0; |
| 1863 |
for (int x = 0; x < historyStates.length; x++) { |
| 1864 |
if (state.equals(historyStates[x])) { |
| 1865 |
distance += (getNativeDistance(historyTraits[x + 1], rootTrait) - getNativeDistance(historyTraits[x], rootTrait)); |
| 1866 |
} |
| 1867 |
} |
| 1868 |
return distance; |
| 1869 |
} |
| 1870 |
|
| 1871 |
} |
| 1872 |
|
| 1873 |
class Trait { |
| 1874 |
|
| 1875 |
Trait(Object obj) { |
| 1876 |
this.obj = obj; |
| 1877 |
if (obj instanceof Object[]) { |
| 1878 |
isMultivariate = true; |
| 1879 |
array = (Object[]) obj; |
| 1880 |
} |
| 1881 |
} |
| 1882 |
|
| 1883 |
public boolean isMultivariate() { |
| 1884 |
return isMultivariate; |
| 1885 |
} |
| 1886 |
|
| 1887 |
public boolean isNumber() { |
| 1888 |
if (!isMultivariate) |
| 1889 |
return (obj instanceof Double); |
| 1890 |
return (array[0] instanceof Double); |
| 1891 |
} |
| 1892 |
|
| 1893 |
public int getDim() { |
| 1894 |
if (isMultivariate) { |
| 1895 |
return array.length; |
| 1896 |
} |
| 1897 |
return 1; |
| 1898 |
} |
| 1899 |
|
| 1900 |
public double[] getValue() { |
| 1901 |
int dim = getDim(); |
| 1902 |
double[] result = new double[dim]; |
| 1903 |
for (int i = 0; i < dim; i++) |
| 1904 |
result[i] = (Double) array[i]; |
| 1905 |
return result; |
| 1906 |
} |
| 1907 |
|
| 1908 |
private Object obj; |
| 1909 |
private Object[] array; |
| 1910 |
private boolean isMultivariate = false; |
| 1911 |
|
| 1912 |
public String toString() { |
| 1913 |
if (!isMultivariate) |
| 1914 |
return obj.toString(); |
| 1915 |
StringBuffer sb = new StringBuffer(array[0].toString()); |
| 1916 |
for (int i = 1; i < array.length; i++) |
| 1917 |
sb.append("\t").append(array[i]); |
| 1918 |
return sb.toString(); |
| 1919 |
} |
| 1920 |
} |
| 1921 |
|
| 1922 |
|
| 1923 |
} |