Debian Codegraph @

src/dr/app/tools/MixtureModelLogAnalyser.java

raw symbols SCIP
1 /*
2 * MixtureModelLogAnalyser.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.app.util.Utils;
31 import dr.inference.trace.PathSamplingAnalysis;
32 import dr.inference.trace.TraceException;
33 import dr.util.Attribute;
34 import dr.util.FileHelpers;
35 import dr.util.Version;
36 import dr.xml.AbstractXMLObjectParser;
37 import dr.xml.AttributeRule;
38 import dr.xml.ElementRule;
39 import dr.xml.StringAttributeRule;
40 import dr.xml.XMLObject;
41 import dr.xml.XMLObjectParser;
42 import dr.xml.XMLParseException;
43 import dr.xml.XMLSyntaxRule;
44
45 import java.io.*;
46 import java.util.*;
47
48 /**
49 * @author Wai Lok Sibon Li
50 */
51
52 public class MixtureModelLogAnalyser {
53
54 private final static Version version = new BeastVersion();
55
56 public static final String MIXTURE_MODEL_LOG_ANALYSER = "mixtureModelLogAnalyser";
57 public static final String BURNIN = "burnin";
58 public static final String DISCRETE_VARIABLE = "discreteVariable";
59
60 public MixtureModelLogAnalyser(int burnin, String inputFileName, String outputFileName, String discreteVariableName
61 ) throws IOException, TraceException {
62
63 File parentFile = new File(inputFileName);
64
65 if (parentFile.isDirectory()) {
66 System.out.println("Analysing all log files below directory: " + inputFileName);
67 } else if (parentFile.isFile()) {
68 System.out.println("Analysing log file: " + inputFileName);
69 } else {
70 System.err.println(inputFileName + " does not exist!");
71 System.exit(0);
72 }
73
74 if (outputFileName != null) {
75 FileOutputStream outputStream = new FileOutputStream(outputFileName);
76 System.setOut(new PrintStream(outputStream));
77 }
78
79 analyze(parentFile, burnin, discreteVariableName);
80 }
81
82 /**
83 * Recursively analyzes log files.
84 *
85 * @param file the file to analyze (if this is a directory then the files within it are analyzed)
86 * @param burnin the burnin to use
87 * @param discreteVariableName tag for the name of the discrete variable
88 * @throws dr.inference.trace.TraceException
89 * if the trace file is in the wrong format or corrupted
90 */
91 private void analyze(File file, int burnin, String discreteVariableName) throws TraceException {
92
93 if (file.isFile()) {
94 try {
95
96 String name = file.getCanonicalPath();
97
98 report(name, burnin, discreteVariableName);
99
100 } catch (IOException e) {
101 //e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
102 }
103 } else {
104 File[] files = file.listFiles();
105 for (File f : files) {
106 if (f.isDirectory()) {
107 analyze(f, burnin, discreteVariableName);
108 } else if (f.getName().endsWith(".log")) {
109 analyze(f, burnin, discreteVariableName);
110 }
111 }
112 }
113 }
114
115
116 /**
117 * Recursively analyzes trees files.
118 *
119 * @param name the file to analyze (if this is a directory then the files within it are analyzed)
120 * @param burnin the burnin to use
121 * @param discreteVariableName tag for the name of the discrete variable
122 */
123 private void report(String name, int burnin, String discreteVariableName) {
124
125 try {
126 FileReader fileReader = new FileReader(new File(name));
127 BufferedReader br = new BufferedReader(fileReader);
128
129 String line;
130 String previousLine =null;
131 int discreteVariableIndex = -1;
132 Hashtable<String, Integer> hash = new Hashtable<String, Integer>();
133 while((line=br.readLine()) != null) {
134
135 if(line.matches("\\d+\\t.+")) {
136 String[] split = line.split("\t");
137 if(split[0].equals("0")) {
138 String[] headerSplit = previousLine.split("\t");
139 for(int i=0; i<headerSplit.length; i++) {
140 String s = headerSplit[i];
141 if(s.equals(discreteVariableName)) {
142 discreteVariableIndex = i;
143 }
144 }
145 }
146
147 if(Integer.parseInt(split[0])>=burnin) {
148 if(hash.containsKey(split[discreteVariableIndex])) {
149 hash.put(split[discreteVariableIndex], new Integer(hash.get(split[discreteVariableIndex]) + 1));
150 }
151 else {
152 hash.put(split[discreteVariableIndex], new Integer(1));
153 }
154 }
155 }
156
157 previousLine = line;
158 }
159
160 Vector<String> v = new Vector(hash.keySet());
161 Collections.sort(v);
162
163
164 System.out.print("name" + "\t");
165 for(String s : v) {
166
167 double state = Double.parseDouble(s);
168
169 if(Math.floor(state)!=state) {
170 throw new RuntimeException("State is not a whole number: " + state);
171 }
172
173 System.out.print("state " + (int) state + "\t");
174 }
175 System.out.print("\n" + name + "\t");
176 for (String aV : v) {
177 String element = aV;
178 System.out.print(hash.get(element) + "\t");
179 }
180 System.out.println();
181 br.close();
182 } catch (IOException e) {
183 System.err.println("Error Parsing Input log: " + e.getMessage());
184 }
185 }
186
187 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
188
189 public String getParserName() {
190 return MIXTURE_MODEL_LOG_ANALYSER;
191 }
192
193 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
194
195 try {
196
197 String inputFileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
198 String discreteVariableName = xo.getStringAttribute(DISCRETE_VARIABLE);
199
200 int burninLength = 0;
201 if (xo.hasAttribute(BURNIN)) {
202 burninLength = xo.getIntegerAttribute(BURNIN);
203 }
204
205 MixtureModelLogAnalyser mixtureModel = new MixtureModelLogAnalyser(burninLength, inputFileName, null, discreteVariableName);
206
207 return mixtureModel;
208
209 } catch (IOException ioe) {
210 throw new XMLParseException(ioe.getMessage());
211 } catch (TraceException te) {
212 throw new XMLParseException(te.getMessage());
213 }
214
215 }
216
217 //************************************************************************
218 // AbstractXMLObjectParser implementation
219 //************************************************************************
220
221 public String getParserDescription() {
222 return "Performs posterior probabilities calculations.";
223 }
224
225 public Class getReturnType() {
226 return MixtureModelLogAnalyser.class;
227 }
228
229 public XMLSyntaxRule[] getSyntaxRules() {
230 return rules;
231 }
232
233 private final XMLSyntaxRule[] rules = {
234 new StringAttributeRule(FileHelpers.FILE_NAME,
235 "The traceName of a BEAST log file (can not include trees, which should be logged separately"),
236 new StringAttributeRule(DISCRETE_VARIABLE,
237 "The tag name of the discrete variable"),
238 AttributeRule.newIntegerRule(BURNIN, true),
239 };
240
241 };
242
243 public static void printTitle() {
244 System.out.println();
245 centreLine("MixtureModelLogAnalyser " + version.getVersionString() + ", " + version.getDateString(), 60);
246 centreLine("MCMC Output analysis", 60);
247 centreLine("by", 60);
248 centreLine("Andrew Rambaut and Alexei J. Drummond", 60);
249 System.out.println();
250 centreLine("Institute of Evolutionary Biology", 60);
251 centreLine("University of Edinburgh", 60);
252 centreLine("[email protected]", 60);
253 System.out.println();
254 centreLine("Department of Computer Science", 60);
255 centreLine("University of Auckland", 60);
256 centreLine("[email protected]", 60);
257 System.out.println();
258 System.out.println();
259 }
260
261 public static void centreLine(String line, int pageWidth) {
262 int n = pageWidth - line.length();
263 int n1 = n / 2;
264 for (int i = 0; i < n1; i++) {
265 System.out.print(" ");
266 }
267 System.out.println(line);
268 }
269
270
271 public static void printUsage(Arguments arguments) {
272
273 arguments.printUsage("mixturemodelloganalyser", "[-burnin <burnin>][<input-file-name> [<output-file-name>]]");
274 System.out.println();
275 System.out.println(" Example: treelengthfinder test.log");
276 System.out.println(" Example: treelengthfinder -burnin 10000 -discreteVariable branchRates.distributionIndex trees.log out.txt");
277 System.out.println();
278
279 }
280
281 //Main method
282 public static void main(String[] args) throws IOException, TraceException {
283
284 printTitle();
285
286 Arguments arguments = new Arguments(
287 new Arguments.Option[]{
288 new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"),
289 new Arguments.StringOption("discreteVariable", "variable_name", "indicates the name of a variable that is actually discrete in nature"),
290 new Arguments.Option("help", "option to print this message")
291 });
292
293 try {
294 arguments.parseArguments(args);
295 } catch (Arguments.ArgumentException ae) {
296 System.out.println(ae);
297 printUsage(arguments);
298 System.exit(1);
299 }
300
301 if (arguments.hasOption("help")) {
302 printUsage(arguments);
303 System.exit(0);
304 }
305
306 int burnin = -1;
307 if (arguments.hasOption("burnin")) {
308 burnin = arguments.getIntegerOption("burnin");
309 }
310
311 String discreteVariableName = null;
312 if (arguments.hasOption("discreteVariable")) {
313 discreteVariableName = arguments.getStringOption("discreteVariable");
314 }
315
316 String inputFileName = null;
317 String outputFileName = null;
318
319 String[] args2 = arguments.getLeftoverArguments();
320
321 if (args2.length > 2) {
322 System.err.println("Unknown option: " + args2[2]);
323 System.err.println();
324 printUsage(arguments);
325 System.exit(1);
326 }
327
328 if (args2.length > 0) {
329 inputFileName = args2[0];
330 }
331 if (args2.length > 1) {
332 outputFileName = args2[1];
333 }
334
335 if (inputFileName == null) {
336 // No input file name was given so throw up a dialog box...
337 inputFileName = Utils.getLoadFileName("MixtureModelLogAnalyser " + version.getVersionString() + " - Select log file to analyse");
338 }
339
340 if(burnin==-1) {
341 System.out.println("Enter number of trees to burn-in (integer): ");
342 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
343 burnin = Integer.parseInt(br.readLine());
344 }
345 if(discreteVariableName==null) {
346 System.out.println("Enter name of discrete variable: ");
347 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
348 discreteVariableName = br.readLine();
349 }
350
351 new MixtureModelLogAnalyser(burnin, inputFileName, outputFileName, discreteVariableName/*, !shortReport, hpds, ess, stdErr, marginalLikelihood*/);
352
353 System.exit(0);
354 }
355 }