Debian Codegraph @

src/dr/app/tools/TimeSlicer.java

raw symbols SCIP
1 /*
2 * TimeSlicer.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.NewickImporter;
32 import dr.evolution.io.NexusImporter;
33 import dr.evolution.io.TreeImporter;
34 import dr.evolution.tree.NodeRef;
35 import dr.evolution.tree.Tree;
36 import dr.evolution.tree.TreeUtils;
37 import dr.geo.KMLCoordinates;
38 import dr.geo.KernelDensityEstimator2D;
39 import dr.geo.Polygon2D;
40 import dr.geo.contouring.*;
41 import dr.geo.math.SphericalPolarCoordinates;
42 import dr.inference.trace.TraceDistribution;
43 import dr.inference.trace.TraceType;
44 import dr.math.distributions.MultivariateNormalDistribution;
45 import dr.util.HeapSort;
46 import dr.util.Version;
47 import org.jdom.Element;
48 import org.jdom.output.Format;
49 import org.jdom.output.XMLOutputter;
50
51 import java.awt.geom.Point2D;
52 import java.io.*;
53 import java.text.SimpleDateFormat;
54 import java.util.*;
55
56 /**
57 * @author Marc A. Suchard
58 * @author Philippe Lemey
59 * <p/>
60 * example for location slices through time:
61 * -burnin500 -trait location -sliceFileHeights sliceTimes -summary true -mrsd 2007.63 -format KML -progress true -impute true -noise true -HPD 95 WNV_relaxed_gamma_geo.trees output.kml
62 * <p/>
63 * example for Markov reward o backbone summary (note we cannot imput here):
64 * -burnin 50 -trait AC1_R,AC2_R,AC3_R,AC4_R,AC5_R,AC6_R,AC7_R,AC8_R,AC9_R,AC10_R,AC11_R,AC12_R,AC13_R,AC14_R -sliceTimes 2002,2002.25,2002.5,2002.75,2003,2003.25,2003.5,2003.75,2004,2004.25,2004.5,2004.75,2005,2005.25,2005.5,2005.75,2006 -summary true -mrsd 2007 -branchNorm true -format TAB -progress true -backbonetaxa december2006taxa.txt -branchset backbone airCommunitiesMM_rewards.sub.trees TSRewardOutput.txt
65 * example of 1D antigenic summary
66 * -burnin0 -trait antigenic -sliceFileTimes timeInterval -summary true -mrsd 2007 -format TAB -progress true -impute true -noise false -HPD 95 H3N2_antigenic_sub.trees antigenic.txt
67 *
68 * other example
69 * -burnin 100 -trait location -sliceHeights 0,5,15 -summary true -mrsd 2004.7 -rateAttribute location.rate -format KML -progress true -impute true -noise true -HPD 80 -sdr sliceDispersalRates.txt RacRABV_Gamma.trees test.kml
70 */
71
72 public class TimeSlicer {
73
74 public static final String sep = "\t";
75 public static final String PRECISION_STRING = "precision";
76 public static final String RATE_ATTRIBUTE = "rateAttribute";
77
78 public static final String SLICE_ELEMENT = "slice";
79 public static final String REGIONS_ELEMENT = "hpdRegion";
80 public static final String NODE_ELEMENT = "node";
81 public static final String ROOT_ELEMENT = "root";
82 public static final String TRAIT = "trait";
83 public static final String NAME = "name";
84 public static final String DENSITY_VALUE = "density";
85 public static final String SLICE_VALUE = "time";
86
87 public static final String STYLE = "Style";
88 public static final String ID = "id";
89 public static final String WIDTH = "0.5";
90 public static final String startHPDColor = "00F1D6"; //blue=B36600 yellow="00F1D6"
91 public static final String endHPDColor = "00FF00"; //red=0000FF green="00FF00"
92 public static final String opacity = "6f";
93
94 public static final String BURNIN = "burnin";
95 public static final String SKIP = "skip";
96 public static final String SLICE_TIMES = "sliceTimes";
97 public static final String SLICE_HEIGHTS = "sliceHeights";
98 public static final String SLICE_COUNT = "sliceCount";
99 public static final String START_TIME = "startTime";
100 public static final String SLICE_FILE_HEIGHTS = "sliceFileHeights";
101 public static final String SLICE_FILE_TIMES = "sliceFileTimes";
102 public static final String SLICE_MODE = "sliceMode";
103 public static final String ROOT = "root";
104 public static final String TIPS = "tips";
105 public static final String CONTOURS = "contours";
106 public static final String POINTS = "points";
107 public static final String MRSD = "mrsd";
108 public static final String HELP = "help";
109 public static final String NOISE = "noise";
110 public static final String IMPUTE = "impute";
111 public static final String SUMMARY = "summary";
112 public static final String FORMAT = "format";
113 public static final String CONTOUR_MODE = "contourMode";
114 public static final String NORMALIZATION = "normalization";
115 public static final String HPD = "hpd";
116 public static final String SDR = "sdr";
117 public static final String SNR = "snr";
118 public static final String PROGRESS = "progress";
119 public static final double treeLengthPercentage = 0.00;
120 public static final String BRANCH_NORMALIZE = "branchnorm";
121 public static final String BRANCHSET = "branchset";
122 public static final String BACKBONETAXA = "backbonetaxa";
123 public static final String CLADETAXA = "cladetaxa";
124 public static final String LATMAX = "latmax";
125 public static final String LATMIN = "latmin";
126 public static final String LONGMAX = "longmax";
127 public static final String LONGMIN = "longmin";
128 public static final String ICON = "http://maps.google.com/mapfiles/kml/pal4/icon49.png";
129 public static final String GRIDSIZE = "gridsize";
130 public static final double[] BANDWIDTHS = new double[]{1.0,1.0};
131 public static final boolean BANDWIDTHLIMIT = true;
132 public static final boolean GREATCIRCLEDISTANCE = true;
133 public static final String SUBSTITUTION = "N";
134 public static final String DESCENDENTS = "descendents";
135
136 public static final String[] falseTrue = {"false", "true"};
137
138 private final static Calendar calendar = GregorianCalendar.getInstance();
139 private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
140
141 public TimeSlicer(String treeFileName, int burnin, int skipEvery, String[] traits, double[] sliceHeights, boolean impute,
142 boolean trueNoise, double mrsd, ContourMode contourMode, SliceMode sliceMode,
143 final boolean summarizeRoot, final boolean summarizeTips, Normalization normalize, boolean getSDR, boolean getSNR,
144 String progress, boolean branchNormalization, BranchSet branchset, Set taxaSet, int grid,
145 double latMin, double latMax, double longMin, double longMax, Set descendentTaxaSet, String rateString) {
146
147 this.traits = traits;
148 traitCount = traits.length;
149
150 sliceCount = 1;
151 doSlices = false;
152 mostRecentSamplingDate = mrsd;
153 this.contourMode = contourMode;
154 this.sliceMode = sliceMode;
155 sdr = getSDR;
156 snr = getSNR;
157 if (sdr && snr){
158 System.err.println("both SDR and SNR are requested; only one can be summarized.. prioritizing SDR");
159 }
160
161 this.latMin = latMin;
162 this.latMax = latMax;
163 this.longMin = longMin;
164 this.longMax = longMax;
165 // System.out.println("latMin: "+latMin);
166 // System.out.println("latMax: "+latMax);
167 // System.out.println("longMin: "+longMin);
168 // System.out.println("longMax: "+longMax);
169 this.descendentTaxaSet = descendentTaxaSet;
170
171 rateAttributeString = rateString;
172
173 gridSize = grid;
174
175 if (progress != null) {
176 if (progress.equalsIgnoreCase("true")) {
177 sliceProgressReport = true;
178 } else if (progress.equalsIgnoreCase("check")) {
179 sliceProgressReport = true;
180 checkSliceContours = true;
181 }
182 }
183
184 if (sliceHeights != null) {
185 sliceCount = sliceHeights.length;
186 doSlices = true;
187
188 this.sliceHeights = sliceHeights;
189
190 if ((mostRecentSamplingDate - sliceHeights[sliceHeights.length - 1]) < 0) {
191 ancient = true;
192 }
193 }
194
195 values = new ArrayList<List<List<Trait>>>(sliceCount);
196 for (int i = 0; i < sliceCount; i++) {
197 List<List<Trait>> thisSlice = new ArrayList<List<Trait>>(traitCount);
198 values.add(thisSlice);
199 for (int j = 0; j < traitCount; j++) {
200 List<Trait> thisTraitSlice = new ArrayList<Trait>();
201 thisSlice.add(thisTraitSlice);
202 }
203 }
204 if (summarizeRoot) {
205 rootValues = new ArrayList<List<Trait>>(traitCount);
206 for (int k = 0; k < traitCount; k++) {
207 List<Trait> thisTrait = new ArrayList<Trait>();
208 rootValues.add(thisTrait);
209 }
210 }
211 if (summarizeTips) {
212 tipValues = new ArrayList<List<List<Trait>>>();
213 tipNames = new ArrayList<String>();
214 }
215
216 try {
217 readAndAnalyzeTrees(treeFileName, burnin, skipEvery, traits, sliceHeights, impute, trueNoise, normalize, branchNormalization, branchset, taxaSet);
218 } catch (IOException e) {
219 System.err.println("Error reading file: " + treeFileName);
220 System.exit(-1);
221 } catch (Importer.ImportException e) {
222 System.err.println("Error parsing trees in file: " + treeFileName);
223 System.exit(-1);
224 }
225
226 // if (values.get(0).get(0).size() == 0) {
227 // System.err.print("Trait(s), ");
228 // for (int a = 0; a < traits.length; a++){
229 // System.err.print(traits[a]);
230 // }
231 // System.err.println(",values missing from trees.");
232 //
233 // System.exit(-1);
234 // }
235
236 progressStream.println(treesRead + " trees read.");
237 progressStream.println(treesAnalyzed + " trees analyzed.");
238
239 }
240
241
242 private Element rootElement;
243 private Element documentElement;
244 private Element contourFolderElement;
245 private Element pointsFolderElement;
246 private Element nodeFolderElement;
247 private StringBuffer tabOutput = new StringBuffer();
248
249 public void output(String outFileName, boolean summaryOnly, final boolean summarizeRoot, final boolean summarizeTips, boolean contours, boolean points, OutputFormat outputFormat, double[] hpdValues, String sdrFile, String snrFile) {
250
251 resultsStream = System.out;
252
253 if (outFileName != null) {
254 try {
255 resultsStream = new PrintStream(new File(outFileName));
256 } catch (IOException e) {
257 System.err.println("Error opening file: " + outFileName);
258 System.exit(-1);
259 }
260 }
261
262 if (!summaryOnly) {
263 outputHeader(traits);
264
265 if (sliceHeights == null || sliceHeights.length == 0) {
266 outputSlice(0, Double.NaN);
267 } else {
268 for (int i = 0; i < sliceHeights.length; i++) {
269 outputSlice(i, sliceHeights[i]);
270 }
271
272 }
273 } else { // Output summaries
274
275 if (outputFormat == OutputFormat.XML) {
276 rootElement = new Element("xml");
277
278 } else if (outputFormat == OutputFormat.KML) {
279
280 Element hpdSchema = new Element("Schema");
281 hpdSchema.setAttribute("id", "HPD_Schema");
282 hpdSchema.addContent(new Element("SimpleField")
283 .setAttribute("name", "Name")
284 .setAttribute("type", "string")
285 .addContent(new Element("displayName").addContent("Name")));
286 hpdSchema.addContent(new Element("SimpleField")
287 .setAttribute("name", "Description")
288 .setAttribute("type", "string")
289 .addContent(new Element("displayName").addContent("Description")));
290 hpdSchema.addContent(new Element("SimpleField")
291 .setAttribute("name", "Time")
292 .setAttribute("type", "double")
293 .addContent(new Element("displayName").addContent("Time")));
294 hpdSchema.addContent(new Element("SimpleField")
295 .setAttribute("name", "Height")
296 .setAttribute("type", "double")
297 .addContent(new Element("displayName").addContent("Height")));
298 hpdSchema.addContent(new Element("SimpleField")
299 .setAttribute("name", "HPD")
300 .setAttribute("type", "double")
301 .addContent(new Element("displayName").addContent("HPD")));
302
303 Element nodeSchema = new Element("Schema");
304 nodeSchema.setAttribute("id", "Point_Schema");
305 nodeSchema.addContent(new Element("SimpleField")
306 .setAttribute("name", "Name")
307 .setAttribute("type", "string")
308 .addContent(new Element("displayName").addContent("Name")));
309 nodeSchema.addContent(new Element("SimpleField")
310 .setAttribute("name", "Description")
311 .setAttribute("type", "string")
312 .addContent(new Element("displayName").addContent("Description")));
313 nodeSchema.addContent(new Element("SimpleField")
314 .setAttribute("name", "Time")
315 .setAttribute("type", "double")
316 .addContent(new Element("displayName").addContent("Time")));
317 nodeSchema.addContent(new Element("SimpleField")
318 .setAttribute("name", "Height")
319 .setAttribute("type", "double")
320 .addContent(new Element("displayName").addContent("Height")));
321
322 if (contours) {
323 contourFolderElement = new Element("Folder");
324 Element contourFolderNameElement = new Element("name");
325 contourFolderNameElement.addContent("surface HPD regions");
326 //rootElement.setAttribute("xmlns","http://earth.google.com/kml/2.2");
327 contourFolderElement.addContent(contourFolderNameElement);
328 }
329
330 if (points) {
331 pointsFolderElement = new Element("Folder");
332 Element pointsFolderNameElement = new Element("name");
333 pointsFolderNameElement.addContent("points");
334 //rootElement.setAttribute("xmlns","http://earth.google.com/kml/2.2");
335 pointsFolderElement.addContent(pointsFolderNameElement);
336 }
337
338 if (sliceMode == TimeSlicer.SliceMode.NODES) {
339 nodeFolderElement = new Element("Folder");
340 Element nodeFolderNameElement = new Element("name");
341 nodeFolderNameElement.addContent("nodes");
342 //rootElement.setAttribute("xmlns","http://earth.google.com/kml/2.2");
343 nodeFolderElement.addContent(nodeFolderNameElement);
344 }
345 Element documentNameElement = new Element("name");
346 String documentName = outFileName;
347 if (documentName == null)
348 documentName = "default";
349 if (documentName.endsWith(".kml"))
350 documentName = documentName.replace(".kml", "");
351 documentNameElement.addContent(documentName);
352
353 documentElement = new Element("Document");
354 documentElement.addContent(documentNameElement);
355 documentElement.addContent(hpdSchema);
356 documentElement.addContent(nodeSchema);
357 if (contourFolderElement != null) {
358 documentElement.addContent(contourFolderElement);
359 }
360 if (pointsFolderElement != null) {
361 documentElement.addContent(pointsFolderElement);
362 }
363 if (nodeFolderElement != null) {
364 documentElement.addContent(nodeFolderElement);
365 }
366
367 rootElement = new Element("kml");
368 rootElement.addContent(documentElement);
369 }
370
371 if (sliceHeights == null) {
372 for (double hpdValue : hpdValues) {
373 summarizeSlice(0, Double.NaN, contours, points, outputFormat, hpdValue);
374 }
375 } else {
376 if (outputFormat == OutputFormat.TAB) {
377 if (mostRecentSamplingDate > 0) {
378 tabOutput.append("trait\t" + "sliceTime\t" + "mean\t" + "stdev\t" + "HPDlow\t" + "HPDup");
379 } else {
380 tabOutput.append("trait\t" + "sliceHeight\t" + "mean\t" + "stdev\t" + "HPDlow\t" + "HPDup");
381 }
382 }
383 for (int i = 0; i < sliceHeights.length; i++) {
384 for (double hpdValue : hpdValues) {
385 summarizeSlice(i, sliceHeights[i], contours, points, outputFormat, hpdValue);
386 }
387 }
388 }
389
390 if (summarizeRoot) {
391 for (double hpdValue : hpdValues) {
392 summarizeRoot(contours, points, outputFormat, hpdValue);
393 }
394 }
395
396 if (summarizeTips) {
397 for (double hpdValue : hpdValues) {
398 summarizeTips(contours, points, outputFormat, hpdValue);
399 }
400 }
401
402 if (outputFormat == OutputFormat.TAB) {
403 resultsStream.println(tabOutput);
404 } else {
405 XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE));
406 try {
407 xmlOutputter.output(rootElement, resultsStream);
408 } catch (IOException e) {
409 System.err.println("IO Exception encountered: " + e.getMessage());
410 System.exit(-1);
411 }
412 }
413
414 }
415 // writes out dispersal rate summaries for the whole tree, there is a beast xml statistic that can do this now
416 // if (containsLocation) {
417 // try{
418 // PrintWriter dispersalRateFile = new PrintWriter(new FileWriter("dispersalRates.log"), true);
419 // dispersalRateFile.print("state"+"\t"+"dispersalRate(native units)"+"\t"+"dispersalRate(great circle distance, km)\r");
420 // for(int x = 0; x < dispersalrates.size(); x++ ) {
421 // dispersalRateFile.print(x+"\t"+dispersalrates.get(x)+"\r");
422 // }
423 //
424 // } catch (IOException e) {
425 // System.err.println("IO Exception encountered: "+e.getMessage());
426 // System.exit(-1);
427 // }
428 // }
429
430
431 if (sdr || snr) {
432 double[][] sliceTreeWeightedAverageRates = new double[sliceTreeDistanceArrays.size()][sliceCount];
433 double[][] sliceTreeDistancesToSummarize = new double[sliceTreeDistanceArrays.size()][sliceCount];
434 // can be useful for E[N]-E[S] stuff
435 double[][] sliceTreeIntervalDistances = new double[sliceTreeDistanceArrays.size()][sliceCount];
436
437 double[][] sliceTreeMaxPathRates = new double[sliceTreeDistanceArrays.size()][sliceCount];
438 double[][] sliceTreeMaxDistanceFromRootRates = new double[sliceTreeDistanceArrays.size()][sliceCount];
439 double[][] sliceTreeDistances = new double[sliceCount][sliceTreeDistanceArrays.size()];
440 double[][] sliceTreeTimes = new double[sliceCount][sliceTreeDistanceArrays.size()];
441 //double[][] sliceTreeMaxDistances = new double[sliceCount][sliceTreeMaxDistanceArrays.size()];
442 double[][] sliceTreeMaxDistancesFromRoot = new double[sliceTreeMaxDistanceFromRootArrays.size()][sliceCount];
443 double[][] sliceTreeMaxPathDistances = new double[sliceTreeMaxPathDistanceArrays.size()][sliceCount];
444 double[][] sliceTreeTimesFromRoot = new double[sliceCount][sliceTreeTimeFromRootArrays.size()];
445 double[][] sliceTreeDiffusionCoefficients = new double[sliceTreeDiffusionCoefficientArrays.size()][sliceCount];
446 double[][] sliceTreeDiffusionCoefficientVariances = new double[sliceTreeDiffusionCoefficientVarianceArrays.size()][sliceCount];
447 //double[][] sliceTreeWeightedAverageDiffusionCoefficients = new double[sliceTreeDistanceArrays.size()][sliceCount];
448 for (int q = 0; q < sliceTreeDistanceArrays.size(); q++) {
449 double[] distanceArray = (double[]) sliceTreeDistanceArrays.get(q);
450 double[] timeArray = (double[]) sliceTreeTimeArrays.get(q);
451
452 double[] maxDistanceFromRootArray = null;
453 double[] maxPathDistanceArray = null;
454 double[] timeFromRootArray = null;
455 double[] diffusionCoefficientArray = null;
456 double[] diffusionCoefficientVarianceArray = null;
457
458 if (sdr) {
459 maxPathDistanceArray = (double[]) sliceTreeMaxPathDistanceArrays.get(q);
460 maxDistanceFromRootArray = (double[]) sliceTreeMaxDistanceFromRootArrays.get(q);
461 timeFromRootArray = (double[]) sliceTreeTimeFromRootArrays.get(q);
462 diffusionCoefficientArray = (double[]) sliceTreeDiffusionCoefficientArrays.get(q);
463 diffusionCoefficientVarianceArray = (double[]) sliceTreeDiffusionCoefficientVarianceArrays.get(q);
464
465 }
466
467 for (int r = 0; r < distanceArray.length; r++) {
468 sliceTreeDistances[r][q] = distanceArray[r];
469 sliceTreeTimes[r][q] = timeArray[r];
470 if (sdr){
471 sliceTreeMaxPathDistances[q][r] = maxPathDistanceArray[r];
472 sliceTreeMaxDistancesFromRoot[q][r] = maxDistanceFromRootArray[r];
473 sliceTreeTimesFromRoot[r][q] = timeFromRootArray[r];
474 sliceTreeDiffusionCoefficients[q][r] = diffusionCoefficientArray[r];
475 sliceTreeDiffusionCoefficientVariances[q][r] = diffusionCoefficientVarianceArray[r];
476 }
477 }
478 }
479
480 //print2DArray(sliceTreeDistances,"sliceTreeDistances.txt");
481 //print2DArray(sliceTreeTimes,"sliceTreeTimes.txt");
482 print2DTransposedArray(sliceTreeDiffusionCoefficients,"sliceTreeDiffusionCoefficients.txt");
483 print2DTransposedArray(sliceTreeDiffusionCoefficientVariances,"sliceTreeDiffusionCoefficientVariances.txt");
484 //print2DArray(sliceTreeTimesFromRoot,"sliceTreeTimesFromRoot.txt");
485
486 if (sliceCount > 1) {
487 for (int s = 0; s < sliceTreeDistanceArrays.size(); s++) {
488 double[] distanceArray = (double[]) sliceTreeDistanceArrays.get(s);
489 double[] timeArray = (double[]) sliceTreeTimeArrays.get(s);
490 double[] maxDistanceFromRootArray = null;
491 double[] maxPathDistanceArray = null;
492 double[] timeFromRoot = null;
493 if (sdr){
494 maxPathDistanceArray = (double[]) sliceTreeMaxPathDistanceArrays.get(s);
495 maxDistanceFromRootArray = (double[]) sliceTreeMaxDistanceFromRootArrays.get(s);
496 timeFromRoot = (double[]) sliceTreeTimeFromRootArrays.get(s);
497 }
498
499 for (int t = 0; t < (sliceCount - 1); t++) {
500 if (sdr){
501 sliceTreeMaxDistanceFromRootRates[s][t] = (maxDistanceFromRootArray[t]) / (timeFromRoot[t]);
502 sliceTreeMaxPathRates[s][t] = (maxPathDistanceArray[t]) / (timeFromRoot[t]);
503 }
504 if ((timeArray[t] - timeArray[t + 1]) > ((Double) treeLengths.get(s) * treeLengthPercentage)) {
505 sliceTreeWeightedAverageRates[s][t] = (distanceArray[t] - distanceArray[t + 1]) / (timeArray[t] - timeArray[t + 1]);
506 sliceTreeDistancesToSummarize[s][t] = (distanceArray[t]);
507 sliceTreeIntervalDistances[s][t] = (distanceArray[t] - distanceArray[t + 1]);
508 //sliceTreeWeightedAverageRates[s][t] = (sliceTreeDistances[t][s] - sliceTreeDistances[t+1][s])/(sliceTreeTimes[t][s] - sliceTreeTimes[t+1][s]);
509 //sliceTreeWeightedAverageDiffusionCoefficients[s][t] = Math.pow((distanceArray[t] - distanceArray[t+1]),2.0)/(4.0*(timeArray[t] - timeArray[t+1]));
510 } else {
511 if (timeArray[t] > 0) {
512 if (t == 0) {
513 throw new RuntimeException("Philippe to fix: the time slices are expected in ascending height order");
514 }
515 sliceTreeWeightedAverageRates[s][t] = sliceTreeWeightedAverageRates[s][t - 1];
516 sliceTreeDistancesToSummarize[s][t] = sliceTreeDistancesToSummarize[s][t - 1];
517 sliceTreeIntervalDistances[s][t] = sliceTreeIntervalDistances[s][t - 1];
518 //sliceTreeWeightedAverageDiffusionCoefficients[s][t] = sliceTreeWeightedAverageDiffusionCoefficients[s][t-1];
519 } else {
520 //set it to NaN, we ignore NaNs when getting summary stats
521 sliceTreeWeightedAverageRates[s][t] = Double.NaN;
522 sliceTreeDistancesToSummarize[s][t] = Double.NaN;
523 sliceTreeIntervalDistances[s][t] = Double.NaN;
524 //sliceTreeWeightedAverageDiffusionCoefficients[s][t] = Double.NaN;
525 }
526 }
527 }
528
529 if ((timeArray[sliceCount - 1]) > ((Double) treeLengths.get(s) * treeLengthPercentage)) {
530 sliceTreeWeightedAverageRates[s][sliceCount - 1] = (distanceArray[sliceCount - 1]) / (timeArray[sliceCount - 1]);
531 sliceTreeDistancesToSummarize[s][sliceCount - 1] = (distanceArray[sliceCount - 1]);
532 sliceTreeIntervalDistances[s][sliceCount - 1] = (distanceArray[sliceCount - 1]);
533 //sliceTreeWeightedAverageDiffusionCoefficients[s][sliceCount-1] = Math.pow(distanceArray[sliceCount-1],2.0)/(4.0*timeArray[sliceCount-1]);
534 } else {
535 if ((timeArray[sliceCount - 1]) > 0) {
536 sliceTreeWeightedAverageRates[s][sliceCount - 1] = sliceTreeWeightedAverageRates[s][sliceCount - 2];
537 sliceTreeDistancesToSummarize[s][sliceCount - 1] = sliceTreeDistancesToSummarize[s][sliceCount - 2];
538 sliceTreeIntervalDistances[s][sliceCount - 1] = sliceTreeIntervalDistances[s][sliceCount - 2];
539 //sliceTreeWeightedAverageDiffusionCoefficients[s][sliceCount-1] = sliceTreeWeightedAverageDiffusionCoefficients[s][sliceCount-2];
540 } else {
541 sliceTreeWeightedAverageRates[s][sliceCount - 1] = (distanceArray[sliceCount - 1]) / (timeArray[sliceCount - 1]);
542 sliceTreeDistancesToSummarize[s][sliceCount - 1] = (distanceArray[sliceCount - 1]);
543 sliceTreeIntervalDistances[s][sliceCount - 1] = distanceArray[sliceCount - 1];
544 //sliceTreeWeightedAverageDiffusionCoefficients[s][sliceCount-1] = Math.pow(distanceArray[sliceCount-1],2.0)/(4.0*timeArray[sliceCount-1]);
545 }
546 }
547 if(sdr){
548 sliceTreeMaxPathRates[s][sliceCount - 1] = maxPathDistanceArray[sliceCount - 1] / timeFromRoot[sliceCount - 1];
549 sliceTreeMaxDistanceFromRootRates[s][sliceCount - 1] = maxDistanceFromRootArray[sliceCount - 1] / timeFromRoot[sliceCount - 1];
550 }
551 }
552 } else {
553 for (int s = 0; s < sliceTreeDistanceArrays.size(); s++) {
554 double[] distanceArray = (double[]) sliceTreeDistanceArrays.get(s);
555 double[] timeArray = (double[]) sliceTreeTimeArrays.get(s);
556 sliceTreeWeightedAverageRates[s][0] = distanceArray[0] / timeArray[0];
557 sliceTreeDistancesToSummarize[s][0] = distanceArray[0];
558 sliceTreeIntervalDistances[s][0] = distanceArray[0];
559 //sliceTreeWeightedAverageDiffusionCoefficients[s][0] = Math.pow(distanceArray[0],2.0)/(4.0*timeArray[0]);
560 if (sdr){
561 double[] maxPathDistanceArray = (double[]) sliceTreeMaxPathDistanceArrays.get(s);
562 double[] maxDistanceFromRootArray = (double[]) sliceTreeMaxDistanceFromRootArrays.get(s);
563 double[] timeFromRoot = (double[]) sliceTreeTimeFromRootArrays.get(s);
564 sliceTreeMaxPathRates[s][0] = maxPathDistanceArray[0] / timeFromRoot[0];
565 sliceTreeMaxDistanceFromRootRates[s][0] = maxDistanceFromRootArray[0] / timeFromRoot[0];
566 }
567 }
568 }
569
570 //print2DArray(sliceTreeDistancesToSummarize,"sliceTreeDistancesToSummarize.txt");
571 //print2DArray(sliceTreeWeightedAverageRates,"sliceTreeWeightedAverageRates.txt");
572 //print2DArray(sliceTreeIntervalDistances,"sliceTreeIntervalDistances.txt");
573
574
575 try {
576 String outfile = sdrFile;
577 if (!sdr) {
578 outfile = snrFile;
579 }
580 PrintWriter sliceDispersalRateFile = new PrintWriter(new FileWriter(outfile), true);
581 sliceDispersalRateFile.print("sliceTime" + "\t");
582 if (mostRecentSamplingDate > 0) {
583 sliceDispersalRateFile.print("realTime" + "\t");
584 }
585 sliceDispersalRateFile.print("mean dispersalRate" + "\t" + "hpd low" + "\t" + "hpd up");
586 if (sdr){
587 sliceDispersalRateFile.print("\t" +"mean wavefrontRate" + "\t" + "hpd low" + "\t" + "hpd up" + "\t" + "mean wavefrontDistance" + "\t" + "hpd low" + "\t" + "hpd up" + "\t" + "mean cumulative DiffusionCoefficient" + "\t" + "hpd low" + "\t" + "hpd up" + "\r");
588 } else if (snr){
589 sliceDispersalRateFile.print("\r");
590 }
591
592 double[] meanWeightedAverageDispersalRates = meanColNoNaN(sliceTreeWeightedAverageRates);
593 double[][] hpdWeightedAverageDispersalRates = getArrayHPDintervals(sliceTreeWeightedAverageRates);
594 // double[] meanSliceTreeDistancesToSummarize = meanColNoNaN(sliceTreeDistancesToSummarize);
595 // double[][] hpdSliceTreeDistancesToSummarize = getArrayHPDintervals(sliceTreeDistancesToSummarize);
596
597 // double[] meanMaxDispersalDistances = null;
598 // double[][] hpdMaxDispersalDistances = null;
599 // double[] meanMaxDispersalRates = null;
600 // double[][] hpdMaxDispersalRates = null;
601
602 double[] meanMaxPathDispersalDistances = null;
603 double[][] hpdMaxPathDispersalDistances = null;
604 double[] meanMaxPathDispersalRates = null;
605 double[][] hpdMaxPathDispersalRates = null;
606
607 double[] meanMaxRootDispersalDistances = null;
608 double[][] hpdMaxRootDispersalDistances = null;
609 double[] meanMaxRootDispersalRates = null;
610 double[][] hpdMaxRootDispersalRates = null;
611
612 double[] meanDiffusionCoefficients = null;
613 double[][] hpdDiffusionCoefficients = null;
614
615 if (sdr) {
616 meanMaxPathDispersalDistances = meanColNoNaN(sliceTreeMaxPathDistances);
617 hpdMaxPathDispersalDistances = getArrayHPDintervals(sliceTreeMaxPathDistances);
618 meanMaxPathDispersalRates = meanColNoNaN(sliceTreeMaxPathRates);
619 hpdMaxPathDispersalRates = getArrayHPDintervals(sliceTreeMaxPathRates);
620
621 meanMaxRootDispersalDistances = meanColNoNaN(sliceTreeMaxDistancesFromRoot);
622 hpdMaxRootDispersalDistances = getArrayHPDintervals(sliceTreeMaxDistancesFromRoot);
623 meanMaxRootDispersalRates = meanColNoNaN(sliceTreeMaxDistanceFromRootRates);
624 hpdMaxRootDispersalRates = getArrayHPDintervals(sliceTreeMaxDistanceFromRootRates);
625
626 meanDiffusionCoefficients = meanColNoNaN(sliceTreeDiffusionCoefficients);
627 hpdDiffusionCoefficients = getArrayHPDintervals(sliceTreeDiffusionCoefficients);
628 }
629
630 //double[] meanWeightedAverageDiffusionCoefficients = meanColNoNaN(sliceTreeWeightedAverageDiffusionCoefficients);
631 //double[][] hpdWeightedAverageDiffusionCoefficients = getArrayHPDintervals(sliceTreeWeightedAverageDiffusionCoefficients);
632 for (int u = 0; u < sliceCount; u++) {
633 sliceDispersalRateFile.print(sliceHeights[u] + "\t");
634 if (mostRecentSamplingDate > 0) {
635 sliceDispersalRateFile.print((mostRecentSamplingDate - sliceHeights[u]) + "\t");
636 }
637 sliceDispersalRateFile.print(meanWeightedAverageDispersalRates[u] + "\t" + hpdWeightedAverageDispersalRates[u][0] + "\t" + hpdWeightedAverageDispersalRates[u][1]);
638
639 if (sdr){
640 sliceDispersalRateFile.print("\t" + meanMaxRootDispersalRates[u] + "\t" + hpdMaxRootDispersalRates[u][0] + "\t" + hpdMaxRootDispersalRates[u][1] + "\t" + meanMaxRootDispersalDistances[u] + "\t" + hpdMaxRootDispersalDistances[u][0] + "\t" + hpdMaxRootDispersalDistances[u][1] + "\t" + meanDiffusionCoefficients[u] + "\t" + hpdDiffusionCoefficients[u][0] + "\t" + hpdDiffusionCoefficients[u][1] + "\r");
641 // sliceDispersalRateFile.print("\t" + meanMaxPathDispersalRates[u] + "\t" + hpdMaxPathDispersalRates[u][0] + "\t" + hpdMaxPathDispersalRates[u][1] + "\t" + meanMaxPathDispersalDistances[u] + "\t" + hpdMaxPathDispersalDistances[u][0] + "\t" + hpdMaxPathDispersalDistances[u][1] + "\t" + meanDiffusionCoefficients[u] + "\t" + hpdDiffusionCoefficients[u][0] + "\t" + hpdDiffusionCoefficients[u][1] + "\r");
642 } else if (snr){
643 sliceDispersalRateFile.print("\r");
644 }
645
646 }
647 sliceDispersalRateFile.close();
648 } catch (IOException e) {
649 System.err.println("IO Exception encountered: " + e.getMessage());
650 System.exit(-1);
651 }
652 }
653 }
654
655 enum Normalization {
656 LENGTH,
657 HEIGHT,
658 NONE
659 }
660
661 enum OutputFormat {
662 TAB,
663 KML,
664 XML
665 }
666
667 enum BranchSet {
668 ALL,
669 INT,
670 EXT,
671 BACKBONE,
672 CLADE
673 }
674
675 enum SliceMode {
676 BRANCHES,
677 NODES,
678 }
679
680 public static <T extends Enum<T>> String[] enumNamesToStringArray(T[] values) {
681 int i = 0;
682 String[] result = new String[values.length];
683 for (T value : values) {
684 result[i++] = value.name();
685 }
686 return result;
687 }
688
689
690 private void addDimInfo(Element element, int j, int dim) {
691 if (dim > 1)
692 element.setAttribute("dim", Integer.toString(j + 1));
693 }
694
695 private void summarizeRoot(boolean contours, boolean points, OutputFormat outputFormat, double hpdValue){
696
697 if (sliceProgressReport) {
698 progressStream.print("summarizing root" + "\t");
699 progressStream.print("hpd " + (hpdValue * 100) + "\t");
700 }
701
702 Element contourElement = null;
703 Element pointsElement = null;
704 if (contours) {
705 contourElement = new Element("Folder");
706 Element name = new Element("name");
707 name.addContent("root_hpd" + (hpdValue * 100));
708 contourElement.addContent(name);
709 }
710
711 if (points) {
712 pointsElement = new Element("Folder");
713 Element name = new Element("name");
714 name.addContent("root_points");
715 pointsElement.addContent(name);
716 }
717
718 for (int traitIndex = 0; traitIndex < rootValues.size(); traitIndex++) {
719
720 List<Trait> thisTrait = rootValues.get(traitIndex);
721 if (thisTrait.size() == 0) {
722 return;
723 }
724 boolean isNumber = thisTrait.get(0).isNumber();
725 boolean isMultivariate = thisTrait.get(0).isMultivariate();
726 int dim = thisTrait.get(0).getDim();
727 boolean isBivariate = isMultivariate && dim == 2;
728
729 if (isNumber) {
730 if (isBivariate) {
731
732 if (outputFormat == OutputFormat.KML) {
733
734 int count = thisTrait.size();
735 double[][] y = new double[dim][count];
736 double[] h = new double[count];
737 for (int i = 0; i < count; i++) {
738 Trait trait = thisTrait.get(i);
739 double[] value = trait.getValue();
740 h[i] = trait.getHeight();
741 for (int j = 0; j < dim; j++) {
742 y[j][i] = value[j];
743 }
744 }
745
746 if(sliceMode == SliceMode.NODES) {
747 Element nodeSliceElement = generateNodeSliceElement(Double.NaN, y, -1);
748 nodeFolderElement.addContent(nodeSliceElement);
749 }
750
751 if (contourElement != null) {
752 String name = "root_hpd" + (hpdValue * 100);
753 generateContours(name, contourElement, null, y, -1, Double.NaN, Double.NaN, hpdValue);
754 }
755
756 if (pointsElement != null) {
757 String name = "root_points";
758 generatePoints(name, pointsElement, y, 0, 0, h) ;
759 }
760
761 }
762 }
763
764 }
765 }
766
767 if (contourFolderElement != null) {
768 contourFolderElement.addContent(contourElement);
769 }
770
771 if (pointsFolderElement != null) {
772 pointsFolderElement.addContent(pointsElement);
773 }
774
775 if (sliceProgressReport) {
776 progressStream.print("\r");
777 }
778
779 }
780
781 private void summarizeTips(boolean contours, boolean points, OutputFormat outputFormat, double hpdValue){
782
783 if (sliceProgressReport) {
784 progressStream.print("summarizing tips" + "\t");
785 progressStream.print("hpd " + (hpdValue * 100) + "\t");
786 }
787
788 Element contourElement = null;
789 Element pointsElement = null;
790 if (contours) {
791 contourElement = new Element("Folder");
792 Element name = new Element("name");
793 name.addContent("tips_hpd" + (hpdValue * 100));
794 contourElement.addContent(name);
795 }
796
797 if (points) {
798 pointsElement = new Element("Folder");
799 Element name = new Element("name");
800 name.addContent("tips_points");
801 pointsElement.addContent(name);
802 }
803
804 for (int traitIndex = 0; traitIndex < tipValues.size(); traitIndex++) {
805
806 List<List<Trait>> thisTrait = tipValues.get(traitIndex);
807 for (int tipIndex = 0; tipIndex < thisTrait.size(); tipIndex++) {
808 List<Trait> thisTip = thisTrait.get(tipIndex);
809 if (thisTip.size() == 0) {
810 return;
811 }
812 boolean isNumber = thisTip.get(0).isNumber();
813 boolean isMultivariate = thisTip.get(0).isMultivariate();
814 int dim = thisTip.get(0).getDim();
815 boolean isBivariate = isMultivariate && dim == 2;
816
817 if (isNumber) {
818 if (isBivariate) {
819
820 if (outputFormat == OutputFormat.KML) {
821
822 int count = thisTrait.size();
823 double[][] y = new double[dim][count];
824 double[] h = new double[count];
825
826 for (int i = 0; i < count; i++) {
827 Trait trait = thisTip.get(i);
828 h[i] = trait.getHeight();
829 double[] value = trait.getValue();
830 for (int j = 0; j < dim; j++) {
831 y[j][i] = value[j];
832 }
833 }
834
835
836 if (contourElement != null) {
837 String name = tipNames.get(tipIndex) + "_hpd";
838 generateContours(name, contourElement, null, y, -1, Double.NaN, Double.NaN, hpdValue);
839 }
840
841 if (pointsElement != null) {
842 String name = tipNames.get(tipIndex) + "_points";
843 generatePoints(name, pointsElement, y, 0, 0, h) ;
844 }
845
846 }
847 }
848
849 }
850
851 }
852
853 }
854
855 if (contourFolderElement != null) {
856 contourFolderElement.addContent(contourElement);
857 }
858
859 if (pointsFolderElement != null) {
860 pointsFolderElement.addContent(pointsElement);
861 }
862
863 if (sliceProgressReport) {
864 progressStream.print("\r");
865 }
866
867 }
868
869 private void summarizeSlice(int slice, double sliceValue, boolean contours, boolean points, OutputFormat outputFormat, double hpdValue) {
870
871 //if (outputFormat == OutputFormat.TAB)
872 // throw new RuntimeException("Only XML/KML output is implemented");
873
874 Element contourElement = null;
875 Element pointsElement = null;
876
877 if (outputFormat == OutputFormat.XML) {
878 if (contours) {
879 contourElement = new Element(SLICE_ELEMENT);
880 contourElement.setAttribute(SLICE_VALUE, Double.toString(sliceValue));
881 }
882 } else if (outputFormat == OutputFormat.KML) {
883 if (contours) {
884 contourElement = new Element("Folder");
885 Element name = new Element("name");
886 name.addContent("slice" + Double.toString(sliceValue) + "_hpd" + (hpdValue * 100));
887 contourElement.addContent(name);
888 }
889
890 if (points) {
891 pointsElement = new Element("Folder");
892 Element name = new Element("name");
893 name.addContent("slice" + Double.toString(sliceValue) + "_points");
894 pointsElement.addContent(name);
895 }
896 }
897
898 List<List<Trait>> thisSlice = values.get(slice);
899 int traitCount = thisSlice.size();
900
901 for (int traitIndex = 0; traitIndex < traitCount; traitIndex++) {
902
903 // if (outputFormat == OutputFormat.KML) {
904 // summarizeSliceTrait(folder, slice, thisSlice.get(traitIndex), traitIndex, sliceValue,
905 // outputFormat,
906 // hpdValue);
907 //
908 // } else {
909 summarizeSliceTrait(contourElement, pointsElement, slice, thisSlice.get(traitIndex), traitIndex, sliceValue,
910 outputFormat,
911 hpdValue);
912
913 // }
914 }
915
916 if (outputFormat == OutputFormat.KML) {
917 if (contourFolderElement != null) {
918 contourFolderElement.addContent(contourElement);
919 }
920
921 if (pointsFolderElement != null) {
922 pointsFolderElement.addContent(pointsElement);
923 }
924 } else if (outputFormat == OutputFormat.XML && contourElement != null) {
925 if (contourElement != null) {
926 rootElement.addContent(contourElement);
927 }
928
929 if (pointsElement != null) {
930 rootElement.addContent(pointsElement);
931 }
932 }
933 }
934
935 private void summarizeSliceTrait(Element contourElement, Element pointsElement, int slice, List<Trait> thisTrait, int traitIndex, double sliceValue,
936 OutputFormat outputFormat,
937 double hpdValue) {
938
939 if (thisTrait.size() == 0) {
940 return;
941 }
942
943 boolean isNumber = thisTrait.get(0).isNumber();
944 boolean isMultivariate = thisTrait.get(0).isMultivariate();
945 int dim = thisTrait.get(0).getDim();
946 boolean isBivariate = isMultivariate && dim == 2;
947 if (sliceProgressReport) {
948 progressStream.print("slice " + sliceValue + "\t");
949 progressStream.print("hpd " + (hpdValue * 100) + "\t");
950 if (mostRecentSamplingDate > 0) {
951 progressStream.print("time=" + (mostRecentSamplingDate - sliceValue) + "\t");
952 }
953 progressStream.print("trait=" + traits[traitIndex] + "\t");
954 }
955 if (isNumber) {
956
957 Element traitElement = null;
958 if (outputFormat == OutputFormat.XML || outputFormat == OutputFormat.TAB) {
959 traitElement = new Element(TRAIT);
960 traitElement.setAttribute(NAME, traits[traitIndex]);
961 }
962
963 if (outputFormat == OutputFormat.KML) {
964 if (useStyles) {
965 Element styleElement = new Element(STYLE);
966 constructPolygonStyleElement(styleElement, sliceValue);
967 documentElement.addContent(styleElement);
968 }
969 }
970
971 int count = thisTrait.size();
972 // System.out.println("count = "+count+", dim = "+dim);
973 double[][] y = new double[dim][count];
974 for (int i = 0; i < count; i++) {
975 Trait trait = thisTrait.get(i);
976 double[] value = trait.getValue();
977 for (int j = 0; j < dim; j++) {
978 y[j][i] = value[j];
979 }
980 }
981 // System.out.println(y.length+"\t"+y[0].length);
982
983 if (outputFormat == OutputFormat.XML || outputFormat == OutputFormat.TAB) {
984 // Compute marginal means and standard deviations
985 for (int j = 0; j < dim; j++) {
986 List<Double> x = new ArrayList();
987 for (int k = 0; k < y[j].length; k++) {
988 x.add(y[j][k]);
989 }
990 TraceDistribution trace = new TraceDistribution(x, TraceType.REAL);
991 Element statsElement = new Element("stats");
992 addDimInfo(statsElement, j, dim);
993 StringBuffer sb = new StringBuffer();
994 sb.append(KMLCoordinates.NEWLINE);
995 tabOutput.append(KMLCoordinates.NEWLINE);
996 tabOutput.append(traits[traitIndex] + "\t");
997 if (mostRecentSamplingDate > 0) {
998 tabOutput.append((mostRecentSamplingDate - sliceValue) + "\t");
999 } else {
1000 tabOutput.append(sliceValue + "\t");
1001 }
1002 sb.append(String.format(KMLCoordinates.FORMAT,
1003 trace.getMean())).append(KMLCoordinates.SEPARATOR);
1004 tabOutput.append(String.format(KMLCoordinates.FORMAT,
1005 trace.getMean())).append("\t");
1006 sb.append(String.format(KMLCoordinates.FORMAT,
1007 trace.getStdError())).append(KMLCoordinates.SEPARATOR);
1008 tabOutput.append(String.format(KMLCoordinates.FORMAT,
1009 trace.getStdError())).append("\t");
1010 sb.append(String.format(KMLCoordinates.FORMAT,
1011 trace.getLowerHPD())).append(KMLCoordinates.SEPARATOR);
1012 tabOutput.append(String.format(KMLCoordinates.FORMAT,
1013 trace.getLowerHPD())).append("\t");
1014 sb.append(String.format(KMLCoordinates.FORMAT,
1015 trace.getUpperHPD())).append(KMLCoordinates.NEWLINE);
1016 tabOutput.append(String.format(KMLCoordinates.FORMAT,
1017 trace.getUpperHPD())).append("\t");
1018 statsElement.addContent(sb.toString());
1019 traitElement.addContent(statsElement);
1020 }
1021 }
1022
1023 if (isBivariate) {
1024
1025 Element nodeSliceElement = null;
1026
1027 if(sliceMode == SliceMode.NODES) {
1028 nodeSliceElement = generateNodeSliceElement(sliceValue, y, slice);
1029 nodeFolderElement.addContent(nodeSliceElement);
1030
1031 if (useStyles) {
1032 Element styleElement = new Element(STYLE);
1033 constructNodeStyleElement(styleElement, sliceValue);
1034 documentElement.addContent(styleElement);
1035 }
1036 }
1037
1038 double date = mostRecentSamplingDate - sliceValue;
1039
1040 if (pointsElement != null) {
1041 String name = "" + date + "_points";
1042 generatePointsElement(name, pointsElement, y, date, sliceValue);
1043 }
1044
1045 if (contourElement != null) {
1046 String name = "" + date + "_hpd" + hpdValue;
1047 generateContours(name, contourElement, traitElement, y, slice, date, sliceValue, hpdValue);
1048 }
1049
1050 }
1051 if (outputFormat == OutputFormat.XML)
1052 contourElement.addContent(traitElement);
1053 } // else skip
1054 if (sliceProgressReport) {
1055 progressStream.print("\r");
1056 }
1057 }
1058
1059 private void generatePointsElement(String name, Element pointsFolderElement, double[][] y, double date, double height) {
1060 Element pointsElement = new Element("Folder");
1061 Element nameElement = new Element("name");
1062 nameElement.addContent(name);
1063 pointsElement.addContent(nameElement);
1064
1065 for (int a = 0; a < y[0].length; a++) {
1066 Element placemarkElement = new Element("Placemark");
1067
1068 if (sliceCount > 1) {
1069 Element timeSpan = new Element("TimeSpan");
1070 Element begin = new Element("begin");
1071
1072 if (!ancient) {
1073 calendar.set(Calendar.YEAR, (int) Math.floor(date));
1074 calendar.set(Calendar.DAY_OF_YEAR, (int) (365 * (date - Math.floor(date))));
1075
1076 begin.addContent(dateFormat.format(calendar.getTime()));
1077 } else {
1078 begin.addContent(Integer.toString((int)Math.round(date)));
1079 }
1080 timeSpan.addContent(begin);
1081 placemarkElement.addContent(timeSpan);
1082 }
1083
1084 placemarkElement.addContent(generatePointData(name, height));
1085
1086 Element pointElement = new Element("Point");
1087 Element coordinates = new Element("coordinates");
1088 coordinates.addContent(y[1][a]+","+y[0][a]+",0");
1089 pointElement.addContent(coordinates);
1090 placemarkElement.addContent(pointElement);
1091
1092 pointsElement.addContent(placemarkElement);
1093 }
1094
1095 pointsFolderElement.addContent(pointsElement);
1096 }
1097
1098 private void generatePoints(String name, Element pointsFolderElement, double[][] y, double date, double height, double[] heights) {
1099 for (int a = 0; a < y[0].length; a++) {
1100 Element placemarkElement = new Element("Placemark");
1101
1102 if (heights == null) {
1103 placemarkElement.addContent(generatePointData(name, height));
1104 } else {
1105 placemarkElement.addContent(generatePointData(name, heights[a]));
1106 }
1107
1108 Element pointElement = new Element("Point");
1109 Element coordinates = new Element("coordinates");
1110 coordinates.addContent(y[1][a]+","+y[0][a]+",0");
1111 pointElement.addContent(coordinates);
1112 placemarkElement.addContent(pointElement);
1113
1114 pointsFolderElement.addContent(placemarkElement);
1115 }
1116 }
1117
1118 private void generateContours(String name, Element sliceElement, Element traitElement, double[][] y, int slice, double date, double height, double hpdValue) {
1119 //to test how much points are within the polygons
1120 double numberOfPointsInPolygons = 0;
1121 double totalArea = 0;
1122
1123 ContourMaker contourMaker;
1124 if (contourMode == ContourMode.JAVA)
1125 // contourMaker = new KernelDensityEstimator2D(y[0], y[1], gridSize);
1126 contourMaker = new KernelDensityEstimator2D(y[0], y[1], BANDWIDTHLIMIT);
1127 else if (contourMode == ContourMode.R)
1128 contourMaker = new ContourWithR(y[0], y[1], gridSize);
1129 else if (contourMode == ContourMode.SNYDER)
1130 // contourMaker = new ContourWithSynder(y[0], y[1], gridSize);
1131 contourMaker = new ContourWithSynder(y[0], y[1], BANDWIDTHLIMIT);
1132 else
1133 throw new RuntimeException("Unimplemented ContourModel!");
1134
1135 ContourPath[] paths = contourMaker.getContourPaths(hpdValue);
1136 int pathCounter = 1;
1137 for (ContourPath path : paths) {
1138
1139 KMLCoordinates coords = new KMLCoordinates(path.getAllX(), path.getAllY());
1140 if (traitElement != null) {
1141 Element regionElement = new Element(REGIONS_ELEMENT);
1142 regionElement.setAttribute(DENSITY_VALUE, Double.toString(hpdValue));
1143 regionElement.addContent(coords.toXML());
1144 traitElement.addContent(regionElement);
1145 }
1146
1147 // only if the trait is location we will write KML
1148 if (sliceElement != null) {
1149 //because KML polygons require long,lat,alt we need to switch lat and long first
1150 coords.switchXY();
1151
1152 String name1 = name + "_path_"+pathCounter;
1153
1154 Element placemarkElement = generatePlacemarkElementWithPolygon(name1, date, hpdValue, height, coords, slice, pathCounter);
1155
1156 //testing how many points are within the polygon
1157 if (checkSliceContours) {
1158 Element testElement = new Element("test");
1159 testElement.addContent(coords.toXML());
1160 Polygon2D testPolygon = new Polygon2D(testElement);
1161 totalArea += testPolygon.calculateArea();
1162
1163 double[][] dest = new double[y.length][y[0].length];
1164 for (int i = 0; i < y.length; i++) {
1165 for (int j = 0; j < y[0].length; j++) {
1166 dest[i][j] = y[i][j];
1167 }
1168 }
1169 numberOfPointsInPolygons += getNumberOfPointsInPolygon(dest, testPolygon);
1170 }
1171 sliceElement.addContent(placemarkElement);
1172 }
1173 pathCounter ++;
1174 }
1175
1176 if (checkSliceContours) {
1177 progressStream.print("numberOfContours=" + paths.length + "\tfreqOfPointsInContour=" + numberOfPointsInPolygons / y[0].length + "\ttotalArea = " + totalArea);
1178 }
1179 if (paths.length == 0 && !sliceProgressReport) {
1180 progressStream.println("Warning: slice at height " + height + ", contains no contours.");
1181 }
1182 }
1183
1184 public static int getNumberOfPointsInPolygon(double[][] pointsArray, Polygon2D testPolygon) {
1185 int numberOfPointsInPolygon = 0;
1186 for (int x = 0; x < pointsArray[0].length; x++) {
1187 if (testPolygon.containsPoint2D(new Point2D.Double(pointsArray[0][x], pointsArray[1][x]))) {
1188 numberOfPointsInPolygon++;
1189 }
1190 }
1191 return numberOfPointsInPolygon;
1192 }
1193
1194 private void constructPolygonStyleElement(Element styleElement, double sliceValue) {
1195 double date;
1196 if (Double.isNaN(sliceValue)){
1197 date = Double.NaN;
1198 styleElement.setAttribute(ID, ROOT_ELEMENT + "_hpd" + "_style");
1199 } else {
1200 date = mostRecentSamplingDate - sliceValue;
1201 styleElement.setAttribute(ID, REGIONS_ELEMENT + date + "_style");
1202 }
1203 Element lineStyle = new Element("LineStyle");
1204 Element width = new Element("width");
1205 width.addContent(WIDTH);
1206 lineStyle.addContent(width);
1207 Element polyStyle = new Element("PolyStyle");
1208 Element color = new Element("color");
1209 double[] minMax = new double[2];
1210 minMax[0] = sliceHeights[0];
1211 minMax[1] = sliceHeights[(sliceHeights.length - 1)];
1212 String colorString;
1213 if (Double.isNaN(sliceValue)){
1214 colorString = startHPDColor;
1215 } else {
1216 colorString = getKMLColor(sliceValue, minMax, endHPDColor, startHPDColor);
1217 }
1218 color.addContent(opacity + colorString);
1219 Element outline = new Element("outline");
1220 outline.addContent("0");
1221 polyStyle.addContent(color);
1222 polyStyle.addContent(outline);
1223 styleElement.addContent(lineStyle);
1224 styleElement.addContent(polyStyle);
1225 }
1226
1227 private void constructNodeStyleElement(Element styleElement, double sliceValue) {
1228 double date;
1229 if (Double.isNaN(sliceValue)){
1230 date = Double.NaN;
1231 styleElement.setAttribute(ID, ROOT_ELEMENT + date + "_style");
1232 } else {
1233 date = mostRecentSamplingDate - sliceValue;
1234 styleElement.setAttribute(ID, NODE_ELEMENT + date + "_style");
1235 }
1236 Element iconStyle = new Element("IconStyle");
1237 Element scale = new Element("scale");
1238 scale.addContent("1");
1239 iconStyle.addContent(scale);
1240
1241 Element icon = new Element("Icon");
1242 Element href = new Element("href");
1243 href.addContent(ICON);
1244 icon.addContent(href);
1245 iconStyle.addContent(icon);
1246
1247 Element color = new Element("color");
1248 double[] minMax = new double[2];
1249 minMax[0] = sliceHeights[0];
1250 minMax[1] = sliceHeights[(sliceHeights.length - 1)];
1251 String colorString;
1252 if (Double.isNaN(sliceValue)){
1253 colorString = startHPDColor;
1254 } else {
1255 colorString = getKMLColor(sliceValue, minMax, endHPDColor, startHPDColor);
1256 }
1257 color.addContent(opacity + colorString);
1258 iconStyle.addContent(color);
1259
1260 Element colorMode = new Element("colorMode");
1261 colorMode.addContent("normal");
1262 iconStyle.addContent(colorMode);
1263
1264 styleElement.addContent(iconStyle);
1265 }
1266
1267 private Element generatePlacemarkElementWithPolygon(String name, double date, double hpdValue, double sliceValue, KMLCoordinates coords, int sliceInteger, int pathCounter) {
1268 Element placemarkElement = new Element("Placemark");
1269
1270 Element placemarkNameElement = new Element("name");
1271 placemarkNameElement.addContent(name);
1272 placemarkElement.addContent(placemarkNameElement);
1273
1274
1275 Element visibility = new Element("visibility");
1276 if (sliceInteger == -1){
1277 visibility.addContent("0");
1278 } else {
1279 visibility.addContent("1");
1280 }
1281 placemarkElement.addContent(visibility);
1282
1283 if (!Double.isNaN(date)) {
1284 Element timeSpan = new Element("TimeSpan");
1285 Element begin = new Element("begin");
1286
1287 if (!ancient) {
1288 calendar.set(Calendar.YEAR, (int) Math.floor(date));
1289 calendar.set(Calendar.DAY_OF_YEAR, (int) (365 * (date - Math.floor(date))));
1290
1291 begin.addContent(dateFormat.format(calendar.getTime()));
1292 } else {
1293 begin.addContent(Integer.toString((int)Math.round(date)));
1294 }
1295 timeSpan.addContent(begin);
1296 // if (sliceInteger > 1) {
1297 // Element end = new Element("end");
1298 // end.addContent(Double.toString(mostRecentSamplingDate- sliceHeights[(sliceInteger-1)]));
1299 // timeSpan.addContent(end);
1300 // }
1301 placemarkElement.addContent(timeSpan);
1302 }
1303
1304 if (useStyles) {
1305 Element style = new Element("styleUrl");
1306 if (sliceInteger == -1){
1307 style.addContent("#" + ROOT_ELEMENT + "_hpd" + "_style");
1308 } else {
1309 style.addContent("#" + REGIONS_ELEMENT + date + "_style");
1310 }
1311
1312 placemarkElement.addContent(style);
1313 }
1314
1315 placemarkElement.addContent(generateContourData(name, date, sliceValue, hpdValue));
1316
1317 Element polygonElement = new Element("Polygon");
1318 Element altitudeMode = new Element("altitudeMode");
1319 altitudeMode.addContent("clampToGround");
1320 polygonElement.addContent(altitudeMode);
1321 Element tessellate = new Element("tessellate");
1322 tessellate.addContent("1");
1323 polygonElement.addContent(tessellate);
1324 Element outerBoundaryIs = new Element("outerBoundaryIs");
1325 Element LinearRing = new Element("LinearRing");
1326 LinearRing.addContent(coords.toXML());
1327 outerBoundaryIs.addContent(LinearRing);
1328 polygonElement.addContent(outerBoundaryIs);
1329 placemarkElement.addContent(polygonElement);
1330
1331 return placemarkElement;
1332 }
1333
1334 private Element generateNodeSliceElement(double sliceValue, double[][] nodes, int sliceInteger) {
1335 double date;
1336 Element nodeSliceElement = new Element("Folder");
1337 Element nameNodeSliceElement = new Element("name");
1338 String name;
1339 if (sliceInteger == -1){
1340 date = Double.NaN;
1341 name = ROOT_ELEMENT;
1342 } else {
1343 date = mostRecentSamplingDate - sliceValue;
1344 name = "nodeSlice_"+sliceInteger+"_"+date;
1345 }
1346 nameNodeSliceElement.addContent(name);
1347 nodeSliceElement.addContent(nameNodeSliceElement);
1348
1349 Element initialVisibility = new Element("visibility");
1350 initialVisibility.addContent("0");
1351 if (sliceInteger == -1){
1352 nodeSliceElement.addContent(initialVisibility);
1353 }
1354
1355 for (int a = 0; a < nodes[0].length; a++) {
1356 Element placemarkElement = new Element("Placemark");
1357
1358 // Element visibility = new Element("visibility");
1359 // visibility.addContent("1");
1360 // placemarkElement.addContent(visibility);
1361
1362 if (sliceCount > 1) {
1363 Element timeSpan = new Element("TimeSpan");
1364 Element begin = new Element("begin");
1365
1366 if (!ancient) {
1367 calendar.set(Calendar.YEAR, (int) Math.floor(date));
1368 calendar.set(Calendar.DAY_OF_YEAR, (int) (365 * (date - Math.floor(date))));
1369
1370 begin.addContent(dateFormat.format(calendar.getTime()));
1371 } else {
1372 begin.addContent(Integer.toString((int)Math.round(date)));
1373 }
1374 timeSpan.addContent(begin);
1375 placemarkElement.addContent(timeSpan);
1376 }
1377
1378 placemarkElement.addContent(generatePointData(name, sliceValue));
1379
1380 if (useStyles) {
1381 Element style = new Element("styleUrl");
1382 if (sliceInteger == -1){
1383 style.addContent("#" + ROOT_ELEMENT + date + "_style");
1384 } else {
1385 style.addContent("#" + NODE_ELEMENT + date + "_style");
1386 }
1387
1388 placemarkElement.addContent(style);
1389 }
1390
1391 Element pointElement = new Element("Point");
1392 // Element altitudeMode = new Element("altitudeMode");
1393 // altitudeMode.addContent("clampToGround");
1394 // polygonElement.addContent(altitudeMode);
1395 // Element tessellate = new Element("tessellate");
1396 // tessellate.addContent("1");
1397 // polygonElement.addContent(tessellate);
1398 Element coordinates = new Element("coordinates");
1399 coordinates.addContent(nodes[1][a]+","+nodes[0][a]+",0");
1400 pointElement.addContent(coordinates);
1401 placemarkElement.addContent(pointElement);
1402
1403 nodeSliceElement.addContent(placemarkElement);
1404
1405 }
1406
1407 return nodeSliceElement;
1408 }
1409
1410 private Element generateContourData(String name, double date, double height, double hpd) {
1411 Element data = new Element("ExtendedData");
1412 Element schemaData = new Element("SchemaData");
1413 schemaData.setAttribute("schemaUrl", "#HPD_Schema");
1414 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Name").addContent(name));
1415 // schemaData.addContent(new Element("SimpleData").setAttribute("name", "Description"));
1416 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Time").addContent(Double.toString(date)));
1417 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Height").addContent(Double.toString(height)));
1418 if (hpd > 0) {
1419 schemaData.addContent(new Element("SimpleData").setAttribute("name", "HPD").addContent(Double.toString(hpd)));
1420 }
1421 data.addContent(schemaData);
1422 return data;
1423 }
1424
1425 private Element generatePointData(String name, double height) {
1426 Element data = new Element("ExtendedData");
1427 Element schemaData = new Element("SchemaData");
1428 schemaData.setAttribute("schemaUrl", "#Point_Schema");
1429 double date = mostRecentSamplingDate - height;
1430 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Name").addContent(name));
1431 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Time").addContent(Double.toString(date)));
1432 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Height").addContent(Double.toString(height)));
1433 data.addContent(schemaData);
1434 return data;
1435 }
1436 private void outputHeader(String[] traits) {
1437 StringBuffer sb = new StringBuffer("slice");
1438 for (int i = 0; i < traits.length; i++) {
1439 // Load first value to check dimensionality
1440 Trait trait = values.get(0).get(i).get(0);
1441 if (trait.isMultivariate()) {
1442 int dim = trait.getDim();
1443 for (int j = 1; j <= dim; j++)
1444 sb.append(sep).append(traits[i]).append(j);
1445 } else
1446 sb.append(sep).append(traits[i]);
1447 }
1448 sb.append("\n");
1449 resultsStream.print(sb);
1450 }
1451
1452 // private List<Tree> importTrees(String treeFileName, int burnin) throws IOException, Importer.ImportException {
1453 //
1454 // int totalTrees = 10000;
1455 //
1456 // progressStream.println("Reading trees (bar assumes 10,000 trees)...");
1457 // progressStream.println("0 25 50 75 100");
1458 // progressStream.println("|--------------|--------------|--------------|--------------|");
1459 //
1460 // int stepSize = totalTrees / 60;
1461 // if (stepSize < 1) stepSize = 1;
1462 //
1463 // List<Tree> treeList = new ArrayList<Tree>();
1464 // BufferedReader reader1 = new BufferedReader(new FileReader(treeFileName));
1465 //
1466 // String line1 = reader1.readLine();
1467 // TreeImporter importer1;
1468 // if (line1.toUpperCase().startsWith("#NEXUS")) {
1469 // importer1 = new NexusImporter(new FileReader(treeFileName));
1470 // } else {
1471 // importer1 = new NewickImporter(new FileReader(treeFileName));
1472 // }
1473 // totalTrees = 0;
1474 // while (importer1.hasTree()) {
1475 // Tree treeTime = importer1.importNextTree();
1476 //
1477 // if (totalTrees > burnin)
1478 // treeList.add(treeTime);
1479 //
1480 // if (totalTrees > 0 && totalTrees % stepSize == 0) {
1481 // progressStream.print("*");
1482 // progressStream.flush();
1483 // }
1484 // totalTrees++;
1485 // }
1486 // return treeList;
1487 // }
1488
1489 private void readAndAnalyzeTrees(String treeFileName, int burnin, int skipEvery,
1490 String[] traits, double[] slices,
1491 boolean impute, boolean trueNoise, Normalization normalize,
1492 boolean divideByBranchLength, BranchSet branchset, Set taxaSet)
1493 throws IOException, Importer.ImportException {
1494
1495 int totalTrees = 10000;
1496 int totalStars = 0;
1497
1498 progressStream.println("Reading and analyzing trees (bar assumes 10,000 trees)...");
1499 progressStream.println("0 25 50 75 100");
1500 progressStream.println("|--------------|--------------|--------------|--------------|");
1501
1502 int stepSize = totalTrees / 60;
1503 if (stepSize < 1) stepSize = 1;
1504
1505 BufferedReader reader1 = new BufferedReader(new FileReader(treeFileName));
1506
1507 String line1 = reader1.readLine();
1508 TreeImporter importer1;
1509 if (line1.toUpperCase().startsWith("#NEXUS")) {
1510 importer1 = new NexusImporter(new FileReader(treeFileName));
1511 } else {
1512 importer1 = new NewickImporter(new FileReader(treeFileName));
1513 }
1514 totalTrees = 0;
1515
1516 while (importer1.hasTree()) {
1517 Tree treeTime = importer1.importNextTree();
1518 if (totalTrees % skipEvery == 0) {
1519 treesRead++;
1520 if (totalTrees >= burnin) {
1521 analyzeTree(treeTime, traits, slices, impute, trueNoise, normalize, divideByBranchLength, branchset, taxaSet);
1522 }
1523 }
1524 if (totalTrees > 0 && totalTrees % stepSize == 0) {
1525 progressStream.print("*");
1526 totalStars++;
1527 if (totalStars % 61 == 0)
1528 progressStream.print("\n");
1529 progressStream.flush();
1530 }
1531 totalTrees++;
1532 }
1533 progressStream.print("\n");
1534 }
1535
1536 class Trait {
1537
1538 Trait(Object obj) {
1539 this.obj = obj;
1540 if (obj instanceof Object[]) {
1541 isMultivariate = true;
1542 array = (Object[]) obj;
1543 }
1544 this.height = 0.0;
1545 }
1546
1547 Trait(Object obj, double height) {
1548 this.obj = obj;
1549 if (obj instanceof Object[]) {
1550 isMultivariate = true;
1551 array = (Object[]) obj;
1552 }
1553 this.height = height;
1554 }
1555
1556 public boolean isMultivariate() {
1557 return isMultivariate;
1558 }
1559
1560 public boolean isNumber() {
1561 if (!isMultivariate)
1562 return (obj instanceof Double);
1563 return (array[0] instanceof Double);
1564 }
1565
1566 public int getDim() {
1567 if (isMultivariate) {
1568 return array.length;
1569 }
1570 return 1;
1571 }
1572
1573 public double[] getValue() {
1574 int dim = getDim();
1575 double[] result = new double[dim];
1576 if (!isMultivariate) {
1577 result[0] = (Double) obj;
1578 } else {
1579 for (int i = 0; i < dim; i++)
1580 result[i] = (Double) array[i];
1581 }
1582 return result;
1583 }
1584
1585 public double getHeight() {
1586 return height;
1587 }
1588
1589 public void multiplyBy(double factor) {
1590 if (!isMultivariate) {
1591 obj = ((Double) obj * factor);
1592 } else {
1593 for (int i = 0; i < array.length; i++) {
1594 array[i] = ((Double) array[i] * factor);
1595 }
1596 }
1597 }
1598
1599 private Object obj;
1600 private Object[] array;
1601 private boolean isMultivariate = false;
1602 private double height;
1603
1604 public String toString() {
1605 if (!isMultivariate)
1606 return obj.toString();
1607 StringBuffer sb = new StringBuffer(array[0].toString());
1608 for (int i = 1; i < array.length; i++)
1609 sb.append(sep).append(array[i]);
1610 return sb.toString();
1611 }
1612 }
1613
1614 private List<List<List<Trait>>> values;
1615 private List<List<Trait>> rootValues;
1616 private List<List<List<Trait>>> tipValues;
1617 private List<String> tipNames;
1618
1619 private void outputSlice(int slice, double sliceValue) {
1620
1621 List<List<Trait>> thisSlice = values.get(slice);
1622 int traitCount = thisSlice.size();
1623 int valueCount = thisSlice.get(0).size();
1624
1625 StringBuffer sb = new StringBuffer();
1626
1627 for (int v = 0; v < valueCount; v++) {
1628 if (Double.isNaN(sliceValue))
1629 sb.append("All");
1630 else
1631 sb.append(sliceValue);
1632 for (int t = 0; t < traitCount; t++) {
1633 sb.append(sep);
1634 sb.append(thisSlice.get(t).get(v));
1635 }
1636 sb.append("\n");
1637 }
1638
1639 resultsStream.print(sb);
1640 }
1641
1642 private static boolean onBackbone(Tree tree, NodeRef node, Set targetSet) {
1643
1644 if (tree.isExternal(node)) return false;
1645
1646 Set leafSet = TreeUtils.getDescendantLeaves(tree, node);
1647 int size = leafSet.size();
1648
1649 leafSet.retainAll(targetSet);
1650
1651 if (leafSet.size() > 0) {
1652
1653 // if all leaves below are in target then check just above.
1654 if (leafSet.size() == size) {
1655
1656 Set superLeafSet = TreeUtils.getDescendantLeaves(tree, tree.getParent(node));
1657 superLeafSet.removeAll(targetSet);
1658
1659 // the branch is on ancestral path if the super tree has some non-targets in it
1660 return (superLeafSet.size() > 0);
1661
1662 } else return true;
1663
1664 } else return false;
1665 }
1666
1667 private static boolean inClade(Tree tree, NodeRef node, Set targetSet, boolean includeStem) {
1668
1669 Set leafSet = TreeUtils.getDescendantLeaves(tree, node);
1670 int size = leafSet.size();
1671
1672 leafSet.retainAll(targetSet);
1673
1674 if (leafSet.size() > 0) {
1675
1676 // check if node is not ancestral to mrca of targetSet
1677 if (leafSet.size() == size) {
1678
1679 if (!includeStem){
1680 return false;
1681 } else {
1682 Set newLeafSet = TreeUtils.getDescendantLeaves(tree, node);
1683 newLeafSet.removeAll(targetSet);
1684 if (newLeafSet.size() == 0){
1685 return true;
1686 } else {
1687 return false;
1688 }
1689 }
1690
1691 } else return true;
1692
1693 } else return false;
1694 }
1695
1696 private void analyzeTree(Tree treeTime, String[] traits, double[] slices, boolean impute,
1697 boolean trueNoise, Normalization normalize, boolean divideByBranchlength,
1698 BranchSet branchset, Set taxaSet) {
1699
1700 double[][] precision = null;
1701
1702 if (impute) {
1703
1704 Object o = treeTime.getAttribute(PRECISION_STRING);
1705 double treeNormalization = 1; // None
1706 if (normalize == Normalization.LENGTH) {
1707 treeNormalization = TreeUtils.getTreeLength(treeTime, treeTime.getRoot());
1708 } else if (normalize == Normalization.HEIGHT) {
1709 treeNormalization = treeTime.getNodeHeight(treeTime.getRoot());
1710 }
1711
1712 if (o != null) {
1713 Object[] array = (Object[]) o;
1714 int dim = (int) Math.sqrt(1 + 8 * array.length) / 2;
1715 precision = new double[dim][dim];
1716 int c = 0;
1717 for (int i = 0; i < dim; i++) {
1718 for (int j = i; j < dim; j++) {
1719 precision[j][i] = precision[i][j] = ((Double) array[c++]) * treeNormalization;
1720 }
1721 }
1722 }
1723 //System.out.println(treeNormalization+"\t"+precision[0][0]+"\t"+precision[0][1]+"\t"+precision[1][0]+"\t"+precision[1][1]);
1724 }
1725
1726
1727 if (tipValues != null && tipValues.size() == 0) {
1728 // this is the first tree so initialize the tip value lists
1729 for (int i = 0; i < treeTime.getExternalNodeCount(); i++) {
1730 List<List<Trait>> thisTip = new ArrayList<List<Trait>>(traitCount);
1731 tipValues.add(thisTip);
1732 for (int j = 0; j < traitCount; j++) {
1733 List<Trait> thisTipTrait = new ArrayList<Trait>();
1734 thisTip.add(thisTipTrait);
1735 }
1736
1737 tipNames.add(treeTime.getNodeTaxon(treeTime.getExternalNode(i)).getId());
1738 }
1739
1740 }
1741
1742 // employed to get dispersal rates across the whole tree
1743 // double treeNativeDistance = 0;
1744 // double treeKilometerGreatCircleDistance = 0;
1745
1746 double[] treeSliceTime = new double[sliceCount];
1747 double[] treeSliceDistance = new double[sliceCount];
1748 double[] treeSliceMaxDistance = new double[sliceCount];
1749 double[] treeTimeFromRoot = new double[sliceCount];
1750 double[] maxDistanceFromRoot = new double[sliceCount];
1751 //this one will used for weighted average (WA)
1752 //double[] treeSliceDiffusionCoefficientWA = new double[sliceCount];
1753 //this one is used for simple average
1754 double[] treeSliceDiffusionCoefficientA = new double[sliceCount];
1755 // this is for the variance
1756 double[] treeSliceDiffusionCoefficientV = new double[sliceCount];
1757 double[][] treeSliceDiffusionCoefficients = new double[sliceCount][treeTime.getNodeCount() - 1];
1758 double[] treeSliceBranchCount = new double[sliceCount];
1759
1760 treeLengths.add(TreeUtils.getTreeLength(treeTime, treeTime.getRoot()));
1761
1762 for (int x = 0; x < treeTime.getNodeCount(); x++) {
1763
1764 NodeRef node = treeTime.getNode(x);
1765
1766 if (!(treeTime.isRoot(node))) {
1767
1768 double nodeHeight = treeTime.getNodeHeight(node);
1769 double parentHeight = treeTime.getNodeHeight(treeTime.getParent(node));
1770
1771 double oneOverBranchLength = 1.0;
1772 if (divideByBranchlength) {
1773 oneOverBranchLength = 1.0 / treeTime.getBranchLength(node);
1774 }
1775
1776 boolean proceed = false;
1777 // we allow for both branch constraints as well as constraints based on locations, so we define a temp boolean for the first type of constraints to combine with the second one
1778 boolean tempBranchProceed = false;
1779 if (branchset == BranchSet.ALL) {
1780 tempBranchProceed = true;
1781 } else if (branchset == BranchSet.EXT && treeTime.isExternal(node)) {
1782 tempBranchProceed = true;
1783 } else if (branchset == BranchSet.INT && !treeTime.isExternal(node)) {
1784 tempBranchProceed = true;
1785 } else if (branchset == BranchSet.BACKBONE && onBackbone(treeTime, node, taxaSet)) {
1786 tempBranchProceed = true;
1787 } else if (branchset == BranchSet.CLADE && inClade(treeTime, node, taxaSet, true)) { //TODO: make the includeStem an argument
1788 tempBranchProceed = true;
1789 }
1790
1791 if (tempBranchProceed) {
1792 boolean coordinatesOK = false;
1793 if ((latMin > -Double.MAX_VALUE) || (latMax < Double.MAX_VALUE) || (longMin > -Double.MAX_VALUE) || (longMax < Double.MAX_VALUE)){
1794 Trait locTrait = new Trait(treeTime.getNodeAttribute(node, traits[0]));
1795 double[] loc = locTrait.getValue();
1796 // System.out.println("loc0 and loc1 = "+loc[0]+","+loc[1]);
1797 if ((latMin < loc[0]) && (latMax > loc[0]) && (longMin < loc[1]) && (longMax > loc[1])){
1798 coordinatesOK = true;
1799 // Checking the constraints by looking at descendents
1800 // Set leafSet = Tree.Utils.getDescendantLeaves(treeTime, node);
1801 // Iterator iter = leafSet.iterator();
1802 // System.out.println("descendents: ");
1803 // while (iter.hasNext()) {
1804 // System.out.print(iter.next()+" ");
1805 // }
1806 // System.out.println(";");
1807 }
1808 } else {
1809 coordinatesOK = true;
1810 }
1811 boolean descendentsOK = false;
1812 if (descendentTaxaSet!=null){
1813
1814 NodeRef setNode = TreeUtils.getCommonAncestorNode(treeTime, descendentTaxaSet);
1815
1816 if (setNode==null){
1817 System.err.println("no common ancestor node for taxa you have defined:");
1818 Iterator iter = descendentTaxaSet.iterator();
1819 while (iter.hasNext()) {
1820 System.out.print(iter.next()+" ");
1821 }
1822 System.out.println(";");
1823 System.exit(-1);
1824 }
1825
1826 // Set leafSet = Tree.Utils.getDescendantLeaves(treeTime, node);
1827 // Iterator iter2 = leafSet.iterator();
1828 // System.out.println("leafs: ");
1829 // while (iter2.hasNext()) {
1830 // System.out.print(iter2.next()+" ");
1831 // }
1832 // System.out.println(";");
1833
1834
1835 if (node.equals(setNode)){
1836 descendentsOK = true;
1837 // System.out.println("descendenst are .... OK");
1838 }
1839 } else {
1840 descendentsOK = true;
1841 }
1842
1843 if (coordinatesOK && descendentsOK){
1844 proceed = true;
1845 }
1846
1847 }
1848
1849 // if(proceed){
1850 // System.out.println("proceeding");
1851 // }
1852
1853 // employed to get dispersal rates across the whole tree
1854 // if (containsLocation){
1855 //
1856 // Trait nodeLocationTrait = new Trait (treeTime.getNodeAttribute(node, LOCATIONTRAIT));
1857 // Trait parentNodeLocationTrait = new Trait (treeTime.getNodeAttribute(treeTime.getParent(node), LOCATIONTRAIT));
1858 // treeNativeDistance += getNativeDistance(nodeLocationTrait.getValue(),parentNodeLocationTrait.getValue());
1859 // treeKilometerGreatCircleDistance += getKilometerGreatCircleDistance(nodeLocationTrait.getValue(),parentNodeLocationTrait.getValue());
1860 //
1861 // }
1862
1863 for (int i = 0; i < sliceCount; i++) {
1864 //System.out.println(slices[i]);
1865 if (sdr || snr) {
1866 if (!doSlices ||
1867 (slices[i] < nodeHeight)
1868 ) {
1869 if (proceed) {
1870
1871 treeSliceTime[i] += (parentHeight - nodeHeight);
1872 double diffusionCoefficient = 0;
1873
1874 if (sdr) {
1875 Trait nodeLocationTrait = new Trait(treeTime.getNodeAttribute(node, traits[0]));
1876 Trait parentNodeLocationTrait = new Trait(treeTime.getNodeAttribute(treeTime.getParent(node), traits[0]));
1877 if (GREATCIRCLEDISTANCE){
1878 treeSliceDistance[i] += getGeographicalDistance(nodeLocationTrait.getValue(), parentNodeLocationTrait.getValue());
1879 diffusionCoefficient = (Math.pow((getGeographicalDistance(nodeLocationTrait.getValue(), parentNodeLocationTrait.getValue())), 2.0) / (4.0 * (parentHeight - nodeHeight)));
1880 }else{
1881 treeSliceDistance[i] += getNativeDistance(nodeLocationTrait.getValue(), parentNodeLocationTrait.getValue());
1882 diffusionCoefficient = (Math.pow((getNativeDistance(nodeLocationTrait.getValue(), parentNodeLocationTrait.getValue())), 2.0) / (4.0 * (parentHeight - nodeHeight)));
1883 }
1884
1885 } else if (snr) {
1886 treeSliceDistance[i] += (Double)treeTime.getNodeAttribute(node, SUBSTITUTION);
1887 }
1888
1889 //TreeModel model = new TreeModel(treeTime, true);
1890 //treeSliceDistance[i] += getKilometerGreatCircleDistance(model.getMultivariateNodeTrait(node, LOCATIONTRAIT),model.getMultivariateNodeTrait(model.getParent(node), LOCATIONTRAIT));
1891
1892 //treeSliceDiffusionCoefficientWA[i] += (Math.pow((getGeographicalDistance(nodeLocationTrait.getValue(),parentNodeLocationTrait.getValue())),2.0)/(4.0*(parentHeight-nodeHeight)))*(parentHeight-nodeHeight);
1893 treeSliceDiffusionCoefficientA[i] += diffusionCoefficient;
1894 treeSliceDiffusionCoefficients[i][x] = diffusionCoefficient;
1895 treeSliceBranchCount[i]++;
1896 }
1897 }
1898 }
1899
1900 double height = Double.MAX_VALUE;
1901 if (i < sliceCount - 1) {
1902 height = slices[i + 1];
1903 }
1904
1905 if (!doSlices ||
1906 ((sliceMode == SliceMode.BRANCHES) && (slices[i] >= nodeHeight && slices[i] < parentHeight)) ||
1907 ((sliceMode == SliceMode.NODES) && (slices[i] < nodeHeight && height >= nodeHeight))
1908 ) {
1909
1910 if (proceed) {
1911
1912 List<List<Trait>> thisSlice = values.get(i);
1913 for (int j = 0; j < traitCount; j++) {
1914
1915 List<Trait> thisTraitSlice = thisSlice.get(j);
1916 Object tmpTrait = treeTime.getNodeAttribute(node, traits[j]);
1917 if (tmpTrait == null) {
1918 System.err.println("Trait '" + traits[j] + "' not found on branch.");
1919 System.exit(-1);
1920 }
1921 Trait trait = new Trait(tmpTrait);
1922 //System.out.println("trees "+treesAnalyzed+"\tslice "+slices[i]+"\t"+trait.toString());
1923 if (divideByBranchlength) {
1924 trait.multiplyBy(oneOverBranchLength);
1925 }
1926 if (impute && (sliceMode == SliceMode.BRANCHES)) {
1927 double rate = 1.0;
1928 if (!rateAttributeString.equals("none")){
1929 Double rateAttribute = (Double) treeTime.getNodeAttribute(node, rateAttributeString);
1930 if (rateAttribute != null) {
1931 rate = rateAttribute;
1932 if (outputRateWarning) {
1933 progressStream.println("Warning: using "+rateAttributeString+" as rate attribute during imputation!");
1934 outputRateWarning = false;
1935 }
1936 }
1937 }
1938 if (trueNoise && precision == null) {
1939 progressStream.println("Error: not precision available for imputation with correct noise!");
1940 System.exit(-1);
1941 }
1942 // if (slices[i] > nodeHeight) {
1943 trait = imputeValue(trait, new Trait(treeTime.getNodeAttribute(treeTime.getParent(node), traits[j])),
1944 slices[i], nodeHeight, parentHeight, precision, rate, trueNoise);
1945 // System.out.println(slices[i]+"\t"+nodeHeight+"\t"+parentHeight+"\t"+precision[0][0]+"\t"+precision[0][1]+"\t"+precision[1][0]+"\t"+precision[1][1]+"\t"+rate+"\t"+trait);
1946 ////
1947 // }
1948 // QUESTION to PL: MAS does not see how slices[i] is ever less than nodeHeight
1949 // } else if (impute && (sliceMode == SliceMode.NODES)) {
1950 // progressStream.println("no imputation for slice mode = nodes");
1951 }
1952 thisTraitSlice.add(trait);
1953 //System.out.println("trees "+treesAnalyzed+"\tslice "+slices[i]+"\t"+trait.toString());
1954
1955 treeSliceTime[i] += (parentHeight - slices[i]);
1956 double diffusionCoefficient = 0;
1957 //if trait is location
1958 if (sdr) {
1959 Trait parentTrait = new Trait(treeTime.getNodeAttribute(treeTime.getParent(node), traits[j]));
1960 if (GREATCIRCLEDISTANCE){
1961 treeSliceDistance[i] += getGeographicalDistance(trait.getValue(), parentTrait.getValue());
1962 diffusionCoefficient = (Math.pow((getGeographicalDistance(trait.getValue(), parentTrait.getValue())), 2.0) / (4.0 * (parentHeight - slices[i])));
1963 } else{
1964 treeSliceDistance[i] += getNativeDistance(trait.getValue(), parentTrait.getValue());
1965 diffusionCoefficient = (Math.pow((getNativeDistance(trait.getValue(), parentTrait.getValue())), 2.0) / (4.0 * (parentHeight - slices[i])));
1966 // System.out.println(getNativeDistance(trait.getValue(), parentTrait.getValue())+"\t"+(parentHeight - slices[i])+"\t"+getNativeDistance(trait.getValue(), parentTrait.getValue())/(parentHeight - slices[i]));
1967 }
1968 } else if (snr) {
1969 treeSliceDistance[i] += (Double)treeTime.getNodeAttribute(node, SUBSTITUTION)*((parentHeight - slices[i])/(parentHeight - nodeHeight));
1970
1971 }
1972
1973
1974 treeSliceDiffusionCoefficientA[i] += diffusionCoefficient;
1975 treeSliceDiffusionCoefficients[i][x] = diffusionCoefficient;
1976 treeSliceBranchCount[i]++;
1977
1978 if(sdr) {
1979 double tempDistanceFromRoot = getDistanceFromRoot(treeTime, traits[j], trait.getValue());
1980 if (maxDistanceFromRoot[i] < tempDistanceFromRoot) {
1981 maxDistanceFromRoot[i] = tempDistanceFromRoot;
1982 treeSliceMaxDistance[i] = getPathDistance(treeTime, node, traits[j], trait.getValue());
1983 //putting this below here ensures that treeTimeFromRoot is never < 0
1984 treeTimeFromRoot[i] = treeTime.getNodeHeight(treeTime.getRoot()) - slices[i];
1985 }
1986
1987
1988 }
1989 }
1990 }
1991 }
1992 }
1993
1994 if (tipValues != null && treeTime.isExternal(node)) {
1995 List<List<Trait>> thisTip = tipValues.get(x);
1996
1997 for (int j = 0; j < traitCount; j++) {
1998 Object tmpTrait = treeTime.getNodeAttribute(node, traits[j]);
1999 if (tmpTrait == null) {
2000 System.err.println("Trait '" + traits[j] + "' not found for tip.");
2001 System.exit(-1);
2002 }
2003 thisTip.get(j).add(new Trait(tmpTrait, treeTime.getNodeHeight(node)));
2004
2005 }
2006 }
2007
2008 } else {
2009 if (sliceMode == SliceMode.NODES) {
2010 double nodeHeight = treeTime.getNodeHeight(node);
2011 for (int i = 0; i < sliceCount; i++) {
2012 double height = Double.MAX_VALUE;
2013 if (i < sliceCount - 1) {
2014 height = slices[i + 1];
2015 }
2016 if ((slices[i] < nodeHeight && height >= nodeHeight)){
2017 List<List<Trait>> thisSlice = values.get(i);
2018 for (int j = 0; j < traitCount; j++) {
2019 List<Trait> thisTraitSlice = thisSlice.get(j);
2020 Object tmpTrait = treeTime.getNodeAttribute(node, traits[j]);
2021 if (tmpTrait == null) {
2022 System.err.println("Trait '" + traits[j] + "' not found on node.");
2023 System.exit(-1);
2024 }
2025 Trait trait = new Trait(tmpTrait);
2026 thisTraitSlice.add(trait);
2027
2028 }
2029
2030 }
2031
2032 }
2033 }
2034
2035 if (rootValues != null) {
2036 for (int j = 0; j < traitCount; j++) {
2037 List<Trait> thisRootTrait = rootValues.get(j);
2038 Object tmpTrait = treeTime.getNodeAttribute(node, traits[j]);
2039 if (tmpTrait == null) {
2040 System.err.println("Trait '" + traits[j] + "' not found on root node.");
2041 System.exit(-1);
2042 }
2043 Trait trait = new Trait(tmpTrait, treeTime.getNodeHeight(node));
2044 thisRootTrait.add(trait);
2045
2046 }
2047 }
2048 }
2049 }
2050
2051 //System.out.println(Tree.Utils.getTreeLength(treeTime, treeTime.getRoot())+"\t"+test);
2052
2053 if (sdr || snr) {
2054 sliceTreeDistanceArrays.add(treeSliceDistance);
2055 sliceTreeTimeArrays.add(treeSliceTime);
2056 if (sdr){
2057 sliceTreeMaxPathDistanceArrays.add(treeSliceMaxDistance);
2058 sliceTreeMaxDistanceFromRootArrays.add(maxDistanceFromRoot);
2059 sliceTreeTimeFromRootArrays.add(treeTimeFromRoot);
2060 for (int i = 0; i < treeSliceDiffusionCoefficientA.length; i++) {
2061 //treeSliceDiffusionCoefficientWA[i] = treeSliceDiffusionCoefficientWA[i]/treeSliceTime[i];
2062 treeSliceDiffusionCoefficientA[i] = treeSliceDiffusionCoefficientA[i] / treeSliceBranchCount[i];
2063 for (int j = 0; j < treeSliceDiffusionCoefficients[0].length; j++) {
2064 treeSliceDiffusionCoefficientV[i] += Math.pow((treeSliceDiffusionCoefficients[i][j] - treeSliceDiffusionCoefficientA[i]),2);
2065 }
2066 treeSliceDiffusionCoefficientV[i] = treeSliceDiffusionCoefficientV[i] / treeSliceBranchCount[i];
2067 //System.out.println(treeSliceTime[i]+"\t"+treeLengths.get(i));
2068 }
2069 sliceTreeDiffusionCoefficientArrays.add(treeSliceDiffusionCoefficientA);
2070 sliceTreeDiffusionCoefficientVarianceArrays.add(treeSliceDiffusionCoefficientV);
2071 }
2072 }
2073
2074
2075 // employed to get dispersal rates across the whole tree
2076 // if (containsLocation) {
2077 // double treelength = Tree.Utils.getTreeLength(treeTime, treeTime.getRoot());
2078 // double dispersalNativeRate = treeNativeDistance/treelength;
2079 // double dispersalKilometerRate = treeKilometerGreatCircleDistance/treelength;
2080 //System.out.println(dispersalNativeRate+"\t"+dispersalKilometerRate);
2081 // dispersalrates.add(dispersalNativeRate+"\t"+dispersalKilometerRate);
2082 // }
2083
2084 treesAnalyzed++;
2085
2086 }
2087
2088 private static double getNativeDistance(double[] location1, double[] location2) {
2089 return Math.sqrt(Math.pow((location2[0]-location1[0]),2.0)+Math.pow((location2[1]-location1[1]),2.0));
2090 }
2091
2092
2093 private static double getGeographicalDistance(double[] location1, double[] location2) {
2094 if (location1.length == 1) {
2095 // assume we only have latitude so put them on the prime meridian
2096 return getKilometerGreatCircleDistance(new double[] { location1[0], 0.0}, new double[] { location2[0], 0.0});
2097 } else if (location1.length == 2) {
2098 return getKilometerGreatCircleDistance(location1, location2);
2099 }
2100 throw new RuntimeException("Distances can only be calculated for longitude and latitude (or just latitude)");
2101 }
2102
2103 private static double getKilometerGreatCircleDistance(double[] location1, double[] location2) {
2104 SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(location1[0], location1[1]);
2105 SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(location2[0], location2[1]);
2106 return (coord1.distance(coord2));
2107 }
2108
2109 private double getPathDistance(Tree tree, NodeRef node, String locationTrait, double[] sliceTrait) {
2110
2111 double pathDistance = 0;
2112 NodeRef parentNode = tree.getParent(node);
2113 Trait parentTrait = new Trait(tree.getNodeAttribute(parentNode, locationTrait));
2114 if (GREATCIRCLEDISTANCE){
2115 pathDistance += getGeographicalDistance(sliceTrait, parentTrait.getValue());
2116 } else {
2117 pathDistance += getNativeDistance(sliceTrait, parentTrait.getValue());
2118 }
2119
2120 while (parentNode != tree.getRoot()) {
2121 node = tree.getParent(node);
2122 parentNode = tree.getParent(parentNode);
2123 Trait nodeTrait = new Trait(tree.getNodeAttribute(node, locationTrait));
2124 parentTrait = new Trait(tree.getNodeAttribute(parentNode, locationTrait));
2125 if (GREATCIRCLEDISTANCE){
2126 pathDistance += getGeographicalDistance(nodeTrait.getValue(), parentTrait.getValue());
2127 } else {
2128 pathDistance += getNativeDistance(nodeTrait.getValue(), parentTrait.getValue());
2129 }
2130 }
2131 return pathDistance;
2132 }
2133
2134 private double getDistanceFromRoot(Tree tree, String locationTrait, double[] sliceTrait) {
2135 NodeRef rootNode = tree.getRoot();
2136 Trait rootTrait = new Trait(tree.getNodeAttribute(rootNode, locationTrait));
2137 if (GREATCIRCLEDISTANCE){
2138 return getGeographicalDistance(sliceTrait, rootTrait.getValue());
2139 } else {
2140 return getNativeDistance(sliceTrait, rootTrait.getValue());
2141 }
2142
2143 }
2144
2145 private int traitCount;
2146 private int sliceCount;
2147 private String[] traits;
2148 private double[] sliceHeights;
2149 private boolean sliceProgressReport;
2150 private boolean checkSliceContours;
2151 private boolean doSlices;
2152 private int treesRead = 0;
2153 private int treesAnalyzed = 0;
2154 private double mostRecentSamplingDate;
2155 private ContourMode contourMode;
2156 private SliceMode sliceMode;
2157 private boolean ancient = false;
2158 private boolean useStyles = true;
2159 private int gridSize;
2160 private double latMin;
2161 private double latMax;
2162 private double longMin;
2163 private double longMax;
2164 private Set descendentTaxaSet;
2165 private String rateAttributeString;
2166
2167
2168 // employed to get dispersal rates across the whole tree
2169 // private static boolean containsLocation = false;
2170 // private static ArrayList dispersalrates = new ArrayList();
2171
2172 // private void run(List<Tree> trees, String[] traits, double[] slices, boolean impute, boolean trueNoise) {
2173 //
2174 // for (Tree treeTime : trees) {
2175 // analyzeTree(treeTime, traits, slices, impute, trueNoise);
2176 // }
2177 // }
2178
2179 private ArrayList sliceTreeDistanceArrays = new ArrayList();
2180 private ArrayList sliceTreeTimeArrays = new ArrayList();
2181 private ArrayList sliceTreeMaxPathDistanceArrays = new ArrayList();
2182 private ArrayList sliceTreeMaxDistanceFromRootArrays = new ArrayList();
2183 private ArrayList sliceTreeTimeFromRootArrays = new ArrayList();
2184 private ArrayList sliceTreeDiffusionCoefficientArrays = new ArrayList();
2185 private ArrayList sliceTreeDiffusionCoefficientVarianceArrays = new ArrayList();
2186 private boolean sdr;
2187 private boolean snr;
2188 private ArrayList treeLengths = new ArrayList();
2189
2190 private boolean outputRateWarning = true;
2191
2192
2193 private Trait imputeValue(Trait nodeTrait, Trait parentTrait, double time, double nodeHeight, double parentHeight, double[][] precision, double rate, boolean trueNoise) {
2194 if (!nodeTrait.isNumber()) {
2195 System.err.println("Can only impute numbers!");
2196 System.exit(-1);
2197 }
2198
2199 int dim = nodeTrait.getDim();
2200 double[] nodeValue = nodeTrait.getValue();
2201 double[] parentValue = parentTrait.getValue();
2202
2203 final double scaledTimeChild = (time - nodeHeight) * rate;
2204 final double scaledTimeParent = (parentHeight - time) * rate;
2205 final double scaledWeightTotal = 1.0 / scaledTimeChild + 1.0 / scaledTimeParent;
2206
2207 if (scaledTimeChild == 0)
2208 return nodeTrait;
2209
2210 if (scaledTimeParent == 0)
2211 return parentTrait;
2212
2213 // Find mean value, weighted average
2214 double[] mean = new double[dim];
2215 double[][] scaledPrecision = new double[dim][dim];
2216
2217 for (int i = 0; i < dim; i++) {
2218 mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal;
2219 if (trueNoise) {
2220 for (int j = i; j < dim; j++)
2221 scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal;
2222 }
2223 }
2224
2225 // System.out.print(time+"\t"+nodeHeight+"\t"+parentHeight+"\t"+scaledTimeChild+"\t"+scaledTimeParent+"\t"+scaledWeightTotal+"\t"+mean[0]+"\t"+mean[1]+"\t"+scaledPrecision[0][0]+"\t"+scaledPrecision[0][1]+"\t"+scaledPrecision[1][0]+"\t"+scaledPrecision[1][1]);
2226
2227 if (trueNoise) {
2228 mean = MultivariateNormalDistribution.nextMultivariateNormalPrecision(mean, scaledPrecision);
2229 }
2230 // System.out.println("\t"+mean[0]+"\t"+mean[1]+"\r");
2231
2232 Object[] result = new Object[dim];
2233 for (int i = 0; i < dim; i++)
2234 result[i] = mean[i];
2235 return new Trait(result);
2236 }
2237
2238 // for debugging purposes
2239 // private Trait imputeValue(Trait nodeTrait, Trait parentTrait, double time, double nodeHeight, double parentHeight, double[][] precision, double rate, boolean trueNoise) {
2240 // Object[] result = new Object[2];
2241 // double[] nodeValue = nodeTrait.getValue();
2242 // double[] parentValue = parentTrait.getValue();
2243 // result[0] = (nodeValue[0] + parentValue[0])/2;
2244 // result[1] = (nodeValue[1] + parentValue[1])/2;
2245 // return new Trait(result);
2246 // }
2247
2248 // Messages to stderr, output to stdout
2249 private static PrintStream progressStream = System.err;
2250 private PrintStream resultsStream;
2251
2252 private final static Version version = new BeastVersion();
2253
2254 private static final String commandName = "timeslicer";
2255
2256
2257 public static void printUsage(Arguments arguments) {
2258
2259 arguments.printUsage(commandName, "<input-file-name> [<output-file-name>]");
2260 progressStream.println();
2261 progressStream.println(" Example: " + commandName + " test.trees out.kml");
2262 progressStream.println();
2263 }
2264
2265 public static void centreLine(String line, int pageWidth) {
2266 int n = pageWidth - line.length();
2267 int n1 = n / 2;
2268 for (int i = 0; i < n1; i++) {
2269 progressStream.print(" ");
2270 }
2271 progressStream.println(line);
2272 }
2273
2274 public static void printTitle() {
2275 progressStream.println();
2276 centreLine("TimeSlicer " + version.getVersionString() + ", " + version.getDateString(), 60);
2277 centreLine("MCMC Output analysis", 60);
2278 centreLine("by", 60);
2279 centreLine("Marc A. Suchard, Philippe Lemey,", 60);
2280 centreLine("Alexei J. Drummond and Andrew Rambaut", 60);
2281 progressStream.println();
2282 centreLine("Department of Biomathematics", 60);
2283 centreLine("University of California, Los Angeles", 60);
2284 centreLine("[email protected]", 60);
2285 progressStream.println();
2286 centreLine("Rega Institute for Medical Research", 60);
2287 centreLine("Katholieke Universiteit Leuven", 60);
2288 centreLine("[email protected]", 60);
2289 progressStream.println();
2290 centreLine("Department of Computer Science", 60);
2291 centreLine("University of Auckland", 60);
2292 centreLine("[email protected]", 60);
2293 progressStream.println();
2294 centreLine("Institute of Evolutionary Biology", 60);
2295 centreLine("University of Edinburgh", 60);
2296 centreLine("[email protected]", 60);
2297 progressStream.println();
2298 progressStream.println();
2299 }
2300
2301 public static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException {
2302
2303 List<Double> returnList = new ArrayList<Double>();
2304 StringTokenizer st = new StringTokenizer(inString, ",");
2305 while (st.hasMoreTokens()) {
2306 try {
2307 returnList.add(Double.parseDouble(st.nextToken()));
2308 } catch (NumberFormatException e) {
2309 throw new Arguments.ArgumentException();
2310 }
2311
2312 }
2313
2314 if (returnList.size() > 0) {
2315 double[] doubleArray = new double[returnList.size()];
2316 for (int i = 0; i < doubleArray.length; i++)
2317 doubleArray[i] = returnList.get(i);
2318
2319 return doubleArray;
2320 }
2321 return null;
2322 }
2323
2324 private static String[] parseVariableLengthStringArray(String inString) {
2325
2326 List<String> returnList = new ArrayList<String>();
2327 StringTokenizer st = new StringTokenizer(inString, ",");
2328 while (st.hasMoreTokens()) {
2329 returnList.add(st.nextToken());
2330 }
2331
2332 if (returnList.size() > 0) {
2333 String[] stringArray = new String[returnList.size()];
2334 stringArray = returnList.toArray(stringArray);
2335 return stringArray;
2336 }
2337 return null;
2338 }
2339
2340 private static Set parseVariableLengthStringSet(String inString) {
2341
2342 Set targetSet = new HashSet();
2343
2344 StringTokenizer st = new StringTokenizer(inString, ",");
2345 // System.out.println(inString);
2346 while (st.hasMoreTokens()) {
2347 targetSet.add(st.nextToken());
2348 }
2349
2350 return targetSet;
2351 }
2352
2353 private static double[] parseFileWithArray(String file) {
2354 List<Double> returnList = new ArrayList<Double>();
2355 try {
2356 BufferedReader readerTimes = new BufferedReader(new FileReader(file));
2357 String line = readerTimes.readLine();
2358 while (line != null && !line.equals("")) {
2359 returnList.add(Double.valueOf(line));
2360 line = readerTimes.readLine();
2361 }
2362 } catch (IOException e) {
2363 System.err.println("Error reading " + file);
2364 System.exit(1);
2365 }
2366
2367 if (returnList.size() > 0) {
2368 double[] doubleArray = new double[returnList.size()];
2369 for (int i = 0; i < doubleArray.length; i++)
2370 doubleArray[i] = returnList.get(i);
2371
2372 //System.out.println(doubleArray.length);
2373 return doubleArray;
2374 }
2375 return null;
2376 }
2377
2378 public static String getKMLColor(double value, double[] minMaxMedian, String startColor, String endColor) {
2379
2380 startColor = startColor.toLowerCase();
2381 String startBlue = startColor.substring(0, 2);
2382 String startGreen = startColor.substring(2, 4);
2383 String startRed = startColor.substring(4, 6);
2384
2385 endColor = endColor.toLowerCase();
2386 String endBlue = endColor.substring(0, 2);
2387 String endGreen = endColor.substring(2, 4);
2388 String endRed = endColor.substring(4, 6);
2389
2390 double proportion = (value - minMaxMedian[0]) / (minMaxMedian[1] - minMaxMedian[0]);
2391
2392 // generate an array with hexadecimal code for each RGB entry number
2393 String[] colorTable = new String[256];
2394
2395 int colorTableCounter = 0;
2396
2397 for (int a = 0; a < 10; a++) {
2398
2399 for (int b = 0; b < 10; b++) {
2400
2401 colorTable[colorTableCounter] = a + "" + b;
2402 colorTableCounter++;
2403 }
2404
2405 for (int c = (int) ('a'); c < 6 + (int) ('a'); c++) {
2406 colorTable[colorTableCounter] = a + "" + (char) c;
2407 colorTableCounter++;
2408 }
2409
2410 }
2411 for (int d = (int) ('a'); d < 6 + (int) ('a'); d++) {
2412
2413 for (int e = 0; e < 10; e++) {
2414
2415 colorTable[colorTableCounter] = (char) d + "" + e;
2416 colorTableCounter++;
2417 }
2418
2419 for (int f = (int) ('a'); f < 6 + (int) ('a'); f++) {
2420 colorTable[colorTableCounter] = (char) d + "" + (char) f;
2421 colorTableCounter++;
2422 }
2423
2424 }
2425
2426
2427 int startBlueInt = 0;
2428 int startGreenInt = 0;
2429 int startRedInt = 0;
2430
2431 int endBlueInt = 0;
2432 int endGreenInt = 0;
2433 int endRedInt = 0;
2434
2435 for (int i = 0; i < colorTable.length; i++) {
2436
2437 if (colorTable[i].equals(startBlue)) {
2438 startBlueInt = i;
2439 }
2440 if (colorTable[i].equals(startGreen)) {
2441 startGreenInt = i;
2442 }
2443 if (colorTable[i].equals(startRed)) {
2444 startRedInt = i;
2445 }
2446 if (colorTable[i].equals(endBlue)) {
2447 endBlueInt = i;
2448 }
2449 if (colorTable[i].equals(endGreen)) {
2450 endGreenInt = i;
2451 }
2452 if (colorTable[i].equals(endRed)) {
2453 endRedInt = i;
2454 }
2455
2456 }
2457
2458 int blueInt = startBlueInt + (int) Math.round((endBlueInt - startBlueInt) * proportion);
2459 int greenInt = startGreenInt + (int) Math.round((endGreenInt - startGreenInt) * proportion);
2460 int redInt = startRedInt + (int) Math.round((endRedInt - startRedInt) * proportion);
2461
2462 String blue = null;
2463 String green = null;
2464 String red = null;
2465
2466 for (int j = 0; j < colorTable.length; j++) {
2467
2468 if (j == blueInt) {
2469 blue = colorTable[j];
2470 }
2471 if (j == greenInt) {
2472 green = colorTable[j];
2473 }
2474 if (j == redInt) {
2475 red = colorTable[j];
2476 }
2477
2478 }
2479
2480 return blue + green + red;
2481 }
2482
2483 private static double[] getHPDInterval(double proportion, double[] array, int[] indices) {
2484
2485 double returnArray[] = new double[2];
2486 double minRange = Double.MAX_VALUE;
2487 int hpdIndex = 0;
2488
2489 int diff = (int) Math.round(proportion * (double) array.length);
2490 for (int i = 0; i <= (array.length - diff); i++) {
2491 double minValue = array[indices[i]];
2492 double maxValue = array[indices[i + diff - 1]];
2493 double range = Math.abs(maxValue - minValue);
2494 if (range < minRange) {
2495 minRange = range;
2496 hpdIndex = i;
2497 }
2498 }
2499 returnArray[0] = array[indices[hpdIndex]];
2500 returnArray[1] = array[indices[hpdIndex + diff - 1]];
2501 return returnArray;
2502 }
2503
2504 private static void print2DArray(double[][] array, String name) {
2505 try {
2506 PrintWriter outFile = new PrintWriter(new FileWriter(name), true);
2507
2508 for (double[] anArray : array) {
2509 for (int j = 0; j < array[0].length; j++) {
2510 outFile.print(anArray[j] + "\t");
2511 }
2512 outFile.println("");
2513 }
2514 outFile.close();
2515
2516 } catch (IOException io) {
2517 System.err.print("Error writing to file: " + name);
2518 }
2519 }
2520
2521 private static void print2DTransposedArray(double[][] array, String name) {
2522 try {
2523 PrintWriter outFile = new PrintWriter(new FileWriter(name), true);
2524
2525 for (int i = 0; i < array[0].length; i++) {
2526 for (double[] anArray : array) {
2527 outFile.print(anArray[i] + "\t");
2528 }
2529 outFile.println("");
2530 }
2531 outFile.close();
2532
2533 } catch (IOException io) {
2534 System.err.print("Error writing to file: " + name);
2535 }
2536 }
2537
2538 private static double[] meanColNoNaN(double[][] x) {
2539 double[] returnArray = new double[x[0].length];
2540
2541 for (int i = 0; i < x[0].length; i++) {
2542
2543 double m = 0.0;
2544 int lenNoZero = 0;
2545
2546
2547 for (int j = 0; j < x.length; j++) {
2548
2549 if (!(((Double) x[j][i]).isNaN())) {
2550 m += x[j][i];
2551 lenNoZero += 1;
2552 }
2553 }
2554 returnArray[i] = m / (double) lenNoZero;
2555
2556 }
2557 return returnArray;
2558 }
2559
2560 private static double[][] getArrayHPDintervals(double[][] array) {
2561
2562 double[][] returnArray = new double[array[0].length][2];
2563
2564 for (int col = 0; col < array[0].length; col++) {
2565
2566 int counter = 0;
2567
2568 for (int row = 0; row < array.length; row++) {
2569
2570 if (!(((Double) array[row][col]).isNaN())) {
2571 counter += 1;
2572 }
2573 }
2574
2575 if (counter > 0) {
2576 double[] columnNoNaNArray = new double[counter];
2577
2578 int index = 0;
2579 for (int row = 0; row < array.length; row++) {
2580
2581 if (!(((Double) array[row][col]).isNaN())) {
2582 columnNoNaNArray[index] = array[row][col];
2583 index += 1;
2584 }
2585 }
2586 int[] indices = new int[counter];
2587 HeapSort.sort(columnNoNaNArray, indices);
2588 double hpdBinInterval[] = getHPDInterval(0.95, columnNoNaNArray, indices);
2589
2590 returnArray[col][0] = hpdBinInterval[0];
2591 returnArray[col][1] = hpdBinInterval[1];
2592 } else {
2593 returnArray[col][0] = Double.NaN;
2594 returnArray[col][1] = Double.NaN;
2595 }
2596
2597 }
2598
2599 return returnArray;
2600 }
2601
2602 private static Set getTargetSet(String x) {
2603 Set targetSet = null;
2604 targetSet = new HashSet();
2605 try {
2606 BufferedReader reader = new BufferedReader(new FileReader(x));
2607 try {
2608 String line = reader.readLine().trim();
2609 while (line != null && !line.equals("")) {
2610 targetSet.add(line);
2611 line = reader.readLine();
2612 if (line != null) line = line.trim();
2613 }
2614 }
2615 catch (IOException io) {
2616 System.err.println("Error reading " + x);
2617 }
2618 }
2619 catch (FileNotFoundException a) {
2620 System.err.println("Error finding " + x);
2621 }
2622 return targetSet;
2623 }
2624
2625 public static void main(String[] args) throws IOException {
2626
2627 String inputFileName = null;
2628 String outputFileName = null;
2629 String[] traitNames = null;
2630 double[] sliceHeights = null;
2631 OutputFormat outputFormat = OutputFormat.KML;
2632 boolean impute = false;
2633 boolean trueNoise = true;
2634 boolean summaryOnly = true;
2635 ContourMode contourMode = ContourMode.SNYDER;
2636 Normalization normalize = Normalization.LENGTH;
2637 int burnin = -1;
2638 int skipEvery = 1;
2639 double mrsd = 0;
2640 boolean summarizeRoot = false;
2641 boolean summarizeTips = false;
2642 boolean contours = true;
2643 boolean points = false;
2644 double[] hpdValues = { 0.80 };
2645 String outputFileSDR = null;
2646 String outputFileSNR = null;
2647 boolean getSDR = false;
2648 boolean getSNR = false;
2649 String progress = null;
2650 boolean branchNormalization = false;
2651 BranchSet set = BranchSet.ALL;
2652 Set taxaSet = null;
2653 SliceMode sliceMode = SliceMode.BRANCHES;
2654 int grid = 200;
2655 double latMax = Double.MAX_VALUE;
2656 double latMin = -Double.MAX_VALUE;
2657 double longMax = Double.MAX_VALUE;
2658 double longMin = -Double.MAX_VALUE;
2659 String rateString = "location.rate";
2660 Set descendents = null;
2661
2662 // if (args.length == 0) {
2663 // // TODO Make flash GUI
2664 // }
2665
2666 printTitle();
2667
2668 Arguments arguments = new Arguments(
2669 new Arguments.Option[]{
2670 new Arguments.IntegerOption(BURNIN, "the number of states to be considered as 'burn-in' [default = 0]"),
2671 new Arguments.IntegerOption(SKIP, "skip every i'th tree [default = 0]"),
2672 new Arguments.StringOption(TRAIT, "trait_name", "specifies an attribute-list to use to create a density map [default = location.rate]"),
2673 new Arguments.StringOption(SLICE_TIMES, "slice_times", "specifies a slice time-list [default=none]"),
2674 new Arguments.StringOption(SLICE_HEIGHTS, "slice_heights", "specifies a slice height-list [default=none]"),
2675 new Arguments.StringOption(SLICE_FILE_HEIGHTS, "heights_file", "specifies a file with a slice heights-list, is overwritten by command-line specification of slice heights [default=none]"),
2676 new Arguments.StringOption(SLICE_FILE_TIMES, "Times_file", "specifies a file with a slice Times-list, is overwritten by command-line specification of slice times [default=none]"),
2677 new Arguments.StringOption(RATE_ATTRIBUTE, "rate_attribute", "specifies the trait rate attribute string [default=location.rate]; use 'none' when no rate needs to be used (homogeneous Brownian model)"),
2678 new Arguments.IntegerOption(SLICE_COUNT, "the number of time slices to use [default=0]"),
2679 new Arguments.StringOption(SLICE_MODE, "Slice_mode", "specifies how to perform the slicing [default=branches]"),
2680 new Arguments.StringOption(ROOT, falseTrue, false, "include a summary for the root [default=off]"),
2681 new Arguments.StringOption(TIPS, falseTrue, false, "include a summary for the tips [default=off]"),
2682 new Arguments.StringOption(CONTOURS, falseTrue, true, "include contours in summary [default=true]"),
2683 new Arguments.StringOption(POINTS, falseTrue, false, "include all points for the summary [default=off]"),
2684 new Arguments.RealOption(START_TIME, "the time of the earliest slice [default=0]"),
2685 new Arguments.RealOption(MRSD, "specifies the most recent sampling data in fractional years to rescale time [default=0]"),
2686 new Arguments.Option(HELP, "option to print this message"),
2687 new Arguments.StringOption(NOISE, falseTrue, false,
2688 "add true noise [default = true])"),
2689 new Arguments.StringOption(IMPUTE, falseTrue, false,
2690 "impute trait at time-slice [default = false]"),
2691 new Arguments.StringOption(SUMMARY, falseTrue, false,
2692 "compute summary statistics [default = true]"),
2693 new Arguments.StringOption(FORMAT, enumNamesToStringArray(OutputFormat.values()), false,
2694 "summary output format [default = KML]"),
2695 new Arguments.StringOption(HPD, "hpd", "mass (1 - 99%) to include in HPD regions (or list) [default = 80]"),
2696 new Arguments.StringOption(CONTOUR_MODE, enumNamesToStringArray(ContourMode.values()), false,
2697 "contouring model [default = snyder]"),
2698 new Arguments.StringOption(NORMALIZATION, enumNamesToStringArray(Normalization.values()), false,
2699 "tree normalization [default = length"),
2700 new Arguments.StringOption(SDR, "sliceDispersalRate", "specifies output file name for dispersal rates for each slice (from previous sliceTime[or root of the trees] up to current sliceTime"),
2701 new Arguments.StringOption(SNR, "sliceNonynonymousRate", "specifies output file name for Nonynsonymous rates for each slice (from previous sliceTime[or root of the trees] up to current sliceTime"),
2702 new Arguments.StringOption(PROGRESS, "progress report", "reports slice progress and checks the bivariate contour HPD regions by calculating what fraction of points the polygons for a given slice contain [default = false]"),
2703 new Arguments.StringOption(BRANCH_NORMALIZE, falseTrue, false,
2704 "devide a branch trait by branch length (can be useful for 'rewards' [default = false]"),
2705 new Arguments.StringOption(BRANCHSET, TimeSlicer.enumNamesToStringArray(BranchSet.values()), false,
2706 "branch set [default = all]"),
2707 new Arguments.StringOption(BACKBONETAXA, "Backbone taxa file", "specifies a file with taxa that define the backbone"),
2708 new Arguments.RealOption(LATMAX, "specifies the maximum latitude for a child node for a branch to be included in the summary [default=MAX_VALUE]"),
2709 new Arguments.RealOption(LATMIN, "specifies the minimum latitude for a child node for a branch to be included in the summary [default=MIN_VALUE]"),
2710 new Arguments.RealOption(LONGMAX, "specifies the maximum longitude for a child node for a branch to be included in the summary [default=MAX_VALUE]"),
2711 new Arguments.RealOption(LONGMIN, "specifies the minimum longitude for a child node for a branch to be included in the summary [default=MIN_VALUE]"),
2712 new Arguments.IntegerOption(GRIDSIZE, "the grid size for contouring [default=200]"),
2713 new Arguments.StringOption(DESCENDENTS, "descendent taxa", "specifies a branch based on the descendent taxa [default=all branches]")
2714
2715 });
2716
2717 try {
2718 arguments.parseArguments(args);
2719 } catch (Arguments.ArgumentException ae) {
2720 progressStream.println(ae);
2721 printUsage(arguments);
2722 System.exit(1);
2723 }
2724
2725 if (arguments.hasOption(HELP)) {
2726 printUsage(arguments);
2727 System.exit(0);
2728 }
2729
2730 try { // Make sense of arguments
2731
2732 String sliceHeightsFileString = arguments.getStringOption(SLICE_FILE_HEIGHTS);
2733 if (sliceHeightsFileString != null) {
2734 sliceHeights = parseFileWithArray(sliceHeightsFileString);
2735 }
2736
2737 if (arguments.hasOption(MRSD)) {
2738 mrsd = arguments.getRealOption(MRSD);
2739 }
2740
2741 if (arguments.hasOption(LATMAX)) {
2742 latMax = arguments.getRealOption(LATMAX);
2743 }
2744
2745 if (arguments.hasOption(LATMIN)) {
2746 latMin = arguments.getRealOption(LATMIN);
2747 }
2748
2749 if (arguments.hasOption(LONGMAX)) {
2750 longMax = arguments.getRealOption(LONGMAX);
2751 }
2752
2753 if (arguments.hasOption(LONGMIN)) {
2754 longMin = arguments.getRealOption(LONGMIN);
2755 }
2756
2757 String taxaString = arguments.getStringOption(DESCENDENTS);
2758 if (taxaString != null) {
2759 descendents = parseVariableLengthStringSet(taxaString);
2760 }
2761
2762 String sliceTimesFileString = arguments.getStringOption(SLICE_FILE_TIMES);
2763 if (sliceTimesFileString != null) {
2764 //System.out.println(sliceTimesFileString);
2765 double[] sliceTimes = parseFileWithArray(sliceTimesFileString);
2766 sliceHeights = new double[sliceTimes.length];
2767 for (int i = 0; i < sliceTimes.length; i++) {
2768 if (mrsd == 0) {
2769 sliceHeights[i] = sliceTimes[i];
2770 } else {
2771 //System.out.println((mrsd - sliceTimes[i]));
2772 sliceHeights[i] = mrsd - sliceTimes[i];
2773
2774 }
2775 }
2776 }
2777
2778 String sliceModeString = arguments.getStringOption(SLICE_MODE);
2779 if (sliceModeString != null) {
2780 try {
2781 sliceMode = SliceMode.valueOf(sliceModeString.toUpperCase());
2782 } catch (IllegalArgumentException iae) {
2783 System.err.println("Unrecognized slice mode: " + sliceModeString);
2784 }
2785 }
2786
2787 String traitRateString = arguments.getStringOption(RATE_ATTRIBUTE);
2788 if (traitRateString != null) {
2789 rateString = traitRateString;
2790 }
2791
2792 if (arguments.hasOption(BURNIN)) {
2793 burnin = arguments.getIntegerOption(BURNIN);
2794 System.err.println("Ignoring a burnin of " + burnin + " trees.");
2795 }
2796
2797 if (arguments.hasOption(SKIP)) {
2798 skipEvery = arguments.getIntegerOption(SKIP);
2799 System.err.println("Skipping every " + skipEvery + " trees.");
2800 }
2801 if (skipEvery < 1) {
2802 skipEvery = 1;
2803 }
2804
2805 String hpdString = arguments.getStringOption(HPD);
2806 if (hpdString != null) {
2807 hpdValues = parseVariableLengthDoubleArray(hpdString);
2808 if (hpdValues.length > 0) {
2809 for (int i = 0; i < hpdValues.length; i++) {
2810 if (hpdValues[i] < 1 || hpdValues[i] > 99) {
2811 progressStream.println("HPD Region mass falls outside of 1 - 99% range.");
2812 System.exit(-1);
2813 }
2814 hpdValues[i] = hpdValues[i] / 100.0;
2815 }
2816
2817 } else {
2818 hpdValues = new double[] { 80.0 };
2819 }
2820 }
2821
2822 String traitString = arguments.getStringOption(TRAIT);
2823 if (traitString != null) {
2824 traitNames = parseVariableLengthStringArray(traitString);
2825 //employed to get dispersal rates across the whole tree
2826 // for (int y = 0; y < traitNames.length; y++) {
2827 // if (traitNames[y].equals(LOCATIONTRAIT)){
2828 // containsLocation = true;
2829 // }
2830 // }
2831 }
2832
2833 if (traitNames == null) {
2834 traitNames = new String[1];
2835 traitNames[0] = "location.rate";
2836 }
2837
2838 String sliceTimeString = arguments.getStringOption(SLICE_TIMES);
2839 if (sliceTimeString != null) {
2840 double[] sliceTimes = parseVariableLengthDoubleArray(sliceTimeString);
2841 sliceHeights = new double[sliceTimes.length];
2842 for (int i = 0; i < sliceTimes.length; i++) {
2843 if (mrsd == 0) {
2844 sliceHeights[i] = sliceTimes[i];
2845 } else {
2846 sliceHeights[i] = mrsd - sliceTimes[i];
2847 }
2848 }
2849 }
2850
2851 String sliceHeightString = arguments.getStringOption(SLICE_HEIGHTS);
2852 if (sliceHeightString != null) {
2853 if (sliceTimeString != null) {
2854 progressStream.println("Either sliceTimes, sliceHeights, timesFile or sliceCount" +
2855 "nt.");
2856 System.exit(-1);
2857 }
2858 sliceHeights = parseVariableLengthDoubleArray(sliceHeightString);
2859 }
2860
2861 if (arguments.hasOption(SLICE_COUNT)) {
2862 int sliceCount = arguments.getIntegerOption(SLICE_COUNT);
2863 double startTime = arguments.getRealOption(START_TIME);
2864 double delta;
2865 if (mrsd != 0) {
2866 delta = (mrsd - startTime) / (sliceCount - 1);
2867 } else {
2868 delta = startTime / (sliceCount - 1);
2869 }
2870 sliceHeights = new double[sliceCount];
2871 // double height = mrsd - startTime;
2872 // for (int i = 0; i < sliceCount; i++) {
2873 // sliceHeights[i] = height;
2874 // height -= delta;
2875 // }
2876 double height = 0;
2877 for (int i = 0; i < sliceCount; i++) {
2878 sliceHeights[i] = height;
2879 height += delta;
2880 }
2881 }
2882
2883 String optionString = arguments.getStringOption(ROOT);
2884 if (optionString != null && optionString.compareToIgnoreCase("true") == 0) {
2885 summarizeRoot = true;
2886 }
2887
2888 optionString = arguments.getStringOption(TIPS);
2889 if (optionString != null && optionString.compareToIgnoreCase("true") == 0) {
2890 summarizeTips = true;
2891 }
2892
2893 optionString = arguments.getStringOption(CONTOURS);
2894 if (optionString != null && optionString.compareToIgnoreCase("false") == 0) {
2895 contours = false;
2896 }
2897
2898 optionString = arguments.getStringOption(POINTS);
2899 if (optionString != null && optionString.compareToIgnoreCase("true") == 0) {
2900 points = true;
2901 }
2902
2903 //sorting sliceHeights
2904 if (sliceHeights != null) {
2905 Arrays.sort(sliceHeights);
2906 }
2907
2908 String imputeString = arguments.getStringOption(IMPUTE);
2909 if (imputeString != null && imputeString.compareToIgnoreCase("true") == 0)
2910 impute = true;
2911
2912 String branchNormString = arguments.getStringOption(BRANCH_NORMALIZE);
2913 if (branchNormString != null && branchNormString.compareToIgnoreCase("true") == 0)
2914 branchNormalization = true;
2915
2916 String noiseString = arguments.getStringOption(NOISE);
2917 if (noiseString != null && noiseString.compareToIgnoreCase("false") == 0)
2918 trueNoise = false;
2919
2920 String summaryString = arguments.getStringOption(SUMMARY);
2921 if (summaryString != null && summaryString.compareToIgnoreCase("true") == 0)
2922 summaryOnly = true;
2923
2924 String modeString = arguments.getStringOption(CONTOUR_MODE);
2925 if (modeString != null) {
2926 contourMode = ContourMode.valueOf(modeString.toUpperCase());
2927 if (contourMode == ContourMode.R && !ContourWithR.processWithR)
2928 contourMode = ContourMode.SNYDER;
2929 }
2930
2931 String normalizeString = arguments.getStringOption(NORMALIZATION);
2932 if (normalizeString != null) {
2933 normalize = Normalization.valueOf(normalizeString.toUpperCase());
2934 }
2935
2936 String summaryFormat = arguments.getStringOption(FORMAT);
2937 if (summaryFormat != null) {
2938 outputFormat = OutputFormat.valueOf(summaryFormat.toUpperCase());
2939 }
2940
2941 String sdrString = arguments.getStringOption(SDR);
2942 if (sdrString != null) {
2943 outputFileSDR = sdrString;
2944 getSDR = true;
2945 }
2946
2947 String snrString = arguments.getStringOption(SNR);
2948 if (snrString != null) {
2949 outputFileSNR = snrString;
2950 getSNR = true;
2951 }
2952
2953 String progressString = arguments.getStringOption(PROGRESS);
2954 if (progressString != null) {
2955 progress = progressString;
2956 }
2957
2958 String branch = arguments.getStringOption(BRANCHSET);
2959 if (branch != null) {
2960 set = BranchSet.valueOf(branch.toUpperCase());
2961 System.out.println("Using the branch set: " + set.name());
2962 }
2963 if (set == set.BACKBONE) {
2964 if (arguments.hasOption(BACKBONETAXA)) {
2965 taxaSet = getTargetSet(arguments.getStringOption(BACKBONETAXA));
2966 } else {
2967 System.err.println("you want to summarize the backbone, but have no taxa to define it??");
2968 }
2969 }
2970 if (set == set.CLADE) {
2971 if (arguments.hasOption(CLADETAXA)) {
2972 taxaSet = getTargetSet(arguments.getStringOption(BACKBONETAXA));
2973 } else {
2974 System.err.println("you want to get summaries for a clade, but have no taxa to define it??");
2975 }
2976
2977 }
2978
2979 if (arguments.hasOption(GRIDSIZE)) {
2980 grid = arguments.getIntegerOption(GRIDSIZE);
2981 }
2982
2983
2984
2985 } catch (Arguments.ArgumentException e) {
2986 progressStream.println(e);
2987 printUsage(arguments);
2988 System.exit(-1);
2989 }
2990
2991
2992 final String[] args2 = arguments.getLeftoverArguments();
2993
2994 switch (args2.length) {
2995 case 0:
2996 printUsage(arguments);
2997 System.exit(1);
2998 case 2:
2999 outputFileName = args2[1];
3000 // fall to
3001 case 1:
3002 inputFileName = args2[0];
3003 break;
3004 default: {
3005 System.err.println("Unknown option: " + args2[2]);
3006 System.err.println();
3007 printUsage(arguments);
3008 System.exit(1);
3009 }
3010 }
3011
3012 TimeSlicer timeSlicer = new TimeSlicer(inputFileName, burnin, skipEvery, traitNames, sliceHeights, impute,
3013 trueNoise, mrsd, contourMode, sliceMode,summarizeRoot, summarizeTips, normalize, getSDR, getSNR, progress,
3014 branchNormalization, set, taxaSet, grid, latMin, latMax, longMin, longMax, descendents, rateString);
3015 timeSlicer.output(outputFileName, summaryOnly, summarizeRoot, summarizeTips, contours, points, outputFormat, hpdValues, outputFileSDR, outputFileSNR);
3016
3017 System.exit(0);
3018 }
3019 }