Debian Codegraph @

src/dr/app/tools/LogCombiner.java

raw symbols SCIP
1 /*
2 * LogCombiner.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.app.tools;
27
28 import dr.app.beast.BeastVersion;
29 import dr.app.util.Arguments;
30 import dr.evolution.io.Importer;
31 import dr.evolution.io.NexusImporter;
32 import dr.evolution.io.TreeImporter;
33 import dr.evolution.tree.MutableTree;
34 import dr.evolution.tree.NodeRef;
35 import dr.evolution.tree.Tree;
36 import dr.evolution.util.Taxon;
37 import dr.util.Version;
38 import jam.console.ConsoleApplication;
39
40 import javax.swing.*;
41 import java.io.*;
42 import java.text.DecimalFormat;
43 import java.text.DecimalFormatSymbols;
44 import java.util.HashMap;
45 import java.util.Iterator;
46 import java.util.Locale;
47 import java.util.Map;
48 import java.util.regex.Matcher;
49 import java.util.regex.Pattern;
50
51 /**
52 * @author Andrew Rambaut
53 * @author Alexei Drummond
54 * @version $Id:$
55 */
56 public class LogCombiner {
57
58 private final static Version version = new BeastVersion();
59
60 public LogCombiner(long[] burnins, long resample, String[] inputFileNames, String outputFileName, boolean treeFiles,
61 boolean convertToDecimal, boolean stripAnnotations,
62 boolean renumberOutput, boolean useScale, double scale) throws IOException {
63
64 System.out.println("Creating combined " + (treeFiles ? "tree" : "log") + " file: '" + outputFileName + "'");
65
66 if (convertToDecimal) {
67 System.out.println("Converting to decimal.");
68 }
69
70 if (treeFiles && stripAnnotations) {
71 System.out.println("Stripping annotations from trees.");
72 }
73
74 if (renumberOutput) {
75 System.out.println("Renumbering output.");
76 }
77
78 if (useScale) {
79 System.out.println("Rescaling using scale factor: " + scale);
80 }
81
82 System.out.println();
83
84 PrintWriter writer = new PrintWriter(new FileOutputStream(outputFileName));
85
86 boolean firstFile = true;
87 boolean firstTree = true;
88 long stateCount = (renumberOutput ? -1 : 0);
89 long stateStep = -1;
90 int columnCount = 0;
91
92 String[] titles = null;
93
94 System.out.println();
95 for (int i = 0; i < inputFileNames.length; i++) {
96 File inputFile = new File(inputFileNames[i]);
97
98 if (!inputFile.exists()) {
99 System.err.println(inputFileNames[i] + " does not exist!");
100 return;
101 } else if (inputFile.isDirectory()) {
102 System.err.println(inputFileNames[i] + " is a directory.");
103 return;
104 }
105
106 long burnin = burnins[0];
107 if (burnins.length > i) {
108 burnin = burnins[i];
109 }
110
111 if (burnin > 0) {
112 System.out.print("Combining file: '" + inputFileNames[i] + "' removing burnin: " + burnin);
113 } else {
114 System.out.print("Combining file: '" + inputFileNames[i] + "' without removing burnin");
115 }
116
117 if (resample > 0) {
118 System.out.print(", resampling with frequency: " + resample);
119 }
120
121 if (useScale) {
122 System.out.println(", rescaling by: " + scale);
123 } else {
124 System.out.println();
125 }
126
127 if (treeFiles) {
128
129 TreeImporter importer = new NexusImporter(new FileReader(inputFile), stripAnnotations);
130 try {
131 while (importer.hasTree()) {
132 Tree tree = importer.importNextTree();
133 if (firstTree) {
134 startLog(tree, writer);
135 firstTree = false;
136 }
137
138 String name = tree.getId();
139 if (name == null) {
140 System.err.println("ERROR: Trees do not give state numbers as tree attributes.");
141 return;
142 }
143
144 // split on underscore in STATE_xxxx
145 String[] bits = name.split("_");
146 long state = Long.parseLong(bits[1]);
147
148 if (stateStep < 0 && state > 0) {
149 stateStep = state;
150 }
151
152 if (state >= burnin) {
153 if (stateStep > 0) {
154 if (!renumberOutput) {
155 stateCount += stateStep;
156 } else {
157 stateCount += 1;
158 }
159 }
160
161 if (resample >= 0) {
162 if (resample % stateStep != 0) {
163 System.err.println("ERROR: Resampling frequency is not a multiple of existing sampling frequency");
164 return;
165 }
166 }
167
168 boolean logThis;
169 if (resample < 0) {
170 // not resampling, log every state
171 logThis=true;
172 } else if (!renumberOutput) {
173 // resampling but not renumbering
174 logThis=(stateCount % resample == 0);
175 } else {
176 logThis=(stateCount*stateStep % resample == 0);
177 }
178
179 long stateLineEntry;
180 if (!renumberOutput){
181 stateLineEntry=stateCount;
182 } else {
183 stateLineEntry=stateCount/(resample/stateStep);
184 }
185
186 if (logThis){
187 writeTree(stateLineEntry, tree, convertToDecimal, writer);
188 }
189
190 }
191 }
192 } catch (Importer.ImportException e) {
193 System.err.println("Error Parsing Input Tree: " + e.getMessage());
194 return;
195 }
196
197 } else {
198 BufferedReader reader = new BufferedReader(new FileReader(inputFile));
199 //int lineCount = 1;
200 String line = reader.readLine();
201
202 // lines starting with [ are ignored, assuming comments in MrBayes file
203 // lines starting with # are ignored, assuming comments in Migrate or BEAST file
204 while (line.startsWith("[") || line.startsWith("#")) {
205
206 line = reader.readLine();
207 }
208
209
210 if (firstFile) {
211 titles = line.split("\t");
212 writer.println(line);
213 } else {
214 String[] newTitles = line.split("\t");
215 if (newTitles.length != titles.length) {
216 System.err.println("ERROR: The number of columns in file, " + inputFileNames[i] + ", does not match that of the first file");
217 return;
218 }
219 for (int k = 0; k < newTitles.length; k++) {
220 if (!newTitles[k].equals(titles[k])) {
221 System.err.println("WARNING: The column heading, " + newTitles[k] + " in file, " + inputFileNames[i] + ", does not match the first file's heading, " + titles[k]);
222 }
223 }
224 }
225 line = reader.readLine();
226 //lineCount++;
227
228 while (line != null) {
229 String[] parts = line.split("\t");
230
231 long state = -1;
232
233 boolean skip = false;
234 try {
235 state = Long.parseLong(parts[0]);
236 } catch (NumberFormatException nfe) {
237 skip = true;
238 }
239
240 if (!skip) {
241 if (stateStep < 0 && state > 0) {
242 stateStep = state;
243 columnCount = parts.length;
244 }
245
246 // if the columnCount is not the same then perhaps the line is corrupt so skip it.
247 if (state >= burnin && parts.length == columnCount) {
248 for (int j = 1; j < parts.length; j++) {
249 try {
250 if (!parts[j].startsWith("{")) {
251 // complex log values start with a curly bracket - otherwise attempt to parse
252 // it as a number. If it fails, skip the line as a possible corruption.
253
254 // attempt to convert the column value...
255 double value = Double.valueOf(parts[j]);
256 }
257 } catch (NumberFormatException nfe) {
258 skip = true;
259 break;
260 }
261 }
262
263 if (!skip) {
264
265 if (stateStep > 0) {
266 if (!renumberOutput) {
267 stateCount += stateStep;
268 } else {
269 stateCount += 1;
270 }
271 }
272
273 if (resample >= 0) {
274 if (resample % stateStep != 0) {
275 System.err.println("ERROR: Resampling frequency is not a multiple of existing sampling frequency");
276 return;
277 }
278 }
279
280 boolean logThis;
281 if (resample < 0) {
282 logThis = true;
283 } else if (!renumberOutput){
284 logThis = (stateCount % resample == 0);
285 } else {
286 logThis = ((stateCount * stateStep) % resample == 0);
287 }
288
289 long stateLineEntry;
290 if (!renumberOutput){
291 stateLineEntry = stateCount;
292 } else {
293
294 // System.out.println("stateCount: " + stateCount);
295 // System.out.println("resample: " + resample);
296 // System.out.println("stateStep: " + stateStep);
297 // System.out.println("resample / stateStep: " + (resample / stateStep));
298
299 stateLineEntry = stateCount / (resample / stateStep);
300 }
301
302 if (logThis) {
303 writer.print(stateLineEntry);
304 for (int j = 1; j < parts.length; j++) {
305 String value = parts[j];
306
307 if (useScale) {
308 if (titles[j].equals("clock.rate") || titles[j].startsWith("skyline.popSize")) {
309 value = reformatNumbers(value, convertToDecimal, true, 1.0 / scale);
310 } else if (titles[j].equals("treeModel.rootHeight")) {
311 value = reformatNumbers(value, convertToDecimal, true, scale);
312 }
313 } else if (convertToDecimal) {
314 value = reformatNumbers(value, convertToDecimal, false, 1.0);
315 }
316 writer.print("\t" + value);
317 }
318 writer.println();
319 }
320 }
321
322 }
323 }
324 line = reader.readLine();
325 //lineCount++;
326 }
327 }
328
329 firstFile = false;
330 }
331
332 if (treeFiles) {
333 stopLog(writer);
334 }
335 writer.close();
336 }
337
338 private void rescaleTree(Tree tree, double scale) {
339 if (tree instanceof MutableTree) {
340 MutableTree mutableTree = (MutableTree) tree;
341
342 for (int i = 0; i < tree.getNodeCount(); i++) {
343 NodeRef node = tree.getNode(i);
344 if (node != tree.getRoot()) {
345 double length = tree.getBranchLength(node);
346 mutableTree.setBranchLength(node, length * scale);
347 }
348 }
349 } else {
350 throw new IllegalArgumentException("Tree not mutable");
351 }
352 }
353
354 private final Map<String, Integer> taxonMap = new HashMap<String, Integer>();
355
356 private void startLog(Tree tree, PrintWriter writer) {
357
358 int taxonCount = tree.getTaxonCount();
359 writer.println("#NEXUS");
360 writer.println("");
361 writer.println("Begin taxa;");
362 writer.println("\tDimensions ntax=" + taxonCount + ";");
363 writer.println("\tTaxlabels");
364 for (int i = 0; i < taxonCount; i++) {
365 String id = tree.getTaxon(i).getId();
366 if (id.matches(NexusExporter.SPECIAL_CHARACTERS_REGEX)) {
367 id = "'" + id + "'";
368 }
369 writer.println("\t\t" + id);
370 }
371 writer.println("\t\t;");
372 writer.println("End;");
373 writer.println("");
374 writer.println("Begin trees;");
375
376 // This is needed if the trees use numerical taxon labels
377 writer.println("\tTranslate");
378 for (int i = 0; i < taxonCount; i++) {
379 int k = i + 1;
380 Taxon taxon = tree.getTaxon(i);
381 taxonMap.put(taxon.getId(), k);
382 String id = taxon.getId();
383 if (id.matches(NexusExporter.SPECIAL_CHARACTERS_REGEX)) {
384 id = "'" + id + "'";
385 }
386
387 writer.println("\t\t" + k + " " + id + (k < taxonCount ? "," : ""));
388 }
389 writer.println("\t\t;");
390 }
391
392 private void writeTree(long state, Tree tree, boolean convertToDecimal, PrintWriter writer) {
393
394 StringBuffer buffer = new StringBuffer("tree STATE_");
395 buffer.append(state);
396 // Double lnP = (Double) tree.getAttribute("lnP");
397 // if (lnP != null) {
398 // buffer.append(" [&lnP=").append(lnP).append("]");
399 // }
400
401 boolean hasAttribute = false;
402 Iterator iter = tree.getAttributeNames();
403 while (iter != null && iter.hasNext()) {
404 String name = (String) iter.next();
405 Object value = tree.getAttribute(name);
406
407 if (!hasAttribute) {
408 buffer.append(" [&");
409 hasAttribute = true;
410 } else {
411 buffer.append(",");
412 }
413
414 buffer.append(name).append("=").append(formatValue(value));
415 }
416
417 if (hasAttribute) {
418 buffer.append("]");
419 }
420
421 buffer.append(" = [&R] ");
422
423 writeTree(tree, tree.getRoot(), taxonMap, convertToDecimal, buffer);
424
425 buffer.append(";");
426 writer.println(buffer.toString());
427 }
428
429 private String formatValue(Object value) {
430 if( value instanceof String ) {
431 return (String) value;
432 } else if (value instanceof Object[] ) {
433 String val = "{";
434 for( Object v : (Object[]) value ) {
435 val += formatValue(v);
436 val += ',';
437 }
438 return val.substring(0, val.length() - 1 ) + '}';
439 }
440 return value.toString();
441 }
442
443 private void writeTree(Tree tree, NodeRef node, Map taxonMap, boolean convertToDecimal, StringBuffer buffer) {
444
445 NodeRef parent = tree.getParent(node);
446
447 if (tree.isExternal(node)) {
448 String taxon = tree.getNodeTaxon(node).getId();
449 Integer taxonNo = (Integer) taxonMap.get(taxon);
450 if (taxonNo == null) {
451 throw new IllegalArgumentException("Taxon, " + taxon + ", not recognized from first tree file");
452 }
453 buffer.append(taxonNo);
454 } else {
455 buffer.append("(");
456 writeTree(tree, tree.getChild(node, 0), taxonMap, convertToDecimal, buffer);
457 for (int i = 1; i < tree.getChildCount(node); i++) {
458 buffer.append(",");
459 writeTree(tree, tree.getChild(node, i), taxonMap, convertToDecimal, buffer);
460 }
461 buffer.append(")");
462 }
463
464 boolean hasAttribute = false;
465 Iterator iter = tree.getNodeAttributeNames(node);
466 while (iter != null && iter.hasNext()) {
467 String name = (String) iter.next();
468 Object value = tree.getNodeAttribute(node, name);
469
470 if (!hasAttribute) {
471 buffer.append("[&");
472 hasAttribute = true;
473 } else {
474 buffer.append(",");
475 }
476
477 buffer.append(name).append("=").append(formatValue(value));
478 }
479
480 if (hasAttribute) {
481 buffer.append("]");
482 }
483
484 if (parent != null) {
485 buffer.append(":");
486 double length = tree.getBranchLength(node);
487 buffer.append(convertToDecimal ? decimalFormatter.format(length) : scientificFormatter.format(length));
488 }
489 }
490
491 private void stopLog(PrintWriter writer) {
492 writer.println("End;");
493 }
494
495 private static final DecimalFormat decimalFormatter = new DecimalFormat("#.############", new DecimalFormatSymbols(Locale.US));
496 private static final DecimalFormat scientificFormatter = new DecimalFormat("#.############E0", new DecimalFormatSymbols(Locale.US));
497
498 private String reformatNumbers(String line, boolean convertDecimal, boolean useScale, double scale) {
499 StringBuffer outLine = new StringBuffer();
500
501 Pattern pattern = Pattern.compile("\\d+\\.\\d+(E[\\-\\d\\.]+)?");
502 Matcher matcher = pattern.matcher(line);
503
504 int lastEnd = 0;
505 while (matcher.find()) {
506 int start = matcher.start();
507 String token = matcher.group();
508 double value = Double.parseDouble(token);
509 if (useScale) {
510 value *= scale;
511 }
512 String outToken = (convertDecimal ? decimalFormatter.format(value) : scientificFormatter.format(value));
513
514 outLine.append(line.substring(lastEnd, start));
515 outLine.append(outToken);
516
517 lastEnd = matcher.end();
518 }
519 outLine.append(line.substring(lastEnd));
520 return outLine.toString();
521 }
522
523 public static void printTitle() {
524 System.out.println();
525 centreLine("LogCombiner " + version.getVersionString() + ", " + version.getDateString(), 60);
526 centreLine("MCMC Output Combiner", 60);
527 centreLine("by", 60);
528 centreLine("Andrew Rambaut and Alexei J. Drummond", 60);
529 System.out.println();
530 centreLine("Institute of Evolutionary Biology", 60);
531 centreLine("University of Edinburgh", 60);
532 centreLine("[email protected]", 60);
533 System.out.println();
534 centreLine("Department of Computer Science", 60);
535 centreLine("University of Auckland", 60);
536 centreLine("[email protected]", 60);
537 System.out.println();
538 System.out.println();
539 }
540
541 public static void centreLine(String line, int pageWidth) {
542 int n = pageWidth - line.length();
543 int n1 = n / 2;
544 for (int i = 0; i < n1; i++) {
545 System.out.print(" ");
546 }
547 System.out.println(line);
548 }
549
550
551 public static void printUsage(Arguments arguments) {
552
553 arguments.printUsage("logcombiner", "<input-file-name1> [<input-file-name2> ...] <output-file-name>");
554 System.out.println();
555 System.out.println(" Example: logcombiner test1.log test2.log combined.log");
556 System.out.println(" Example: logcombiner -burnin 10000 test1.log test2.log combined.log");
557 System.out.println();
558
559 }
560
561 //Main method
562 public static void main(String[] args) throws IOException {
563
564 // There is a major issue with languages that use the comma as a decimal separator.
565 // To ensure compatibility between programs in the package, enforce the US locale.
566 Locale.setDefault(Locale.US);
567
568 boolean treeFiles;
569 boolean convertToDecimal;
570 boolean stripAnnotations = false;
571 boolean renumberOutput;
572
573 long burnin;
574 long resample = -1;
575 double scale = 1.0;
576 boolean useScale = false;
577
578 if (args.length == 0) {
579 System.setProperty("com.apple.macos.useScreenMenuBar", "true");
580 System.setProperty("apple.laf.useScreenMenuBar", "true");
581 System.setProperty("apple.awt.showGrowBox", "true");
582
583 java.net.URL url = LogCombiner.class.getResource("/images/utility.png");
584 javax.swing.Icon icon = null;
585
586 if (url != null) {
587 icon = new javax.swing.ImageIcon(url);
588 }
589
590 final String versionString = version.getVersionString();
591 String nameString = "LogCombiner " + versionString;
592 String aboutString = "<html><center><p>" + versionString + ", " + version.getDateString() + "</p>" +
593 "<p>by<br>" +
594 "Andrew Rambaut and Alexei J. Drummond</p>" +
595 "<p>Institute of Evolutionary Biology, University of Edinburgh<br>" +
596 "<a href=\"mailto:[email protected]\">[email protected]</a></p>" +
597 "<p>Department of Computer Science, University of Auckland<br>" +
598 "<a href=\"mailto:[email protected]\">[email protected]</a></p>" +
599 "<p>Part of the BEAST package:<br>" +
600 "<a href=\"http://beast.community\">http://beast.community</a></p>" +
601 "</center></html>";
602
603 ConsoleApplication consoleApp = new ConsoleApplication(nameString, aboutString, icon, true);
604
605 printTitle();
606
607 LogCombinerDialog dialog = new LogCombinerDialog(new JFrame());
608
609 if (!dialog.showDialog("LogCombiner " + versionString)) {
610 return;
611 }
612
613 treeFiles = dialog.isTreeFiles();
614 convertToDecimal = dialog.convertToDecimal();
615 renumberOutput = dialog.renumberOutputStates();
616 if (dialog.isResampling()) {
617 resample = dialog.getResampleFrequency();
618 }
619
620 String[] inputFiles = dialog.getFileNames();
621 long[] burnins = dialog.getBurnins();
622
623 String outputFileName = dialog.getOutputFileName();
624
625 if (outputFileName == null) {
626 System.err.println("No output file specified");
627 }
628
629 try {
630 new LogCombiner(burnins, resample, inputFiles, outputFileName, treeFiles, convertToDecimal,
631 stripAnnotations, renumberOutput, useScale, scale);
632
633 } catch (Exception ex) {
634 System.err.println("Exception: " + ex.getMessage());
635 ex.printStackTrace();
636 }
637 System.out.println("Finished - Quit program to exit.");
638 while (true) {
639 try {
640 Thread.sleep(1000);
641 } catch (InterruptedException e) {
642 e.printStackTrace();
643 }
644 }
645 } else {
646 printTitle();
647
648 Arguments arguments = new Arguments(
649 new Arguments.Option[]{
650 new Arguments.Option("trees", "use this option to combine tree log files"),
651 new Arguments.Option("decimal", "this option converts numbers from scientific to decimal notation"),
652 new Arguments.LongOption("burnin", "the number of states to be considered as 'burn-in'"),
653 new Arguments.LongOption("resample", "resample the log files to this frequency " +
654 "(the original sampling frequency must be a factor of this value)"),
655 new Arguments.RealOption("scale", "a scaling factor that will multiply any time units by this value"),
656 new Arguments.Option("strip", "strip out all annotations (trees only)"),
657 new Arguments.Option("renumber", "this option renumbers output states consecutively"),
658 new Arguments.Option("help", "option to print this message")
659 });
660
661 try {
662 arguments.parseArguments(args);
663 } catch (Arguments.ArgumentException ae) {
664 System.out.println(ae);
665 printUsage(arguments);
666 System.exit(1);
667 }
668
669 if (arguments.hasOption("help")) {
670 printUsage(arguments);
671 System.exit(0);
672 }
673
674 treeFiles = arguments.hasOption("trees");
675
676 convertToDecimal = arguments.hasOption("decimal");
677
678 stripAnnotations = arguments.hasOption("strip");
679
680 renumberOutput = arguments.hasOption("renumber");
681
682 burnin = -1;
683 if (arguments.hasOption("burnin")) {
684 burnin = arguments.getLongOption("burnin");
685 }
686
687 resample = -1;
688 if (arguments.hasOption("resample")) {
689 resample = arguments.getLongOption("resample");
690 }
691
692 scale = 1.0;
693 useScale = false;
694 if (arguments.hasOption("scale")) {
695 scale = arguments.getRealOption("scale");
696 useScale = true;
697 }
698
699 String[] args2 = arguments.getLeftoverArguments();
700
701 if (args2.length < 2) {
702 System.err.println("Requires a minimum of 1 input filename and 1 output filename");
703 System.err.println();
704 printUsage(arguments);
705 System.exit(1);
706 }
707
708 String[] inputFileNames = new String[args2.length - 1];
709 System.arraycopy(args2, 0, inputFileNames, 0, inputFileNames.length);
710 String outputFileName = args2[args2.length - 1];
711
712 new LogCombiner(new long[]{burnin}, resample, inputFileNames, outputFileName, treeFiles, convertToDecimal,
713 stripAnnotations, renumberOutput, useScale, scale);
714
715 System.out.println("Finished.");
716 }
717
718 System.exit(0);
719 }
720 }
721