| 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.*; |
| 35 |
import dr.evolution.util.TaxonList; |
| 36 |
import dr.geo.contouring.ContourMaker; |
| 37 |
import dr.geo.contouring.ContourPath; |
| 38 |
import dr.geo.contouring.ContourWithSynder; |
| 39 |
import dr.stats.DiscreteStatistics; |
| 40 |
import dr.util.HeapSort; |
| 41 |
import dr.util.Version; |
| 42 |
import jam.console.ConsoleApplication; |
| 43 |
import org.rosuda.JRI.REXP; |
| 44 |
import org.rosuda.JRI.RVector; |
| 45 |
import org.rosuda.JRI.Rengine; |
| 46 |
|
| 47 |
import javax.swing.*; |
| 48 |
import java.io.FileOutputStream; |
| 49 |
import java.io.FileReader; |
| 50 |
import java.io.IOException; |
| 51 |
import java.io.PrintStream; |
| 52 |
import java.util.*; |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
public class TreeAnnotator { |
| 59 |
|
| 60 |
private final static Version version = new BeastVersion(); |
| 61 |
|
| 62 |
private final static boolean USE_R = false; |
| 63 |
|
| 64 |
private static boolean forceIntegerToDiscrete = false; |
| 65 |
|
| 66 |
enum Target { |
| 67 |
MAX_CLADE_CREDIBILITY("Maximum clade credibility tree"), |
| 68 |
|
| 69 |
USER_TARGET_TREE("User target tree"); |
| 70 |
|
| 71 |
String desc; |
| 72 |
|
| 73 |
Target(String s) { |
| 74 |
desc = s; |
| 75 |
} |
| 76 |
|
| 77 |
public String toString() { |
| 78 |
return desc; |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
enum HeightsSummary { |
| 83 |
MEDIAN_HEIGHTS("Median heights"), |
| 84 |
MEAN_HEIGHTS("Mean heights"), |
| 85 |
KEEP_HEIGHTS("Keep target heights"), |
| 86 |
CA_HEIGHTS("Common Ancestor heights"); |
| 87 |
|
| 88 |
String desc; |
| 89 |
|
| 90 |
HeightsSummary(String s) { |
| 91 |
desc = s; |
| 92 |
} |
| 93 |
|
| 94 |
public String toString() { |
| 95 |
return desc; |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
private static PrintStream progressStream = System.err; |
| 102 |
|
| 103 |
private final String location1Attribute = "longLat1"; |
| 104 |
private final String location2Attribute = "longLat2"; |
| 105 |
private final String locationOutputAttribute = "location"; |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
public TreeAnnotator(final int burninTrees, |
| 122 |
final long burninStates, |
| 123 |
HeightsSummary heightsOption, |
| 124 |
double posteriorLimit, |
| 125 |
double[] hpd2D, |
| 126 |
Target targetOption, |
| 127 |
String targetTreeFileName, |
| 128 |
String inputFileName, |
| 129 |
String outputFileName |
| 130 |
) throws IOException { |
| 131 |
|
| 132 |
this.posteriorLimit = posteriorLimit; |
| 133 |
this.hpd2D = hpd2D; |
| 134 |
|
| 135 |
attributeNames.add("height"); |
| 136 |
attributeNames.add("length"); |
| 137 |
|
| 138 |
CladeSystem cladeSystem = new CladeSystem(); |
| 139 |
|
| 140 |
int burnin = -1; |
| 141 |
|
| 142 |
totalTrees = 10000; |
| 143 |
totalTreesUsed = 0; |
| 144 |
|
| 145 |
progressStream.println("Reading trees (bar assumes 10,000 trees)..."); |
| 146 |
progressStream.println("0 25 50 75 100"); |
| 147 |
progressStream.println("|--------------|--------------|--------------|--------------|"); |
| 148 |
|
| 149 |
long stepSize = totalTrees / 60; |
| 150 |
if (stepSize < 1) stepSize = 1; |
| 151 |
|
| 152 |
if (targetOption != Target.USER_TARGET_TREE) { |
| 153 |
cladeSystem = new CladeSystem(); |
| 154 |
FileReader fileReader = new FileReader(inputFileName); |
| 155 |
TreeImporter importer = new NexusImporter(fileReader, true); |
| 156 |
try { |
| 157 |
totalTrees = 0; |
| 158 |
while (importer.hasTree()) { |
| 159 |
Tree tree = importer.importNextTree(); |
| 160 |
|
| 161 |
long state = Long.MAX_VALUE; |
| 162 |
|
| 163 |
if (burninStates > 0) { |
| 164 |
|
| 165 |
String name = tree.getId().trim(); |
| 166 |
|
| 167 |
if (name != null && name.length() > 0 && name.startsWith("STATE_")) { |
| 168 |
state = Long.parseLong(name.split("_")[1]); |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
if (totalTrees >= burninTrees && state >= burninStates) { |
| 173 |
|
| 174 |
|
| 175 |
if (burnin < 0) { |
| 176 |
|
| 177 |
|
| 178 |
burnin = totalTrees; |
| 179 |
} |
| 180 |
|
| 181 |
cladeSystem.add(tree, false); |
| 182 |
|
| 183 |
totalTreesUsed += 1; |
| 184 |
} |
| 185 |
|
| 186 |
if (totalTrees > 0 && totalTrees % stepSize == 0) { |
| 187 |
progressStream.print("*"); |
| 188 |
progressStream.flush(); |
| 189 |
} |
| 190 |
totalTrees++; |
| 191 |
} |
| 192 |
|
| 193 |
} catch (Importer.ImportException e) { |
| 194 |
System.err.println("Error Parsing Input Tree: " + e.getMessage()); |
| 195 |
return; |
| 196 |
} |
| 197 |
fileReader.close(); |
| 198 |
progressStream.println(); |
| 199 |
progressStream.println(); |
| 200 |
|
| 201 |
if (totalTrees < 1) { |
| 202 |
System.err.println("No trees"); |
| 203 |
return; |
| 204 |
} |
| 205 |
if (totalTreesUsed <= 1) { |
| 206 |
if (burnin > 0) { |
| 207 |
System.err.println("No trees to use: burnin too high"); |
| 208 |
return; |
| 209 |
} |
| 210 |
} |
| 211 |
cladeSystem.calculateCladeCredibilities(totalTreesUsed); |
| 212 |
|
| 213 |
progressStream.println("Total trees read: " + totalTrees); |
| 214 |
if (burninTrees > 0) { |
| 215 |
progressStream.println("Ignoring first " + burninTrees + " trees" + |
| 216 |
(burninStates > 0 ? " (" + burninStates + " states)." : "." )); |
| 217 |
} else if (burninStates > 0) { |
| 218 |
progressStream.println("Ignoring first " + burninStates + " states (" + burnin + " trees)."); |
| 219 |
} |
| 220 |
|
| 221 |
progressStream.println("Total unique clades: " + cladeSystem.getCladeMap().keySet().size()); |
| 222 |
progressStream.println(); |
| 223 |
} |
| 224 |
|
| 225 |
MutableTree targetTree = null; |
| 226 |
|
| 227 |
switch (targetOption) { |
| 228 |
case USER_TARGET_TREE: { |
| 229 |
if (targetTreeFileName != null) { |
| 230 |
progressStream.println("Reading user specified target tree, " + targetTreeFileName); |
| 231 |
|
| 232 |
NexusImporter importer = new NexusImporter(new FileReader(targetTreeFileName)); |
| 233 |
try { |
| 234 |
Tree tree = importer.importNextTree(); |
| 235 |
if (tree == null) { |
| 236 |
NewickImporter x = new NewickImporter(new FileReader(targetTreeFileName)); |
| 237 |
tree = x.importNextTree(); |
| 238 |
} |
| 239 |
if (tree == null) { |
| 240 |
System.err.println("No tree in target nexus or newick file " + targetTreeFileName); |
| 241 |
return; |
| 242 |
} |
| 243 |
targetTree = new FlexibleTree(tree); |
| 244 |
} catch (Importer.ImportException e) { |
| 245 |
System.err.println("Error Parsing Target Tree: " + e.getMessage()); |
| 246 |
return; |
| 247 |
} |
| 248 |
} else { |
| 249 |
System.err.println("No user target tree specified."); |
| 250 |
return; |
| 251 |
} |
| 252 |
break; |
| 253 |
} |
| 254 |
case MAX_CLADE_CREDIBILITY: { |
| 255 |
progressStream.println("Finding maximum credibility tree..."); |
| 256 |
targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName )); |
| 257 |
break; |
| 258 |
} |
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
default: throw new IllegalArgumentException("Unknown targetOption"); |
| 265 |
} |
| 266 |
|
| 267 |
progressStream.println("Collecting node information..."); |
| 268 |
progressStream.println("0 25 50 75 100"); |
| 269 |
progressStream.println("|--------------|--------------|--------------|--------------|"); |
| 270 |
|
| 271 |
stepSize = totalTrees / 60; |
| 272 |
if (stepSize < 1) stepSize = 1; |
| 273 |
|
| 274 |
FileReader fileReader = new FileReader(inputFileName); |
| 275 |
NexusImporter importer = new NexusImporter(fileReader); |
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
cladeSystem = new CladeSystem(targetTree); |
| 280 |
totalTreesUsed = 0; |
| 281 |
try { |
| 282 |
boolean firstTree = true; |
| 283 |
int counter = 0; |
| 284 |
while (importer.hasTree()) { |
| 285 |
Tree tree = importer.importNextTree(); |
| 286 |
|
| 287 |
if (counter >= burnin) { |
| 288 |
if (firstTree) { |
| 289 |
setupAttributes(tree); |
| 290 |
firstTree = false; |
| 291 |
} |
| 292 |
|
| 293 |
cladeSystem.collectAttributes(tree); |
| 294 |
totalTreesUsed += 1; |
| 295 |
} |
| 296 |
if (counter > 0 && counter % stepSize == 0) { |
| 297 |
progressStream.print("*"); |
| 298 |
progressStream.flush(); |
| 299 |
} |
| 300 |
counter++; |
| 301 |
|
| 302 |
} |
| 303 |
cladeSystem.removeClades(targetTree, targetTree.getRoot(), true); |
| 304 |
|
| 305 |
cladeSystem.calculateCladeCredibilities(totalTreesUsed); |
| 306 |
} catch (Importer.ImportException e) { |
| 307 |
System.err.println("Error Parsing Input Tree: " + e.getMessage()); |
| 308 |
return; |
| 309 |
} |
| 310 |
progressStream.println(); |
| 311 |
progressStream.println(); |
| 312 |
fileReader.close(); |
| 313 |
|
| 314 |
progressStream.println("Annotating target tree..."); |
| 315 |
|
| 316 |
try { |
| 317 |
cladeSystem.annotateTree(targetTree, targetTree.getRoot(), null, heightsOption); |
| 318 |
|
| 319 |
if( heightsOption == HeightsSummary.CA_HEIGHTS ) { |
| 320 |
setTreeHeightsByCA(targetTree, inputFileName, burnin); |
| 321 |
} |
| 322 |
} catch (Exception e) { |
| 323 |
System.err.println("Error annotating tree: " + e.getMessage() + "\nPlease check the tree log file format."); |
| 324 |
return; |
| 325 |
} |
| 326 |
|
| 327 |
progressStream.println("Writing annotated tree...."); |
| 328 |
|
| 329 |
try { |
| 330 |
final PrintStream stream = outputFileName != null ? |
| 331 |
new PrintStream(new FileOutputStream(outputFileName)) : |
| 332 |
System.out; |
| 333 |
|
| 334 |
new NexusExporter(stream).exportTree(targetTree); |
| 335 |
} catch (Exception e) { |
| 336 |
System.err.println("Error to write annotated tree file: " + e.getMessage()); |
| 337 |
return; |
| 338 |
} |
| 339 |
|
| 340 |
} |
| 341 |
|
| 342 |
private void setupAttributes(Tree tree) { |
| 343 |
for (int i = 0; i < tree.getNodeCount(); i++) { |
| 344 |
NodeRef node = tree.getNode(i); |
| 345 |
Iterator iter = tree.getNodeAttributeNames(node); |
| 346 |
if (iter != null) { |
| 347 |
while (iter.hasNext()) { |
| 348 |
String name = (String) iter.next(); |
| 349 |
attributeNames.add(name); |
| 350 |
} |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
for (TreeAnnotationPlugin plugin : plugins) { |
| 355 |
Set<String> claimed = plugin.setAttributeNames(attributeNames); |
| 356 |
attributeNames.removeAll(claimed); |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
private Tree summarizeTrees(int burnin, CladeSystem cladeSystem, String inputFileName ) |
| 361 |
throws IOException { |
| 362 |
|
| 363 |
Tree bestTree = null; |
| 364 |
double bestScore = Double.NEGATIVE_INFINITY; |
| 365 |
|
| 366 |
progressStream.println("Analyzing " + totalTreesUsed + " trees..."); |
| 367 |
progressStream.println("0 25 50 75 100"); |
| 368 |
progressStream.println("|--------------|--------------|--------------|--------------|"); |
| 369 |
|
| 370 |
int stepSize = totalTrees / 60; |
| 371 |
if (stepSize < 1) stepSize = 1; |
| 372 |
|
| 373 |
int counter = 0; |
| 374 |
int bestTreeNumber = 0; |
| 375 |
TreeImporter importer = new NexusImporter(new FileReader(inputFileName), true); |
| 376 |
try { |
| 377 |
while (importer.hasTree()) { |
| 378 |
Tree tree = importer.importNextTree(); |
| 379 |
|
| 380 |
if (counter >= burnin) { |
| 381 |
double score = scoreTree(tree, cladeSystem ); |
| 382 |
|
| 383 |
if (score > bestScore) { |
| 384 |
bestTree = tree; |
| 385 |
bestScore = score; |
| 386 |
bestTreeNumber = counter + 1; |
| 387 |
} |
| 388 |
} |
| 389 |
if (counter > 0 && counter % stepSize == 0) { |
| 390 |
progressStream.print("*"); |
| 391 |
progressStream.flush(); |
| 392 |
} |
| 393 |
counter++; |
| 394 |
} |
| 395 |
} catch (Importer.ImportException e) { |
| 396 |
System.err.println("Error Parsing Input Tree: " + e.getMessage()); |
| 397 |
return null; |
| 398 |
} |
| 399 |
progressStream.println(); |
| 400 |
progressStream.println(); |
| 401 |
progressStream.println("Best tree: " + bestTree.getId() + " (tree number " + bestTreeNumber + ")"); |
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
progressStream.println("Highest Log Clade Credibility: " + bestScore); |
| 406 |
|
| 407 |
|
| 408 |
return bestTree; |
| 409 |
} |
| 410 |
|
| 411 |
private double scoreTree(Tree tree, CladeSystem cladeSystem ) { |
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
return cladeSystem.getLogCladeCredibility(tree, tree.getRoot(), null); |
| 416 |
|
| 417 |
} |
| 418 |
|
| 419 |
private class CladeSystem { |
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
public CladeSystem() { |
| 427 |
} |
| 428 |
|
| 429 |
|
| 430 |
|
| 431 |
public CladeSystem(Tree targetTree) { |
| 432 |
this.targetTree = targetTree; |
| 433 |
add(targetTree, true); |
| 434 |
} |
| 435 |
|
| 436 |
|
| 437 |
|
| 438 |
|
| 439 |
public void add(Tree tree, boolean includeTips) { |
| 440 |
if (taxonList == null) { |
| 441 |
taxonList = tree; |
| 442 |
} |
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
addClades(tree, tree.getRoot(), includeTips); |
| 448 |
} |
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
|
| 454 |
private BitSet addClades(Tree tree, NodeRef node, boolean includeTips) { |
| 455 |
|
| 456 |
BitSet bits = new BitSet(); |
| 457 |
|
| 458 |
if (tree.isExternal(node)) { |
| 459 |
|
| 460 |
int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); |
| 461 |
bits.set(index); |
| 462 |
|
| 463 |
if (includeTips) { |
| 464 |
addClade(bits); |
| 465 |
} |
| 466 |
|
| 467 |
} else { |
| 468 |
|
| 469 |
for (int i = 0; i < tree.getChildCount(node); i++) { |
| 470 |
|
| 471 |
NodeRef node1 = tree.getChild(node, i); |
| 472 |
|
| 473 |
bits.or(addClades(tree, node1, includeTips)); |
| 474 |
} |
| 475 |
|
| 476 |
addClade(bits); |
| 477 |
} |
| 478 |
|
| 479 |
return bits; |
| 480 |
} |
| 481 |
|
| 482 |
private void addClade(BitSet bits) { |
| 483 |
Clade clade = cladeMap.get(bits); |
| 484 |
if (clade == null) { |
| 485 |
clade = new Clade(bits); |
| 486 |
cladeMap.put(bits, clade); |
| 487 |
} |
| 488 |
clade.setCount(clade.getCount() + 1); |
| 489 |
} |
| 490 |
|
| 491 |
public void collectAttributes(Tree tree) { |
| 492 |
collectAttributes(tree, tree.getRoot()); |
| 493 |
} |
| 494 |
|
| 495 |
private BitSet collectAttributes(Tree tree, NodeRef node) { |
| 496 |
|
| 497 |
BitSet bits = new BitSet(); |
| 498 |
|
| 499 |
if (tree.isExternal(node)) { |
| 500 |
|
| 501 |
int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); |
| 502 |
if (index < 0) { |
| 503 |
throw new IllegalArgumentException("Taxon, " + tree.getNodeTaxon(node).getId() + ", not found in target tree"); |
| 504 |
} |
| 505 |
bits.set(index); |
| 506 |
|
| 507 |
} else { |
| 508 |
|
| 509 |
for (int i = 0; i < tree.getChildCount(node); i++) { |
| 510 |
|
| 511 |
NodeRef node1 = tree.getChild(node, i); |
| 512 |
|
| 513 |
bits.or(collectAttributes(tree, node1)); |
| 514 |
} |
| 515 |
} |
| 516 |
|
| 517 |
collectAttributesForClade(bits, tree, node); |
| 518 |
|
| 519 |
return bits; |
| 520 |
} |
| 521 |
|
| 522 |
private void collectAttributesForClade(BitSet bits, Tree tree, NodeRef node) { |
| 523 |
Clade clade = cladeMap.get(bits); |
| 524 |
if (clade != null) { |
| 525 |
|
| 526 |
if (clade.attributeValues == null) { |
| 527 |
clade.attributeValues = new ArrayList<Object[]>(); |
| 528 |
} |
| 529 |
|
| 530 |
int i = 0; |
| 531 |
Object[] values = new Object[attributeNames.size()]; |
| 532 |
for (String attributeName : attributeNames) { |
| 533 |
boolean processed = false; |
| 534 |
|
| 535 |
if (!processed) { |
| 536 |
Object value; |
| 537 |
if (attributeName.equals("height")) { |
| 538 |
value = tree.getNodeHeight(node); |
| 539 |
} else if (attributeName.equals("length")) { |
| 540 |
value = tree.getBranchLength(node); |
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
|
| 551 |
|
| 552 |
} else { |
| 553 |
value = tree.getNodeAttribute(node, attributeName); |
| 554 |
if (value instanceof String && ((String) value).startsWith("\"")) { |
| 555 |
value = ((String) value).replaceAll("\"", ""); |
| 556 |
} |
| 557 |
} |
| 558 |
|
| 559 |
|
| 560 |
|
| 561 |
|
| 562 |
|
| 563 |
values[i] = value; |
| 564 |
} |
| 565 |
i++; |
| 566 |
} |
| 567 |
clade.attributeValues.add(values); |
| 568 |
|
| 569 |
|
| 570 |
clade.setCount(clade.getCount() + 1); |
| 571 |
} |
| 572 |
} |
| 573 |
|
| 574 |
public Map getCladeMap() { |
| 575 |
return cladeMap; |
| 576 |
} |
| 577 |
|
| 578 |
public void calculateCladeCredibilities(int totalTreesUsed) { |
| 579 |
for (Clade clade : cladeMap.values()) { |
| 580 |
|
| 581 |
if (clade.getCount() > totalTreesUsed) { |
| 582 |
|
| 583 |
throw new AssertionError("clade.getCount=(" + clade.getCount() + |
| 584 |
") should be <= totalTreesUsed = (" + totalTreesUsed + ")"); |
| 585 |
} |
| 586 |
|
| 587 |
clade.setCredibility(((double) clade.getCount()) / (double) totalTreesUsed); |
| 588 |
} |
| 589 |
} |
| 590 |
|
| 591 |
|
| 592 |
|
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
|
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) { |
| 620 |
|
| 621 |
double logCladeCredibility = 0.0; |
| 622 |
|
| 623 |
if (tree.isExternal(node)) { |
| 624 |
|
| 625 |
int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); |
| 626 |
bits.set(index); |
| 627 |
} else { |
| 628 |
|
| 629 |
BitSet bits2 = new BitSet(); |
| 630 |
for (int i = 0; i < tree.getChildCount(node); i++) { |
| 631 |
|
| 632 |
NodeRef node1 = tree.getChild(node, i); |
| 633 |
|
| 634 |
logCladeCredibility += getLogCladeCredibility(tree, node1, bits2); |
| 635 |
} |
| 636 |
|
| 637 |
logCladeCredibility += Math.log(getCladeCredibility(bits2)); |
| 638 |
|
| 639 |
if (bits != null) { |
| 640 |
bits.or(bits2); |
| 641 |
} |
| 642 |
} |
| 643 |
|
| 644 |
return logCladeCredibility; |
| 645 |
} |
| 646 |
|
| 647 |
private double getCladeCredibility(BitSet bits) { |
| 648 |
Clade clade = cladeMap.get(bits); |
| 649 |
if (clade == null) { |
| 650 |
return 0.0; |
| 651 |
} |
| 652 |
return clade.getCredibility(); |
| 653 |
} |
| 654 |
|
| 655 |
public void annotateTree(MutableTree tree, NodeRef node, BitSet bits, HeightsSummary heightsOption) { |
| 656 |
|
| 657 |
BitSet bits2 = new BitSet(); |
| 658 |
|
| 659 |
if (tree.isExternal(node)) { |
| 660 |
|
| 661 |
int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); |
| 662 |
bits2.set(index); |
| 663 |
|
| 664 |
annotateNode(tree, node, bits2, true, heightsOption); |
| 665 |
} else { |
| 666 |
|
| 667 |
for (int i = 0; i < tree.getChildCount(node); i++) { |
| 668 |
|
| 669 |
NodeRef node1 = tree.getChild(node, i); |
| 670 |
|
| 671 |
annotateTree(tree, node1, bits2, heightsOption); |
| 672 |
} |
| 673 |
|
| 674 |
annotateNode(tree, node, bits2, false, heightsOption); |
| 675 |
} |
| 676 |
|
| 677 |
if (bits != null) { |
| 678 |
bits.or(bits2); |
| 679 |
} |
| 680 |
} |
| 681 |
|
| 682 |
private void annotateNode(MutableTree tree, NodeRef node, BitSet bits, boolean isTip, HeightsSummary heightsOption) { |
| 683 |
Clade clade = cladeMap.get(bits); |
| 684 |
assert clade != null : "Clade missing?"; |
| 685 |
|
| 686 |
boolean filter = false; |
| 687 |
if (!isTip) { |
| 688 |
final double posterior = clade.getCredibility(); |
| 689 |
tree.setNodeAttribute(node, "posterior", posterior); |
| 690 |
if (posterior < posteriorLimit) { |
| 691 |
filter = true; |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
int i = 0; |
| 696 |
for (String attributeName : attributeNames) { |
| 697 |
|
| 698 |
if (clade.attributeValues != null && clade.attributeValues.size() > 0) { |
| 699 |
double[] values = new double[clade.attributeValues.size()]; |
| 700 |
|
| 701 |
HashMap<Object, Integer> hashMap = new HashMap<Object, Integer>(); |
| 702 |
|
| 703 |
Object[] v = clade.attributeValues.get(0); |
| 704 |
if (v[i] != null) { |
| 705 |
|
| 706 |
final boolean isHeight = attributeName.equals("height"); |
| 707 |
boolean isBoolean = v[i] instanceof Boolean; |
| 708 |
|
| 709 |
boolean isDiscrete = v[i] instanceof String; |
| 710 |
|
| 711 |
if (forceIntegerToDiscrete && v[i] instanceof Integer) isDiscrete = true; |
| 712 |
|
| 713 |
double minValue = Double.MAX_VALUE; |
| 714 |
double maxValue = -Double.MAX_VALUE; |
| 715 |
|
| 716 |
final boolean isArray = v[i] instanceof Object[]; |
| 717 |
boolean isDoubleArray = isArray && ((Object[]) v[i])[0] instanceof Double; |
| 718 |
|
| 719 |
if (isDoubleArray) { |
| 720 |
for (Object n : (Object[]) v[i]) { |
| 721 |
if (!(n instanceof Double)) { |
| 722 |
isDoubleArray = false; |
| 723 |
break; |
| 724 |
} |
| 725 |
} |
| 726 |
} |
| 727 |
|
| 728 |
|
| 729 |
double[][] valuesArray = null; |
| 730 |
double[] minValueArray = null; |
| 731 |
double[] maxValueArray = null; |
| 732 |
int lenArray = 0; |
| 733 |
|
| 734 |
if (isDoubleArray) { |
| 735 |
lenArray = ((Object[]) v[i]).length; |
| 736 |
|
| 737 |
valuesArray = new double[lenArray][clade.attributeValues.size()]; |
| 738 |
minValueArray = new double[lenArray]; |
| 739 |
maxValueArray = new double[lenArray]; |
| 740 |
|
| 741 |
for (int k = 0; k < lenArray; k++) { |
| 742 |
minValueArray[k] = Double.MAX_VALUE; |
| 743 |
maxValueArray[k] = -Double.MAX_VALUE; |
| 744 |
} |
| 745 |
} |
| 746 |
|
| 747 |
for (int j = 0; j < clade.attributeValues.size(); j++) { |
| 748 |
Object value = clade.attributeValues.get(j)[i]; |
| 749 |
if (isDiscrete) { |
| 750 |
final Object s = value; |
| 751 |
if (hashMap.containsKey(s)) { |
| 752 |
hashMap.put(s, hashMap.get(s) + 1); |
| 753 |
} else { |
| 754 |
hashMap.put(s, 1); |
| 755 |
} |
| 756 |
} else if (isBoolean) { |
| 757 |
values[j] = (((Boolean) value) ? 1.0 : 0.0); |
| 758 |
} else if (isDoubleArray) { |
| 759 |
|
| 760 |
Object[] array = (Object[]) value; |
| 761 |
for (int k = 0; k < lenArray; k++) { |
| 762 |
valuesArray[k][j] = ((Double) array[k]); |
| 763 |
if (valuesArray[k][j] < minValueArray[k]) minValueArray[k] = valuesArray[k][j]; |
| 764 |
if (valuesArray[k][j] > maxValueArray[k]) maxValueArray[k] = valuesArray[k][j]; |
| 765 |
} |
| 766 |
} else { |
| 767 |
|
| 768 |
if (value instanceof Number) { |
| 769 |
values[j] = ((Number) value).doubleValue(); |
| 770 |
if (values[j] < minValue) minValue = values[j]; |
| 771 |
if (values[j] > maxValue) maxValue = values[j]; |
| 772 |
} |
| 773 |
} |
| 774 |
} |
| 775 |
if (isHeight) { |
| 776 |
if (heightsOption == HeightsSummary.MEAN_HEIGHTS) { |
| 777 |
final double mean = DiscreteStatistics.mean(values); |
| 778 |
tree.setNodeHeight(node, mean); |
| 779 |
} else if (heightsOption == HeightsSummary.MEDIAN_HEIGHTS) { |
| 780 |
final double median = DiscreteStatistics.median(values); |
| 781 |
tree.setNodeHeight(node, median); |
| 782 |
} else { |
| 783 |
|
| 784 |
} |
| 785 |
} |
| 786 |
|
| 787 |
if (!filter) { |
| 788 |
boolean processed = false; |
| 789 |
for (TreeAnnotationPlugin plugin : plugins) { |
| 790 |
if (plugin.handleAttribute(tree, node, attributeName, values)) { |
| 791 |
processed = true; |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
if (!processed) { |
| 796 |
if (!isDiscrete) { |
| 797 |
if (!isDoubleArray) |
| 798 |
annotateMeanAttribute(tree, node, attributeName, values); |
| 799 |
else { |
| 800 |
for (int k = 0; k < lenArray; k++) { |
| 801 |
annotateMeanAttribute(tree, node, attributeName + (k + 1), valuesArray[k]); |
| 802 |
} |
| 803 |
} |
| 804 |
} else { |
| 805 |
annotateModeAttribute(tree, node, attributeName, hashMap); |
| 806 |
annotateFrequencyAttribute(tree, node, attributeName, hashMap); |
| 807 |
} |
| 808 |
if (!isBoolean && minValue < maxValue && !isDiscrete && !isDoubleArray) { |
| 809 |
|
| 810 |
|
| 811 |
annotateMedianAttribute(tree, node, attributeName + "_median", values); |
| 812 |
annotateHPDAttribute(tree, node, attributeName + "_95%_HPD", 0.95, values); |
| 813 |
annotateRangeAttribute(tree, node, attributeName + "_range", values); |
| 814 |
} |
| 815 |
|
| 816 |
if (isDoubleArray) { |
| 817 |
String name = attributeName; |
| 818 |
|
| 819 |
|
| 820 |
|
| 821 |
|
| 822 |
boolean want2d = processBivariateAttributes && lenArray == 2; |
| 823 |
if (name.equals("dmv")) { |
| 824 |
want2d = false; |
| 825 |
} |
| 826 |
for (int k = 0; k < lenArray; k++) { |
| 827 |
if (minValueArray[k] < maxValueArray[k]) { |
| 828 |
annotateMedianAttribute(tree, node, name + (k + 1) + "_median", valuesArray[k]); |
| 829 |
annotateRangeAttribute(tree, node, name + (k + 1) + "_range", valuesArray[k]); |
| 830 |
if (!want2d) |
| 831 |
annotateHPDAttribute(tree, node, name + (k + 1) + "_95%_HPD", 0.95, valuesArray[k]); |
| 832 |
} |
| 833 |
} |
| 834 |
|
| 835 |
if (want2d) { |
| 836 |
|
| 837 |
boolean variationInFirst = (minValueArray[0] < maxValueArray[0]); |
| 838 |
boolean variationInSecond = (minValueArray[1] < maxValueArray[1]); |
| 839 |
|
| 840 |
if (variationInFirst && !variationInSecond) |
| 841 |
annotateHPDAttribute(tree, node, name + "1" + "_95%_HPD", 0.95, valuesArray[0]); |
| 842 |
|
| 843 |
if (variationInSecond && !variationInFirst) |
| 844 |
annotateHPDAttribute(tree, node, name + "2" + "_95%_HPD", 0.95, valuesArray[1]); |
| 845 |
|
| 846 |
if (variationInFirst && variationInSecond){ |
| 847 |
|
| 848 |
for (int l = 0; l < hpd2D.length; l++) { |
| 849 |
|
| 850 |
if (hpd2D[l] > 1) { |
| 851 |
System.err.println("no HPD for proportion > 1 (" + hpd2D[l] + ")"); |
| 852 |
} else if (hpd2D[l] < 0){ |
| 853 |
System.err.println("no HPD for proportion < 0 (" + hpd2D[l] + ")"); |
| 854 |
} else { |
| 855 |
annotate2DHPDAttribute(tree, node, name, "_" + (int) (100 * hpd2D[l]) + "%HPD", hpd2D[l], valuesArray); |
| 856 |
} |
| 857 |
|
| 858 |
} |
| 859 |
} |
| 860 |
} |
| 861 |
} |
| 862 |
} |
| 863 |
} |
| 864 |
} |
| 865 |
} |
| 866 |
i++; |
| 867 |
} |
| 868 |
} |
| 869 |
|
| 870 |
private void annotateMeanAttribute(MutableTree tree, NodeRef node, String label, double[] values) { |
| 871 |
double mean = DiscreteStatistics.mean(values); |
| 872 |
tree.setNodeAttribute(node, label, mean); |
| 873 |
} |
| 874 |
|
| 875 |
private void annotateMedianAttribute(MutableTree tree, NodeRef node, String label, double[] values) { |
| 876 |
double median = DiscreteStatistics.median(values); |
| 877 |
tree.setNodeAttribute(node, label, median); |
| 878 |
|
| 879 |
} |
| 880 |
|
| 881 |
private void annotateModeAttribute(MutableTree tree, NodeRef node, String label, HashMap<Object, Integer> values) { |
| 882 |
Object mode = null; |
| 883 |
int maxCount = 0; |
| 884 |
int totalCount = 0; |
| 885 |
int countInMode = 1; |
| 886 |
|
| 887 |
for (Object key : values.keySet()) { |
| 888 |
int thisCount = values.get(key); |
| 889 |
if (thisCount == maxCount) { |
| 890 |
|
| 891 |
mode = mode.toString().concat("+" + key); |
| 892 |
countInMode++; |
| 893 |
} else if (thisCount > maxCount) { |
| 894 |
mode = key; |
| 895 |
maxCount = thisCount; |
| 896 |
countInMode = 1; |
| 897 |
} |
| 898 |
totalCount += thisCount; |
| 899 |
} |
| 900 |
double freq = (double) maxCount / (double) totalCount * countInMode; |
| 901 |
tree.setNodeAttribute(node, label, mode); |
| 902 |
tree.setNodeAttribute(node, label + ".prob", freq); |
| 903 |
} |
| 904 |
|
| 905 |
private void annotateFrequencyAttribute(MutableTree tree, NodeRef node, String label, HashMap<Object, Integer> values) { |
| 906 |
double totalCount = 0; |
| 907 |
Set keySet = values.keySet(); |
| 908 |
int length = keySet.size(); |
| 909 |
String[] name = new String[length]; |
| 910 |
Double[] freq = new Double[length]; |
| 911 |
int index = 0; |
| 912 |
for (Object key : values.keySet()) { |
| 913 |
name[index] = key.toString(); |
| 914 |
freq[index] = new Double(values.get(key)); |
| 915 |
totalCount += freq[index]; |
| 916 |
index++; |
| 917 |
} |
| 918 |
for (int i = 0; i < length; i++) |
| 919 |
freq[i] /= totalCount; |
| 920 |
|
| 921 |
tree.setNodeAttribute(node, label + ".set", name); |
| 922 |
tree.setNodeAttribute(node, label + ".set.prob", freq); |
| 923 |
} |
| 924 |
|
| 925 |
private void annotateRangeAttribute(MutableTree tree, NodeRef node, String label, double[] values) { |
| 926 |
double min = DiscreteStatistics.min(values); |
| 927 |
double max = DiscreteStatistics.max(values); |
| 928 |
tree.setNodeAttribute(node, label, new Object[]{min, max}); |
| 929 |
} |
| 930 |
|
| 931 |
private void annotateHPDAttribute(MutableTree tree, NodeRef node, String label, double hpd, double[] values) { |
| 932 |
int[] indices = new int[values.length]; |
| 933 |
HeapSort.sort(values, indices); |
| 934 |
|
| 935 |
double minRange = Double.MAX_VALUE; |
| 936 |
int hpdIndex = 0; |
| 937 |
|
| 938 |
int diff = (int) Math.round(hpd * (double) values.length); |
| 939 |
for (int i = 0; i <= (values.length - diff); i++) { |
| 940 |
double minValue = values[indices[i]]; |
| 941 |
double maxValue = values[indices[i + diff - 1]]; |
| 942 |
double range = Math.abs(maxValue - minValue); |
| 943 |
if (range < minRange) { |
| 944 |
minRange = range; |
| 945 |
hpdIndex = i; |
| 946 |
} |
| 947 |
} |
| 948 |
double lower = values[indices[hpdIndex]]; |
| 949 |
double upper = values[indices[hpdIndex + diff - 1]]; |
| 950 |
tree.setNodeAttribute(node, label, new Object[]{lower, upper}); |
| 951 |
} |
| 952 |
|
| 953 |
|
| 954 |
Rengine rEngine = null; |
| 955 |
|
| 956 |
private final String[] rArgs = {"--no-save"}; |
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
private final String[] rBootCommands = { |
| 961 |
"library(MASS)", |
| 962 |
"makeContour = function(var1, var2, prob=0.95, n=50, h=c(1,1)) {" + |
| 963 |
"post1 = kde2d(var1, var2, n = n, h=h); " + |
| 964 |
"dx = diff(post1$x[1:2]); " + |
| 965 |
"dy = diff(post1$y[1:2]); " + |
| 966 |
"sz = sort(post1$z); " + |
| 967 |
"c1 = cumsum(sz) * dx * dy; " + |
| 968 |
"levels = sapply(prob, function(x) { approx(c1, sz, xout = 1 - x)$y }); " + |
| 969 |
"line = contourLines(post1$x, post1$y, post1$z, level = levels); " + |
| 970 |
"return(line) }" |
| 971 |
}; |
| 972 |
|
| 973 |
private String makeRString(double[] values) { |
| 974 |
StringBuffer sb = new StringBuffer("c("); |
| 975 |
sb.append(values[0]); |
| 976 |
for (int i = 1; i < values.length; i++) { |
| 977 |
sb.append(","); |
| 978 |
sb.append(values[i]); |
| 979 |
} |
| 980 |
sb.append(")"); |
| 981 |
return sb.toString(); |
| 982 |
} |
| 983 |
|
| 984 |
public static final String CORDINATE = "cordinates"; |
| 985 |
|
| 986 |
|
| 987 |
|
| 988 |
|
| 989 |
|
| 990 |
private String formattedLocation(double x) { |
| 991 |
return String.format("%5.8f", x); |
| 992 |
} |
| 993 |
|
| 994 |
private void annotate2DHPDAttribute(MutableTree tree, NodeRef node, String preLabel, String postLabel, |
| 995 |
double hpd, double[][] values) { |
| 996 |
int N = 50; |
| 997 |
if (USE_R) { |
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
if (rEngine == null) { |
| 1002 |
|
| 1003 |
if (!Rengine.versionCheck()) { |
| 1004 |
throw new RuntimeException("JRI library version mismatch"); |
| 1005 |
} |
| 1006 |
|
| 1007 |
rEngine = new Rengine(rArgs, false, null); |
| 1008 |
|
| 1009 |
if (!rEngine.waitForR()) { |
| 1010 |
throw new RuntimeException("Cannot load R"); |
| 1011 |
} |
| 1012 |
|
| 1013 |
for (String command : rBootCommands) { |
| 1014 |
rEngine.eval(command); |
| 1015 |
} |
| 1016 |
} |
| 1017 |
|
| 1018 |
|
| 1019 |
|
| 1020 |
|
| 1021 |
REXP x = rEngine.eval("makeContour(" + |
| 1022 |
makeRString(values[0]) + "," + |
| 1023 |
makeRString(values[1]) + "," + |
| 1024 |
hpd + "," + |
| 1025 |
N + ")"); |
| 1026 |
|
| 1027 |
RVector contourList = x.asVector(); |
| 1028 |
int numberContours = contourList.size(); |
| 1029 |
|
| 1030 |
if (numberContours > 1) { |
| 1031 |
System.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!"); |
| 1032 |
System.err.println("Try decreasing the enclosed mass or increasing the number of samples."); |
| 1033 |
} |
| 1034 |
|
| 1035 |
|
| 1036 |
tree.setNodeAttribute(node, preLabel + postLabel + "_modality", numberContours); |
| 1037 |
|
| 1038 |
StringBuffer output = new StringBuffer(); |
| 1039 |
for (int i = 0; i < numberContours; i++) { |
| 1040 |
output.append("\n<" + CORDINATE + ">\n"); |
| 1041 |
RVector oneContour = contourList.at(i).asVector(); |
| 1042 |
double[] xList = oneContour.at(1).asDoubleArray(); |
| 1043 |
double[] yList = oneContour.at(2).asDoubleArray(); |
| 1044 |
StringBuffer xString = new StringBuffer("{"); |
| 1045 |
StringBuffer yString = new StringBuffer("{"); |
| 1046 |
for (int k = 0; k < xList.length; k++) { |
| 1047 |
xString.append(formattedLocation(xList[k])).append(","); |
| 1048 |
yString.append(formattedLocation(yList[k])).append(","); |
| 1049 |
} |
| 1050 |
xString.append(formattedLocation(xList[0])).append("}"); |
| 1051 |
yString.append(formattedLocation(yList[0])).append("}"); |
| 1052 |
|
| 1053 |
tree.setNodeAttribute(node, preLabel + "1" + postLabel + "_" + (i + 1), xString); |
| 1054 |
tree.setNodeAttribute(node, preLabel + "2" + postLabel + "_" + (i + 1), yString); |
| 1055 |
} |
| 1056 |
|
| 1057 |
|
| 1058 |
} else { |
| 1059 |
|
| 1060 |
|
| 1061 |
|
| 1062 |
|
| 1063 |
boolean bandwidthLimit = false; |
| 1064 |
|
| 1065 |
ContourMaker kde = new ContourWithSynder(values[0], values[1], bandwidthLimit); |
| 1066 |
|
| 1067 |
ContourPath[] paths = kde.getContourPaths(hpd); |
| 1068 |
|
| 1069 |
tree.setNodeAttribute(node, preLabel + postLabel + "_modality", paths.length); |
| 1070 |
|
| 1071 |
if (paths.length > 1) { |
| 1072 |
System.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!"); |
| 1073 |
System.err.println("Try decreasing the enclosed mass or increasing the number of samples."); |
| 1074 |
} |
| 1075 |
|
| 1076 |
StringBuffer output = new StringBuffer(); |
| 1077 |
int i = 0; |
| 1078 |
for (ContourPath p : paths) { |
| 1079 |
output.append("\n<" + CORDINATE + ">\n"); |
| 1080 |
double[] xList = p.getAllX(); |
| 1081 |
double[] yList = p.getAllY(); |
| 1082 |
StringBuffer xString = new StringBuffer("{"); |
| 1083 |
StringBuffer yString = new StringBuffer("{"); |
| 1084 |
for (int k = 0; k < xList.length; k++) { |
| 1085 |
xString.append(formattedLocation(xList[k])).append(","); |
| 1086 |
yString.append(formattedLocation(yList[k])).append(","); |
| 1087 |
} |
| 1088 |
xString.append(formattedLocation(xList[0])).append("}"); |
| 1089 |
yString.append(formattedLocation(yList[0])).append("}"); |
| 1090 |
|
| 1091 |
tree.setNodeAttribute(node, preLabel + "1" + postLabel + "_" + (i + 1), xString); |
| 1092 |
tree.setNodeAttribute(node, preLabel + "2" + postLabel + "_" + (i + 1), yString); |
| 1093 |
i++; |
| 1094 |
|
| 1095 |
} |
| 1096 |
} |
| 1097 |
} |
| 1098 |
|
| 1099 |
public BitSet removeClades(Tree tree, NodeRef node, boolean includeTips) { |
| 1100 |
|
| 1101 |
BitSet bits = new BitSet(); |
| 1102 |
|
| 1103 |
if (tree.isExternal(node)) { |
| 1104 |
|
| 1105 |
int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); |
| 1106 |
bits.set(index); |
| 1107 |
|
| 1108 |
if (includeTips) { |
| 1109 |
removeClade(bits); |
| 1110 |
} |
| 1111 |
|
| 1112 |
} else { |
| 1113 |
|
| 1114 |
for (int i = 0; i < tree.getChildCount(node); i++) { |
| 1115 |
|
| 1116 |
NodeRef node1 = tree.getChild(node, i); |
| 1117 |
|
| 1118 |
bits.or(removeClades(tree, node1, includeTips)); |
| 1119 |
} |
| 1120 |
|
| 1121 |
removeClade(bits); |
| 1122 |
} |
| 1123 |
|
| 1124 |
return bits; |
| 1125 |
} |
| 1126 |
|
| 1127 |
private void removeClade(BitSet bits) { |
| 1128 |
Clade clade = cladeMap.get(bits); |
| 1129 |
if (clade != null) { |
| 1130 |
clade.setCount(clade.getCount() - 1); |
| 1131 |
} |
| 1132 |
|
| 1133 |
} |
| 1134 |
|
| 1135 |
|
| 1136 |
|
| 1137 |
|
| 1138 |
void getTreeCladeCodes(Tree tree, BitSet[] codes) { |
| 1139 |
getTreeCladeCodes(tree, tree.getRoot(), codes); |
| 1140 |
} |
| 1141 |
|
| 1142 |
int getTreeCladeCodes(Tree tree, NodeRef node, BitSet[] codes) { |
| 1143 |
final int inode = node.getNumber(); |
| 1144 |
codes[inode].clear(); |
| 1145 |
if (tree.isExternal(node)) { |
| 1146 |
int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); |
| 1147 |
codes[inode].set(index); |
| 1148 |
} else { |
| 1149 |
for (int i = 0; i < tree.getChildCount(node); i++) { |
| 1150 |
final NodeRef child = tree.getChild(node, i); |
| 1151 |
final int childIndex = getTreeCladeCodes(tree, child, codes); |
| 1152 |
|
| 1153 |
codes[inode].or(codes[childIndex]); |
| 1154 |
} |
| 1155 |
} |
| 1156 |
return inode; |
| 1157 |
} |
| 1158 |
|
| 1159 |
class Clade { |
| 1160 |
public Clade(BitSet bits) { |
| 1161 |
this.bits = bits; |
| 1162 |
count = 0; |
| 1163 |
credibility = 0.0; |
| 1164 |
} |
| 1165 |
|
| 1166 |
public int getCount() { |
| 1167 |
return count; |
| 1168 |
} |
| 1169 |
|
| 1170 |
public void setCount(int count) { |
| 1171 |
this.count = count; |
| 1172 |
} |
| 1173 |
|
| 1174 |
public double getCredibility() { |
| 1175 |
return credibility; |
| 1176 |
} |
| 1177 |
|
| 1178 |
public void setCredibility(double credibility) { |
| 1179 |
this.credibility = credibility; |
| 1180 |
} |
| 1181 |
|
| 1182 |
public boolean equals(Object o) { |
| 1183 |
if (this == o) return true; |
| 1184 |
if (o == null || getClass() != o.getClass()) return false; |
| 1185 |
|
| 1186 |
final Clade clade = (Clade) o; |
| 1187 |
|
| 1188 |
return !(bits != null ? !bits.equals(clade.bits) : clade.bits != null); |
| 1189 |
|
| 1190 |
} |
| 1191 |
|
| 1192 |
public int hashCode() { |
| 1193 |
return (bits != null ? bits.hashCode() : 0); |
| 1194 |
} |
| 1195 |
|
| 1196 |
public String toString() { |
| 1197 |
return "clade " + bits.toString(); |
| 1198 |
} |
| 1199 |
|
| 1200 |
int count; |
| 1201 |
double credibility; |
| 1202 |
BitSet bits; |
| 1203 |
List<Object[]> attributeValues = null; |
| 1204 |
} |
| 1205 |
|
| 1206 |
|
| 1207 |
|
| 1208 |
|
| 1209 |
TaxonList taxonList = null; |
| 1210 |
Map<BitSet, Clade> cladeMap = new HashMap<BitSet, Clade>(); |
| 1211 |
|
| 1212 |
Tree targetTree; |
| 1213 |
} |
| 1214 |
|
| 1215 |
int totalTrees = 0; |
| 1216 |
int totalTreesUsed = 0; |
| 1217 |
double posteriorLimit = 0.0; |
| 1218 |
|
| 1219 |
double[] hpd2D = {0.80}; |
| 1220 |
|
| 1221 |
private final List<TreeAnnotationPlugin> plugins = new ArrayList<TreeAnnotationPlugin>(); |
| 1222 |
|
| 1223 |
Set<String> attributeNames = new HashSet<String>(); |
| 1224 |
TaxonList taxa = null; |
| 1225 |
|
| 1226 |
static boolean processBivariateAttributes = false; |
| 1227 |
|
| 1228 |
static { |
| 1229 |
try { |
| 1230 |
System.loadLibrary("jri"); |
| 1231 |
processBivariateAttributes = true; |
| 1232 |
System.err.println("JRI loaded. Will process bivariate attributes"); |
| 1233 |
} catch (UnsatisfiedLinkError e) { |
| 1234 |
|
| 1235 |
if (!USE_R) { |
| 1236 |
processBivariateAttributes = true; |
| 1237 |
|
| 1238 |
} else { |
| 1239 |
|
| 1240 |
} |
| 1241 |
} |
| 1242 |
} |
| 1243 |
|
| 1244 |
public static void printTitle() { |
| 1245 |
progressStream.println(); |
| 1246 |
centreLine("TreeAnnotator " + version.getVersionString() + ", " + version.getDateString(), 60); |
| 1247 |
centreLine("MCMC Output analysis", 60); |
| 1248 |
centreLine("by", 60); |
| 1249 |
centreLine("Andrew Rambaut and Alexei J. Drummond", 60); |
| 1250 |
progressStream.println(); |
| 1251 |
centreLine("Institute of Evolutionary Biology", 60); |
| 1252 |
centreLine("University of Edinburgh", 60); |
| 1253 |
centreLine("[email protected]", 60); |
| 1254 |
progressStream.println(); |
| 1255 |
centreLine("Department of Computer Science", 60); |
| 1256 |
centreLine("University of Auckland", 60); |
| 1257 |
centreLine("[email protected]", 60); |
| 1258 |
progressStream.println(); |
| 1259 |
progressStream.println(); |
| 1260 |
} |
| 1261 |
|
| 1262 |
public static void centreLine(String line, int pageWidth) { |
| 1263 |
int n = pageWidth - line.length(); |
| 1264 |
int n1 = n / 2; |
| 1265 |
for (int i = 0; i < n1; i++) { |
| 1266 |
progressStream.print(" "); |
| 1267 |
} |
| 1268 |
progressStream.println(line); |
| 1269 |
} |
| 1270 |
|
| 1271 |
|
| 1272 |
public static void printUsage(Arguments arguments) { |
| 1273 |
|
| 1274 |
arguments.printUsage("treeannotator", "<input-file-name> [<output-file-name>]"); |
| 1275 |
progressStream.println(); |
| 1276 |
progressStream.println(" Example: treeannotator test.trees out.txt"); |
| 1277 |
progressStream.println(" Example: treeannotator -burnin 100 -heights mean test.trees out.txt"); |
| 1278 |
progressStream.println(" Example: treeannotator -burnin 100 -target map.tree test.trees out.txt"); |
| 1279 |
progressStream.println(); |
| 1280 |
} |
| 1281 |
|
| 1282 |
public static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException { |
| 1283 |
|
| 1284 |
List<Double> returnList = new ArrayList<Double>(); |
| 1285 |
StringTokenizer st = new StringTokenizer(inString,","); |
| 1286 |
while(st.hasMoreTokens()) { |
| 1287 |
try { |
| 1288 |
returnList.add(Double.parseDouble(st.nextToken())); |
| 1289 |
} catch (NumberFormatException e) { |
| 1290 |
throw new Arguments.ArgumentException(); |
| 1291 |
} |
| 1292 |
|
| 1293 |
} |
| 1294 |
|
| 1295 |
if (returnList.size()>0) { |
| 1296 |
double[] doubleArray = new double[returnList.size()]; |
| 1297 |
for(int i=0; i<doubleArray.length; i++) |
| 1298 |
doubleArray[i] = returnList.get(i); |
| 1299 |
return doubleArray; |
| 1300 |
} |
| 1301 |
return null; |
| 1302 |
} |
| 1303 |
|
| 1304 |
|
| 1305 |
public static void main(String[] args) throws IOException { |
| 1306 |
|
| 1307 |
|
| 1308 |
|
| 1309 |
Locale.setDefault(Locale.US); |
| 1310 |
|
| 1311 |
String targetTreeFileName = null; |
| 1312 |
String inputFileName = null; |
| 1313 |
String outputFileName = null; |
| 1314 |
|
| 1315 |
if (args.length == 0) { |
| 1316 |
System.setProperty("com.apple.macos.useScreenMenuBar", "true"); |
| 1317 |
System.setProperty("apple.laf.useScreenMenuBar", "true"); |
| 1318 |
System.setProperty("apple.awt.showGrowBox", "true"); |
| 1319 |
|
| 1320 |
java.net.URL url = LogCombiner.class.getResource("/images/utility.png"); |
| 1321 |
javax.swing.Icon icon = null; |
| 1322 |
|
| 1323 |
if (url != null) { |
| 1324 |
icon = new javax.swing.ImageIcon(url); |
| 1325 |
} |
| 1326 |
|
| 1327 |
final String versionString = version.getVersionString(); |
| 1328 |
String nameString = "TreeAnnotator " + versionString; |
| 1329 |
String aboutString = "<html><center><p>" + versionString + ", " + version.getDateString() + "</p>" + |
| 1330 |
"<p>by<br>" + |
| 1331 |
"Andrew Rambaut and Alexei J. Drummond</p>" + |
| 1332 |
"<p>Institute of Evolutionary Biology, University of Edinburgh<br>" + |
| 1333 |
"<a href=\"mailto:[email protected]\">[email protected]</a></p>" + |
| 1334 |
"<p>Department of Computer Science, University of Auckland<br>" + |
| 1335 |
"<a href=\"mailto:[email protected]\">[email protected]</a></p>" + |
| 1336 |
"<p>Part of the BEAST package:<br>" + |
| 1337 |
"<a href=\"http://beast.community\">http://beast.community</a></p>" + |
| 1338 |
"</center></html>"; |
| 1339 |
|
| 1340 |
new ConsoleApplication(nameString, aboutString, icon, true); |
| 1341 |
|
| 1342 |
|
| 1343 |
|
| 1344 |
progressStream = System.out; |
| 1345 |
|
| 1346 |
printTitle(); |
| 1347 |
|
| 1348 |
TreeAnnotatorDialog dialog = new TreeAnnotatorDialog(new JFrame()); |
| 1349 |
|
| 1350 |
if (!dialog.showDialog("TreeAnnotator " + versionString)) { |
| 1351 |
return; |
| 1352 |
} |
| 1353 |
|
| 1354 |
long burninStates = dialog.getBurninStates(); |
| 1355 |
int burninTrees = dialog.getBurninTrees(); |
| 1356 |
double posteriorLimit = dialog.getPosteriorLimit(); |
| 1357 |
double[] hpd2D = {0.80}; |
| 1358 |
Target targetOption = dialog.getTargetOption(); |
| 1359 |
HeightsSummary heightsOption = dialog.getHeightsOption(); |
| 1360 |
|
| 1361 |
targetTreeFileName = dialog.getTargetFileName(); |
| 1362 |
if (targetOption == Target.USER_TARGET_TREE && targetTreeFileName == null) { |
| 1363 |
System.err.println("No target file specified"); |
| 1364 |
return; |
| 1365 |
} |
| 1366 |
|
| 1367 |
inputFileName = dialog.getInputFileName(); |
| 1368 |
if (inputFileName == null) { |
| 1369 |
System.err.println("No input file specified"); |
| 1370 |
return; |
| 1371 |
} |
| 1372 |
|
| 1373 |
outputFileName = dialog.getOutputFileName(); |
| 1374 |
if (outputFileName == null) { |
| 1375 |
System.err.println("No output file specified"); |
| 1376 |
return; |
| 1377 |
} |
| 1378 |
|
| 1379 |
try { |
| 1380 |
new TreeAnnotator( |
| 1381 |
burninTrees, |
| 1382 |
burninStates, |
| 1383 |
heightsOption, |
| 1384 |
posteriorLimit, |
| 1385 |
hpd2D, |
| 1386 |
targetOption, |
| 1387 |
targetTreeFileName, |
| 1388 |
inputFileName, |
| 1389 |
outputFileName); |
| 1390 |
|
| 1391 |
} catch (Exception ex) { |
| 1392 |
System.err.println("Exception: " + ex.getMessage()); |
| 1393 |
} |
| 1394 |
|
| 1395 |
progressStream.println("Finished - Quit program to exit."); |
| 1396 |
while (true) { |
| 1397 |
try { |
| 1398 |
Thread.sleep(1000); |
| 1399 |
} catch (InterruptedException e) { |
| 1400 |
e.printStackTrace(); |
| 1401 |
} |
| 1402 |
} |
| 1403 |
} |
| 1404 |
|
| 1405 |
printTitle(); |
| 1406 |
|
| 1407 |
Arguments arguments = new Arguments( |
| 1408 |
new Arguments.Option[]{ |
| 1409 |
|
| 1410 |
new Arguments.StringOption("heights", new String[]{"keep", "median", "mean", "ca"}, false, |
| 1411 |
"an option of 'keep' (default), 'median', 'mean' or 'ca'"), |
| 1412 |
new Arguments.LongOption("burnin", "the number of states to be considered as 'burn-in'"), |
| 1413 |
new Arguments.IntegerOption("burninTrees", "the number of trees to be considered as 'burn-in'"), |
| 1414 |
new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annotated"), |
| 1415 |
new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"), |
| 1416 |
new Arguments.Option("help", "option to print this message"), |
| 1417 |
new Arguments.Option("forceDiscrete", "forces integer traits to be treated as discrete traits."), |
| 1418 |
new Arguments.StringOption("hpd2D", "the HPD interval to be used for the bivariate traits", "specifies a (vector of comma seperated) HPD proportion(s)") |
| 1419 |
}); |
| 1420 |
|
| 1421 |
try { |
| 1422 |
arguments.parseArguments(args); |
| 1423 |
} catch (Arguments.ArgumentException ae) { |
| 1424 |
progressStream.println(ae); |
| 1425 |
printUsage(arguments); |
| 1426 |
System.exit(1); |
| 1427 |
} |
| 1428 |
|
| 1429 |
if (arguments.hasOption("forceDiscrete")) { |
| 1430 |
System.out.println(" Forcing integer traits to be treated as discrete traits."); |
| 1431 |
forceIntegerToDiscrete = true; |
| 1432 |
} |
| 1433 |
|
| 1434 |
if (arguments.hasOption("help")) { |
| 1435 |
printUsage(arguments); |
| 1436 |
System.exit(0); |
| 1437 |
} |
| 1438 |
|
| 1439 |
HeightsSummary heights = HeightsSummary.KEEP_HEIGHTS; |
| 1440 |
if (arguments.hasOption("heights")) { |
| 1441 |
String value = arguments.getStringOption("heights"); |
| 1442 |
if (value.equalsIgnoreCase("mean")) { |
| 1443 |
heights = HeightsSummary.MEAN_HEIGHTS; |
| 1444 |
} else if (value.equalsIgnoreCase("median")) { |
| 1445 |
heights = HeightsSummary.MEDIAN_HEIGHTS; |
| 1446 |
} else if (value.equalsIgnoreCase("ca")) { |
| 1447 |
heights = HeightsSummary.CA_HEIGHTS; |
| 1448 |
System.out.println("Please cite: Heled and Bouckaert: Looking for trees in the forest:\n" + |
| 1449 |
"summary tree from posterior samples. BMC Evolutionary Biology 2013 13:221."); |
| 1450 |
} |
| 1451 |
} |
| 1452 |
|
| 1453 |
long burninStates = -1; |
| 1454 |
int burninTrees = -1; |
| 1455 |
if (arguments.hasOption("burnin")) { |
| 1456 |
burninStates = arguments.getLongOption("burnin"); |
| 1457 |
} |
| 1458 |
if (arguments.hasOption("burninTrees")) { |
| 1459 |
burninTrees = arguments.getIntegerOption("burninTrees"); |
| 1460 |
} |
| 1461 |
|
| 1462 |
double posteriorLimit = 0.0; |
| 1463 |
if (arguments.hasOption("limit")) { |
| 1464 |
posteriorLimit = arguments.getRealOption("limit"); |
| 1465 |
} |
| 1466 |
|
| 1467 |
double[] hpd2D = {80}; |
| 1468 |
if (arguments.hasOption("hpd2D")) { |
| 1469 |
try { |
| 1470 |
hpd2D = parseVariableLengthDoubleArray(arguments.getStringOption("hpd2D")); |
| 1471 |
} catch (Arguments.ArgumentException e) { |
| 1472 |
System.err.println("Error reading " + arguments.getStringOption("hpd2D")); |
| 1473 |
} |
| 1474 |
} |
| 1475 |
|
| 1476 |
Target target = Target.MAX_CLADE_CREDIBILITY; |
| 1477 |
if (arguments.hasOption("target")) { |
| 1478 |
target = Target.USER_TARGET_TREE; |
| 1479 |
targetTreeFileName = arguments.getStringOption("target"); |
| 1480 |
} |
| 1481 |
|
| 1482 |
final String[] args2 = arguments.getLeftoverArguments(); |
| 1483 |
|
| 1484 |
switch (args2.length) { |
| 1485 |
case 2: |
| 1486 |
outputFileName = args2[1]; |
| 1487 |
|
| 1488 |
case 1: |
| 1489 |
inputFileName = args2[0]; |
| 1490 |
break; |
| 1491 |
default: { |
| 1492 |
System.err.println("Unknown option: " + args2[2]); |
| 1493 |
System.err.println(); |
| 1494 |
printUsage(arguments); |
| 1495 |
System.exit(1); |
| 1496 |
} |
| 1497 |
} |
| 1498 |
|
| 1499 |
new TreeAnnotator(burninTrees, burninStates, heights, posteriorLimit, hpd2D, target, targetTreeFileName, inputFileName, outputFileName); |
| 1500 |
|
| 1501 |
System.exit(0); |
| 1502 |
} |
| 1503 |
|
| 1504 |
|
| 1505 |
|
| 1506 |
|
| 1507 |
|
| 1508 |
public static interface TreeAnnotationPlugin { |
| 1509 |
Set<String> setAttributeNames(Set<String> attributeNames); |
| 1510 |
|
| 1511 |
boolean handleAttribute(Tree tree, NodeRef node, String attributeName, double[] values); |
| 1512 |
} |
| 1513 |
|
| 1514 |
|
| 1515 |
|
| 1516 |
|
| 1517 |
static boolean isSubSet(BitSet x, BitSet y) { |
| 1518 |
y = (BitSet) y.clone(); |
| 1519 |
y.and(x); |
| 1520 |
return y.equals(x); |
| 1521 |
} |
| 1522 |
|
| 1523 |
boolean setTreeHeightsByCA(MutableTree targetTree, final String inputFileName, final int burnin) |
| 1524 |
throws IOException, Importer.ImportException { |
| 1525 |
progressStream.println("Setting node heights..."); |
| 1526 |
progressStream.println("0 25 50 75 100"); |
| 1527 |
progressStream.println("|--------------|--------------|--------------|--------------|"); |
| 1528 |
|
| 1529 |
int reportStepSize = totalTrees / 60; |
| 1530 |
if (reportStepSize < 1) reportStepSize = 1; |
| 1531 |
|
| 1532 |
final FileReader fileReader = new FileReader(inputFileName); |
| 1533 |
final NexusImporter importer = new NexusImporter(fileReader, true); |
| 1534 |
|
| 1535 |
|
| 1536 |
|
| 1537 |
CladeSystem cladeSystem = new CladeSystem(targetTree); |
| 1538 |
final int nClades = cladeSystem.getCladeMap().size(); |
| 1539 |
|
| 1540 |
|
| 1541 |
int[] postOrderList = new int[nClades]; |
| 1542 |
BitSet[] ctarget = new BitSet[nClades]; |
| 1543 |
BitSet[] ctree = new BitSet[nClades]; |
| 1544 |
|
| 1545 |
for (int k = 0; k < nClades; ++k) { |
| 1546 |
ctarget[k] = new BitSet(); |
| 1547 |
ctree[k] = new BitSet(); |
| 1548 |
} |
| 1549 |
|
| 1550 |
cladeSystem.getTreeCladeCodes(targetTree, ctarget); |
| 1551 |
|
| 1552 |
|
| 1553 |
double[] hs = new double[nClades]; |
| 1554 |
|
| 1555 |
|
| 1556 |
double[] ths = new double[nClades]; |
| 1557 |
|
| 1558 |
totalTreesUsed = 0; |
| 1559 |
|
| 1560 |
int counter = 0; |
| 1561 |
while (importer.hasTree()) { |
| 1562 |
final Tree tree = importer.importNextTree(); |
| 1563 |
|
| 1564 |
if (counter >= burnin) { |
| 1565 |
TreeUtils.preOrderTraversalList(tree, postOrderList); |
| 1566 |
cladeSystem.getTreeCladeCodes(tree, ctree); |
| 1567 |
for (int k = 0; k < nClades; ++k) { |
| 1568 |
int j = postOrderList[k]; |
| 1569 |
for (int i = 0; i < nClades; ++i) { |
| 1570 |
if( isSubSet(ctarget[i], ctree[j]) ) { |
| 1571 |
hs[i] = tree.getNodeHeight(tree.getNode(j)); |
| 1572 |
} |
| 1573 |
} |
| 1574 |
} |
| 1575 |
for (int k = 0; k < nClades; ++k) { |
| 1576 |
ths[k] += hs[k]; |
| 1577 |
} |
| 1578 |
totalTreesUsed += 1; |
| 1579 |
} |
| 1580 |
if (counter > 0 && counter % reportStepSize == 0) { |
| 1581 |
progressStream.print("*"); |
| 1582 |
progressStream.flush(); |
| 1583 |
} |
| 1584 |
counter++; |
| 1585 |
|
| 1586 |
} |
| 1587 |
cladeSystem.removeClades(targetTree, targetTree.getRoot(), true); |
| 1588 |
for (int k = 0; k < nClades; ++k) { |
| 1589 |
ths[k] /= totalTreesUsed; |
| 1590 |
final NodeRef node = targetTree.getNode(k); |
| 1591 |
targetTree.setNodeHeight(node, ths[k]); |
| 1592 |
} |
| 1593 |
fileReader.close(); |
| 1594 |
|
| 1595 |
progressStream.println(); |
| 1596 |
progressStream.println(); |
| 1597 |
|
| 1598 |
return true; |
| 1599 |
} |
| 1600 |
} |
| 1601 |
|