Debian Codegraph @

src/dr/app/phylogeography/tools/TreeKMLGenerator.java

raw symbols SCIP
1 /*
2 * TreeKMLGenerator.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.app.phylogeography.tools;
27
28 import dr.app.phylogeography.tools.kml.*;
29 import jebl.evolution.trees.RootedTree;
30 import jebl.evolution.graphs.Node;
31 import jebl.evolution.io.TreeImporter;
32 import jebl.evolution.io.NexusImporter;
33 import jebl.evolution.io.ImportException;
34 import org.jdom.*;
35 import org.jdom.output.XMLOutputter;
36 import org.jdom.output.Format;
37
38 import java.util.*;
39 import java.util.List;
40 import java.awt.*;
41 import java.io.FileReader;
42 import java.io.IOException;
43 import java.io.BufferedWriter;
44 import java.io.FileWriter;
45
46 /**
47 * @author Philippe Lemey
48 * @author Andrew Rambaut
49 * @author Marc A. Suchard
50 */
51 public class TreeKMLGenerator {
52
53 // used to calibrate the color range for the branches
54 double minRate;
55 double maxRate;
56 double medianRate;
57
58 double maxHeight;
59 double maxBranchLength;
60
61 String altitudeMode = "clampToGround";
62
63 private final RootedTree tree;
64 private final Map<String, Location> locationMap;
65
66
67 public TreeKMLGenerator(RootedTree tree) {
68 this(tree, null);
69 }
70
71 public TreeKMLGenerator(RootedTree tree, List<Location> locationList) {
72 this.tree = tree;
73
74 // double[] rates = new double[(tree.getNodes().size() - 1)];
75 //
76 // maxBranchLength = 0.0;
77 // int counter = 0;
78 // for (Node node : tree.getNodes()) {
79 // if (!tree.isRoot(node)) {
80 // rates[counter] = (Double)node.getAttribute("rate");
81 // counter ++;
82 //
83 // if (tree.getLength(node) > maxBranchLength) {
84 // maxBranchLength = tree.getLength(node);
85 // }
86 // }
87 // }
88 //
89 // minRate = DiscreteStatistics.min(rates);
90 // maxRate = DiscreteStatistics.max(rates);
91 // medianRate = DiscreteStatistics.quantile(0.5, rates);
92
93 maxHeight = tree.getHeight(tree.getRootNode());
94 maxBranchLength = 0.0;
95 for (Node node : tree.getNodes()) {
96 if (!tree.isRoot(node)) {
97 if (tree.getLength(node) > maxBranchLength) {
98 maxBranchLength = tree.getLength(node);
99 }
100 }
101 }
102
103 if (locationList != null) {
104 double minLat = Double.MAX_VALUE;
105 double maxLat = -Double.MAX_VALUE;
106 double minLong = Double.MAX_VALUE;
107 double maxLong = -Double.MAX_VALUE;
108
109 locationMap = new HashMap<String, Location>();
110
111 for (Location location : locationList) {
112 if (location.getLatitude() < minLat) {
113 minLat = location.getLatitude();
114 }
115 if (location.getLatitude() > maxLat) {
116 maxLat = location.getLatitude();
117 }
118
119 if (location.getLongitude() < minLong) {
120 minLong = location.getLongitude();
121 }
122 if (location.getLongitude() > maxLong) {
123 maxLong = location.getLongitude();
124 }
125 locationMap.put(location.getState(), location);
126 }
127
128 // radius = 100*Math.abs(maxLat-minLat)*Math.abs(maxLong-minLong);
129 // radius = 200000;
130
131 // if (mostRecentDate - treeToExport.getHeight(treeToExport.getRootNode()) < 0) {
132 // ancient = true;
133 // }
134
135 } else {
136 locationMap = null;
137 }
138 }
139
140 public Element generate(String documentName, Settings settings) {
141
142 Element root = new Element("kml");
143
144 Element doc = new Element("Document");
145 doc.addContent(generateElement("name", documentName));
146
147 List<Element> schema = new ArrayList<Element>();
148 Element branchSchema = new Element("Schema");
149 branchSchema.setAttribute("id", "Branch_Schema");
150 branchSchema.addContent(new Element("SimpleField")
151 .setAttribute("name", "Name")
152 .setAttribute("type", "string")
153 .addContent(new Element("displayName").addContent("Name")));
154 branchSchema.addContent(new Element("SimpleField")
155 .setAttribute("name", "Height")
156 .setAttribute("type", "double")
157 .addContent(new Element("displayName").addContent("Height")));
158 branchSchema.addContent(new Element("SimpleField")
159 .setAttribute("name", "StartTime")
160 .setAttribute("type", "double")
161 .addContent(new Element("displayName").addContent("StartTime")));
162 branchSchema.addContent(new Element("SimpleField")
163 .setAttribute("name", "FinishTime")
164 .setAttribute("type", "double")
165 .addContent(new Element("displayName").addContent("FinishTime")));
166 branchSchema.addContent(new Element("SimpleField")
167 .setAttribute("name", "Support")
168 .setAttribute("type", "double")
169 .addContent(new Element("displayName").addContent("Support")));
170 branchSchema.addContent(new Element("SimpleField")
171 .setAttribute("name", "Rate")
172 .setAttribute("type", "double")
173 .addContent(new Element("displayName").addContent("Rate")));
174 schema.add(branchSchema);
175
176 Element nodeSchema = new Element("Schema");
177 branchSchema.setAttribute("id", "Node_Schema");
178 branchSchema.addContent(new Element("SimpleField")
179 .setAttribute("name", "Label")
180 .setAttribute("type", "string")
181 .addContent(new Element("displayName").addContent("Label")));
182 branchSchema.addContent(new Element("SimpleField")
183 .setAttribute("name", "Height")
184 .setAttribute("type", "double")
185 .addContent(new Element("displayName").addContent("Height")));
186 branchSchema.addContent(new Element("SimpleField")
187 .setAttribute("name", "Time")
188 .setAttribute("type", "double")
189 .addContent(new Element("displayName").addContent("Time")));
190 schema.add(nodeSchema);
191
192 List<Element> styles = new ArrayList<Element>();
193 List<Element> trees = new ArrayList<Element>();
194 List<Element> projections = new ArrayList<Element>();
195 List<Element> taxonLabels = new ArrayList<Element>();
196 List<Element> locationLabels = new ArrayList<Element>();
197 List<Element> contours = new ArrayList<Element>();
198
199 // styles.add(generateLineStyle("projections", 1.0, Color.lightGray));
200 // styles.add(generatePolyStyle("contours", new Color(64, 255, 0, 128)));
201
202 if (settings.getAnalysisType() == AnalysisType.CONTINUOUS) {
203 // trees.add(generateTree(tree, settings, settings.getAltitudeTreeSettings(), styles));
204 trees.add(generateTree(tree, settings, settings.getGroundTreeSettings(), styles));
205
206 // double scaleFactor = settings.getPlotAltitude()/tree.getHeight(tree.getRootNode());
207 //
208 // int nodeNumber = 0;
209 // for (Node node : tree.getNodes()) {
210 // nodeNumber++;
211 //
212 // double latitude = getDoubleNodeAttribute(node, settings.getLatitudeName());
213 // double longitude = getDoubleNodeAttribute(node, settings.getLongitudeName());
214 // double altitude = (tree.getHeight(node)*scaleFactor);
215 //
216 //
217 // if (tree.isExternal(node)) {
218 // projections.add(generateProjection(altitude, latitude, longitude));
219 //
220 // taxonLabels.add(generateTaxonLabel(tree, node, latitude, longitude));
221 // } else {
222 // double date = settings.getMostRecentDate() - tree.getHeight(node);
223 // if (settings.getAgeCutOff() > 0.0 && date > settings.getAgeCutOff()) {
224 //
225 // contours.add(generateContour(
226 // settings.getGroundContours(), tree, node, nodeNumber, 0.0, date,
227 // settings.getTraitName(), settings.getLatitudeName(), settings.getLongitudeName(),
228 // true, styles));
229 // }
230 // }
231 // }
232
233 } else if (settings.getAnalysisType() == AnalysisType.DISCRETE) {
234
235 for (Location location : locationMap.values()) {
236 locationLabels.add(generateLocation(location));
237 }
238
239 } else {
240 throw new IllegalArgumentException("Unknown AnalysisType");
241 }
242
243 doc.addContent(schema);
244 // doc.addContent(styles);
245 doc.addContent(trees);
246
247 if (projections.size() > 0) {
248 Element placeMark = generateContainer("Placemark", "Projections", "projections from tips to surface", true, "projections");
249 placeMark.addContent(new Element("MultiGeometry").addContent(projections));
250 doc.addContent(placeMark);
251 }
252
253 if (taxonLabels.size() > 0) {
254 Element folder = generateContainer("Folder", "Taxon Labels", "Taxon labels", settings.getTaxonLabels().isVisible(), null);
255 folder.addContent(taxonLabels);
256 // placeMark.addContent(new Element("MultiGeometry").addContent(labels));
257 doc.addContent(folder);
258 }
259
260 if (locationLabels.size() > 0) {
261 Element folder = generateContainer("Folder", "Location Labels", "Location labels", settings.getLocationLabels().isVisible(), null);
262 folder.addContent(locationLabels);
263 // placeMark.addContent(new Element("MultiGeometry").addContent(labels));
264 doc.addContent(folder);
265 }
266
267 if (contours.size() > 0) {
268 Element folder = generateContainer("Folder", "Surface Contours", "Contours overlaid on the surface to represent location", true, null);
269 folder.addContent(contours);
270 doc.addContent(folder);
271 }
272
273 root.addContent(doc);
274
275 return root;
276 }
277
278 private Element generateTree(RootedTree tree, Settings settings, TreeSettings treeSettings, List<Element> styles) {
279
280 BranchStyle branchStyle = treeSettings.getBranchStyle();
281
282 Element element = generateContainer("Folder", treeSettings.getName(), treeSettings.getDescription(), true, null);
283
284 double scaleFactor = settings.getPlotAltitude() / tree.getHeight(tree.getRootNode());
285
286 int nodeNumber = 0;
287 for (Node node : tree.getNodes()) {
288 nodeNumber++;
289
290 double latitude;
291 double longitude;
292 Object[] location = getArrayNodeAttribute(node, settings.getTraitName());
293 if (location != null) {
294 latitude = (Double)location[0];
295 longitude = (Double)location[0];
296 } else {
297 latitude = getDoubleNodeAttribute(node, settings.getLatitudeName());
298 longitude = getDoubleNodeAttribute(node, settings.getLongitudeName());
299 }
300 double altitude = (tree.getHeight(node)*scaleFactor);
301 double date = settings.getMostRecentDate() - tree.getHeight(node);
302
303 if (tree.isExternal(node)) {
304 System.out.println(tree.getTaxon(node).getName() + "\t" + latitude + "\t" + longitude);
305 }
306
307 if (!tree.isRoot(node)) {
308
309 // Create each branch of the tree..
310 Element branch;
311
312 String nodeName = treeSettings.getName() + "_node" + nodeNumber;
313 if (tree.isExternal(node)) {
314 Element tip = generateTaxonLabel(tree, node, tree.getTaxon(node).getName(), tree.getHeight(node), date, latitude, longitude);
315 element.addContent(tip);
316 }
317
318 Node parentNode = tree.getParent(node);
319 double parentLatitude = getDoubleNodeAttribute(parentNode, settings.getLatitudeName());
320 double parentLongitude = getDoubleNodeAttribute(parentNode, settings.getLongitudeName());
321 double parentAltitude = (tree.getHeight(parentNode)*scaleFactor);
322 double parentDate = settings.getMostRecentDate() - tree.getHeight(parentNode);
323
324 double width = branchStyle.getWidthBase();
325 if (branchStyle.getWidthProperty() != null) {
326 double property = getDoubleNodeAttribute(node, branchStyle.getWidthProperty(), 0.0);
327 width += ((property - branchStyle.getWidthPropertyMinimum()) /
328 (branchStyle.getWidthPropertyMaximum() - branchStyle.getWidthPropertyMinimum())) * branchStyle.getWidthScale();
329 }
330
331 Color color = branchStyle.getColorStart();
332 if (branchStyle.getColorProperty() != null) {
333 double property;
334 if (branchStyle.getColorProperty().equalsIgnoreCase("height")) {
335 property = tree.getHeight(node) / maxHeight;
336 } else {
337 property = getDoubleNodeAttribute(node, branchStyle.getColorProperty());
338 property = ((property - branchStyle.getWidthPropertyMinimum()) /
339 (branchStyle.getWidthPropertyMaximum() - branchStyle.getWidthPropertyMinimum())) * branchStyle.getWidthScale();
340 }
341 color = getBlendedColor((float)property, branchStyle.getColorStart(), branchStyle.getColorFinish());
342 }
343
344 LineStyle lineStyle = new LineStyle(width, color);
345
346 if (treeSettings.getTreeType() == TreeType.RECTANGLE_TREE ||
347 treeSettings.getTreeType() == TreeType.TRIANGLE_TREE) {
348
349 branch = generateBranch(treeSettings.getTreeType(), tree, node, nodeName,
350 parentLatitude, latitude,
351 parentLongitude, longitude,
352 parentAltitude, altitude,
353 0.0, parentAltitude,
354 date, date,
355 settings.getAgeCutOff(),
356 lineStyle, null,
357 0,
358 styles);
359 } else if (treeSettings.getTreeType() == TreeType.ARC_TREE) {
360
361 LineStyle lineStyle2 = null;
362
363 // If we are coloring by height and we are using subdivided branches (ARC_TREE) then we can give the
364 // color range from the parent height to the node height.
365 if (branchStyle.getColorProperty() != null && branchStyle.getColorProperty().equalsIgnoreCase("height")) {
366 double divisor = (settings.getAgeCutOff() > 0 ? settings.getMostRecentDate() - settings.getAgeCutOff(): maxHeight);
367 color = getBlendedColor((float)(tree.getHeight(parentNode) / divisor), branchStyle.getColorStart(), branchStyle.getColorFinish());
368 lineStyle = new LineStyle(width, color);
369 color = getBlendedColor((float)(tree.getHeight(node) / divisor), branchStyle.getColorStart(), branchStyle.getColorFinish());
370 lineStyle2 = new LineStyle(width, color);
371 }
372
373 branch = generateBranch(treeSettings.getTreeType(), tree, node, nodeName,
374 parentLatitude, latitude,
375 parentLongitude, longitude,
376 parentAltitude, altitude,
377 0.0, parentAltitude,
378 parentDate, date,
379 settings.getAgeCutOff(),
380 lineStyle, lineStyle2,
381 50,
382 styles);
383 } else if (treeSettings.getTreeType() == TreeType.SURFACE_TREE) {
384 double maxAltitude = settings.getPlotAltitude() * (tree.getHeight(parentNode) - tree.getHeight(node)) / maxBranchLength;
385
386 LineStyle lineStyle2 = null;
387
388 // If we are coloring by height and we are using subdivided branches (ARC_TREE) then we can give the
389 // color range from the parent height to the node height.
390 if (branchStyle.getColorProperty() != null && branchStyle.getColorProperty().equalsIgnoreCase("height")) {
391 double divisor = (settings.getAgeCutOff() > 0 ? settings.getMostRecentDate() - settings.getAgeCutOff(): maxHeight);
392 color = getBlendedColor((float)(tree.getHeight(parentNode) / divisor), branchStyle.getColorStart(), branchStyle.getColorFinish());
393 lineStyle = new LineStyle(width, color);
394 color = getBlendedColor((float)(tree.getHeight(node) / divisor), branchStyle.getColorStart(), branchStyle.getColorFinish());
395 lineStyle2 = new LineStyle(width, color);
396 }
397
398 branch = generateBranch(treeSettings.getTreeType(), tree, node, nodeName,
399 parentLatitude, latitude,
400 parentLongitude, longitude,
401 0.0, 0.0,
402 0.5, maxAltitude,
403 parentDate, date,
404 settings.getAgeCutOff(),
405 lineStyle, lineStyle2,
406 settings.getTimeDivisionCount(),
407 styles);
408
409
410 } else {
411 throw new IllegalArgumentException("Unknown TreeType");
412 }
413 element.addContent(branch);
414 }
415 }
416
417 return element;
418 }
419
420 /**
421 * Create a branch that goes from [startLatitude, startLongitude, startAltitude] to
422 * [finishLatitude, finishLongitude, finishAltitude], optionally arching through
423 * peakAltitude. If divisionCount > 0 then the branch is subdivided into segments,
424 * this is required if the branch is arcing or has a colour gradient.
425 * @param treeType the tree type
426 * @param tree the tree
427 * @param node the node
428 * @param nodeName the node's name
429 * @param startLatitude the starting (parental) latitude
430 * @param finishLatitude the finishing (descendent) latitude
431 * @param startLongitude the starting (parental) longitude
432 * @param finishLongitude the finishing (descendent) longitude
433 * @param startAltitude the starting (parental) altitude
434 * @param finishAltitude the finishing (descendent) altitude
435 * @param peakPosition the position of the peak (0 = beginning, 0.5 = midpoint)
436 * @param peakAltitude the peak altitude
437 * @param startDate the starting date
438 * @param finishDate the finishing date
439 * @param divisionCount the number of divisions
440 * @param styles an array into which style elements are put
441 * @return the branch element
442 */
443 private Element generateBranch(TreeType treeType, RootedTree tree, Node node,
444 String nodeName,
445 double startLatitude, double finishLatitude,
446 double startLongitude, double finishLongitude,
447 double startAltitude, double finishAltitude,
448 double peakPosition, double peakAltitude,
449 double startDate, double finishDate,
450 double ageCutOff,
451 LineStyle startStyle, LineStyle finishStyle,
452 int divisionCount,
453 List<Element> styles) {
454
455 Element element;
456
457 Double rate = (Double)node.getAttribute("rate");
458 Double support = (Double)node.getAttribute("posterior");
459 double height = tree.getHeight(node);
460
461 boolean hasDivisionStyles = startStyle != null && finishStyle != null;
462
463 if (divisionCount > 0) {
464 double latDiff = finishLatitude - startLatitude;
465 double latDelta = latDiff / divisionCount;
466
467 double longDiff = finishLongitude - startLongitude;
468 double longDelta = longDiff / divisionCount;
469
470 double altDiff = finishAltitude - startAltitude;
471 double altDelta = altDiff / divisionCount;
472
473 double dateDiff = finishDate - startDate;
474 double dateDelta = dateDiff / divisionCount;
475
476 double lastLatitude = startLatitude;
477 double latitude = startLatitude + latDelta;
478
479 double lastLongitude = startLongitude;
480 double longitude = startLongitude + longDelta;
481
482 // x goes 0 to 1, offset by peak Position
483 double x = -peakPosition;
484 double xDelta = 1.0 / divisionCount;
485 // assume a parabolic curve that peaks at peakAltitude
486 double a = peakAltitude - finishAltitude;
487 if (peakPosition == 0.5) {
488 a *= 4;
489 }
490 double altitude = peakAltitude - (a * (x * x));
491 double lastAltitude = altitude;
492 x += xDelta;
493
494 double date = startDate;
495
496 String styleName = null;
497 if (!hasDivisionStyles && startStyle != null) {
498 styleName = nodeName + "_style";
499
500 styles.add(generateLineStyle(styleName, startStyle.getWidth(), startStyle.getColor()));
501 }
502
503 element = generateContainer("Folder", nodeName, null, (styleName != null ? "#" + styleName : null));
504
505 for (int division = 0; division < divisionCount; division++) {
506 if (ageCutOff == 0.0 || date > ageCutOff) {
507 String partName = nodeName + "_part" + (division + 1);
508 styleName = null;
509 if (hasDivisionStyles) {
510 styleName = partName + "_style";
511 }
512 Element placeMark = generateContainer("Placemark", partName, null, (styleName != null ? "#" + styleName : null));
513
514 annotateBranch(placeMark, height, startDate, finishDate, rate, support);
515
516 if (hasDivisionStyles) {
517 // Create a style for this branch segment
518 double width = startStyle.getWidth();
519 Color color = getBlendedColor(((float)division) / (divisionCount - 1), startStyle.getColor(), finishStyle.getColor());
520 styles.add(generateLineStyle(styleName, width, color));
521 }
522
523 if (dateDiff > 0.0) {
524 Element timeSpan = new Element("TimeSpan");
525
526 //convert height of the branch segment to a real date (based on th date for the most recent sample)
527 timeSpan.addContent(generateElement("begin", getKMLDate(date)));
528 placeMark.addContent(timeSpan);
529
530 }
531
532 Element lineString = new Element("LineString");
533 Element coordinates = new Element("coordinates");
534 if (altDiff > 0.0 || peakAltitude > 0.0) {
535 lineString.addContent(generateElement("altitudeMode", altitudeMode));
536
537 altitude = peakAltitude - (a * (x * x));
538
539 coordinates.addContent("" +lastLongitude + "," +lastLatitude + "," + lastAltitude + "\r");
540 coordinates.addContent("" +longitude + "," +latitude + "," + altitude + "\r");
541 } else {
542 lineString.addContent(generateElement("altitudeMode", "clampToGround"));
543 lineString.addContent(generateElement("tessellate", true));
544
545 coordinates.addContent("" +lastLongitude + "," +lastLatitude + "\r");
546 coordinates.addContent("" +longitude + "," +latitude + "\r");
547 }
548
549 lastLatitude = latitude;
550 latitude += latDelta;
551
552 lastLongitude = longitude;
553 longitude += longDelta;
554
555 lastAltitude = altitude;
556 x += xDelta;
557
558 date += dateDelta;
559
560 lineString.addContent(coordinates);
561
562 placeMark.addContent(lineString);
563
564 element.addContent(placeMark);
565 }
566
567 }
568
569 } else {
570 String styleName = null;
571 if (startStyle != null) {
572 styleName = nodeName + "_style";
573
574 double width = startStyle.getWidth();
575 styles.add(generateLineStyle(styleName, width, startStyle.getColor()));
576 }
577
578 element = generateContainer("Placemark", nodeName, null, (styleName != null ? "#" + styleName : null));
579
580 annotateBranch(element, height, startDate, finishDate, rate, support);
581
582 Element lineString = new Element("LineString");
583 lineString.addContent(generateElement("altitudeMode", altitudeMode));
584
585 Element coordinates = new Element("coordinates");
586 if (treeType == TreeType.RECTANGLE_TREE) {
587 coordinates.addContent(""+finishLongitude+","+finishLatitude+","+finishAltitude+"\r");
588 coordinates.addContent(""+finishLongitude+","+finishLatitude+","+startAltitude+"\r");
589 coordinates.addContent(""+startLongitude+","+startLatitude+","+startAltitude+"\r");
590 } else { // TRIANGLE_TREE
591 coordinates.addContent(""+finishLongitude+","+finishLatitude+","+finishAltitude+"\r");
592 coordinates.addContent(""+startLongitude+","+startLatitude+","+startAltitude+"\r");
593
594 }
595 lineString.addContent(coordinates);
596
597 element.addContent(lineString);
598
599 }
600
601 return element;
602 }
603
604 private void annotateBranch(final Element placeMark, final double height, final double startDate, final double finishDate, final Double rate, final Double support) {
605 Element data = new Element("ExtendedData");
606 Element schemaData = new Element("SchemaData");
607 schemaData.setAttribute("schemaUrl", "#Branch_Schema");
608 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Height").addContent(Double.toString(height)));
609 schemaData.addContent(new Element("SimpleData").setAttribute("name", "StartTime").addContent(Double.toString(startDate)));
610 schemaData.addContent(new Element("SimpleData").setAttribute("name", "FinishTime").addContent(Double.toString(finishDate)));
611 if (support != null) {
612 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Support").addContent(Double.toString(support)));
613 }
614 if (rate != null) {
615 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Rate").addContent(Double.toString(rate)));
616 }
617 data.addContent(schemaData);
618 placeMark.addContent(data);
619 }
620
621 private void annotateTip(final Element placeMark, final String label, final double height, final double date) {
622 Element data = new Element("ExtendedData");
623 Element schemaData = new Element("SchemaData");
624 schemaData.setAttribute("schemaUrl", "#Node_Schema");
625 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Label").addContent(label));
626 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Height").addContent(Double.toString(height)));
627 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Time").addContent(Double.toString(date)));
628 data.addContent(schemaData);
629 placeMark.addContent(data);
630 }
631
632 private Element generateContour(SurfaceDecoration surfaces, RootedTree tree,
633 Node node, int nodeNumber, double plotHeight, double date,
634 String latLongName, String latitudeName, String longitudeName,
635 boolean clampToGround, List<Element> styles) {
636
637 String nodeName = "contour" + nodeNumber;
638 String styleName = "contours";
639 Element placemark = generateContainer("Placemark", nodeName, null, (styleName != null ? "#" + styleName : null));
640
641
642 Element timeSpan = new Element("TimeSpan");
643 timeSpan.addContent(generateElement("begin", getKMLDate(date)));
644 placemark.addContent(timeSpan);
645
646 double altitude = 0;
647
648 if (!clampToGround) {
649 double scaleFactor = plotHeight/tree.getHeight(tree.getRootNode());
650 altitude = (tree.getHeight(node)*scaleFactor);
651 }
652
653 int modality = getIntegerNodeAttribute(node, latLongName+"_95%HPD_modality");
654
655 Element container = placemark;
656 if (modality > 1) {
657 container = new Element("MultiGeometry");
658 placemark.addContent(container);
659 }
660
661 for (int x = 0; x < modality; x++) {
662 Object[] latitudeHPDs = getArrayNodeAttribute(node, latitudeName+"_95%HPD_"+(x + 1));
663 Object[] longitudeHPDs = getArrayNodeAttribute(node, longitudeName+"_95%HPD_"+(x + 1));
664
665 container.addContent(generateContourPolygon(latitudeHPDs, longitudeHPDs, altitude, clampToGround));
666 }
667
668 // if (styleName != null) {
669 // styles.add(generatePolyStyle(styleName, surfaces.getStartColor()));
670 // }
671
672 return placemark;
673 }
674
675 private Element generateContourPolygon(Object[] latitudeHPDs, Object[] longitudeHPDs, double altitude, boolean clampToGround) {
676
677 Element polygon = new Element("Polygon");
678 if (clampToGround) {
679 polygon.addContent(generateElement("altitudeMode", "clampToGround"));
680 polygon.addContent(generateElement("tessellate", true));
681 } else {
682 polygon.addContent(generateElement("altitudeMode", altitudeMode));
683 }
684 Element outerBoundaryIs = new Element("outerBoundaryIs");
685 Element linearRing = new Element("LinearRing");
686 Element coordinates = new Element("coordinates");
687 if (clampToGround) {
688 for (int y = 0; y < longitudeHPDs.length; y++) {
689 coordinates.addContent(""+longitudeHPDs[y]+","+latitudeHPDs[y]+"\r");
690 }
691 } else {
692 for (int y = 0; y < longitudeHPDs.length; y++) {
693 coordinates.addContent(""+longitudeHPDs[y]+","+latitudeHPDs[y]+","+altitude+"\r");
694 }
695 }
696 linearRing.addContent(coordinates);
697 outerBoundaryIs.addContent(linearRing);
698 polygon.addContent(outerBoundaryIs);
699
700 return polygon;
701 }
702
703
704
705 private Element generateProjection(double altitude, double latitude, double longitude) {
706
707 Element lineString = new Element("LineString");
708 lineString.addContent(generateElement("altitudeMode", altitudeMode));
709 Element coordinates = new Element("coordinates");
710 coordinates.addContent(""+longitude+","+latitude+","+altitude+"\r");
711 coordinates.addContent(""+longitude+","+latitude+",0\r");
712 lineString.addContent(coordinates);
713
714 return lineString;
715 }
716
717
718 private Element generateTaxonLabel(RootedTree tree, Node node, String label, double height, double date, double latitude, double longitude) {
719
720 Element placeMark = generateContainer("Placemark", tree.getTaxon(node).getName(), null, null);
721
722 annotateTip(placeMark, label, height, date);
723
724 Element point = new Element("Point");
725 point.addContent(generateElement("altitudeMode", "clampToGround"));
726 Element coordinates = new Element("coordinates");
727 coordinates.addContent(""+longitude+","+latitude+"\r");
728 point.addContent(coordinates);
729 placeMark.addContent(point);
730
731 return placeMark;
732 }
733
734
735 private Element generateLocation(Location location) {
736
737 Element placeMark = generateContainer("Placemark", location.getName(), null, null);
738
739 Element point = new Element("Point");
740 point.addContent(generateElement("altitudeMode", "clampToGround"));
741 Element coordinates = new Element("coordinates");
742 coordinates.addContent("" + location.getLongitude() + "," + location.getLatitude() + ",0\r");
743 point.addContent(coordinates);
744 placeMark.addContent(point);
745
746 return placeMark;
747 }
748
749 private Element generateLineStyle(String styleName, double width, Color color) {
750 Element style = new Element("Style");
751 style.setAttribute("id", styleName);
752
753 Element lineStyle = new Element("LineStyle");
754 lineStyle.addContent(generateElement("width", "" + width));
755 lineStyle.addContent(generateElement("color", getKMLColor(color)));
756 style.addContent(lineStyle);
757
758 return style;
759 }
760
761 private Element generatePolyStyle(String styleName, Color color) {
762 Element style = new Element("Style");
763 style.setAttribute("id", styleName);
764
765 Element polyStyle = new Element("PolyStyle");
766 polyStyle.addContent(generateElement("color", getKMLColor(color)));
767 polyStyle.addContent(generateElement("outline", false));
768 style.addContent(polyStyle);
769
770 return style;
771 }
772
773 private Element generatePolyStyle(String styleName, Color color, double outlineWidth, Color outlineColor) {
774 Element style = new Element("Style");
775 style.setAttribute("id", styleName);
776
777 Element lineStyle = new Element("LineStyle");
778 lineStyle.addContent(generateElement("width", "" + outlineWidth));
779 lineStyle.addContent(generateElement("color", getKMLColor(outlineColor)));
780 style.addContent(lineStyle);
781
782 Element polyStyle = new Element("PolyStyle");
783 polyStyle.addContent(generateElement("color", getKMLColor(color)));
784 polyStyle.addContent(generateElement("outline", true));
785 style.addContent(polyStyle);
786
787 return style;
788 }
789
790
791 private Element generateContainer(String elementTag, String name, String description, String styleURL) {
792 Element element = new Element(elementTag);
793 if (name != null) {
794 element.addContent(generateElement("name", name));
795 }
796 if (description != null) {
797 element.addContent(generateElement("description", description));
798 }
799 if (styleURL != null) {
800 element.addContent(generateElement("styleUrl", styleURL));
801 }
802 return element;
803 }
804
805 private Element generateContainer(String elementTag, String name, String description, boolean visibility, String styleURL) {
806 Element element = new Element(elementTag);
807 if (name != null) {
808 element.addContent(generateElement("name", name));
809 }
810 if (description != null) {
811 element.addContent(generateElement("description", description));
812 }
813 if (styleURL != null) {
814 element.addContent(generateElement("styleUrl", styleURL));
815 }
816 element.addContent(generateElement("visibility", visibility));
817 return element;
818 }
819
820 private Element generateElement(String elementName, boolean content) {
821 Element e = new Element(elementName);
822 e.addContent(content ? "1" : "0");
823 return e;
824 }
825
826 private Element generateElement(String elementName, String content) {
827 Element e = new Element(elementName);
828 e.addContent(content);
829 return e;
830 }
831
832 private static String getKMLDate(double fractionalDate) {
833
834 int year = (int) fractionalDate;
835 String yearString;
836
837 if (year < 10) {
838 yearString = "000"+year;
839 } else if (year < 100) {
840 yearString = "00"+year;
841 } else if (year < 1000) {
842 yearString = "0"+year;
843 } else {
844 yearString = ""+year;
845 }
846
847 double fractionalMonth = fractionalDate - year;
848
849 int month = (int) (12.0 * fractionalMonth);
850 String monthString;
851
852 if (month < 10) {
853 monthString = "0"+month;
854 } else {
855 monthString = ""+month;
856 }
857
858 int day = (int) Math.round(30*(12*fractionalMonth - month));
859 String dayString;
860
861 if (day < 10) {
862 dayString = "0"+day;
863 } else {
864 dayString = ""+day;
865 }
866
867
868 return yearString + "-" + monthString + "-" + dayString;
869 }
870
871
872 private int getIntegerNodeAttribute(Node node, String attributeName) {
873 if (node.getAttribute(attributeName) == null) {
874 throw new RuntimeException("Attribute, " + attributeName + ", missing from node");
875 }
876 return (Integer)node.getAttribute(attributeName);
877 }
878
879 private int getIntegerNodeAttribute(Node node, String attributeName, int defaultValue) {
880 if (node.getAttribute(attributeName) == null) {
881 return defaultValue;
882 }
883 return (Integer)node.getAttribute(attributeName);
884 }
885
886 private double getDoubleNodeAttribute(Node node, String attributeName) {
887 if (node.getAttribute(attributeName) == null) {
888 throw new RuntimeException("Attribute, " + attributeName + ", missing from node");
889 }
890 return (Double)node.getAttribute(attributeName);
891 }
892
893 private double getDoubleNodeAttribute(Node node, String attributeName, double defaultValue) {
894 if (node.getAttribute(attributeName) == null) {
895 return defaultValue;
896 }
897 return (Double)node.getAttribute(attributeName);
898 }
899
900 private Object[] getArrayNodeAttribute(Node node, String attributeName) {
901 if (node.getAttribute(attributeName) == null) {
902 return null;
903 // throw new RuntimeException("Attribute, " + attributeName + ", missing from node");
904 }
905 return (Object[])node.getAttribute(attributeName);
906 }
907
908 /**
909 * converts a Java color into a 4 channel hex color string.
910 * @param color
911 * @return the color string
912 */
913 public static String getKMLColor(Color color) {
914 String a = Integer.toHexString(color.getAlpha());
915 String b = Integer.toHexString(color.getBlue());
916 String g = Integer.toHexString(color.getGreen());
917 String r = Integer.toHexString(color.getRed());
918 return (a.length() < 2 ? "0" : "") + a +
919 (b.length() < 2 ? "0" : "") + b +
920 (g.length() < 2 ? "0" : "") + g +
921 (r.length() < 2 ? "0" : "") + r;
922 }
923
924 /**
925 * converts a Java color into a 4 channel hex color string.
926 * @param color
927 * @return the color string
928 */
929 public static String getKMLColor(Color color, double opacity) {
930 int alpha = (int)(256 * (1.0 - opacity));
931 String a = Integer.toHexString(alpha);
932 String b = Integer.toHexString(color.getBlue());
933 String g = Integer.toHexString(color.getGreen());
934 String r = Integer.toHexString(color.getRed());
935 return (a.length() < 2 ? "0" : "") + a +
936 (b.length() < 2 ? "0" : "") + b +
937 (g.length() < 2 ? "0" : "") + g +
938 (r.length() < 2 ? "0" : "") + r;
939 }
940
941 public static Color getBlendedColor(float proportion, Color startColor, Color endColor) {
942 proportion = Math.max(proportion, 0.0F);
943 proportion = Math.min(proportion, 1.0F);
944 float[] start = startColor.getRGBColorComponents(null);
945 float[] end = endColor.getRGBColorComponents(null);
946
947 float[] color = new float[start.length];
948 for (int i = 0; i < start.length; i++) {
949 color[i] = start[i] + ((end[i] - start[i]) * proportion);
950 }
951
952 return new Color(color[0], color[1], color[2]);
953 }
954
955 public static void main(String[] args) {
956
957
958 String inputTreeFile = args[0];
959 RootedTree tree = null;
960
961 try {
962 TreeImporter importer = new NexusImporter(new FileReader(inputTreeFile));
963 tree = (RootedTree)importer.importNextTree();
964 } catch (ImportException e) {
965 e.printStackTrace();
966 return;
967 } catch (IOException e) {
968 e.printStackTrace();
969 return;
970 }
971
972 TreeKMLGenerator generator = new TreeKMLGenerator(tree);
973 Settings settings = new Settings(AnalysisType.CONTINUOUS);
974 // settings.getAltitudeTreeSettings().setTreeType(TreeType.ARC_TREE);
975 // settings.getAltitudeTreeSettings().getBranchStyle().setColorProperty("height");
976 settings.getGroundTreeSettings().setTreeType(TreeType.SURFACE_TREE);
977 settings.getGroundTreeSettings().getBranchStyle().setColorProperty("height");
978 settings.setPlotAltitude(0);
979 settings.setMostRecentDate(2003);
980 //settings.setAgeCutOff(1995);
981 settings.setTimeDivisionCount(0);
982
983 settings.setTraitName("antigenic");
984 settings.setLatitudeName("antigenic1");
985 settings.setLongitudeName("antigenic2");
986
987 try {
988
989 BufferedWriter out = new BufferedWriter(new FileWriter(args[0]+".kml"));
990 Document doc = new Document(generator.generate(args[0], settings));
991
992 try {
993 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
994 outputter.output(doc, out);
995 }
996 catch (IOException e) {
997 System.err.println(e);
998 }
999 out.close();
1000 } catch (IOException e) {
1001 e.printStackTrace();
1002 return;
1003 }
1004
1005 }
1006
1007 }