Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * DiscreteTreeToKML.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
29 import java.io.BufferedReader;
30 import java.io.BufferedWriter;
31 import java.io.FileReader;
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.io.PrintStream;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.StringTokenizer;
38
39 import dr.app.util.Arguments;
40 import jebl.evolution.io.ImportException;
41 import jebl.evolution.io.NexusImporter;
42 import jebl.evolution.io.TreeImporter;
43 import jebl.evolution.trees.RootedTree;
44
45 /**
46 * @author Philippe Lemey
47 * @author Andrew Rambaut
48 * @author Marc A. Suchard
49 */
50
51 public class DiscreteTreeToKML {
52
53 public static final String HELP = "help";
54 public static final String ANNOTATION = "annotation";
55 public static final String COORDINATES = "coordinates";
56 public static final String TIMESCALER = "timescaler";
57 public static final String MRSD = "mrsd";
58 public static final String BWC = "bwc";
59 public static final String BWM = "bwm";
60 public static final String DIVIDER = "divider";
61 public static final String USP = "usp";
62 public static final String BW = "bw";
63 public static final String BCUSE = "bcuse";
64 public static final String BCOLOR = "bcolor";
65 public static final String BSTARTCOLOR = "bstartcolor";
66 public static final String BENDCOLOR = "bendcolor";
67 public static final String ARCHBRANCH = "archbranch";
68 public static final String ARCHHEIGHT = "archheight";
69 public static final String ALTITUDE = "altitude";
70 public static final String TEMP = "temp";
71 public static final String CIRCLESEGMENTS = "circlesegments";
72 public static final String RADIUS = "radius";
73 public static final String AUTORADIUS = "autoradius";
74 public static final String CIRCLEOP = "circleop";
75 public static final String COORDSFORTAXA = "coordsfortaxa";
76 public static final String SLICES = "slices";
77 public static final String SLICEBW = "slicebw";
78 public static final String SLICEMIDPOINT = "slicemidpoint";
79
80
81 public static final String[] use = new String[] {"heights","posteriors"};
82 public static final String[] arch = new String[] {"distance","time"};
83 public static final String[] falseTrue = new String[] {"false","true"};
84 private static final PrintStream progressStream = System.out;
85
86 private static final String commandName = "discrete_tree_to_kml";
87
88 public static void printUsage(Arguments arguments) {
89
90 arguments.printUsage(commandName, "[<inputTree-file-name>] [<output-file-name>]"); //TODO: set this right
91 progressStream.println();
92 progressStream.println(" Example: " + commandName + " -coordinates coordinates.txt input.tre");
93 progressStream.println();
94 }
95
96 private static int[] countLinesAndTokens(String coordinatesFileString){
97 int lineCounter = 0;
98 int tokenCounter = 0;
99 int[] container = new int[2];
100 try{
101 BufferedReader reader1 = new BufferedReader(new FileReader(coordinatesFileString));
102 String current1 = reader1.readLine();
103 while (current1 != null && !reader1.equals("")) {
104 lineCounter++;
105 if (lineCounter == 1) {
106 StringTokenizer tokens = new StringTokenizer(current1);
107 while (tokens.hasMoreTokens()) {
108 tokenCounter++;
109 tokens.nextToken();
110 }
111 }
112 current1 = reader1.readLine();
113 }
114
115 } catch (IOException e) {
116 System.err.println("Error reading " + coordinatesFileString);
117 System.exit(1);
118 }
119 container[0] = lineCounter;
120 container[1] = tokenCounter;
121 return container;
122 }
123
124 private static void readLocationsCoordinates(String coordinatesFileString, String[][] locationsAndCoordinates){
125 try {
126 BufferedReader reader2 = new BufferedReader(new FileReader(coordinatesFileString));
127 String current2 = reader2.readLine();
128 int counter2 = 0;
129 while (current2 != null && !reader2.equals("")) {
130 StringTokenizer tokens2 = new StringTokenizer(current2);
131 for (int i = 0; i < locationsAndCoordinates[0].length; i++) {
132 locationsAndCoordinates[counter2][i] = tokens2.nextToken();
133 progressStream.print(locationsAndCoordinates[counter2][i]+"\t");
134 }
135 progressStream.print("\r");
136 counter2 ++;
137 current2 = reader2.readLine();
138 }
139 } catch (IOException e) {
140 e.printStackTrace();
141 return;
142 }
143 }
144
145 public static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException {
146
147 List<Double> returnList = new ArrayList<Double>();
148 StringTokenizer st = new StringTokenizer(inString,",");
149 while(st.hasMoreTokens()) {
150 try {
151 returnList.add(Double.parseDouble(st.nextToken()));
152 } catch (NumberFormatException e) {
153 throw new Arguments.ArgumentException();
154 }
155
156 }
157
158 if (returnList.size()>0) {
159 double[] doubleArray = new double[returnList.size()];
160 for(int i=0; i<doubleArray.length; i++)
161 doubleArray[i] = returnList.get(i);
162 return doubleArray;
163 }
164 return null;
165 }
166
167 private static RootedTree readTree(String inString) throws Arguments.ArgumentException {
168
169 RootedTree tree;
170 try {
171 TreeImporter importer = new NexusImporter(new FileReader(inString));
172 tree = (RootedTree)importer.importNextTree();
173 } catch (ImportException e) {
174 e.printStackTrace();
175 return null;
176 } catch (IOException e) {
177 e.printStackTrace();
178 return null;
179 }
180 return tree;
181 }
182
183 public static void main(String[] args) throws Arguments.ArgumentException {
184
185 String inputFileName = null;
186 String outputFileName = null;
187 RootedTree tree = null;
188 String[][] locations = null;
189
190 String stateAnnotation = "state";
191
192 //in case trees are scaled in other time units
193 double timeScaler = 1;
194
195 double branchWidthConstant = 2.0; // the width of branches will be stateProbability*branchWidthMultiplier+branchWidthConstant
196 double branchWidthMultiplier = 5.0;
197
198 double divider = 100; // this is to chop up the branches of the surface tree in 'divider' segments
199 boolean useStateProbability = true; // use state probabilities for branch width
200 double branchWidth = 10.0; // branch width if posterior probabilities are not used
201 boolean usePosterior = false; // use posterior probabilities to color branch
202 boolean useHeights = true; // use heights (time) to color branches
203 String startBranchColor = "FF00FF"; //red: 0000FF green: 00FF00 magenta: FF00FF white: FFFFFF yellow: 00FFFF cyan: FFFF00
204 String endBranchColor = "FFFF00";
205 String branchColor = "ffffff"; // branch color if color range based on rates is not used
206 boolean arcBranches = true; // branches are arcs with heights proportional to the distance between locations
207 boolean arcTimeHeight = false; // the height of the arcs is proportional to the time the branch spans, by default arch-heights are proportional to the distance between locations
208 double altitudeFactor = 100; // this is the factor with which to multiply the time of the branch to get the altitude for that branch in the surface Tree
209 boolean temporary = false;
210
211 double mostRecentDate = 2010; // required to convert heights to calendar dates
212
213 //circles
214 int numberOfIntervals = 100;
215 //boolean autoRadius = false;
216 double radius = 0;
217 String circleOpacity = "8F";
218
219 //extra coordinates for some taxa
220 boolean coordinatesForTaxa = false;
221 String[][] taxaCoordinates = null;
222
223 //tree slices for google maps, requires treeHeight in exporterString: e.g., exporterString.writeTreeToKML(0.025);
224 //TODO: have this outputed to a different file (what happens now)?
225 boolean makeTreeSlices = false;
226 double[] sliceTimes = null;
227 double treeSliceBranchWidth = 3;
228 boolean showBranchAtMidPoint = false; // shows complete branch for slice if time is more recent than the branch's midpoint
229
230
231 Arguments arguments = new Arguments(
232 new Arguments.Option[]{
233 new Arguments.StringOption(COORDINATES, "coordinate file", "specifies a tab-delimited file with coordinates for the locations"),
234 new Arguments.StringOption(ANNOTATION, "location state annotation string", "specifies the string used for location state annotation [default=state]"),
235 new Arguments.RealOption(TIMESCALER,"specifies the scaling factor by which to rescale time [default=1]"),
236 new Arguments.RealOption(MRSD,"specifies the most recent sampling data in fractional years to rescale time [default=2010]"),
237 new Arguments.RealOption(BWC,"specifies the branch width constant [default=2]"),
238 new Arguments.RealOption(BWM,"specifies the branch width multiplier [default=5]"),
239 new Arguments.StringOption(USP, falseTrue, false,
240 "use state probabilities for branch width [default = true]"),
241 new Arguments.StringOption(BCUSE, use, false,
242 "use heights or posterior probabilities for branch colors [default = heights]"),
243 new Arguments.RealOption(BW,"specifies the branch width if posterior probabilities are not used [default=10]"),
244 new Arguments.IntegerOption(DIVIDER,"specifies in how many segments at branch should be chopped up [default=50]"),
245 new Arguments.StringOption(BSTARTCOLOR, "branch start color", "specifies a starting color for the branches [default=FF00FF]"),
246 new Arguments.StringOption(BENDCOLOR, "branch end color", "specifies an end color for the branches [default=FFFF00]"),
247 new Arguments.StringOption(BCOLOR, "branch color", "specifies a branch color if color range based on rates is not used [default=ffffff]"),
248 new Arguments.StringOption(ARCHBRANCH, falseTrue, false,
249 "use arcs for the branches [default = true], by default arc-heights are proportional to the distance between locations"),
250 new Arguments.StringOption(ARCHHEIGHT, arch, false,
251 "use time or distance for arch heights [default = no arcs]"),
252 new Arguments.RealOption(ALTITUDE,"specifies the altitudefactor for the branches [default=1000]"),
253 new Arguments.StringOption(TEMP, falseTrue, false,
254 "display branches only temporary [default=false"),
255 new Arguments.IntegerOption(CIRCLESEGMENTS,"specifies the number of segments to construct circles [default=100]"),
256 new Arguments.IntegerOption(RADIUS,"specifies the radiusfactor for the circles [default='autoradius']"),
257 new Arguments.StringOption(CIRCLEOP, "circle opacity", "sets the opacity of the circles [default=8F]"),
258 new Arguments.Option(HELP, "option to print this message"),
259 new Arguments.StringOption(COORDSFORTAXA, "file with taxa coords", "specifies a file with additional coordinates for particular taxa"),
260 new Arguments.RealOption(SLICEBW,"specifies the branch width for tree slices [default=3]"),
261 new Arguments.StringOption(SLICES,"time","specifies a slice time-list [default=none]"),
262 new Arguments.StringOption(SLICEMIDPOINT, falseTrue, false,
263 "shows complete branch for sliced tree if time is more recent than the branch's midpoint [default=false"),
264 });
265
266 try {
267 arguments.parseArguments(args);
268 } catch (Arguments.ArgumentException ae) {
269 progressStream.println(ae);
270 printUsage(arguments);
271 System.exit(1);
272 }
273
274 if (args.length == 0 || arguments.hasOption(HELP)) {
275 printUsage(arguments);
276 System.exit(0);
277 }
278
279 try {
280
281 String coordinatesFileString = arguments.getStringOption(COORDINATES);
282 //System.out.println(coordinatesFileString);
283 if (coordinatesFileString != null) {
284 // count lines in locations file and tokens per line
285 int counts[] = countLinesAndTokens(coordinatesFileString);
286 //System.out.println(counts[0]+"\t"+counts[1]);
287 //read in locations
288 locations = new String[counts[0]][counts[1]];
289 readLocationsCoordinates(coordinatesFileString,locations);
290 } else {
291 progressStream.println("no coordinates for taxa??");
292 System.exit(1);
293 }
294
295 if (arguments.hasOption(MRSD)) {
296 mostRecentDate = arguments.getRealOption(MRSD);
297 }
298
299 if (arguments.hasOption(TIMESCALER)) {
300 timeScaler = arguments.getRealOption(TIMESCALER);
301 }
302
303 if (arguments.hasOption(DIVIDER)) {
304 divider = arguments.getRealOption(DIVIDER);
305 }
306
307 if (arguments.hasOption(ALTITUDE)) {
308 altitudeFactor = arguments.getRealOption(ALTITUDE);
309 }
310
311 String stateAnnotationString = arguments.getStringOption(ANNOTATION);
312 if (stateAnnotationString != null){
313 stateAnnotation = stateAnnotationString;
314 }
315
316 String useStateProbString = arguments.getStringOption(USP);
317 if (useStateProbString != null && useStateProbString.compareToIgnoreCase("posteriors") != 0)
318 useStateProbability = false;
319
320 String useColorString = arguments.getStringOption(BCUSE);
321 if (useColorString != null && useColorString.compareToIgnoreCase("posteriors") == 0) {
322 usePosterior = true;
323 useHeights = false;
324 }
325 if (useColorString != null && useColorString.compareToIgnoreCase("heights") == 0) {
326 useHeights = true;
327 usePosterior = false;
328 }
329
330 if (arguments.hasOption(BWC)) {
331 branchWidthConstant = arguments.getRealOption(BWC);
332 }
333
334 if (arguments.hasOption(BWM)) {
335 branchWidthMultiplier = arguments.getRealOption(BWM);
336 }
337
338 if (arguments.hasOption(BW)) {
339 branchWidth = arguments.getRealOption(BW);
340 }
341
342 String color1String = arguments.getStringOption(BSTARTCOLOR);
343 if (color1String != null) {
344 startBranchColor = color1String;
345 }
346
347 String color2String = arguments.getStringOption(BENDCOLOR);
348 if (color2String != null) {
349 endBranchColor = color2String;
350 }
351
352 String colorString = arguments.getStringOption(BCOLOR);
353 if (colorString != null) {
354 branchColor = colorString;
355 }
356
357 String archString = arguments.getStringOption(ARCHBRANCH);
358 if (archString != null && archString.compareToIgnoreCase("false") == 0)
359 arcBranches = false;
360
361 String archHeightString = arguments.getStringOption(ARCHHEIGHT);
362 if (archHeightString != null && archHeightString.compareToIgnoreCase("time") == 0) {
363 arcTimeHeight = true;
364 }
365
366 String tempString = arguments.getStringOption(TEMP);
367 if (tempString != null && tempString.compareToIgnoreCase("true") == 0)
368 temporary = true;
369
370 if (arguments.hasOption(CIRCLESEGMENTS)) {
371 numberOfIntervals = arguments.getIntegerOption(CIRCLESEGMENTS);
372 }
373
374 if (arguments.hasOption(RADIUS)) {
375 radius = arguments.getIntegerOption(RADIUS);
376 }
377
378 String circleOpacityString = arguments.getStringOption(CIRCLEOP);
379 if (circleOpacityString != null) {
380 circleOpacity = circleOpacityString;
381 }
382
383 //read in extra taxon locations
384 String taxaCoordinatesFileString = arguments.getStringOption(COORDSFORTAXA);
385 if (taxaCoordinatesFileString != null) {
386 coordinatesForTaxa = true;
387 progressStream.println("\radditional taxa locations:");
388 // count lines in locations file and tokens per line
389 int[] counts = countLinesAndTokens(taxaCoordinatesFileString);
390 //read in locations
391 taxaCoordinates = new String[counts[0]][counts[1]];
392 readLocationsCoordinates(taxaCoordinatesFileString,taxaCoordinates);
393 }
394
395 String sliceString = arguments.getStringOption(SLICES);
396 if (sliceString != null) {
397 makeTreeSlices = true;
398 sliceTimes = parseVariableLengthDoubleArray(sliceString);
399 }
400
401 if (arguments.hasOption(SLICEBW)) {
402 treeSliceBranchWidth = arguments.getRealOption(SLICEBW);
403 }
404
405 String midpointString = arguments.getStringOption(SLICEMIDPOINT);
406 if (midpointString != null && midpointString.compareToIgnoreCase("true") == 0)
407 showBranchAtMidPoint = true;
408
409 } catch (Arguments.ArgumentException e) {
410 progressStream.println(e);
411 printUsage(arguments);
412 System.exit(-1);
413 }
414
415 final String[] args2 = arguments.getLeftoverArguments();
416
417 outputFileName = args2[0]+".kml";
418 switch (args2.length) {
419 case 0:
420 printUsage(arguments);
421 System.exit(1);
422 case 2:
423 outputFileName = args2[1];
424 // fall to
425 case 1:
426 inputFileName = args2[0];
427 tree = readTree(inputFileName);
428 break;
429 default: {
430 System.err.println("Unknown option: " + args2[2]);
431 System.err.println();
432 printUsage(arguments);
433 System.exit(1);
434 }
435 }
436
437 DiscreteKMLString exporterString = new DiscreteKMLString(tree, stateAnnotation, locations, inputFileName, mostRecentDate, timeScaler, divider, branchWidthConstant, branchWidthMultiplier, useStateProbability, branchWidth, startBranchColor, endBranchColor, branchColor, useHeights, usePosterior, arcBranches, arcTimeHeight, altitudeFactor, temporary, numberOfIntervals, radius, circleOpacity, coordinatesForTaxa, taxaCoordinates, makeTreeSlices);
438
439 try {
440 BufferedWriter out1 = new BufferedWriter(new FileWriter(outputFileName));
441 StringBuffer buffer = new StringBuffer();
442
443 if (makeTreeSlices) {
444 for (int i = 0; i < sliceTimes.length; i++)
445 exporterString.writeTreeToKML(sliceTimes[i], treeSliceBranchWidth, showBranchAtMidPoint);
446 } else {
447 exporterString.writeTreeToKML();
448 exporterString.writeLineagesToCircles();
449 }
450 exporterString.writeLocationsKML();
451 exporterString.compileBuffer(buffer);
452 out1.write(buffer.toString());
453 out1.close();
454 } catch (IOException e) {
455 e.printStackTrace();
456 return;
457 }
458
459 }
460
461 }