Debian Codegraph @

src/dr/inference/trace/TraceAnalysis.java

raw symbols SCIP
1 /*
2 * TraceAnalysis.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.inference.trace;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.text.DecimalFormat;
31 import java.util.List;
32
33 /**
34 * @author Alexei Drummond
35 * @version $Id: TraceAnalysis.java,v 1.23 2005/05/24 20:26:00 rambaut Exp $
36 */
37 public class TraceAnalysis {
38
39 /**
40 * @param fileName the name of the log file to analyze
41 * @param burnin the state to discard up to
42 * @return an array og analyses of the statistics in a log file.
43 * @throws java.io.IOException if general error reading file
44 * @throws TraceException if trace file in wrong format or corrupted
45 */
46 public static LogFileTraces analyzeLogFile(String fileName, long burnin) throws java.io.IOException, TraceException {
47
48 File file = new File(fileName);
49 LogFileTraces traces = new LogFileTraces(fileName, file);
50 traces.loadTraces();
51 traces.setBurnIn(burnin);
52
53 for (int i = 0; i < traces.getTraceCount(); i++) {
54 traces.analyseTrace(i);
55 }
56 return traces;
57 }
58
59 public static TraceList report(String fileName) throws java.io.IOException, TraceException {
60 return report(fileName, -1, null);
61 }
62
63 public static TraceList report(String fileName, int burnin, String likelihoodName) throws java.io.IOException, TraceException {
64 return report(fileName, burnin, likelihoodName, true);
65 }
66
67 public static TraceList report(String fileName, int inBurnin, String likelihoodName, boolean withStdError)
68 throws java.io.IOException, TraceException {
69
70 // int fieldWidth = 14;
71 // int firstField = 25;
72 // NumberFormatter formatter = new NumberFormatter(4);
73 // formatter.setPadding(true);
74 // formatter.setFieldWidth(fieldWidth);
75
76 File file = new File(fileName);
77
78 LogFileTraces traces = new LogFileTraces(fileName, file);
79 // if (traces == null) {
80 // throw new TraceException("Trace file is empty.");
81 // }
82 traces.loadTraces();
83
84 // traces.addTrace("R0", traces.getTraceIndex("bdss.psi"));
85
86 int burnin = inBurnin;
87 if (burnin == -1) {
88 burnin = (int) (traces.getMaxState() / 10);
89 }
90
91 traces.setBurnIn(burnin);
92
93 // System.out.println();
94 System.out.println("burnIn <= " + burnin + ", maxState = " + traces.getMaxState());
95 // System.out.println();
96
97 System.out.print("statistic");
98 String[] names;
99
100 if (!withStdError)
101 names = new String[]{"mean", "hpdLower", "hpdUpper", "ESS"};
102 else
103 names = new String[]{"mean", "stdErr", "median", "hpdLower", "hpdUpper", "ESS", "50hpdLower", "50hpdUpper"};
104
105 for (String name : names) {
106 System.out.print("\t" + name);
107 }
108 System.out.println();
109
110 int warning = 0;
111 for (int i = 0; i < traces.getTraceCount(); i++) {
112 traces.analyseTrace(i);
113 TraceCorrelation distribution = traces.getCorrelationStatistics(i);
114
115 double ess = distribution.getESS();
116 System.out.print(traces.getTraceName(i));
117 System.out.print("\t" + formattedNumber(distribution.getMean()));
118
119 if (withStdError) {
120 System.out.print("\t" + formattedNumber(distribution.getStdError()));
121 System.out.print("\t" + formattedNumber(distribution.getMedian()));
122 }
123
124 System.out.print("\t" + formattedNumber(distribution.getLowerHPD()));
125 System.out.print("\t" + formattedNumber(distribution.getUpperHPD()));
126
127 System.out.print("\t" + formattedNumber(ess));
128
129 if (withStdError) {
130 System.out.print("\t" + formattedNumber(distribution.getHpdLowerCustom()));
131 System.out.print("\t" + formattedNumber(distribution.getHpdUpperCustom()));
132 }
133
134 if (ess < 100) {
135 warning += 1;
136 System.out.println("\t" + "*");
137 } else {
138 System.out.println("\t");
139 }
140 }
141 System.out.println();
142
143 if (warning > 0) {
144 System.out.println(" * WARNING: The results of this MCMC analysis may be invalid as ");
145 System.out.println(" one or more statistics had very low effective sample sizes (ESS)");
146 }
147
148 if (likelihoodName != null) {
149 System.out.println();
150 int traceIndex = -1;
151 for (int i = 0; i < traces.getTraceCount(); i++) {
152 String traceName = traces.getTraceName(i);
153 if (traceName.equals(likelihoodName)) {
154 traceIndex = i;
155 break;
156 }
157 }
158
159 if (traceIndex == -1) {
160 throw new TraceException("Column '" + likelihoodName +
161 "' can not be found for marginal likelihood analysis.");
162 }
163
164 String analysisType = "aicm";
165 int bootstrapLength = 1000;
166
167 List<Double> sample = (List)traces.getValues(traceIndex);
168
169 MarginalLikelihoodAnalysis analysis = new MarginalLikelihoodAnalysis(sample,
170 traces.getTraceName(traceIndex), burnin, analysisType, bootstrapLength);
171
172 System.out.println(analysis.toString());
173 }
174
175 System.out.flush();
176 return traces;
177 }
178
179 public static void reportTrace(String fileName, long inBurnin, String traceName) throws IOException, TraceException {
180 File file = new File(fileName);
181
182 LogFileTraces traces = new LogFileTraces(fileName, file);
183 traces.loadTraces();
184 long burnin = inBurnin;
185 if (burnin == -1) {
186 burnin = traces.getMaxState() / 10;
187 }
188
189 traces.setBurnIn(burnin);
190
191 // System.out.println();
192 // System.out.println("burnIn <= " + burnin + ", maxState = " + traces.getMaxState());
193 // System.out.println();
194
195 // System.out.print("statistic");
196 // String[] names = new String[]{"mean", "stdErr", "median", "hpdLower", "hpdUpper", "50hpdLower", "50hpdUpper"};//, "ESS"};
197 //
198 // for (String name : names) {
199 // System.out.print("\t" + name);
200 // }
201 // System.out.println();
202
203 int id = traces.getTraceIndex(traceName);
204
205 traces.analyseTrace(id);
206 TraceCorrelation distribution = traces.getCorrelationStatistics(id);
207
208 double ess = distribution.getESS();
209 // System.out.print(traces.getTraceName(id) + "\t");
210 System.out.print(formattedNumber(distribution.getMean()) + "\t");
211
212
213 System.out.print(formattedNumber(distribution.getStdError()) + "\t");
214 System.out.print(formattedNumber(distribution.getMedian()) + "\t");
215
216
217 System.out.print(formattedNumber(distribution.getLowerHPD()) + "\t");
218 System.out.print(formattedNumber(distribution.getUpperHPD()) + "\t");
219
220 System.out.print(formattedNumber(distribution.getHpdLowerCustom()) + "\t");
221 System.out.print(formattedNumber(distribution.getHpdUpperCustom()) + "\t");
222 System.out.println();
223
224 // System.out.print(SummaryStatisticsPanel.formattedNumber(ess));
225
226 }
227
228 /**
229 * @param burnin the number of states of burnin or if -1 then use 10%
230 * @param filename the file name of the log file to report on
231 * @param drawHeader if true then draw header
232 * @param stdErr if true then report the standard deviation of the mean
233 * @param hpds if true then report 95% hpd upper and lower
234 * @param individualESSs minimum number of ESS with which to throw warning
235 * @param likelihoodName column name
236 * @return the traces loaded from given file to create this short report
237 * @throws java.io.IOException if general error reading file
238 * @throws TraceException if trace file in wrong format or corrupted
239 */
240 public static TraceList shortReport(String filename,
241 final int burnin, boolean drawHeader,
242 boolean hpds, boolean individualESSs, boolean stdErr,
243 String likelihoodName) throws java.io.IOException, TraceException {
244
245 TraceList traces = analyzeLogFile(filename, burnin);
246
247 long maxState = traces.getMaxState();
248
249 double minESS = Double.MAX_VALUE;
250
251 if (drawHeader) {
252 System.out.print("file\t");
253 for (int i = 0; i < traces.getTraceCount(); i++) {
254 String traceName = traces.getTraceName(i);
255 System.out.print(traceName + "\t");
256 if (stdErr)
257 System.out.print(traceName + " stdErr\t");
258 if (hpds) {
259 System.out.print(traceName + " hpdLower\t");
260 System.out.print(traceName + " hpdUpper\t");
261 }
262 if (individualESSs) {
263 System.out.print(traceName + " ESS\t");
264 }
265 }
266 System.out.print("minESS\t");
267 if (likelihoodName != null) {
268 System.out.print("marginal likelihood\t");
269 System.out.print("stdErr\t");
270 }
271 System.out.println("chainLength");
272 }
273
274 System.out.print(filename + "\t");
275 for (int i = 0; i < traces.getTraceCount(); i++) {
276 //TraceDistribution distribution = traces.getDistributionStatistics(i);
277 TraceCorrelation distribution = traces.getCorrelationStatistics(i);
278 System.out.print(distribution.getMean() + "\t");
279 if (stdErr)
280 System.out.print(distribution.getStdErrorOfMean() + "\t");
281 if (hpds) {
282 System.out.print(distribution.getLowerHPD() + "\t");
283 System.out.print(distribution.getUpperHPD() + "\t");
284 }
285 if (individualESSs) {
286 System.out.print(distribution.getESS() + "\t");
287 }
288 double ess = distribution.getESS();
289 if (ess < minESS) {
290 minESS = ess;
291 }
292 }
293
294 System.out.print(minESS + "\t");
295
296 if (likelihoodName != null) {
297 int traceIndex = -1;
298 for (int i = 0; i < traces.getTraceCount(); i++) {
299 String traceName = traces.getTraceName(i);
300 if (traceName.equals(likelihoodName)) {
301 traceIndex = i;
302 break;
303 }
304 }
305
306 if (traceIndex == -1) {
307 throw new TraceException("Column '" + likelihoodName + "' can not be found in file " + filename + ".");
308 }
309
310 String analysisType = "aicm";
311 int bootstrapLength = 1000;
312
313 List<Double> sample = (List)traces.getValues(traceIndex);
314
315 MarginalLikelihoodAnalysis analysis = new MarginalLikelihoodAnalysis(sample,
316 traces.getTraceName(traceIndex), burnin, analysisType, bootstrapLength);
317
318 System.out.print(analysis.getLogMarginalLikelihood() + "\t");
319 System.out.print(analysis.getBootstrappedSE() + "\t");
320 }
321
322 System.out.println(maxState);
323 return traces;
324 }
325
326 public static String formattedNumber(double value) {
327 DecimalFormat formatter = new DecimalFormat("0.####E0");
328 DecimalFormat formatter2 = new DecimalFormat("####0.####");
329
330 if (value > 0 && (Math.abs(value) < 0.01 || Math.abs(value) >= 100000.0)) {
331 return formatter.format(value);
332 } else return formatter2.format(value);
333 }
334
335 public static String formattedNumber(double value, int decimalPlaces) {
336 String pattern = "####0.";
337 for (int i = 0; i < decimalPlaces; i++) {
338 pattern += "#";
339 }
340 return new DecimalFormat(pattern).format(value);
341 }
342
343 static final String[] colNamesNumeric = {"mean", "stderr_of_mean", "stdev", "variance", "median", "min", "max",
344 "quantile1", "quantile3", "95_hpd_lower", "95_hpd_upper", "ACT", "ESS", "num_samples", "geometric_mean"};
345 static final String[] colNamesCategorical = {"mode", "mode_frequency", "mode_probability",
346 "unique_values", "95_credible_set"};
347
348 /**
349 * Output a tab-delimited result of the full statistic summary in a string,
350 * given a list of <code>TraceList</code> (log or combined trace).
351 * The rows are traces, columns are statistics.
352 * The left section of statistics is for numbers, the right for categorical values,
353 * if null or NA, then return empty string in that particular row and column.
354 *
355 * @param traceLists
356 * @return
357 */
358 public static String getStatisticSummary(List<TraceList> traceLists) {
359 StringBuffer buffer = new StringBuffer();
360
361 String[] colNames = colNamesNumeric;
362 if (TraceTypeUtils.anyCategorical(traceLists, null)) {
363 colNames = new String[colNamesNumeric.length + colNamesCategorical.length];
364 System.arraycopy(colNamesNumeric, 0, colNames, 0, colNamesNumeric.length);
365 System.arraycopy(colNamesCategorical, 0, colNames, colNamesNumeric.length, colNamesCategorical.length);
366 }
367
368 for (int i = 0; i < traceLists.size(); i++) {
369 TraceList tl = traceLists.get(i);
370 // trace list name
371 String prefix = "";
372 // add prefix to multi-log
373 if (traceLists.size() > 1) {
374 prefix = tl.getName() + ".";
375
376 // rm all spaces
377 prefix = prefix.replaceAll("\\s+", "");
378 // file extension
379 if (prefix.contains(".txt") || prefix.contains(".log"))
380 prefix = prefix.replaceAll("\\.txt|\\.log", "");
381 }
382
383 // write column names
384 if (i == 0) {
385 for (String colName : colNames) {
386 buffer.append("\t");
387 buffer.append(colName);
388 }
389 buffer.append("\n");
390 }
391
392 // main
393 for (int row = 0; row < tl.getTraceCount(); row++) {
394 // row name
395 buffer.append(prefix + tl.getTrace(row).getName());
396
397 TraceCorrelation tc = tl.getCorrelationStatistics(row);
398 // stats
399 for (int col = 0; col < colNames.length; col++) {
400 buffer.append("\t");
401 String stats = getStatistic(col, tc);
402 buffer.append(stats);
403 }
404 buffer.append("\n");
405 }
406 }
407 return buffer.toString();
408 }
409
410 private static String getStatistic(int i, TraceCorrelation tc) {
411 if (tc == null)
412 return "";
413 if (tc.getTraceType().isContinuous() && i >= colNamesNumeric.length)
414 return "";
415 if (tc.getTraceType().isCategorical() && i < colNamesNumeric.length)
416 return "";
417
418 Object value = null;
419 switch (i) { // i is the index of colNamesNumeric + colNamesCategorical
420 case 0:
421 value = tc.getMean();
422 break;
423 case 1:
424 value = tc.getStdErrorOfMean();
425 break;
426 case 2:
427 value = tc.getStdError();
428 break;
429 case 3:
430 value = tc.getVariance();
431 break;
432 case 4:
433 value = tc.getMedian();
434 break;
435 case 5:
436 value = tc.getMinimum();
437 break;
438 case 6:
439 value = tc.getMaximum();
440 break;
441 case 7:
442 value = tc.getQ1();
443 break;
444 case 8:
445 value = tc.getQ3();
446 break;
447 case 9:
448 value = tc.getLowerHPD();
449 break;
450 case 10:
451 value = tc.getUpperHPD();
452 break;
453 case 11:
454 value = tc.getACT();
455 break;
456 case 12:
457 value = tc.getESS();
458 break;
459 case 13:
460 value = tc.getSize();
461 break;
462 case 14:
463 if (!tc.hasGeometricMean()) return "";
464 value = tc.getGeometricMean();
465 break;
466 //+++++ categorical +++++
467 case 15:
468 value = Integer.toString(tc.getMode()); // todo map to category string
469 break;
470 case 16:
471 value = tc.getFrequencyOfMode();
472 break;
473 case 17:
474 value = tc.getProbabilityOfMode();
475 break;
476 case 18:
477 value = tc.getCredibleSet().toString(); // todo full set
478 break;
479 case 19:
480 value = tc.getCredibleSet().toString(); // todo render as list using category strings
481 break;
482 }
483 if (value == null)
484 return "";
485 else if (value instanceof Double && Double.isNaN((Double) value))
486 return "";
487 else
488 return value.toString();
489 }
490
491 }