Debian Codegraph @

src/dr/app/tools/AntigenicPlotter.java

raw symbols SCIP
1 /*
2 * AntigenicPlotter.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.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.NexusImporter;
32 import dr.evolution.tree.NodeRef;
33 import dr.evolution.tree.Tree;
34 import dr.geo.KMLCoordinates;
35 import dr.geo.KernelDensityEstimator2D;
36 import dr.geo.contouring.*;
37 import dr.inference.trace.*;
38 import dr.math.Procrustes;
39 import dr.util.Version;
40 import org.apache.commons.math.linear.*;
41 import org.apache.commons.math.stat.StatUtils;
42 import org.apache.commons.math.stat.correlation.Covariance;
43 import org.jdom.Element;
44 import org.jdom.output.Format;
45 import org.jdom.output.XMLOutputter;
46
47 import javax.transaction.xa.Xid;
48 import java.awt.geom.AffineTransform;
49 import java.awt.geom.Point2D;
50 import java.io.*;
51 import java.util.*;
52
53 /*
54 * @author Marc Suchard and Andrew Rambaut
55 */
56
57 public class AntigenicPlotter {
58
59 private final static Version version = new BeastVersion();
60
61 public final static ContourMode CONTOUR_MODE = ContourMode.SNYDER;
62 public final static double HPD_VALUE = 0.95;
63 public static final int GRIDSIZE = 200;
64
65 public AntigenicPlotter(int burnin,
66 boolean tabFormat,
67 boolean discreteModel,
68 final String inputFileName,
69 final String treeFileName,
70 final String outputFileName
71 ) throws IOException {
72
73 double[][] reference = null;
74 List<String> tipLabels = null;
75
76 if (treeFileName != null) {
77 System.out.println("Reading tree file...");
78
79
80 NexusImporter importer = new NexusImporter(new FileReader(treeFileName));
81 try {
82 Tree tree = importer.importNextTree();
83
84 reference = new double[tree.getExternalNodeCount()][2];
85 tipLabels = new ArrayList<String>();
86
87 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
88 NodeRef tip = tree.getExternalNode(i);
89 tipLabels.add(tree.getNodeTaxon(tip).getId());
90
91 reference[i][0] = (Double)tree.getNodeAttribute(tip, "antigenic1");
92 reference[i][1] = (Double)tree.getNodeAttribute(tip, "antigenic2");
93 }
94 } catch (Importer.ImportException e) {
95 e.printStackTrace();
96 return;
97 }
98 }
99
100 System.out.println("Reading log file...");
101
102 FileReader fileReader = new FileReader(inputFileName);
103 try {
104 File file = new File(inputFileName);
105
106 LogFileTraces traces = new LogFileTraces(inputFileName, file);
107 traces.loadTraces();
108
109 if (burnin == -1) {
110 burnin = (int) (traces.getMaxState() / 10);
111 }
112
113 traces.setBurnIn(burnin);
114
115 System.out.println();
116 System.out.println("burnIn <= " + burnin);
117 System.out.println("maxState = " + traces.getMaxState());
118 System.out.println();
119
120 int traceCount = traces.getTraceCount();
121 if (discreteModel) {
122 // for the discrete model, there are 4 sets of traces, pairs coordinates, cluster allocations, and cluster sizes
123 traceCount /= 4;
124 } else {
125 // for continuous, just pairs of coordinates
126 traceCount /= 2;
127 }
128
129 int stateCount = traces.getStateCount();
130
131 double[][][] data;
132 String[] labels = new String[traceCount];
133
134 if (tipLabels != null) {
135 data = new double[stateCount][tipLabels.size()][2];
136 } else {
137 data = new double[stateCount][traceCount][2];
138 }
139
140 for (int i = 0; i < traceCount; i++) {
141 String name = traces.getTraceName(i * 2);
142 name = name.substring(0, name.length() - 1);
143
144 if (tipLabels != null) {
145 int index = tipLabels.indexOf(name);
146 if (index != -1) {
147 for (int j = 0; j < stateCount; j++) {
148 data[j][index][0] = traces.getStateValue(i * 2, j);
149 data[j][index][1] = traces.getStateValue((i * 2) + 1, j);
150 }
151 }
152 } else {
153 for (int j = 0; j < stateCount; j++) {
154 data[j][i][0] = traces.getStateValue(i * 2, j);
155 data[j][i][1] = traces.getStateValue((i * 2) + 1, j);
156 }
157 labels[i] = name;
158 }
159 }
160
161 int[][] clusterIndices = null;
162 int[][] clusterSizes = null;
163
164 if (discreteModel) {
165 clusterIndices = new int[stateCount][traceCount];
166 clusterSizes = new int[stateCount][traceCount];
167
168 for (int i = 0; i < traceCount; i++) {
169 for (int j = 0; j < stateCount; j++) {
170 clusterIndices[j][i] = (int)traces.getStateValue((traceCount * 2) + i, j);
171 clusterSizes[j][i] = (int)traces.getStateValue((traceCount * 3) + i, j);
172 }
173 }
174
175 Map<BitSet, Integer> clusterMap = new HashMap<BitSet, Integer>();
176
177 for (int i = 0; i < stateCount; i++) {
178 BitSet[] clusters = new BitSet[clusterIndices[i].length];
179 for (int j = 0; j < clusterIndices[i].length; j++) {
180 BitSet bits = clusters[clusterIndices[i][j]];
181
182 if (bits == null) {
183 bits = new BitSet();
184 clusters[clusterIndices[i][j]] = bits;
185 }
186 bits.set(j);
187
188 Integer count = clusterMap.get(bits);
189 if (count == null) {
190 count = 0;
191 }
192 clusterMap.put(bits, count+1);
193 }
194
195 Arrays.sort(clusters, new Comparator<BitSet>() {
196 public int compare(BitSet bitSet1, BitSet bitSet2) {
197 if (bitSet1 == null) {
198 return -1;
199 }
200 if (bitSet2 == null) {
201 return 1;
202 }
203 return bitSet2.cardinality() - bitSet1.cardinality();
204 }
205 });
206 }
207
208 for (BitSet bits : clusterMap.keySet()) {
209 int count = clusterMap.get(bits);
210 if (count > 1) {
211 System.out.print(count);
212 for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i+1)) {
213 System.out.print("\t" + labels[i]);
214 }
215 System.out.println();
216 }
217 }
218 }
219
220 if (tipLabels != null) {
221 labels = new String[tipLabels.size()];
222 tipLabels.toArray(labels);
223 }
224
225 if (reference != null) {
226 procrustinate(data, reference);
227 } else {
228 procrustinate(data);
229 }
230
231 if (tabFormat) {
232 writeTabformat(outputFileName, labels, data);
233 } else {
234 if (discreteModel) {
235 writeKML(outputFileName, labels, data, clusterIndices, clusterSizes);
236 } else {
237 writeKML(outputFileName, labels, data);
238 }
239 }
240
241 } catch (Exception e) {
242 System.err.println("Error Parsing Input File: " + e.getMessage());
243
244 e.printStackTrace(System.err);
245 return;
246 }
247 fileReader.close();
248
249 }
250
251
252 private void procrustinate(final double[][][] data) {
253 RealMatrix Xstar = new Array2DRowRealMatrix(data[data.length - 1]);
254 for (int i = 0; i < data.length - 1; i++) {
255 RealMatrix X = new Array2DRowRealMatrix(data[i]);
256 RealMatrix Xnew = Procrustes.procrustinate(X, Xstar, true, true);
257 data[i] = Xnew.getData();
258 }
259 }
260
261 private void procrustinate(final double[][][] data, final double[][] reference) {
262 RealMatrix Xstar = new Array2DRowRealMatrix(reference);
263 for (int i = 0; i < data.length; i++) {
264 RealMatrix X = new Array2DRowRealMatrix(data[i]);
265 RealMatrix Xnew = Procrustes.procrustinate(X, Xstar, true, true);
266 data[i] = Xnew.getData();
267 }
268 }
269
270 private void writeTabformat(String fileName, String[] labels, double[][][] data) {
271 int[] traceOrder = sortTraces(labels);
272
273 try {
274 PrintWriter writer = new PrintWriter(new FileWriter(fileName));
275
276 writer.print("state");
277
278 for (int j = 0; j < data[0].length; j++) {
279 writer.print("\t"+labels[traceOrder[j]] + "_1");
280 writer.print("\t"+labels[traceOrder[j]] + "_2");
281 }
282 writer.println();
283
284 for (int i = 0; i < data.length; i++) {
285 writer.print(i);
286 for (int j = 0; j < data[i].length; j++) {
287 writer.print("\t" + data[i][traceOrder[j]][0]+"\t"+data[i][traceOrder[j]][1]);
288 }
289 writer.println();
290 }
291
292 writer.close();
293 } catch (IOException e) {
294 System.err.println("Error opening file: " + fileName);
295 System.exit(-1);
296 }
297
298 }
299 private void writeKML(String fileName, String[] labels, double[][][] data) {
300 int[] traceOrder = sortTraces(labels);
301
302 // Element hpdSchema = new Element("Schema");
303 // hpdSchema.setAttribute("id", "HPD_Schema");
304 // hpdSchema.addContent(new Element("SimpleField")
305 // .setAttribute("name", "Label")
306 // .setAttribute("type", "string")
307 // .addContent(new Element("displayName").addContent("Label")));
308 // hpdSchema.addContent(new Element("SimpleField")
309 // .setAttribute("name", "Point")
310 // .setAttribute("type", "double")
311 // .addContent(new Element("displayName").addContent("Point")));
312 // hpdSchema.addContent(new Element("SimpleField")
313 // .setAttribute("name", "Year")
314 // .setAttribute("type", "double")
315 // .addContent(new Element("displayName").addContent("Year")));
316 // hpdSchema.addContent(new Element("SimpleField")
317 // .setAttribute("name", "HPD")
318 // .setAttribute("type", "double")
319 // .addContent(new Element("displayName").addContent("HPD")));
320
321 Element traceSchema = new Element("Schema");
322 traceSchema.setAttribute("id", "Trace_Schema");
323 traceSchema.addContent(new Element("SimpleField")
324 .setAttribute("name", "Label")
325 .setAttribute("type", "string")
326 .addContent(new Element("displayName").addContent("Label")));
327 traceSchema.addContent(new Element("SimpleField")
328 .setAttribute("name", "Trace")
329 .setAttribute("type", "double")
330 .addContent(new Element("displayName").addContent("Trace")));
331 traceSchema.addContent(new Element("SimpleField")
332 .setAttribute("name", "Year")
333 .setAttribute("type", "double")
334 .addContent(new Element("displayName").addContent("Year")));
335 traceSchema.addContent(new Element("SimpleField")
336 .setAttribute("name", "State")
337 .setAttribute("type", "double")
338 .addContent(new Element("displayName").addContent("State")));
339
340 Element centroidSchema = new Element("Schema");
341 centroidSchema.setAttribute("id", "Centroid_Schema");
342 centroidSchema.addContent(new Element("SimpleField")
343 .setAttribute("name", "Label")
344 .setAttribute("type", "string")
345 .addContent(new Element("displayName").addContent("Label")));
346 centroidSchema.addContent(new Element("SimpleField")
347 .setAttribute("name", "Year")
348 .setAttribute("type", "double")
349 .addContent(new Element("displayName").addContent("Year")));
350 centroidSchema.addContent(new Element("SimpleField")
351 .setAttribute("name", "Trace")
352 .setAttribute("type", "double")
353 .addContent(new Element("displayName").addContent("Trace")));
354
355 // final Element contourFolderElement = new Element("Folder");
356 // Element contourFolderNameElement = new Element("name");
357 // contourFolderNameElement.addContent("HPDs");
358 // contourFolderElement.addContent(contourFolderNameElement);
359
360 final Element traceFolderElement = new Element("Folder");
361 Element traceFolderNameElement = new Element("name");
362 traceFolderNameElement.addContent("traces");
363 traceFolderElement.addContent(traceFolderNameElement);
364
365 final Element centroidFolderElement = new Element("Folder");
366 Element centroidFolderNameElement = new Element("name");
367 centroidFolderNameElement.addContent("centroids");
368 centroidFolderElement.addContent(centroidFolderNameElement);
369
370 Element documentNameElement = new Element("name");
371 String documentName = fileName;
372 if (documentName.endsWith(".kml"))
373 documentName = documentName.replace(".kml", "");
374 documentNameElement.addContent(documentName);
375
376 final Element documentElement = new Element("Document");
377 documentElement.addContent(documentNameElement);
378 documentElement.addContent(traceSchema);
379 documentElement.addContent(centroidSchema);
380 // documentElement.addContent(hpdSchema);
381 documentElement.addContent(centroidFolderElement);
382 documentElement.addContent(traceFolderElement);
383 // documentElement.addContent(contourFolderElement);
384
385 final Element rootElement = new Element("kml");
386 rootElement.addContent(documentElement);
387
388 Element traceElement = generateTraceElement(labels, data, traceOrder);
389 traceFolderElement.addContent(traceElement);
390
391 Element centroidElement = generateCentroidElement(labels, data, traceOrder);
392 centroidFolderElement.addContent(centroidElement);
393
394 // Element contourElement = generateKDEElement(0.95, labels, data, traceOrder);
395 // contourFolderElement.addContent(contourElement);
396
397 PrintStream resultsStream;
398
399 try {
400 resultsStream = new PrintStream(new File(fileName));
401 XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE));
402 xmlOutputter.output(rootElement, resultsStream);
403
404 } catch (IOException e) {
405 System.err.println("Error opening file: " + fileName);
406 System.exit(-1);
407 }
408
409 }
410
411 /**
412 * Discrete KML
413 * @param fileName
414 * @param labels
415 * @param data
416 * @param clusterIndices
417 * @param clusterSizes
418 */
419 private void writeKML(String fileName, String[] labels, double[][][] data, int[][] clusterIndices, int[][] clusterSizes) {
420 int[] traceOrder = sortTraces(labels);
421
422 Element traceSchema = new Element("Schema");
423 traceSchema.setAttribute("id", "Cluster_Schema");
424 traceSchema.addContent(new Element("SimpleField")
425 .setAttribute("name", "Label")
426 .setAttribute("type", "string")
427 .addContent(new Element("displayName").addContent("Label")));
428 traceSchema.addContent(new Element("SimpleField")
429 .setAttribute("name", "Number")
430 .setAttribute("type", "double")
431 .addContent(new Element("displayName").addContent("Number")));
432 traceSchema.addContent(new Element("SimpleField")
433 .setAttribute("name", "Year")
434 .setAttribute("type", "double")
435 .addContent(new Element("displayName").addContent("Year")));
436 traceSchema.addContent(new Element("SimpleField")
437 .setAttribute("name", "State")
438 .setAttribute("type", "double")
439 .addContent(new Element("displayName").addContent("State")));
440
441 Element virusSchema = new Element("Schema");
442 virusSchema.setAttribute("id", "Virus_Schema");
443 virusSchema.addContent(new Element("SimpleField")
444 .setAttribute("name", "Label")
445 .setAttribute("type", "string")
446 .addContent(new Element("displayName").addContent("Label")));
447 virusSchema.addContent(new Element("SimpleField")
448 .setAttribute("name", "Year")
449 .setAttribute("type", "double")
450 .addContent(new Element("displayName").addContent("Year")));
451 virusSchema.addContent(new Element("SimpleField")
452 .setAttribute("name", "Trace")
453 .setAttribute("type", "double")
454 .addContent(new Element("displayName").addContent("Trace")));
455
456 // final Element contourFolderElement = new Element("Folder");
457 // Element contourFolderNameElement = new Element("name");
458 // contourFolderNameElement.addContent("HPDs");
459 // contourFolderElement.addContent(contourFolderNameElement);
460
461 final Element traceFolderElement = new Element("Folder");
462 Element traceFolderNameElement = new Element("name");
463 traceFolderNameElement.addContent("traces");
464 traceFolderElement.addContent(traceFolderNameElement);
465
466 final Element clustersFolderElement = new Element("Folder");
467 Element clustersFolderNameElement = new Element("name");
468 clustersFolderNameElement.addContent("clusters");
469 clustersFolderElement.addContent(clustersFolderNameElement);
470
471 Element documentNameElement = new Element("name");
472 String documentName = fileName;
473 if (documentName.endsWith(".kml"))
474 documentName = documentName.replace(".kml", "");
475 documentNameElement.addContent(documentName);
476
477 final Element documentElement = new Element("Document");
478 documentElement.addContent(documentNameElement);
479 documentElement.addContent(traceSchema);
480 documentElement.addContent(virusSchema);
481 // documentElement.addContent(hpdSchema);
482 documentElement.addContent(clustersFolderElement);
483 documentElement.addContent(traceFolderElement);
484 // documentElement.addContent(contourFolderElement);
485
486 final Element rootElement = new Element("kml");
487 rootElement.addContent(documentElement);
488
489 Element traceElement = generateTraceElement(labels, data, traceOrder);
490 traceFolderElement.addContent(traceElement);
491
492 Element clustersElement = generateClusterElement(labels, data, clusterIndices, clusterSizes, traceOrder);
493 clustersFolderElement.addContent(clustersElement);
494
495 // Element contourElement = generateKDEElement(0.95, labels, data, traceOrder);
496 // contourFolderElement.addContent(contourElement);
497
498 PrintStream resultsStream;
499
500 try {
501 resultsStream = new PrintStream(new File(fileName));
502 XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE));
503 xmlOutputter.output(rootElement, resultsStream);
504
505 } catch (IOException e) {
506 System.err.println("Error opening file: " + fileName);
507 System.exit(-1);
508 }
509 }
510
511 private int[] sortTraces(final String[] labels) {
512 Map<Label, Integer> orderMap = new HashMap<Label, Integer>();
513
514 List<Label> labelList = new ArrayList<Label>();
515 int i = 0;
516 for (String label : labels) {
517 Label l = new Label(label);
518 labelList.add(l);
519 orderMap.put(l, i);
520 i++;
521 }
522 Collections.sort(labelList);
523
524 int[] order = new int[labels.length];
525 i = 0;
526 for (Label label : labelList) {
527 int index = orderMap.get(label);
528 order[i] = index;
529 i++;
530 }
531
532 return order;
533 }
534
535 class Label implements Comparable<Label> {
536 Label(final String label) {
537 this.label = label;
538 String[] parts = label.split("[/_-]");
539 try {
540 year = Integer.parseInt(parts[parts.length - 1]);
541 } catch (NumberFormatException nfe) {
542 return;
543 }
544 if (year < 12) {
545 year += 2000;
546 } else {
547 year += 1900;
548 }
549 }
550
551 public int compareTo(final Label label) {
552 return this.year - label.year;
553 }
554
555 String label;
556 int year;
557
558
559 }
560 private Element generateKDEElement(double hpdValue, String[] labels, double[][][] points, int[] order) {
561 Element traceElement = new Element("Folder");
562 Element nameElement = new Element("name");
563 String name = "intervals";
564
565 nameElement.addContent(name);
566 traceElement.addContent(nameElement);
567
568 for (int j = 0; j < points[0].length; j++) {
569 double x[] = new double[points.length];
570 double y[] = new double[points.length];
571 for (int i = 0; i < points.length; i++) {
572 x[i] = points[i][order[j]][0];
573 y[i] = points[i][order[j]][1];
574 }
575
576 ContourMaker contourMaker;
577 if (CONTOUR_MODE == ContourMode.JAVA)
578 contourMaker = new KernelDensityEstimator2D(x, y, GRIDSIZE);
579 else if (CONTOUR_MODE == ContourMode.R)
580 contourMaker = new ContourWithR(x, y, GRIDSIZE);
581 else if (CONTOUR_MODE == ContourMode.SNYDER)
582 contourMaker = new ContourWithSynder(x, y, GRIDSIZE);
583 else
584 throw new RuntimeException("Unimplemented ContourModel!");
585
586 ContourPath[] paths = contourMaker.getContourPaths(HPD_VALUE);
587 int pathCounter = 1;
588 for (ContourPath path : paths) {
589
590 KMLCoordinates coords = new KMLCoordinates(path.getAllX(), path.getAllY());
591
592 //because KML polygons require long,lat,alt we need to switch lat and long first
593 coords.switchXY();
594 Element placemarkElement = generatePlacemarkElementWithPolygon(hpdValue, coords, -1, pathCounter);
595 //testing how many points are within the polygon
596 traceElement.addContent(placemarkElement);
597
598 pathCounter ++;
599 }
600
601 }
602 return traceElement;
603 }
604
605 private Element generateTraceElement(String[] labels, double[][][] points, int[] order) {
606 Element traceElement = new Element("Folder");
607 Element nameElement = new Element("name");
608 String name = "points";
609
610 nameElement.addContent(name);
611 traceElement.addContent(nameElement);
612
613 for (int i = 0; i < points.length; i++) {
614 for (int j = 0; j < points[i].length; j++) {
615 Element placemarkElement = new Element("Placemark");
616
617 placemarkElement.addContent(generateTraceData(labels[order[j]], j, i));
618
619
620 Element pointElement = new Element("Point");
621 Element coordinates = new Element("coordinates");
622 coordinates.addContent(points[i][order[j]][1]+","+points[i][order[j]][0]+",0");
623 pointElement.addContent(coordinates);
624 placemarkElement.addContent(pointElement);
625
626 traceElement.addContent(placemarkElement);
627
628 }
629
630 }
631 return traceElement;
632 }
633
634 private Element generateTraceData(String label, int trace, int state) {
635 Element data = new Element("ExtendedData");
636 Element schemaData = new Element("SchemaData");
637 schemaData.setAttribute("schemaUrl", "Trace_Schema");
638 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Label").addContent(label));
639 Label l = new Label(label);
640 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Year").addContent(Integer.toString(l.year)));
641 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Trace").addContent(Integer.toString(trace)));
642 schemaData.addContent(new Element("SimpleData").setAttribute("name", "State").addContent(Integer.toString(state)));
643 data.addContent(schemaData);
644 return data;
645 }
646
647 private Element generateCentroidElement(String[] labels, double[][][] points, int[] order) {
648 Element centroidElement = new Element("Folder");
649 Element nameElement = new Element("name");
650 String name = "centroids";
651
652 nameElement.addContent(name);
653 centroidElement.addContent(nameElement);
654
655 double[][] centroids = new double[points[0].length][points[0][0].length];
656 for (int i = 0; i < points.length; i++) {
657 for (int j = 0; j < points[i].length; j++) {
658 for (int k = 0; k < points[i][j].length; k++) {
659 centroids[j][k] += points[i][j][k];
660 }
661 }
662 }
663 for (int j = 0; j < points[0].length; j++) {
664 for (int k = 0; k < points[0][j].length; k++) {
665 centroids[j][k] /= points.length;
666 }
667 }
668
669 for (int j = 0; j < points[0].length; j++) {
670 Element placemarkElement = new Element("Placemark");
671
672 placemarkElement.addContent(generateCentroidData(labels[order[j]], j));
673
674
675 Element pointElement = new Element("Point");
676 Element coordinates = new Element("coordinates");
677 coordinates.addContent(centroids[order[j]][1]+","+centroids[order[j]][0]+",0");
678 pointElement.addContent(coordinates);
679 placemarkElement.addContent(pointElement);
680
681 centroidElement.addContent(placemarkElement);
682 }
683 return centroidElement;
684 }
685
686 private Element generateCentroidData(String label, int trace) {
687 Element data = new Element("ExtendedData");
688 Element schemaData = new Element("SchemaData");
689 schemaData.setAttribute("schemaUrl", "Centroid_Schema");
690 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Label").addContent(label));
691 Label l = new Label(label);
692 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Year").addContent(Integer.toString(l.year)));
693 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Trace").addContent(Integer.toString(trace)));
694 data.addContent(schemaData);
695 return data;
696 }
697
698 private Element generateClusterElement(String[] labels, double[][][] points, int[][] clusterIndices, int[][] clusterSizes, int[] traceOrder) {
699 Element element = new Element("Folder");
700 Element nameElement = new Element("name");
701 String name = "clusters";
702
703 nameElement.addContent(name);
704 element.addContent(nameElement);
705
706 double[][] centroids = new double[points[0].length][points[0][0].length];
707 for (int i = 0; i < points.length; i++) {
708 for (int j = 0; j < points[i].length; j++) {
709 for (int k = 0; k < points[i][j].length; k++) {
710 centroids[j][k] += points[i][j][k];
711 }
712 }
713 }
714 for (int j = 0; j < points[0].length; j++) {
715 for (int k = 0; k < points[0][j].length; k++) {
716 centroids[j][k] /= points.length;
717 }
718 }
719
720 for (int j = 0; j < points[0].length; j++) {
721 Element placemarkElement = new Element("Placemark");
722
723 placemarkElement.addContent(generateCentroidData(labels[traceOrder[j]], j));
724
725
726 Element pointElement = new Element("Point");
727 Element coordinates = new Element("coordinates");
728 coordinates.addContent(centroids[traceOrder[j]][1]+","+centroids[traceOrder[j]][0]+",0");
729 pointElement.addContent(coordinates);
730 placemarkElement.addContent(pointElement);
731
732 element.addContent(placemarkElement);
733 }
734 return element;
735 }
736
737 private Element generateClusterData(String label, int trace) {
738 Element data = new Element("ExtendedData");
739 Element schemaData = new Element("SchemaData");
740 schemaData.setAttribute("schemaUrl", "Centroid_Schema");
741 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Label").addContent(label));
742 Label l = new Label(label);
743 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Year").addContent(Integer.toString(l.year)));
744 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Trace").addContent(Integer.toString(trace)));
745 data.addContent(schemaData);
746 return data;
747 }
748
749
750 private Element generatePlacemarkElementWithPolygon(double hpdValue, KMLCoordinates coords, int pointNumber, int pathCounter) {
751 Element placemarkElement = new Element("Placemark");
752
753 String name;
754 Element placemarkNameElement = new Element("name");
755 name = "kde_" + pathCounter;
756
757 placemarkNameElement.addContent(name);
758 placemarkElement.addContent(placemarkNameElement);
759
760 placemarkElement.addContent(generateContourData(name, pointNumber, hpdValue));
761
762 Element polygonElement = new Element("Polygon");
763 Element altitudeMode = new Element("altitudeMode");
764 altitudeMode.addContent("clampToGround");
765 polygonElement.addContent(altitudeMode);
766 Element tessellate = new Element("tessellate");
767 tessellate.addContent("1");
768 polygonElement.addContent(tessellate);
769 Element outerBoundaryIs = new Element("outerBoundaryIs");
770 Element LinearRing = new Element("LinearRing");
771 LinearRing.addContent(coords.toXML());
772 outerBoundaryIs.addContent(LinearRing);
773 polygonElement.addContent(outerBoundaryIs);
774 placemarkElement.addContent(polygonElement);
775
776 return placemarkElement;
777 }
778
779 private Element generateContourData(String label, int point, double hpd) {
780 Element data = new Element("ExtendedData");
781 Element schemaData = new Element("SchemaData");
782 schemaData.setAttribute("schemaUrl", "HPD_Schema");
783 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Label").addContent(label));
784 // Label l = new Label(label);
785 // schemaData.addContent(new Element("SimpleData").setAttribute("name", "Year").addContent(Integer.toString(l.year)));
786 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Point").addContent(Integer.toString(point)));
787 if (hpd > 0) {
788 schemaData.addContent(new Element("SimpleData").setAttribute("name", "HPD").addContent(Double.toString(hpd)));
789 }
790 data.addContent(schemaData);
791 return data;
792 }
793
794 public static void printTitle() {
795 System.out.println();
796 centreLine("AntigenicPlotter " + version.getVersionString() + ", " + version.getDateString(), 60);
797 centreLine("BEAST time vs. parameter density analysis", 60);
798 centreLine("by", 60);
799 centreLine("Andrew Rambaut and Marc A. Suchard", 60);
800 System.out.println();
801 System.out.println();
802 }
803
804 public static void centreLine(String line, int pageWidth) {
805 int n = pageWidth - line.length();
806 int n1 = n / 2;
807 for (int i = 0; i < n1; i++) {
808 System.out.print(" ");
809 }
810 System.out.println(line);
811 }
812
813
814 public static void printUsage(Arguments arguments) {
815
816 arguments.printUsage("antigenicplotter", "<input-file-name> [<output-file-name>]");
817 System.out.println();
818 System.out.println(" Example: antigenicplotter -burnin 100 locations.log locations.kml");
819 System.out.println();
820 }
821
822 //Main method
823 public static void main(String[] args) throws IOException {
824
825 String inputFileName = null;
826 String outputFileName = null;
827 String treeFileName = null;
828
829 printTitle();
830
831 Arguments arguments = new Arguments(
832 new Arguments.Option[]{
833 new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in' [default = 0]"),
834 new Arguments.Option("discrete", "generated under the discrete antigenic model [default = continuous]"),
835 new Arguments.Option("tab", "generate tab delimited file [default = KML]"),
836 new Arguments.Option("help", "option to print this message")
837 });
838
839 try {
840 arguments.parseArguments(args);
841 } catch (Arguments.ArgumentException ae) {
842 System.out.println(ae);
843 printUsage(arguments);
844 System.exit(1);
845 }
846
847 if (arguments.hasOption("help")) {
848 printUsage(arguments);
849 System.exit(0);
850 }
851
852 int burnin = -1;
853 if (arguments.hasOption("burnin")) {
854 burnin = arguments.getIntegerOption("burnin");
855 }
856
857 boolean tabFormat = arguments.hasOption("tab");
858
859 boolean discreteModel = arguments.hasOption("discrete");
860
861 String[] args2 = arguments.getLeftoverArguments();
862
863 if (args2.length > 3) {
864 System.err.println("Unknown option: " + args2[3]);
865 System.err.println();
866 printUsage(arguments);
867 System.exit(1);
868 }
869
870 if (args2.length == 2) {
871 inputFileName = args2[0];
872 outputFileName = args2[1];
873 } else if (args2.length == 3) {
874 inputFileName = args2[0];
875 treeFileName = args2[1];
876 outputFileName = args2[2];
877 } else {
878 System.err.println("Missing input or output file name");
879 printUsage(arguments);
880 System.exit(1);
881 }
882
883 new AntigenicPlotter(burnin,
884 tabFormat,
885 discreteModel,
886 inputFileName,
887 treeFileName,
888 outputFileName
889 );
890
891 System.exit(0);
892 }
893
894 }