Debian Codegraph @

src/dr/app/tools/JumpHistoryAnalyser.java

raw symbols SCIP
1 /*
2 * JumpHistoryAnalyser.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.util.Arguments;
29 import dr.inference.trace.TraceException;
30 import jebl.evolution.io.ImportException;
31
32 import java.io.BufferedReader;
33 import java.io.FileReader;
34 import java.io.IOException;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41
42 /**
43 * @author Andrew Rambaut
44 * @author Marc A. Suchard
45 * @version $Id$
46 */
47 public class JumpHistoryAnalyser {
48
49 private int binCount;
50 private double minTime;
51 private double maxTime;
52 private double ageOfYoungest;
53
54 public JumpHistoryAnalyser(String inputFileName, Set<String> fromStates, Set<String> toStates, boolean iterateFrom,
55 boolean iterateTo, int burnin, int binCount, double minTime, double maxTime,
56 boolean backwardsTime, double ageOfYoungest)
57 throws IOException, ImportException, TraceException {
58
59 this.binCount = binCount;
60 this.minTime = minTime;
61 this.maxTime = maxTime;
62 this.ageOfYoungest = ageOfYoungest;
63
64 double delta = (maxTime - minTime) / (binCount - 1);
65
66 Set<Set<String>> fromSets = new HashSet<Set<String>>();
67
68 // if a particular set of from states is specified then use them
69 if (fromStates.size() > 0) {
70 if (iterateFrom) {
71 for (String state : fromStates) {
72 Set<String> set = new HashSet<String>();
73 set.add(state);
74 fromSets.add(set);
75 }
76 } else {
77 fromSets.add(fromStates);
78 }
79 }
80
81 // if a particular set of to states is specified then use them
82 Set<Set<String>> toSets = new HashSet<Set<String>>();
83 if (toStates.size() > 0) {
84 if (iterateTo) {
85 for (String state : toStates) {
86 Set<String> set = new HashSet<String>();
87 set.add(state);
88 toSets.add(set);
89 }
90 } else {
91 toSets.add(toStates);
92 }
93 }
94
95 Pattern pattern = Pattern.compile("\\[([^:]+):([^:]+):([^\\]]+)\\]");
96 Set<String> allStates = new HashSet<String>();
97
98 if (fromSets.size() == 0 || toSets.size() == 0) {
99 // from or to states have not been specified so parse file to get full set.
100 BufferedReader reader = new BufferedReader(new FileReader(inputFileName));
101
102 String line = reader.readLine();
103 while (line != null && line.startsWith("#")) {
104 line = reader.readLine();
105 }
106
107 // read heading line
108 line = reader.readLine();
109
110 // read next line
111 line = reader.readLine();
112
113 while (line != null) {
114 String[] columns = line.split("\t");
115 if (columns.length == 3) {
116 Matcher matcher = pattern.matcher(columns[2]);
117 while (matcher.find()) {
118 String fromState = matcher.group(1);
119 allStates.add(fromState);
120 String toState = matcher.group(2);
121 allStates.add(toState);
122 }
123 }
124
125 line = reader.readLine();
126 }
127
128 reader.close();
129 }
130
131 if (fromStates.size() == 0) {
132 // if particular from states have not been specified, use them all
133 if (iterateFrom) {
134 for (String state : allStates) {
135 Set<String> set = new HashSet<String>();
136 set.add(state);
137 fromSets.add(set);
138 }
139 } else {
140 fromSets.add(allStates);
141 }
142 }
143
144 if (toStates.size() == 0) {
145 // if particular to states have not been specified, use them all
146 if (iterateTo) {
147 for (String state : allStates) {
148 Set<String> set = new HashSet<String>();
149 set.add(state);
150 toSets.add(set);
151 }
152 } else {
153 toSets.add(allStates);
154 }
155 }
156
157 int fromSetCount = fromSets.size();
158 int toSetCount = toSets.size();
159
160 int[][][] bins = new int[fromSetCount][toSetCount][binCount];
161
162 Set<Double>[][] allTimes = new Set[fromSetCount][toSetCount];
163 for (int i = 0; i < fromSetCount; ++i) {
164 for (int j = 0; j < toSetCount; ++j) {
165 allTimes[i][j] = new HashSet<Double>();
166 }
167 }
168
169 int index = 0;
170 Map<Set<String>, Integer> fromSetIndices = new HashMap<Set<String>, Integer>();
171 for (Set<String> fromSet : fromSets) {
172 fromSetIndices.put(fromSet, index);
173 index++;
174 }
175
176 index = 0;
177 Map<Set<String>, Integer> toSetIndices = new HashMap<Set<String>, Integer>();
178 for (Set<String> toSet : toSets) {
179 toSetIndices.put(toSet, index);
180 index++;
181 }
182
183 BufferedReader reader = new BufferedReader(new FileReader(inputFileName));
184
185 String line = reader.readLine();
186 while (line != null && line.startsWith("#")) {
187 line = reader.readLine();
188 }
189
190 // read heading line
191 line = reader.readLine();
192
193 // read next line
194 line = reader.readLine();
195
196 while (line != null) {
197 String[] columns = line.split("\t");
198 if (columns.length == 3) {
199 int state = Integer.parseInt(columns[0]);
200 int count = (int)Double.parseDouble(columns[1]);
201
202 if (state >= burnin) {
203 Matcher matcher = pattern.matcher(columns[2]);
204 while (matcher.find()) {
205 String fromState = matcher.group(1);
206 String toState = matcher.group(2);
207 String timeString = matcher.group(3);
208
209 Set<String> fromSet = null;
210 for (Set<String> set : fromSets) {
211 if (set.contains(fromState)) {
212 fromSet = set;
213 break;
214 }
215 }
216 if (fromSet != null) {
217 int fromIndex = fromSetIndices.get(fromSet);
218
219 Set<String> toSet = null;
220 for (Set<String> set : toSets) {
221 if (set.contains(toState)) {
222 toSet = set;
223 break;
224 }
225 }
226
227 if (toSet != null) {
228
229 int toIndex = toSetIndices.get(toSet);
230
231 double time = Double.parseDouble(timeString);
232 if (!backwardsTime) {
233 time = ageOfYoungest - time;
234 }
235
236 (allTimes[fromIndex][toIndex]).add(time);
237
238 double binTime = minTime;
239 int bin = -1;
240 while (time > binTime) {
241 binTime += delta;
242 bin ++;
243 }
244 try {
245 bins[fromIndex][toIndex][bin] ++;
246 } catch (Exception e) {
247 System.err.println("Caught error: " + e.getMessage());
248 System.err.println(fromState + " ->" + toState + ": " + timeString);
249 System.err.println("Min time: " + minTime);
250 System.err.println("Max time: " + maxTime);
251 System.err.println("Bin est : " + bin);
252 System.err.println("Delta : " + delta);
253 }
254 }
255 }
256 // System.out.println(fromState + " ->" + toState + ": " + timeString);
257 }
258 }
259 }
260
261 line = reader.readLine();
262 }
263
264 reader.close();
265
266 boolean allToAllCounts = false;
267
268 boolean useBinning = true;
269
270 System.out.print("time");
271 for (Set<String> fromSet : fromSets) {
272 String fromLabel = "all";
273 if (fromSet.size() == 1) {
274 fromLabel = fromSet.toArray(new String[1])[0];
275 } else if (!fromSet.equals(allStates)) {
276 StringBuilder sb = new StringBuilder("{");
277 boolean first = true;
278 for (String state : fromSet) {
279 if (!first) {
280 sb.append(",");
281 } else {
282 first = false;
283 }
284 sb.append(state);
285 }
286 sb.append("}");
287 fromLabel = sb.toString();
288 }
289
290 for (Set<String> toSet : toSets) {
291 String toLabel = "all";
292 if (toSet.size() == 1) {
293 toLabel = toSet.toArray(new String[1])[0];
294 } else if (!toSet.equals(allStates)) {
295 StringBuilder sb = new StringBuilder("{");
296 boolean first = true;
297 for (String state : toSet) {
298 if (!first) {
299 sb.append(",");
300 } else {
301 first = false;
302 }
303 sb.append(state);
304 }
305 sb.append("}");
306 toLabel = sb.toString();
307 }
308 allToAllCounts = (fromLabel.equals("all") && toLabel.equals("all"));
309 if (fromSet.size() > 1 || toSet.size() > 1 || !fromSet.equals(toSet)) {
310 System.out.print("\t" + fromLabel + "->" + toLabel);
311 }
312 }
313 }
314 System.out.println();
315
316
317 if (useBinning) {
318 double time = minTime;
319 for (int bin = 0; bin < binCount; bin++) {
320 System.out.print(time);
321
322 for (Set<String> fromSet : fromSets) {
323 int fromIndex = fromSetIndices.get(fromSet);
324
325 for (Set<String> toSet : toSets) {
326 int toIndex = toSetIndices.get(toSet);
327 if (fromSet.size() > 1 || toSet.size() > 1 || !fromSet.equals(toSet)) {
328 System.out.print("\t" + bins[fromIndex][toIndex][bin]);
329 }
330 }
331 }
332 System.out.println();
333
334 time += delta;
335 }
336 } else {
337 for (Set<String> fromSet : fromSets) {
338 int fromIndex = fromSetIndices.get(fromSet);
339 for (Set<String> toSet: toSets) {
340 int toIndex = toSetIndices.get(toSet);
341
342 for (Double time : (allTimes[fromIndex][toIndex])) {
343 System.out.println(time);
344 }
345 }
346 }
347 }
348 }
349
350 public static void printUsage(Arguments arguments) {
351
352 arguments.printUsage("jumphistoryanalyser", "<input-file-name> [<output-file-name>]");
353 System.out.println();
354 System.out.println(" Example: jumphistoryanalyser -burnin 100000 -min 1950 -max 2010 -mrsd 2009.9 jumps.txt");
355 System.out.println(" Example: jumphistoryanalyser -burnin 100000 -from \"usa\" -to \"uk,fr\" -min 1950 -max 2010 -mrsd 2009.9 jumps.txt");
356 System.out.println();
357 }
358
359
360 public static void main(String[] args) {
361 String inputFileName = null;
362
363
364 // printTitle();
365
366 Arguments arguments = new Arguments(
367 new Arguments.Option[]{
368 new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"),
369 new Arguments.StringOption("from", "from_states", "set of 'from' states to limit the history [default all states]"),
370 new Arguments.StringOption("to", "to_states", "set of 'to' states to limit the history [default all states]"),
371 new Arguments.Option("iterateFrom", "iterate over 'from' states [default combine states]"),
372 new Arguments.Option("iterateTo", "iterate over 'to' states [default combine states]"),
373 new Arguments.Option("backwardsTime", "time runs backwards [default false]"),
374 new Arguments.IntegerOption("bins", "the number of discrete bins [default 100]"),
375 new Arguments.RealOption("min", "the minimum bound of the time range"),
376 new Arguments.RealOption("max", "the maximum bound of the time range"),
377 new Arguments.RealOption("mrsd", "the date of the most recently sampled tip"),
378 new Arguments.Option("help", "option to print this message"),
379 });
380
381 try {
382 arguments.parseArguments(args);
383 } catch (Arguments.ArgumentException ae) {
384 System.err.println(ae);
385 printUsage(arguments);
386 System.exit(1);
387 }
388
389 if (arguments.hasOption("help")) {
390 printUsage(arguments);
391 System.exit(0);
392 }
393
394 int burnin = -1;
395 if (arguments.hasOption("burnin")) {
396 burnin = arguments.getIntegerOption("burnin");
397 }
398
399 int binCount = 100;
400 if (arguments.hasOption("bins")) {
401 binCount = arguments.getIntegerOption("bins");
402 }
403
404 double minTime = arguments.getRealOption("min");
405 double maxTime = arguments.getRealOption("max");
406
407 if (minTime >= maxTime) {
408 System.err.println("The minimum time must be less than the maximum time");
409 printUsage(arguments);
410 System.exit(1);
411 }
412 double mrsd = arguments.getRealOption("mrsd");
413
414 Set<String> fromStates = new HashSet<String>();
415 Set<String> toStates = new HashSet<String>();
416
417 if (arguments.hasOption("from")) {
418 String stateString = arguments.getStringOption("from");
419 String[] states = stateString.split("[\"\\s,]");
420 for (String state : states) {
421 if (state.length() > 0) {
422 fromStates.add(state);
423 }
424 }
425 }
426
427 if (arguments.hasOption("to")) {
428 String stateString = arguments.getStringOption("to");
429 String[] states = stateString.split("[\"\\s,]");
430 for (String state : states) {
431 if (state.length() > 0) {
432 toStates.add(state);
433 }
434 }
435 }
436
437 boolean iterateFrom = arguments.hasOption("iterateFrom");
438 boolean iterateTo = arguments.hasOption("iterateTo");
439
440 boolean backwardsTime = arguments.hasOption("backwardsTime");
441
442 final String[] args2 = arguments.getLeftoverArguments();
443
444 switch (args2.length) {
445 case 1:
446 inputFileName = args2[0];
447 break;
448 default: {
449 System.err.println("Unknown option: " + args2[2]);
450 System.err.println();
451 printUsage(arguments);
452 System.exit(1);
453 }
454 }
455
456 // command line options to follow shortly...
457 try {
458 JumpHistoryAnalyser jumpHistory = new JumpHistoryAnalyser(
459 inputFileName,
460 fromStates,
461 toStates,
462 iterateFrom,
463 iterateTo,
464 burnin,
465 binCount,
466 minTime,
467 maxTime,
468 backwardsTime,
469 mrsd
470 );
471 } catch (IOException e) {
472 e.printStackTrace();
473 } catch (ImportException e) {
474 e.printStackTrace();
475 } catch (TraceException e) {
476 e.printStackTrace();
477 }
478
479 System.exit(0);
480 }
481 }
482