Debian Codegraph @

src/dr/inference/trace/LogFileTraces.java

raw symbols SCIP
1 /*
2 * LogFileTraces.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 package dr.inference.trace;
26
27 import java.io.*;
28 import java.util.ArrayList;
29 import java.util.List;
30 import java.util.StringTokenizer;
31
32 /**
33 * A class that stores a set of traces from a single chain
34 *
35 * @author Andrew Rambaut
36 * @author Alexei Drummond
37 * @version $Id: LogFileTraces.java,v 1.4 2006/11/30 17:39:29 rambaut Exp $
38 */
39
40 public class LogFileTraces extends AbstractTraceList {
41
42 public LogFileTraces(String name, File file) {
43 this.name = name;
44 this.file = file;
45 }
46
47 /**
48 * @return the name of this traceset
49 */
50 public String getName() {
51 return name;
52 }
53
54 /**
55 * @return the path of this traceset
56 */
57 public String getFullName() {
58 return file.getPath();
59 }
60
61 public File getFile() {
62 return file;
63 }
64
65 /**
66 * @return the last state in the chain
67 */
68 public long getMaxState() {
69 return lastState;
70 }
71
72 public boolean isIncomplete() {
73 return false;
74 }
75
76 /**
77 * @return the number of states excluding the burnin
78 */
79 public int getStateCount() {
80 // This is done as two integer divisions to ensure the same rounding for
81 // the burnin...
82 return (int) (((lastState - firstState) / stepSize) - (getBurnIn() / stepSize) + 1);
83 }
84
85 /**
86 * @return the number of states in the burnin
87 */
88 public int getBurninStateCount() {
89 return (int) (getBurnIn() / stepSize);
90 }
91
92 /**
93 * @return the size of the step between states
94 */
95 public long getStepSize() {
96 return stepSize;
97 }
98
99 public long getBurnIn() {
100 return burnIn;
101 }
102
103 /**
104 * @return the number of traces in this traceset
105 */
106 public int getTraceCount() {
107 return traces.size();
108 }
109
110 /**
111 * @return the index of the trace with the given name
112 */
113 public int getTraceIndex(String name) {
114 for (int i = 0; i < traces.size(); i++) {
115 Trace trace = getTrace(i);
116 if (name.equals(trace.getName())) {
117 return i;
118 }
119 }
120 return -1;
121 }
122
123 /**
124 * @return the name of the trace with the given index
125 */
126 public String getTraceName(int index) {
127 return getTrace(index).getName();
128 }
129
130 /**
131 * @param index requested trace index
132 * @return the trace for a given index
133 */
134 public Trace getTrace(int index) {
135 return traces.get(index);
136 }
137
138 public void setBurnIn(long burnin) {
139 this.burnIn = burnin;
140 for (Trace trace : traces) {
141 trace.setTraceStatistics(null);
142 }
143 }
144
145 public double getStateValue(int trace, int index) {
146 return (Double) getTrace(trace).getValue(index + (int) (getBurnIn() / stepSize));
147 }
148
149 /**
150 * Read several consecutive values of one state into a destination array
151 *
152 * @param nState State index number
153 * @param destination array to store result
154 * @param offset first trace index
155 */
156 public void getStateValues(int nState, double[] destination, int offset) {
157 final int index1 = nState + (int) (getBurnIn() / stepSize);
158 for (int k = 0; k < destination.length; ++k) {
159 destination[k] = (Double) getTrace(k + offset).getValue(index1);
160 }
161 }
162
163 /**
164 * Use the flag boolean[] filtered in FilteredTraceList
165 * to determine whether to remove filtered values,
166 * when filtered != null
167 * @param index the index of trace
168 * @param fromIndex low endpoint (inclusive) of the subList.
169 * @param toIndex high endpoint (exclusive) of the subList.
170 * @return
171 */
172 public List<Double> getValues(int index, int fromIndex, int toIndex) {
173 List<Double> values = null;
174 try {
175 Trace trace = getTrace(index);
176 values = trace.getValues(fromIndex, toIndex, super.filtered);
177 } catch (IndexOutOfBoundsException e) {
178 System.err.println("getValues error: trace index = " + index);
179 }
180 return values;
181 }
182
183 public List<Double> getValues(int index) {
184 return this.getValues(index, getBurninStateCount(), getTrace(index).getValueCount());
185 }
186
187 public List<Double> getBurninValues(int index) {
188 return this.getValues(index, 0, getBurninStateCount());
189 }
190
191 /**
192 * Use the {@link #loadTraces(File) loadTraces} method,
193 * where <code>File</code> is defined from the constructor.
194 *
195 * @throws TraceException
196 * @throws IOException
197 */
198 public void loadTraces() throws TraceException, IOException {
199 loadTraces(file);
200 }
201
202 /**
203 * Read through <code>File</code> created from a log file,
204 * fill in <code>traces</code> list, and set <code>TraceType</code>.
205 *
206 * @param file <code>File</code>
207 * @throws TraceException
208 * @throws IOException
209 */
210 public void loadTraces(File file) throws TraceException, IOException {
211 final Reader reader = new FileReader(file);
212 loadTraces(reader);
213 reader.close();
214 }
215
216 /**
217 * Read through <code>InputStream</code> created from a log file,
218 * fill in <code>traces</code> list, and set <code>TraceType</code>.
219 *
220 * @param in <code>InputStream</code>
221 * @throws TraceException
222 * @throws IOException
223 */
224 public void loadTraces(InputStream in) throws TraceException, IOException {
225 final Reader reader = new InputStreamReader(in);
226 loadTraces(reader);
227 reader.close();
228 }
229
230 /**
231 * Read through either <code>FileReader</code> or <code>InputStreamReader</code>
232 * created from a log file,
233 * fill in <code>traces</code> list, and set <code>TraceType</code>.
234 *
235 * @param r The input for <code>TrimLineReader</code>.
236 * Use either <code>FileReader</code> or <code>InputStreamReader</code>
237 * @throws TraceException
238 * @throws java.io.IOException
239 */
240 private void loadTraces(Reader r) throws TraceException, java.io.IOException {
241
242 final TrimLineReader reader = new LogFileTraces.TrimLineReader(r);
243
244 // Read through to first token
245 StringTokenizer tokens = reader.tokenizeLine();
246
247 if (tokens == null) {
248 throw new TraceException("Trace file is empty.");
249 }
250
251 // read over empty lines
252 while (!tokens.hasMoreTokens()) {
253 tokens = reader.tokenizeLine();
254 }
255
256 // skip the first column which should be the state number
257 String token = tokens.nextToken();
258
259 // lines starting with [ are ignored, assuming comments in MrBayes file
260 // lines starting with # are ignored, assuming comments in Migrate or BEAST file
261 while (token.startsWith("[") || token.startsWith("#")) {
262 // readTraceType(token, tokens); // using # to define type
263 tokens = reader.tokenizeLine();
264
265 // read over empty lines
266 while (!tokens.hasMoreTokens()) {
267 tokens = reader.tokenizeLine();
268 }
269
270 // read state token and ignore
271 token = tokens.nextToken();
272 }
273
274 // read label tokens
275 String[] labels = new String[tokens.countTokens()];
276
277 for (int i = 0; i < labels.length; i++) {
278 labels[i] = tokens.nextToken();
279 addTrace(labels[i]);
280 }
281
282 int traceCount = getTraceCount();
283
284 long num_samples = 0;
285
286 String line = reader.readLine();
287 tokens = reader.getStringTokenizer(line);
288 String lastLine = line;
289 while (tokens != null && tokens.hasMoreTokens()) {
290
291 String stateString = tokens.nextToken();
292 long state = 0;
293
294 try {
295 try {
296 // Changed this to parseDouble because LAMARC uses scientific notation for the state number
297 state = (long) Double.parseDouble(stateString);
298 } catch (NumberFormatException nfe) {
299 throw new TraceException("Unable to parse state number in column 1 (Line " +
300 reader.getLineNumber() + ")");
301 }
302
303 if (num_samples < 1) {
304 // MrBayes puts 1 as the first state, BEAST puts 0
305 // In order to get the same gap between subsequent samples,
306 // we force this to 0.
307 if (state == 1) state = 0;
308 }
309 num_samples += 1;
310
311 if (!addState(state, num_samples)) {
312 throw new TraceException("State " + state + " is not consistent with previous spacing (Line " +
313 reader.getLineNumber() + ")");
314 }
315
316 } catch (NumberFormatException nfe) {
317 throw new TraceException("State " + state + ":Expected real value in column " + reader.getLineNumber());
318 }
319
320 for (int i = 0; i < traceCount; i++) {
321 if (tokens.hasMoreTokens()) {
322 String value = tokens.nextToken();
323
324 addParsedValue(i, value);
325
326 } else {
327 throw new TraceException("State " + state + ": missing values at line " + reader.getLineNumber());
328 }
329 }
330 // used to keep the last valid line
331 lastLine = line;
332 // tokens = reader.tokenizeLine();
333 line = reader.readLine();
334 tokens = reader.getStringTokenizer(line);
335 }
336
337 if (num_samples == 0)
338 throw new TraceException("Incorrect file format, no sample is found !");
339
340 burnIn = lastState / 10;
341
342 if (lastState < 0)
343 lastState = firstState;
344 if (stepSize < 0 && lastState > 0)
345 stepSize = lastState;
346
347 validateTraceType(lastLine);
348 validateUniqueValues();
349 }
350 public static final int MIN_SAMPLE = 5; // used in StatisticsModel
351
352 private final int MAX_UNIQUE_VALUE = 200;
353 // change integer type into real, if too many unique values
354 private void validateUniqueValues() throws TraceException {
355 for (int id = 0; id < getTraceCount(); id++) {
356 Trace trace = getTrace(id);
357 if (trace.getTraceType().isInteger()) {
358 int uniqueValue = trace.getUniqueValueCount();
359 if (uniqueValue > MAX_UNIQUE_VALUE) {
360 System.out.println("Too many unique values (>" + MAX_UNIQUE_VALUE +
361 ") found in trace " + trace.getName() + " at " + id);
362 changeTraceType(id, TraceType.REAL);
363 }
364 }
365 }
366 }
367
368
369 // validate TraceType at the last value of trace,
370 // in case integer is logged for double values in the first (even several) row.
371 // it must use original line, because the data type of values in traces are changed
372 private void validateTraceType(String lastLine) throws TraceException {
373 String[] values = lastLine.split("\\t");
374 // the 1st is state
375 for (int i=1; i < values.length; i++) {
376 int traceId = i-1;
377 Trace trace = getTrace(traceId);
378 // avoid to assign integer to double incorrectly
379 if (trace.getTraceType().isInteger() && NumberUtils.hasDecimalPoint(values[i]))
380 changeTraceType(traceId, TraceType.REAL);
381 }
382 }
383
384 /**
385 * Auto assign INTEGER or CATEGORICAL type to traces
386 * according their values in the first line.
387 * Default type is REAL.
388 *
389 * @param traceIndex
390 * @param value
391 */
392 private void addParsedValue(int traceIndex, String value) throws TraceException {
393 Trace trace = getTrace(traceIndex);
394
395 TraceType type = trace.getTraceType();
396
397 if (type != TraceType.CATEGORICAL) {
398 // once categorical, always categorical
399
400 if (NumberUtils.isNumber(value)) {
401 if (type != TraceType.REAL) {
402 // once real, always real (unless categorical)
403
404 if (NumberUtils.hasDecimalPoint(value)) { // Real
405 // if a single number has a decimal point then switch to real
406 type = TraceType.REAL;
407 // System.out.println("Auto detect " + type + " type for trace " + name + " at " + traceIndex);
408 changeTraceType(traceIndex, type);
409 }
410 }
411 } else { // String
412 type = TraceType.CATEGORICAL;
413 // System.out.println("Auto detect " + type + " type for trace " + name + " at " + traceIndex);
414 trace = changeTraceType(traceIndex, type);
415 }
416 }
417
418 if (type == TraceType.REAL) {
419 trace.add(Double.parseDouble(value));
420 } else if (type == TraceType.INTEGER) {
421 trace.add(Double.parseDouble(value));
422 } else if (type == TraceType.CATEGORICAL) {
423 trace.add(value);
424 } else {
425 throw new IllegalArgumentException("Unsupported TraceType");
426 }
427
428 }
429
430 //************************************************************************
431 // private methods
432 //************************************************************************
433
434 // These methods are used by the load function, above
435
436 /**
437 * Add a trace for a statistic of the given name
438 *
439 * @param name trace name
440 */
441 private void addTrace(String name) {
442 // Start by assuming integer. This will be switched if added data
443 // contradicts.
444 traces.add(new Trace(name, TraceType.INTEGER));
445 }
446
447 /**
448 * Add a trace for a statistic of the given name
449 *
450 * @param name trace name
451 */
452 private void addTrace(String name, TraceType traceType) {
453 traces.add(new Trace(name, traceType));
454 }
455
456 public Trace changeTraceType(int id, TraceType newType) throws TraceException {
457 if (id >= getTraceCount() || id < 0)
458 throw new TraceException("Invalid trace id : " + id + ", which should 0 < and >= " + getTraceCount());
459 Trace trace = getTrace(id);
460 TraceType oldType = trace.getTraceType();
461 if (oldType != newType) {
462 if (oldType.isCategorical()) {
463 throw new TraceException("A categorical type cannot be changed to anything else.");
464 }
465
466 Trace newTrace = new Trace(trace.getName(), newType);
467
468 if (newType.isDiscrete()) {
469 int uniqueValue = trace.getUniqueValueCount();
470 if (uniqueValue > MAX_UNIQUE_VALUE)
471 throw new TraceException("Type change is failed, because too many unique values (>" +
472 MAX_UNIQUE_VALUE + ") are found !");
473 }
474
475 if (newType.isCategorical()) {
476 try {
477 // include integer trace
478 for (int i = 0; i < trace.getValueCount(); i++) {
479 // use add(String value) to set categoryLabelMap ...
480 newTrace.add(Double.toString(trace.getValue(i)));
481 }
482 } catch (Exception e) {
483 throw new TraceException("Type change is failed, when parsing " + oldType +
484 " to " + newType + " in trace " + trace.getName());
485 }
486
487 if (newTrace.getValueCount() != trace.getValueCount())
488 throw new TraceException("Type change is failed, because values size is different after copy !");
489
490 traces.set(id, newTrace);
491
492 } else {
493 trace.setTraceType(newType); // change between numeric
494 }
495
496 // do not need code below, they are set by 'add(String value)',
497 // and they will overwrite the correct values
498 // // copy the categorical values across in case it is switched back
499 // newTrace.categoryValueList = trace.categoryValueList;
500 // newTrace.categoryLabelMap = trace.categoryLabelMap;
501 // newTrace.orderType = trace.orderType;
502 // newTrace.categoryOrder = trace.categoryOrder;
503 // newTrace.uniqueValues = trace.uniqueValues;
504
505 // System.out.println("Change " + oldType + " to " + newType + " type for trace " + trace.getName() + " at " + id);
506 return newTrace;
507 }
508 return trace;
509 }
510
511 /**
512 * Add a state number for these traces. This should be
513 * called before adding values for each trace. The spacing
514 * between stateNumbers should remain constant.
515 *
516 * @param stateNumber the state
517 * @param num_samples the number of samples (rows)
518 * @return false if the state number is inconsistent
519 */
520 private boolean addState(long stateNumber, long num_samples) {
521 if (firstState < 0) { // it can use num_samples==1 to replace firstState < 0
522 firstState = stateNumber;
523 } else if (secondState < 0) {
524 secondState = stateNumber;
525 } else if (stepSize < 0) {
526 // delay setting of the stepSize until the step between
527 // the second and third step in case the first step is
528 // 1 (i.e., MrBayes) and the stepsize is 1.
529 stepSize = stateNumber - secondState;
530 } else {
531 long step = stateNumber - lastState;
532 if (step != stepSize) {
533 System.out.println("step: " + step + " != " + stepSize);
534 return false;
535 }
536 }
537 // System.out.println(num_samples + ": stateNumber=" + stateNumber + " lastState=" + lastState + " firstState=" + firstState + " stepSize=" + stepSize);
538 lastState = stateNumber;
539 return true;
540 }
541
542 protected final File file;
543 protected final String name;
544
545 private final List<Trace> traces = new ArrayList<Trace>();
546
547 private long burnIn = -1;
548 private long firstState = -1;
549 private long secondState = -1;
550 private long lastState = -1;
551 private long stepSize = -1;
552
553 public static class TrimLineReader extends BufferedReader {
554
555 public TrimLineReader(Reader reader) {
556 super(reader);
557 }
558
559 public String readLine() throws java.io.IOException {
560 lineNumber += 1;
561 String line = super.readLine();
562 if (line != null) return line.trim();
563 return null;
564 }
565
566 public StringTokenizer tokenizeLine() throws java.io.IOException {
567 String line = readLine();
568 return getStringTokenizer(line);
569 }
570
571 public StringTokenizer getStringTokenizer(String line) {
572 if (line == null) return null;
573 return new StringTokenizer(line, "\t");
574 }
575
576 public int getLineNumber() {
577 return lineNumber;
578 }
579
580 private int lineNumber = 0;
581 }
582
583 }
584