Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * RateIndicatorBF.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.app.phylogeography.tools;
27
28 import dr.app.tools.TimeSlicer;
29 import dr.app.util.Arguments;
30 import dr.util.HeapSort;
31 import org.jdom.Element;
32 import org.jdom.output.Format;
33 import org.jdom.output.XMLOutputter;
34
35 import java.io.*;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.List;
39 import java.util.StringTokenizer;
40
41 /**
42 * @author Philippe Lemey
43 * @author Andrew Rambaut
44 * @author Marc A. Suchard
45 * @author Matthew Hall
46 */
47
48 public class RateIndicatorBF {
49
50 public static final String LOCATIONSFILE = "locationsfile";
51 public static final String HELP = "help";
52 public static final String BURNIN = "burnin";
53 public static final String KML = "kml";
54 public static final String PMEAN = "pmean";
55 public static final String POFFSET = "poffset";
56 public static final String ISTRING = "istring";
57 public static final String RSTRING = "rstring";
58 public static final String PSTRING = "pstring";
59 public static final String FSTRING = "fstring";
60 public static final String CSTRING = "cstring";
61 public static final String USTRING = "ustring";
62 public static final String LOWCOLOR = "lowcolor";
63 public static final String UPCOLOR = "upcolor";
64 public static final String CALCULATERATES = "calculaterates";
65 public static final String WIDTH = "width";
66 public static final String KMLFILE = "kmlfile";
67 public static final String BFCUTOFF = "bfcutoff";
68 public static final String ICUTOFF = "icutoff";
69 public static final String LOCATIONSTATES = "locationstates";
70 public static final String BWC = "bwc";
71 public static final String BWM = "bwm";
72 public static final String ALTITUDE = "altitude";
73
74 private double[] expectedRateIndicators;
75 private boolean nonreversible = false;
76 protected String[][] locations; // contains locations and their coordinates
77 protected String[][] locationNames; // contains start and end locations for transitions
78 protected double[][] longitudes; // contains start and end longitudes for transitions
79 protected double[][] latitudes; // contains start and end latitudes for transitions
80 protected String[][] supportedLocations; // contains start and end locations for transitions
81 protected double[][] supportedLongitudes; // contains start and end longitudes for transitions
82 protected double[][] supportedLatitudes; // contains start and end latitudes for transitions
83 protected double[] supportedBFs;
84 protected double[] supportedRateIndicators;
85 protected double[] supportedActualRates;
86 private double[] meanQMatrix;
87 private boolean bayesFactor;
88 private String inputFileName;
89 private int burnin;
90 private double cutoff;
91 private double meanPoissonPrior;
92 private int offsetPoissonPrior;
93 private String rateIndicatorString;
94 private String actualRateString;
95 private String relativeRateString;
96 private String clockRateString;
97 private String frequencyString;
98 private String unitString;
99 private int generationCount;
100 protected int stateCount;
101 private int rateCount;
102 protected boolean calculateRates;
103 private int[][] columnNumberLookup;
104
105 public static final String[] falseTrue = new String[] {"false","true"};
106
107 protected static PrintStream progressStream = System.out;
108 private static final String commandName = "rateIndicatorBF";
109 public static void printUsage(Arguments arguments) {
110
111 arguments.printUsage(commandName, "<input-file-name> [<output-file-name>]");
112 progressStream.println();
113 progressStream.println(" Example: " + commandName + " indicator.log rates.out");
114 progressStream.println();
115 }
116
117 public RateIndicatorBF(String inputFileName, int burnin, String rateIndicatorString, int numberOfStates,
118 String[][] locations, boolean bayesFactor, double cutoff, double meanPoissonPrior,
119 int offsetPoissonPrior, String actualRateString, String relativeRateString,
120 String frequencyString, String clockRateString, String unitString,
121 boolean calculateRates) {
122
123 //count the number of states in the RateIndicatorLog file
124 generationCount = getGenerationCount(inputFileName);
125
126 //find the first rateIndicator in the RateIndicatorLog file
127 int firstRateIndicator = getFirstEntryOf(inputFileName, rateIndicatorString);
128 //progressStream.println("first rateIndicator is at column "+firstRateIndicator);
129
130 //count the rateIndicators in the RateIndicatorLog file
131 rateCount = getNumberOfEntries(inputFileName, firstRateIndicator, rateIndicatorString);
132
133 if (numberOfStates > 0) {
134 stateCount = numberOfStates;
135 progressStream.println("number of states provided = "+stateCount);
136 } else {
137 stateCount = locations.length;
138 progressStream.println("number of states in coordinates file = "+stateCount);
139 }
140
141 this.inputFileName = inputFileName;
142 this.burnin = burnin;
143 this.bayesFactor = bayesFactor;
144 this.cutoff = cutoff;
145 this.meanPoissonPrior = meanPoissonPrior;
146 this.offsetPoissonPrior = offsetPoissonPrior;
147 this.rateIndicatorString = rateIndicatorString;
148 this.actualRateString = actualRateString;
149 this.relativeRateString = relativeRateString;
150 this.clockRateString = clockRateString;
151 this.frequencyString = frequencyString;
152 this.unitString = unitString;
153 this.calculateRates = calculateRates;
154
155 if (rateCount != ((stateCount*(stateCount-1.0))/2.0)) {
156 if (rateCount == (stateCount*(stateCount-1.0))) {
157 progressStream.println("K*(K-1) rateIndicators, with K = "+ stateCount+". " +
158 "So, nonreversible matrix!");
159 nonreversible = true;
160 } else {
161 System.err.println("the number of rateIndicators ("+rateCount+") does not match " +
162 "(K*(K-1)/2) states ("+((stateCount*(stateCount-1.0))/2.0)+"; with K " +
163 "= "+stateCount+").");
164 }
165 }
166
167 //The following just makes life easier...
168
169 columnNumberLookup = new int[stateCount][stateCount];
170 int columnCount=0;
171 for(int row=0; row<stateCount; row++){
172 for(int column=0; column<stateCount; column++){
173 if(row==column){
174 columnNumberLookup[row][column]=-1;
175 } else if(row<column){
176 columnNumberLookup[row][column]=columnCount;
177 columnCount++;
178 }
179 }
180 }
181 for(int column=0; column<stateCount; column++){
182 for(int row=0; row<stateCount; row++){
183 if(row>column){
184 columnNumberLookup[row][column]=columnCount;
185 columnCount++;
186 }
187 }
188 }
189
190 // so now we know the dimension of the rateIndicator array
191 if ((generationCount - burnin)< 10) {
192 System.err.println("With burn-in = "+burnin+", there are only "+(generationCount - burnin)+" state(s) in " +
193 "indicator log file??");
194 }
195 double[][] rateIndicators = new double[((generationCount - 1)-burnin)][rateCount];
196 fill2DArray(inputFileName, rateIndicators, burnin, firstRateIndicator, rateCount);
197 expectedRateIndicators = meanCol(rateIndicators);
198
199 int ratesOfInterest = !nonreversible && calculateRates ? rateCount*2 : rateCount;
200
201 //compile locations
202 locationNames = new String [ratesOfInterest][2];
203 longitudes = new double [ratesOfInterest][2];
204 latitudes = new double [ratesOfInterest][2];
205
206 this.locations = locations;
207 compileLocations(locations,locationNames,latitudes,longitudes);
208
209 if(calculateRates){
210 double[][] QMatrices = getQMatrices();
211 meanQMatrix = meanCol(QMatrices);
212 }
213
214 supportedRateIndicators = getSupportedRateIndicators();
215 }
216
217 //Diagonal entries in the Q matrices are omitted for obvious reasons. Note that if the frequencies are not equal
218 //then the Q matrix is not symmetric even if the rates are.
219
220 private double[][] getQMatrices() {
221
222 int firstRateIndicator = getFirstEntryOf(inputFileName, rateIndicatorString);
223 double[][] rateIndicators = new double[((generationCount - 1) - burnin)][rateCount];
224 fill2DArray(inputFileName, rateIndicators, burnin, firstRateIndicator, rateCount);
225
226 boolean containsClockRate = hasEntryOf(inputFileName, clockRateString);
227 double[] clockRates = new double[(generationCount - 1) - burnin];
228 int clockColumn = getFirstEntryOf(inputFileName, clockRateString);
229
230 if (!containsClockRate) {
231 progressStream.println("WARNING: No overall clock rate entry found. Rates will be given assuming one " +
232 "transition (of any sort) per unit time; variation in clock rates will not be accounted for!");
233 Arrays.fill(clockRates, 1);
234 } else {
235 fill1DArray(inputFileName, clockRates, burnin, clockColumn);
236 }
237
238 //boolean to see it the rateLog contains productStatistics, if not, we make 'em ourselves
239 boolean containsActualRates = hasEntryOf(inputFileName, actualRateString);
240 double[][] actualRates = new double[((generationCount - 1) - burnin)][rateCount];
241 if (!containsActualRates) {
242 // if there are no actualRate entries, we will look for the relative rates instead
243 int firstRelativeRate = getFirstEntryOf(inputFileName, relativeRateString);
244 fill2DArray(inputFileName, actualRates, burnin, firstRelativeRate, rateCount);
245 for (int i = 0; i < actualRates.length; i++) {
246 for (int j = 0; j < actualRates[i].length; j++) {
247 actualRates[i][j] = actualRates[i][j] * rateIndicators[i][j];
248 }
249 }
250 } else {
251 int firstActualRate = getFirstEntryOf(inputFileName, actualRateString);
252 fill2DArray(inputFileName, actualRates, burnin, firstActualRate, rateCount);
253 }
254
255 //Double up the actual rate matrix for a nonreversible model - separate entries are needed for both directions
256
257 if (!nonreversible) {
258 double[][] tempActualRates = new double[((generationCount - 1) - burnin)][actualRates[0].length * 2];
259 for (int gen = 0; gen < (generationCount - 1) - burnin; gen++) {
260 for (int col = 0; col < actualRates[0].length; col++) {
261 tempActualRates[gen][col] = actualRates[gen][col];
262 tempActualRates[gen][actualRates[0].length + col] = actualRates[gen][col];
263 }
264 }
265 actualRates = tempActualRates;
266 }
267
268 boolean containsFrequencies = hasEntryOf(inputFileName, frequencyString);
269 double[][] frequencies = new double[((generationCount - 1) - burnin)][stateCount];
270 if (!containsFrequencies) {
271 progressStream.println("No state frequencies recorded; assuming all equal.");
272 for (int i = 0; i < ((generationCount - 1) - burnin); i++) {
273 Arrays.fill(frequencies[i], (1 / (double) stateCount));
274 }
275 } else {
276 int firstFrequency = getFirstEntryOf(inputFileName, frequencyString);
277 fill2DArray(inputFileName, frequencies, burnin, firstFrequency, stateCount);
278 }
279
280 double[][] QMatrixEntries = new double[((generationCount - 1) - burnin)][nonreversible ? rateCount : rateCount * 2];
281
282 for (int generation = 0; generation < (generationCount - 1) - burnin; generation++) {
283 double normalisationConstant = 0;
284 for (int row = 0; row < stateCount; row++) {
285 double rowSum = 0;
286 for (int column = 0; column < stateCount; column++) {
287 int dataColumn = columnNumberLookup[row][column];
288 if (dataColumn != -1) {
289 double unnormalisedMatrixEntry = actualRates[generation][dataColumn]
290 * frequencies[generation][column];
291 QMatrixEntries[generation][dataColumn] = unnormalisedMatrixEntry;
292 rowSum += unnormalisedMatrixEntry;
293 }
294 }
295 normalisationConstant += rowSum * frequencies[generation][row];
296
297 }
298 //normalise to one transition per unit time and multiply by the clock rate
299 for (int row = 0; row < stateCount; row++) {
300 for (int column = 0; column < stateCount; column++) {
301 int dataColumn = columnNumberLookup[row][column];
302 if (dataColumn != -1) {
303 QMatrixEntries[generation][dataColumn] = QMatrixEntries[generation][dataColumn]
304 * clockRates[generation] / normalisationConstant;
305 }
306 }
307 }
308 }
309 return QMatrixEntries;
310 }
311
312 private double[] getSupportedRateIndicators(){
313
314 int indicatorCounter = 0;
315
316 // If the indicators are symmetric but the frequencies aren't equal, you still need to retrieve rates in
317 // both directions (if you're interested in the rates at all). So the array of rates needs to be doubled up.
318
319 double[] expectedIndicatorsTemp;
320 if(!nonreversible && calculateRates){
321 expectedIndicatorsTemp = new double[expectedRateIndicators.length*2];
322 for(int i=0; i< expectedRateIndicators.length; i++){
323 expectedIndicatorsTemp[i] = expectedRateIndicators[i];
324 expectedIndicatorsTemp[expectedRateIndicators.length+i] = expectedRateIndicators[i];
325 }
326 } else {
327 expectedIndicatorsTemp = expectedRateIndicators;
328 }
329
330 for (double indicator : expectedIndicatorsTemp) {
331 if (!bayesFactor) {
332 if (indicator > cutoff) {
333 indicatorCounter++;
334 }
335 } else {
336 if (indicator > getBayesFactorCutOff(cutoff, meanPoissonPrior, offsetPoissonPrior, stateCount,
337 nonreversible)) {
338 indicatorCounter++;
339 }
340 }
341 }
342
343
344 double[] supportedIndicators = new double[indicatorCounter];
345 supportedBFs = new double[indicatorCounter];
346 supportedLocations = new String[indicatorCounter][2];
347 supportedLatitudes = new double[indicatorCounter][2];
348 supportedLongitudes = new double[indicatorCounter][2];
349 supportedActualRates = new double[indicatorCounter];
350 int[] indices = new int[expectedIndicatorsTemp.length];
351 HeapSort.sort(expectedIndicatorsTemp, indices);
352 int fillCount = 0;
353
354 for (int o = 0; o < expectedIndicatorsTemp.length; o++){
355 //we order rate indicators in decreasing order
356 double indicator = expectedIndicatorsTemp[indices[expectedIndicatorsTemp.length - o - 1]];
357 double BF = getBayesFactor(indicator, meanPoissonPrior, stateCount, offsetPoissonPrior, nonreversible,
358 0);
359 if (BF == Double.POSITIVE_INFINITY) {
360 BF = getBayesFactor(indicator, meanPoissonPrior, stateCount, offsetPoissonPrior, nonreversible,
361 generationCount);
362 }
363
364 double threshold = (bayesFactor ? getBayesFactorCutOff(cutoff, meanPoissonPrior, offsetPoissonPrior,
365 stateCount, nonreversible) : cutoff);
366 if (indicator > threshold) {
367 supportedIndicators[fillCount] = indicator;
368 supportedBFs[fillCount] = BF;
369 supportedLocations[fillCount][0] = locationNames[indices[(expectedIndicatorsTemp.length - o - 1)]][0];
370 supportedLocations[fillCount][1] = locationNames[indices[(expectedIndicatorsTemp.length - o - 1)]][1];
371 supportedLatitudes[fillCount][0] = latitudes[indices[(expectedIndicatorsTemp.length - o - 1)]][0];
372 supportedLatitudes[fillCount][1] = latitudes[indices[(expectedIndicatorsTemp.length - o - 1)]][1];
373 supportedLongitudes[fillCount][0] = longitudes[indices[(expectedIndicatorsTemp.length - o - 1)]][0];
374 supportedLongitudes[fillCount][1] = longitudes[indices[(expectedIndicatorsTemp.length - o - 1)]][1];
375 if(calculateRates){
376 supportedActualRates[fillCount] = meanQMatrix[indices[(expectedIndicatorsTemp.length - o - 1)]];
377 }
378 fillCount ++;
379 }
380 }
381 return supportedIndicators;
382 }
383
384 private void compileLocations(String[][] locations, String[][] locationNames, double[][] latitudes,
385 double[][] longitudes){
386 //begin of new code
387 int elementCounter = 0;
388 int secondCounter = 0;
389 for (int i = 0; i < (stateCount - 1); i++) {
390
391 secondCounter ++;
392
393 for (int j = secondCounter; j < stateCount; j++) {
394
395 if (locations != null) {
396 locationNames[elementCounter][0] = locations[i][0];
397 longitudes[elementCounter][0] = Double.parseDouble(locations[i][2]);
398 latitudes[elementCounter][0] = Double.parseDouble(locations[i][1]);
399 locationNames[elementCounter][1] = locations[j][0];
400 longitudes[elementCounter][1] = Double.parseDouble(locations[j][2]);
401 latitudes[elementCounter][1] = Double.parseDouble(locations[j][1]);
402 } else {
403 locationNames[elementCounter][0] = "location"+(i+1);
404 longitudes[elementCounter][0] = Double.NaN;
405 latitudes[elementCounter][0] = Double.NaN;
406 locationNames[elementCounter][1] = "location"+(j+1);
407 longitudes[elementCounter][1] = Double.NaN;
408 latitudes[elementCounter][1] = Double.NaN;
409 }
410
411 elementCounter ++;
412 }
413 }
414 // for nonreversible models, we keep on filling the arrays
415 if (nonreversible||calculateRates) {
416 for (int k = 0; k < elementCounter; k++) {
417
418 locationNames[elementCounter + k][0] = locationNames[k][1];
419 longitudes[elementCounter + k][0] = longitudes[k][1];
420 latitudes[elementCounter + k][0] = latitudes[k][1];
421 locationNames[elementCounter + k][1] = locationNames[k][0];
422 longitudes[elementCounter + k][1] = longitudes[k][0];
423 latitudes[elementCounter + k][1] = latitudes[k][0];
424 }
425 }
426
427 }
428
429 public void outputKML(String KMLoutputFile, String lowerLinkColor, String upperLinkColor,
430 double branchWidthConstant, double branchWidthMultiplier, double altitudeFactor){
431
432 double divider = 100;
433
434 PrintStream resultsStream = System.out;
435 if (KMLoutputFile != null) {
436 try {
437 resultsStream = new PrintStream(new File(KMLoutputFile));
438 } catch (IOException e) {
439 System.err.println("Error opening file: "+KMLoutputFile);
440 System.exit(-1);
441 }
442 }
443
444 Element rootElement = new Element("kml");
445 Element documentElement = new Element("Document");
446 Element folderElement = new Element("Folder");
447
448 Element documentNameElement = new Element("name");
449 documentNameElement.addContent(KMLoutputFile);
450 documentElement.addContent(documentNameElement);
451
452 List<Element> schema = new ArrayList<Element>();
453 Element locationSchema = new Element("Schema");
454 locationSchema.setAttribute("id", "Locations_Schema");
455 locationSchema.addContent(new Element("SimpleField")
456 .setAttribute("name", "Name")
457 .setAttribute("type", "string"));
458 locationSchema.addContent(new Element("SimpleField")
459 .setAttribute("name", "In")
460 .setAttribute("type", "number"));
461 locationSchema.addContent(new Element("SimpleField")
462 .setAttribute("name", "Out")
463 .setAttribute("type", "number"));
464 locationSchema.addContent(new Element("SimpleField")
465 .setAttribute("name", "Total")
466 .setAttribute("type", "number"));
467 Element ratesSchema = new Element("Schema");
468 ratesSchema.setAttribute("id", "Rates_Schema");
469 ratesSchema.addContent(new Element("SimpleField")
470 .setAttribute("name", "Name")
471 .setAttribute("type", "string"));
472 ratesSchema.addContent(new Element("SimpleField")
473 .setAttribute("name", "BF")
474 .setAttribute("type", "double"));
475 ratesSchema.addContent(new Element("SimpleField")
476 .setAttribute("name", "Indicator")
477 .setAttribute("type", "double"));
478 if(calculateRates){
479 ratesSchema.addContent(new Element("SimpleField")
480 .setAttribute("name", "meanRate")
481 .setAttribute("type", "double"));
482 }
483 schema.add(ratesSchema);
484
485 documentElement.addContent(schema);
486
487 Element folderNameElement = new Element("name");
488 String cutoffString;
489 if (bayesFactor) {
490 cutoffString = "bayes factor";
491 } else {
492 cutoffString = "indicator";
493 }
494 folderNameElement.addContent("discrete rates with "+cutoffString+" larger than "+cutoff);
495 folderElement.addContent(folderNameElement);
496
497 double[] minMax = new double[2];
498 if (supportedRateIndicators.length > 0) {
499 minMax[0] = supportedRateIndicators[supportedRateIndicators.length - 1];
500 minMax[1] = supportedRateIndicators[0];
501 } else {
502 minMax[0] = minMax[1] = 0;
503 System.err.println("No rate indicators above the specified cut-off!");
504 }
505
506 // for (int p = 0; p < supportedRateIndicators.length; p++){
507 // addRateAndStyle(supportedRateIndicators[p], supportedLongitudes[p][0], supportedLatitudes[p][0], supportedLongitudes[p][1], supportedLatitudes[p][1], p+1, branchWidthConstant, branchWidthMultiplier, minMax, altitudeFactor, divider, lowerLinkColor, upperLinkColor, folderElement, documentElement);
508 // }
509
510 for (int p = 0; p < supportedRateIndicators.length; p++){
511 if(calculateRates){
512 addRateWithData(supportedRateIndicators[p], supportedBFs[p], supportedActualRates[p],
513 supportedLocations[p][0], supportedLocations[p][1], supportedLongitudes[p][0],
514 supportedLatitudes[p][0], supportedLongitudes[p][1], supportedLatitudes[p][1], p+1,
515 folderElement);
516 } else {
517 addRateWithData(supportedRateIndicators[p], supportedBFs[p], supportedLocations[p][0],
518 supportedLocations[p][1], supportedLongitudes[p][0], supportedLatitudes[p][0],
519 supportedLongitudes[p][1], supportedLatitudes[p][1], p+1, folderElement);
520 }
521 }
522
523 //add locations
524 Element folder2Element = new Element("Folder");
525 Element folderName2Element = new Element("name");
526 folderName2Element.addContent("Locations");
527 folder2Element.addContent(folderName2Element);
528 addLocations(folder2Element);
529 documentElement.addContent(folder2Element);
530
531 documentElement.addContent(folderElement);
532 rootElement.addContent(documentElement);
533
534 XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE));
535 try {
536 xmlOutputter.output(rootElement,resultsStream);
537 } catch (IOException e) {
538 System.err.println("IO Exception encountered: "+e.getMessage());
539 System.exit(-1);
540 }
541
542 }
543
544 private void addLocations(Element folderElement){
545
546
547 for (String[] location : locations) {
548 Element placemarkElement = new Element("Placemark");
549 Element placemarkNameElement = new Element("name");
550 placemarkNameElement.addContent(location[0]);
551 placemarkElement.addContent(placemarkNameElement);
552
553 int inCount = 0;
554 int outCount = 0;
555
556 for (int j = 0; j < supportedRateIndicators.length; j++) {
557 if (supportedLocations[j][0].equals(location[0])) {
558 inCount++;
559 }
560 if (supportedLocations[j][1].equals(location[0])) {
561 outCount++;
562 }
563 }
564 int totalCount = inCount + outCount;
565
566 Element data = new Element("ExtendedData");
567 Element schemaData = new Element("SchemaData");
568 schemaData.setAttribute("schemaUrl", "#Location_Schema");
569 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Name").addContent(location[0]));
570 schemaData.addContent(new Element("SimpleData").setAttribute("name", "In").addContent(Integer.toString(inCount)));
571 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Out").addContent(Integer.toString(outCount)));
572 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Total").addContent(Integer.toString(totalCount)));
573 data.addContent(schemaData);
574 placemarkElement.addContent(data);
575
576 Element pointElement = new Element("Point");
577 Element altitude = new Element("altitudeMode");
578 altitude.addContent("relativeToGround");
579 pointElement.addContent(altitude);
580 Element coordinates = new Element("coordinates");
581 coordinates.addContent(location[2] + "," + location[1] + ",0");
582 pointElement.addContent(coordinates);
583 placemarkElement.addContent(pointElement);
584
585 folderElement.addContent(placemarkElement);
586 }
587 }
588
589 private void addRateAndStyle(double rateIndicator, double startLongitude, double startLatitude,
590 double endLongitude, double endLatitude, int number, double branchWidthConstant,
591 double branchWidthMultiplier, double[] minAndMaxRateIndicator, double altitudeFactor,
592 double divider, String lowerLinkColor, String upperLinkColor, Element folderElement,
593 Element documentElement) {
594
595 String opacity = "FF";
596
597 double distance = (3958*Math.PI*Math.sqrt((endLatitude-startLatitude)*(endLatitude-startLatitude)
598 +Math.cos(endLatitude/57.29578)*Math.cos(startLatitude/57.29578)
599 *(endLongitude-startLongitude)*(endLongitude-startLongitude))/180);
600
601 double maxAltitude = distance*altitudeFactor;
602 double latitudeDifference = endLatitude - startLatitude;
603 double longitudeDifference = endLongitude - startLongitude;
604
605
606 boolean longitudeBreak = false; //if we go through the 180
607 if (endLongitude*startLongitude < 0) {
608
609 double trialDistance = 0;
610
611 if (endLongitude < 0) {
612 trialDistance += (endLongitude + 180);
613 trialDistance += (180 - startLongitude);
614 //System.out.println(parentLongitude+"\t"+longitude+"\t"+trialDistance+"\t"+longitudeDifference);
615 } else {
616 trialDistance += (startLongitude + 180);
617 trialDistance += (180 - endLongitude);
618 //System.out.println(parentLongitude+"\t"+longitude+"\t"+trialDistance+"\t"+longitudeDifference);
619 }
620
621 if (trialDistance < Math.abs(longitudeDifference)) {
622 longitudeDifference = trialDistance;
623 longitudeBreak = true;
624 //System.out.println("BREAK!"+longitudeDifference);
625 }
626 }
627
628 Element styleElement = new Element("Style");
629 styleElement.setAttribute("id","rate"+number+"_style");
630 Element lineStyle = new Element("LineStyle");
631 Element width = new Element("width");
632 width.addContent(Double.toString(branchWidthConstant+branchWidthMultiplier*rateIndicator));
633 Element color = new Element("color");
634 String colorString = TimeSlicer.getKMLColor(rateIndicator,minAndMaxRateIndicator,lowerLinkColor,upperLinkColor);
635 color.addContent(opacity+colorString);
636 lineStyle.addContent(width);
637 lineStyle.addContent(color);
638 styleElement.addContent(lineStyle);
639 documentElement.addContent(styleElement);
640
641 double currentLongitude1 = 0; //we need this if we go through the 180
642 double currentLongitude2 = 0; //we need this if we go through the 180
643
644 for (int a = 0; a < divider; a ++) {
645
646 Element placemarkElement = new Element("Placemark");
647
648 Element placemarkNameElement = new Element("name");
649 String name = "rate"+number+"_part"+(a+1);
650 placemarkNameElement.addContent(name);
651 placemarkElement.addContent(placemarkNameElement);
652
653 Element placemarkStyleElement = new Element("styleUrl");
654 placemarkStyleElement.addContent("#rate"+number+"_style");
655 placemarkElement.addContent(placemarkStyleElement);
656
657 Element lineStringElement = new Element("LineString");
658 Element altitudeMode = new Element("altitudeMode");
659 altitudeMode.addContent("relativeToGround");
660 lineStringElement.addContent(altitudeMode);
661 Element tessellate = new Element("tessellate");
662 tessellate.addContent("1");
663 lineStringElement.addContent(tessellate);
664 Element coordinatesElement = new Element("coordinates");
665 StringBuffer coordinatesStartBuffer = new StringBuffer();
666 StringBuffer coordinatesEndBuffer = new StringBuffer();
667
668 if (longitudeBreak) {
669
670 if (startLongitude > 0) {
671 currentLongitude1 = startLongitude+a*(longitudeDifference/divider);
672
673 if (currentLongitude1 < 180) {
674 coordinatesStartBuffer.append(currentLongitude1+",");
675 //System.out.println("1 currentLongitude1 < 180\t"+currentLongitude1+"\t"+longitude);
676
677 } else {
678 coordinatesStartBuffer.append((-180-(180-currentLongitude1))+",");
679 //System.out.println("2 currentLongitude1 > 180\t"+currentLongitude1+"\t"+(-180-(180-currentLongitude1))+"\t"+longitude);
680 }
681 } else {
682 currentLongitude1 = startLongitude-a*(longitudeDifference/divider);
683
684 if (currentLongitude1 > (-180)) {
685 coordinatesStartBuffer.append(currentLongitude1+",");
686 //System.out.println("currentLongitude1 > -180\t"+currentLongitude1+"\t"+longitude);
687 } else {
688 coordinatesStartBuffer.append((180+(currentLongitude1+180))+",");
689 //System.out.println("currentLongitude1 > -180\t"+(180+(currentLongitude1+180))+"\t"+longitude);
690 }
691 }
692
693 } else {
694 coordinatesStartBuffer.append((startLongitude+a*(longitudeDifference/divider))+",");
695 }
696
697 coordinatesStartBuffer.append((startLatitude+a*(latitudeDifference/divider))+","
698 +(maxAltitude*Math.sin(Math.acos(1 - a*(1.0/(divider/2.0))))));
699
700 if (longitudeBreak) {
701
702 if (startLongitude > 0) {
703 currentLongitude2 = startLongitude+(a+1)*(longitudeDifference/divider);
704
705 if (currentLongitude2 < 180) {
706 coordinatesEndBuffer.append((currentLongitude2)+",");
707 } else {
708 coordinatesEndBuffer.append((-180-(180-currentLongitude2))+",");
709 }
710 } else {
711 currentLongitude2 = startLongitude-(a+1)*(longitudeDifference/divider);
712
713 if (currentLongitude2 > (-180)) {
714 coordinatesEndBuffer.append(currentLongitude2+",");
715 } else {
716 coordinatesEndBuffer.append((180+(currentLongitude2+180))+",");
717 }
718 }
719
720 } else {
721 coordinatesEndBuffer.append((startLongitude+(a+1)*(longitudeDifference/divider))+",");
722 }
723
724 coordinatesEndBuffer.append((startLatitude+(a+1)*(latitudeDifference/divider))+","
725 +(maxAltitude*Math.sin(Math.acos(1 - (a+1)*(1.0/(divider/2.0))))));
726
727 coordinatesElement.addContent(coordinatesStartBuffer.toString());
728 coordinatesElement.addContent(" ");
729 coordinatesElement.addContent(coordinatesEndBuffer.toString());
730 lineStringElement.addContent(coordinatesElement);
731 placemarkElement.addContent(lineStringElement);
732 folderElement.addContent(placemarkElement);
733 }
734 }
735
736 private Element addRateWithData(double rateIndicator, double BF, String fromLocation, String toLocation,
737 double startLongitude, double startLatitude, double endLongitude, double endLatitude,
738 int number, Element folderElement) {
739
740 Element placemarkElement = new Element("Placemark");
741
742 Element placemarkNameElement = new Element("name");
743 String name = "rate"+number;
744 placemarkNameElement.addContent(name);
745 placemarkElement.addContent(placemarkNameElement);
746
747 Element data = new Element("ExtendedData");
748 Element schemaData = new Element("SchemaData");
749 schemaData.setAttribute("schemaUrl", "#Rate_Schema");
750 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Name").addContent(name));
751 schemaData.addContent(new Element("SimpleData").setAttribute("name", "From").addContent(fromLocation));
752 schemaData.addContent(new Element("SimpleData").setAttribute("name", "To").addContent(toLocation));
753 schemaData.addContent(new Element("SimpleData").setAttribute("name", "BF").addContent(Double.toString(BF)));
754 schemaData.addContent(new Element("SimpleData").setAttribute("name", "Indicator").addContent(Double.toString(rateIndicator)));
755 data.addContent(schemaData);
756 placemarkElement.addContent(data);
757
758 Element lineStringElement = new Element("LineString");
759 Element altitudeMode = new Element("altitudeMode");
760 altitudeMode.addContent("clampToGround");
761 lineStringElement.addContent(altitudeMode);
762 Element tessellate = new Element("tessellate");
763 tessellate.addContent("1");
764 lineStringElement.addContent(tessellate);
765 Element coordinatesElement = new Element("coordinates");
766 coordinatesElement.addContent(startLongitude + "," + startLatitude + " " + endLongitude + "," + endLatitude);
767 lineStringElement.addContent(coordinatesElement);
768 placemarkElement.addContent(lineStringElement);
769 folderElement.addContent(placemarkElement);
770 return placemarkElement;
771 }
772
773 // the actual rate version of this method
774
775 private Element addRateWithData(double rateIndicator, double BF, double actualRate, String fromLocation,
776 String toLocation, double startLongitude, double startLatitude, double endLongitude,
777 double endLatitude, int number, Element folderElement) {
778
779 Element placemarkElement = addRateWithData(rateIndicator, BF, fromLocation, toLocation, startLongitude,
780 startLatitude, endLongitude, endLatitude, number, folderElement);
781
782 Element data = placemarkElement.getChild("ExtendedData");
783 Element schemaData = data.getChild("SchemaData");
784 schemaData.addContent(new Element("SimpleData").setAttribute("name", "meanRate").addContent(Double.toString(actualRate)));
785
786 return placemarkElement;
787 }
788
789 public void outputTextFile(String outFileName) {
790
791 // double[] minMax = new double[2];
792 // minMax[0] = supportedRateIndicators[0];
793 // minMax[1] = supportedRateIndicators[supportedRateIndicators.length - 1];
794
795 try {
796 PrintWriter outFile;
797 if (outFileName != null) {
798 outFile = new PrintWriter(new FileWriter(outFileName), true);
799 } else {
800 outFile = new PrintWriter(System.out);
801 }
802 //sort expected rateIndicator
803 if (bayesFactor) {
804 outFile.println("Indicator cutoff (for BF = "+cutoff+") = "+getBayesFactorCutOff(cutoff,
805 meanPoissonPrior, offsetPoissonPrior, stateCount, nonreversible));
806 } else {
807 outFile.println("Indicator cutoff = "+cutoff);
808 }
809 outFile.println("mean Poisson Prior = "+meanPoissonPrior);
810 outFile.println("Poisson Prior offset = "+offsetPoissonPrior);
811
812 for (int o = 0; o < supportedRateIndicators.length; o++){
813
814 outFile.print(
815 "I="+supportedRateIndicators[o]+"\tBF");
816
817 double BF = getBayesFactor(supportedRateIndicators[o], meanPoissonPrior, stateCount,
818 offsetPoissonPrior, nonreversible, 0);
819 if (BF == Double.POSITIVE_INFINITY) {
820 outFile.print(">"+getBayesFactor(supportedRateIndicators[o], meanPoissonPrior, stateCount,
821 offsetPoissonPrior, nonreversible, generationCount));
822 } else {
823 outFile.print("="+BF);
824 }
825
826 StringBuilder sb = new StringBuilder();
827 sb.append(" : between ")
828 .append(supportedLocations[o][0]);
829 if (!Double.isNaN(supportedLongitudes[o][0])) {
830 sb.append(" (long: ")
831 .append(supportedLongitudes[o][0])
832 .append("; lat: ")
833 .append(supportedLatitudes[o][0])
834 .append(")");
835 }
836 sb.append(" and ")
837 .append(supportedLocations[o][1]);
838 if (!Double.isNaN(supportedLongitudes[o][1])) {
839 sb.append(" (long: ")
840 .append(supportedLongitudes[o][1])
841 .append("; lat: ")
842 .append(supportedLatitudes[o][1])
843 .append(")");
844 }
845 if(calculateRates){
846 sb.append(" with mean rate of transition ")
847 .append(supportedActualRates[o])
848 .append(" per ")
849 .append(unitString);
850 }
851 outFile.print(sb.toString());
852 outFile.println();
853 }
854 outFile.close();
855 } catch(IOException io) {
856 System.err.print("Error writing to file: " + outFileName);
857 }
858
859 }
860
861 private static double getBayesFactor(double meanIndicator, double meanPoissonPrior, int numberOfLocations,
862 int offset, boolean nonreversible, double generations) {
863
864 double bayesFactor = 0;
865 double priorProbabilityDenominator = 0;
866 int numberOfRatesMultiplier = 2;
867 priorProbabilityDenominator = meanPoissonPrior + offset;
868 if (nonreversible) numberOfRatesMultiplier = 1;
869
870 double priorProbability = priorProbabilityDenominator/((numberOfLocations*(numberOfLocations-1))/numberOfRatesMultiplier);
871
872 double priorOdds = priorProbability/(1.0 - priorProbability);
873 double posteriorProbability = meanIndicator;
874 double posteriorOdds;
875 if (generations > 0) {
876 posteriorOdds = (posteriorProbability - (1/generations))/(1 - (posteriorProbability - (1/generations)));
877 } else {
878 posteriorOdds = posteriorProbability/(1 - posteriorProbability);
879 }
880 bayesFactor = posteriorOdds/priorOdds;
881
882 return bayesFactor;
883
884 }
885
886 private static double getBayesFactorCutOff(double bayesFactor, double meanPoissonPrior, int offset,
887 int numberOfLocations, boolean nonreversible) {
888
889 double bayesFactorCutoff = 0;
890 double posteriorOdds = 0;
891 int numberOfRatesMultiplier = 2;
892 if (nonreversible) numberOfRatesMultiplier = 1;
893
894 double priorProbability = (meanPoissonPrior + offset)/((numberOfLocations*(numberOfLocations-1))/numberOfRatesMultiplier);
895 double priorOdds = priorProbability/(1.0 - priorProbability);
896 posteriorOdds = priorOdds*bayesFactor;
897 bayesFactorCutoff = posteriorOdds/(1.0 + posteriorOdds);
898
899 return bayesFactorCutoff;
900
901 }
902
903 private static double[] meanCol(double[][] x) {
904 double[] returnArray = new double[x[0].length];
905
906 for (int i = 0; i < x[0].length; i++) {
907
908 double m = 0.0;
909 int len = 0;
910
911 for (int j = 0; j < x.length; j++) {
912
913 m += x[j][i];
914 len += 1;
915
916 }
917
918 returnArray[i] = m / (double) len;
919
920 }
921 return returnArray;
922 }
923
924 private static void fill1DArray(String logFileName, double[] array, int burnin, int element){
925 try {
926 BufferedReader arrayReader = new BufferedReader(new FileReader(logFileName));
927 String currentLine = arrayReader.readLine();
928 while (currentLine.startsWith("#")) {
929 currentLine = arrayReader.readLine();
930 }
931
932 // skip the headers in the rateIndicator file
933 while (currentLine.startsWith("state")) {
934 currentLine = arrayReader.readLine();
935 }
936
937 double currentElement;
938 int linesRead = 0;
939 //skip burnin
940 while (linesRead < burnin){
941 currentLine = arrayReader.readLine();
942 linesRead ++;
943 }
944
945 int rowCounter = 0;
946
947 while (currentLine!= null && !arrayReader.equals("")) {
948
949
950 int startCounter = 1;
951
952 StringTokenizer tokens = new StringTokenizer(currentLine);
953 currentElement = Double.parseDouble(tokens.nextToken());
954
955 //skip until we encounter rateIndicators
956 while (startCounter < element) {
957 currentElement = Double.parseDouble(tokens.nextToken());
958 startCounter ++;
959 }
960
961 // read the value
962 array[rowCounter] = currentElement;
963
964 rowCounter ++;
965 currentLine = arrayReader.readLine();
966
967 }
968 } catch (IOException e) {
969 System.err.println("Error reading " + logFileName);
970 System.exit(1);
971 }
972 }
973
974
975 private static void fill2DArray(String logFileName, double[][] array, int burnin, int firstElement,
976 int numberOfItems){
977
978 try {
979 BufferedReader arrayReader = new BufferedReader(new FileReader(logFileName));
980 String currentLine = arrayReader.readLine();
981 while (currentLine.startsWith("#")) {
982 currentLine = arrayReader.readLine();
983 }
984
985 // skip the headers in the rateIndicator file
986 while (currentLine.startsWith("state")) {
987 currentLine = arrayReader.readLine();
988 }
989
990 double currentElement;
991 int linesRead = 0;
992 //skip burnin
993 while (linesRead < burnin){
994 currentLine = arrayReader.readLine();
995 linesRead ++;
996 }
997
998 int rowCounter = 0;
999
1000 while (currentLine!= null && !arrayReader.equals("")) {
1001
1002 int columnCounter = 0;
1003
1004 int startCounter = 1;
1005 int columnOfInterestCounter = 0;
1006
1007 StringTokenizer tokens = new StringTokenizer(currentLine);
1008 currentElement = Double.parseDouble(tokens.nextToken());
1009
1010 //skip until we encounter rateIndicators
1011 while (startCounter < firstElement) {
1012 currentElement = Double.parseDouble(tokens.nextToken());
1013 startCounter ++;
1014 }
1015
1016 // read all rateIndicators
1017 while (columnOfInterestCounter < numberOfItems) {
1018 array[rowCounter][columnCounter] = currentElement;
1019 columnCounter ++;
1020 columnOfInterestCounter ++;
1021 if (columnOfInterestCounter < numberOfItems) {
1022 currentElement = Double.parseDouble(tokens.nextToken());
1023 }
1024
1025 }
1026
1027 rowCounter ++;
1028 currentLine = arrayReader.readLine();
1029
1030 }
1031 } catch (IOException e) {
1032 System.err.println("Error reading " + logFileName);
1033 System.exit(1);
1034 }
1035
1036 }
1037
1038 private static int getNumberOfEntries(String file, int firstRateIndicator, String rateIndicatorString) {
1039
1040 int numberOfRateIndicators = 0;
1041
1042 try {
1043 BufferedReader reader = new BufferedReader(new FileReader(file));
1044 String current3 = reader.readLine();
1045
1046 //skip comment lines
1047 while (current3.startsWith("#")) {
1048 current3 = reader.readLine();
1049 }
1050
1051 String rateIndicator = null;
1052 int startCounter = 1;
1053 StringTokenizer tokens = new StringTokenizer(current3);
1054 rateIndicator = tokens.nextToken();
1055 //find first rateIndicator..
1056 while (startCounter < firstRateIndicator) {
1057 rateIndicator = tokens.nextToken();
1058 startCounter ++;
1059 }
1060 // and continue counting from thereon
1061 while(rateIndicator.contains(rateIndicatorString)) {
1062 rateIndicator = tokens.nextToken();
1063 numberOfRateIndicators ++;
1064 }
1065
1066 } catch (IOException e) {
1067 System.err.println("Error reading " + file);
1068 System.exit(1);
1069 }
1070
1071 return numberOfRateIndicators;
1072
1073 }
1074
1075 private static boolean hasEntryOf(String file, String entryString) {
1076
1077 boolean hasEntry = false;
1078
1079 try {
1080 BufferedReader reader2 = new BufferedReader(new FileReader(file));
1081 String current2 = reader2.readLine();
1082
1083 //skip comment lines
1084 while (current2.startsWith("#")) {
1085 current2 = reader2.readLine();
1086 }
1087
1088 String parameter1 = null;
1089 StringTokenizer tokens1 = new StringTokenizer(current2);
1090
1091 while(tokens1.hasMoreTokens()) {
1092 parameter1 = tokens1.nextToken();
1093 if (parameter1.contains(entryString)) {
1094 hasEntry = true;
1095 }
1096 }
1097
1098 } catch (IOException e) {
1099 System.err.println("Error reading " + file);
1100 System.exit(1);
1101 }
1102
1103 return hasEntry;
1104
1105 }
1106
1107 private static int getFirstEntryOf(String file, String entryString) {
1108
1109 int firstRateIndicator = 1;
1110
1111 try {
1112 BufferedReader reader2 = new BufferedReader(new FileReader(file));
1113 String current2 = reader2.readLine();
1114
1115 //skip comment lines
1116 while (current2.startsWith("#")) {
1117 current2 = reader2.readLine();
1118 }
1119
1120 String parameter1 = null;
1121 StringTokenizer tokens1 = new StringTokenizer(current2);
1122 parameter1 = tokens1.nextToken();
1123 while(!parameter1.contains(entryString)) {
1124 parameter1 = tokens1.nextToken();
1125 firstRateIndicator ++;
1126 }
1127
1128 } catch (IOException e) {
1129 System.err.println("Error reading " + file);
1130 System.exit(1);
1131 }
1132
1133 return firstRateIndicator;
1134
1135 }
1136
1137 private static int getGenerationCount(String file) {
1138
1139 int states = 0;
1140
1141 try {
1142 BufferedReader reader1 = new BufferedReader(new FileReader(file));
1143 String current1 = reader1.readLine();
1144 while (current1 != null && !reader1.equals("")) {
1145 while (current1.startsWith("#")) {
1146 current1 = reader1.readLine();
1147 }
1148 current1 = reader1.readLine();
1149 states++;
1150 }
1151
1152 } catch (IOException e) {
1153 System.err.println("Error reading " + file);
1154 System.exit(1);
1155 }
1156
1157 return states;
1158
1159 }
1160
1161 protected static int[] countLinesAndTokens(String coordinatesFileString){
1162 int lineCounter = 0;
1163 int tokenCounter = 0;
1164 int[] container = new int[2];
1165 try{
1166 BufferedReader reader1 = new BufferedReader(new FileReader(coordinatesFileString));
1167 String current1 = reader1.readLine();
1168 while (current1 != null && !reader1.equals("")) {
1169 lineCounter++;
1170 if (lineCounter == 1) {
1171 StringTokenizer tokens = new StringTokenizer(current1);
1172 while (tokens.hasMoreTokens()) {
1173 tokenCounter++;
1174 tokens.nextToken();
1175 }
1176 }
1177 current1 = reader1.readLine();
1178 }
1179
1180 } catch (IOException e) {
1181 System.err.println("Error reading " + coordinatesFileString);
1182 System.exit(1);
1183 }
1184 container[0] = lineCounter;
1185 container[1] = tokenCounter;
1186 return container;
1187 }
1188
1189 protected static void readLocationsCoordinates(String coordinatesFileString, String[][] locationsAndCoordinates){
1190 try {
1191 BufferedReader reader2 = new BufferedReader(new FileReader(coordinatesFileString));
1192 String current2 = reader2.readLine();
1193 int counter2 = 0;
1194 while (current2 != null && !reader2.equals("")) {
1195 StringTokenizer tokens2 = new StringTokenizer(current2);
1196 for (int i = 0; i < locationsAndCoordinates[0].length; i++) {
1197 locationsAndCoordinates[counter2][i] = tokens2.nextToken();
1198 progressStream.print(locationsAndCoordinates[counter2][i]+"\t");
1199 }
1200 progressStream.print("\r");
1201 counter2 ++;
1202 current2 = reader2.readLine();
1203 }
1204 } catch (IOException e) {
1205 e.printStackTrace();
1206 return;
1207 }
1208 }
1209
1210 public static void main(String[] args) throws IOException {
1211
1212 String inputFileName = null;
1213 String outputFileName = null;
1214
1215 String locationsFileName = null;
1216 String[][] locations = null;
1217 boolean kml = false;
1218 boolean calculateRates = false;
1219 String lowerLinkColor = "FFFFFF"; //red: 0000FF green: 00FF00 magenta: FF00FF white: FFFFFF yellow: 00FFFF cyan: FFFF00
1220 String upperLinkColor = "FF00FF";
1221 String KMLoutputFile = "KMLrates.kml";
1222 double branchWidthConstant = 2.5;
1223 double branchWidthMultiplier = 7.0;
1224 double altitudeFactor = 500;
1225 //Double width = 3.0;
1226
1227 int burnin = -1;
1228 double meanPoissonPrior = 0.693;
1229 int offsetPoissonPrior = 0;
1230 int numberOfStates = 0;
1231
1232 double cutoff = 3.0;
1233 boolean bayesFactor = true; // if false, we will use an indicator cut off value
1234
1235 boolean rateSummary = false;
1236 String rateIndicatorString = "indicators";
1237 String actualRateString = "actualRates";
1238 String relativeRateString = "rates";
1239 String frequencyString = "frequencies";
1240 //this is for rate (dist/time) summaries
1241 String clockRateString = "clock.rate";
1242 String unitString = "year";
1243
1244 Arguments arguments = new Arguments(
1245 new Arguments.Option[]{
1246 new Arguments.IntegerOption(BURNIN, "the number of states to be considered as 'burn-in' " +
1247 "[default = 0]"),
1248 new Arguments.StringOption(LOCATIONSFILE,"coordinates file","a file with latitudes and " +
1249 "longitudes for each location (required for a kml output)"),
1250 //boolean for KML
1251 new Arguments.StringOption(KML, falseTrue, false,
1252 "generate a KML file including well-supported rates [default = false]"),
1253 new Arguments.StringOption(CALCULATERATES, falseTrue, false,
1254 "calculate the actual rates for well-supported transitions"),
1255 new Arguments.IntegerOption(LOCATIONSTATES,"the number of locations states used in the " +
1256 "analyses [requires a coordinates file if not provided]"),
1257 new Arguments.IntegerOption(POFFSET,"the offset of the (truncated) Poisson prior " +
1258 "[default=locations-1]"),
1259 new Arguments.RealOption(PMEAN,"the mean of the (truncated) Poisson prior " +
1260 "[default=0.693 (log2)]"),
1261 new Arguments.RealOption(BFCUTOFF,"the Bayes Factor values above which we consider rates to " +
1262 "be well supported [default=3.0]"),
1263 new Arguments.RealOption(ICUTOFF,"the indicator values above which we consider rates to be " +
1264 "well supported [default uses a Bayes factor cut off of 3.0]"),
1265 new Arguments.StringOption(ISTRING, "indicator_string", "prefix string used for outputting " +
1266 "the rate indicators in the log file [default = indicators]"),
1267 new Arguments.StringOption(RSTRING, "relativeRate_string", "prefix string used for " +
1268 "outputting the relative rates in the log file [default = rates]"),
1269 new Arguments.StringOption(FSTRING, "frequencies_string", "prefix string used for outputting " +
1270 "the state frequencies in the log file [default = frequencies]"),
1271 new Arguments.StringOption(PSTRING, "rate*indicator_string", "prefix string used for " +
1272 "outputting the product statistic for rates*indicators [default = actualRates]"),
1273 new Arguments.StringOption(CSTRING, "clock_rate_string", "string used for outputting " +
1274 "the overall clock rate in the log file [default = clock.rate]"),
1275 new Arguments.StringOption(USTRING, "units_string", "string describing the time unit" +
1276 "[default = year]"),
1277 new Arguments.StringOption(KMLFILE,"KML output file","KML output file name " +
1278 "[default=KMLrates.kml]"),
1279 new Arguments.StringOption(LOWCOLOR, "lower link strength color", "specifies an lower link " +
1280 "color for the links [default=FF00FF]"),
1281 new Arguments.StringOption(UPCOLOR, "upper link strength color", "specifies an upper link " +
1282 "color for the links [default=FFFF00]"),
1283 new Arguments.RealOption(BWC,"specifies the connection (rate) width constant [default=2.5]"),
1284 new Arguments.RealOption(BWM,"specifies the connection (rate) width multiplier [default=7.0]"),
1285 new Arguments.RealOption(ALTITUDE,"specifies the altitude factor for the connections (rate) " +
1286 "[default=500]"),
1287 //new Arguments.RealOption(WIDTH,"width for KML rates [default=3.0]"),
1288 });
1289
1290 try {
1291 arguments.parseArguments(args);
1292 } catch (Arguments.ArgumentException ae) {
1293 progressStream.println(ae);
1294 printUsage(arguments);
1295 System.exit(1);
1296 }
1297
1298 if (arguments.hasOption(HELP)) {
1299 printUsage(arguments);
1300 System.exit(0);
1301 }
1302
1303 // Make sense of arguments
1304
1305 if (arguments.hasOption(BURNIN)) {
1306 burnin = arguments.getIntegerOption(BURNIN);
1307 }
1308 progressStream.println("Ignoring "+burnin+" states as burn-in");
1309
1310 if (arguments.hasOption(LOCATIONSTATES)) {
1311 numberOfStates = arguments.getIntegerOption(LOCATIONSTATES);
1312 }
1313
1314 locationsFileName = arguments.getStringOption(LOCATIONSFILE);
1315 if (locationsFileName != null) {
1316 int counts[] = countLinesAndTokens(locationsFileName);
1317 //System.out.println(counts[0]+"\t"+counts[1]);
1318 //read in locations
1319 if (numberOfStates > 0) {
1320 if (numberOfStates != counts[0]) {
1321 System.err.println("number of states provided ("+numberOfStates+") does not match lines in coordinates file ("+counts[0]+") ??");
1322 }
1323 }
1324 locations = new String[counts[0]][counts[1]];
1325 readLocationsCoordinates(locationsFileName,locations);
1326
1327 if (numberOfStates == 0) {
1328 numberOfStates = counts[0];
1329 }
1330
1331 } else {
1332 if (numberOfStates == 0) {
1333 System.err.println("no states provided, nor coordinates file ??");
1334 }
1335 }
1336
1337 String kmlBooleanString = arguments.getStringOption(KML);
1338 if (kmlBooleanString != null && kmlBooleanString.compareToIgnoreCase("true") == 0) {
1339 kml = true;
1340 if (locationsFileName == null) {
1341 System.err.println("you want a KML file without a coordinates file??");
1342 }
1343 }
1344
1345 String ratesBooleanString = arguments.getStringOption(CALCULATERATES);
1346 if (ratesBooleanString != null && ratesBooleanString.compareToIgnoreCase("true") == 0) {
1347 calculateRates = true;
1348 }
1349
1350 String kmlFileName = arguments.getStringOption(KMLFILE);
1351 if (kmlFileName != null) {
1352 KMLoutputFile = kmlFileName;
1353 }
1354
1355 if (arguments.hasOption(PMEAN)) {
1356 meanPoissonPrior = arguments.getRealOption(PMEAN);
1357 progressStream.println("Poisson prior with mean "+meanPoissonPrior);
1358 } else {
1359 progressStream.println("Poisson prior with mean "+meanPoissonPrior+" (default)");
1360 }
1361
1362 if (arguments.hasOption(POFFSET)) {
1363 offsetPoissonPrior = arguments.getIntegerOption(POFFSET);
1364 progressStream.println("Poisson offset = "+offsetPoissonPrior);
1365 } else {
1366 offsetPoissonPrior = numberOfStates - 1;
1367 progressStream.println("Poisson offset = "+offsetPoissonPrior+" (locations - 1)");
1368 }
1369
1370 if (arguments.hasOption(BFCUTOFF)) {
1371 cutoff = arguments.getRealOption(BFCUTOFF);
1372 }
1373 if (arguments.hasOption(ICUTOFF)) {
1374 cutoff = arguments.getRealOption(ICUTOFF);
1375 bayesFactor = false;
1376 }
1377 if (bayesFactor) {
1378 progressStream.println("Bayes factor cutoff = "+cutoff);
1379 } else {
1380 progressStream.println("indicator factor cutoff = "+cutoff);
1381 }
1382
1383
1384 if (arguments.hasOption(BWC)) {
1385 branchWidthConstant = arguments.getRealOption(BWC);
1386 }
1387
1388 if (arguments.hasOption(BWM)) {
1389 branchWidthMultiplier = arguments.getRealOption(BWM);
1390 }
1391
1392 if (arguments.hasOption(ALTITUDE)) {
1393 altitudeFactor = arguments.getRealOption(ALTITUDE);
1394 }
1395
1396 String indicatorString = arguments.getStringOption(ISTRING);
1397 if (indicatorString != null) {
1398 rateIndicatorString = indicatorString;
1399 }
1400
1401 String rateString = arguments.getStringOption(PSTRING);
1402 if (rateString != null) {
1403 actualRateString = rateString;
1404 }
1405
1406 String freqString = arguments.getStringOption(FSTRING);
1407 if (freqString != null) {
1408 frequencyString = freqString;
1409 }
1410
1411 String relRateString = arguments.getStringOption(RSTRING);
1412 if (relRateString != null) {
1413 relativeRateString = relRateString;
1414 }
1415
1416 String clockString = arguments.getStringOption(CSTRING);
1417 if (clockString != null) {
1418 clockRateString = clockString;
1419 }
1420
1421 String color1String = arguments.getStringOption(LOWCOLOR);
1422 if (color1String != null) {
1423 lowerLinkColor = color1String;
1424 if (locationsFileName == null) {
1425 System.err.print("color string but no coordinates file for KML output??");
1426 }
1427 }
1428
1429 String color2String = arguments.getStringOption(UPCOLOR);
1430 if (color2String != null) {
1431 upperLinkColor = color2String;
1432 if (locationsFileName == null) {
1433 System.err.print("color string but no coordinates file for KML output??");
1434 }
1435 }
1436
1437
1438 final String[] args2 = arguments.getLeftoverArguments();
1439
1440 switch (args2.length) {
1441 case 0:
1442 printUsage(arguments);
1443 System.exit(1);
1444 case 2:
1445 outputFileName = args2[1];
1446 // fall to
1447 case 1:
1448 inputFileName = args2[0];
1449 break;
1450 default: {
1451 System.err.println("Unknown option: " + args2[2]);
1452 System.err.println();
1453 printUsage(arguments);
1454 System.exit(1);
1455 }
1456 }
1457
1458 RateIndicatorBF rateIndicatorBF = new RateIndicatorBF(inputFileName, burnin, rateIndicatorString,
1459 numberOfStates, locations, bayesFactor, cutoff, meanPoissonPrior, offsetPoissonPrior, actualRateString,
1460 relativeRateString, frequencyString, clockRateString, unitString, calculateRates);
1461 rateIndicatorBF.outputTextFile(outputFileName);
1462 if (kml) {
1463 rateIndicatorBF.outputKML(KMLoutputFile,lowerLinkColor,upperLinkColor, branchWidthConstant,
1464 branchWidthMultiplier, altitudeFactor);
1465 }
1466 System.exit(0);
1467 }
1468 }