Debian Codegraph @

src/dr/evolution/io/Importer.java

raw symbols SCIP
1 /*
2 * Importer.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.evolution.io;
27
28 import dr.evolution.datatype.DataType;
29
30 import java.io.*;
31
32 /**
33 * Base class for phylogenetic file format importers
34 *
35 * @version $Id: Importer.java,v 1.19 2006/04/25 14:41:08 rambaut Exp $
36 *
37 * @author Andrew Rambaut
38 * @author Alexei Drummond
39 */
40 public abstract class Importer {
41
42 public static class ImportException extends Exception {
43 /**
44 *
45 */
46 private static final long serialVersionUID = 7858834683324203750L;
47 public ImportException() { super(); }
48 public ImportException(String message) { super(message); }
49 }
50
51 public static class DuplicateFieldException extends ImportException {
52 /**
53 *
54 */
55 private static final long serialVersionUID = 8047146381348414810L;
56 public DuplicateFieldException() { super(); }
57 public DuplicateFieldException(String message) { super(message); }
58 }
59
60 public static class BadFormatException extends ImportException {
61 /**
62 *
63 */
64 private static final long serialVersionUID = -8206831989674620748L;
65 public BadFormatException() { super(); }
66 public BadFormatException(String message) { super(message); }
67 }
68
69 public static class UnparsableDataException extends ImportException {
70 /**
71 *
72 */
73 private static final long serialVersionUID = 5905130039882401006L;
74 public UnparsableDataException() { super(); }
75 public UnparsableDataException(String message) { super(message); }
76 }
77
78 public static class MissingFieldException extends ImportException {
79 /**
80 *
81 */
82 private static final long serialVersionUID = -7576489210458327552L;
83 public MissingFieldException() { super(); }
84 public MissingFieldException(String message) { super(message); }
85 }
86
87 public static class ShortSequenceException extends ImportException {
88 /**
89 *
90 */
91 private static final long serialVersionUID = 7460033398106047073L;
92 public ShortSequenceException() { super(); }
93 public ShortSequenceException(String message) { super(message); }
94 }
95
96 public static class TooFewTaxaException extends ImportException {
97 /**
98 *
99 */
100 private static final long serialVersionUID = -6349041350075169247L;
101 public TooFewTaxaException() { super(); }
102 public TooFewTaxaException(String message) { super(message); }
103 }
104
105 public static class UnknownTaxonException extends ImportException {
106 /**
107 *
108 */
109 private static final long serialVersionUID = 6611115782536515250L;
110 public UnknownTaxonException() { super(); }
111 public UnknownTaxonException(String message) { super(message); }
112 }
113
114 /**
115 * Constructor
116 */
117 public Importer(Reader reader) {
118 this.reader = new LineNumberReader(reader);
119 this.commentWriter = null;
120 }
121
122 public Importer(Reader reader, Writer commentWriter) {
123 this.reader = new LineNumberReader(reader);
124 this.commentWriter = commentWriter != null ? new BufferedWriter(commentWriter) : null;
125 }
126
127 public void setCommentDelimiters(char line) {
128 hasComments = true;
129 this.lineComment = line;
130 }
131
132 public void setCommentDelimiters(char start, char stop) {
133 hasComments = true;
134 this.startComment = start;
135 this.stopComment = stop;
136 }
137
138 public void setCommentDelimiters(char start, char stop, char line) {
139 hasComments = true;
140 this.startComment = start;
141 this.stopComment = stop;
142 this.lineComment = line;
143 }
144
145 public void setCommentDelimiters(char start, char stop, char line, char write, char meta) {
146 hasComments = true;
147 this.startComment = start;
148 this.stopComment = stop;
149 this.lineComment = line;
150 this.writeComment = write;
151 this.metaComment = meta;
152 }
153
154 public void setCommentWriter(Writer commentWriter) {
155 this.commentWriter = new BufferedWriter(commentWriter);
156 }
157
158 public int getLineNumber() {
159 return reader.getLineNumber();
160 }
161
162 public int getLastDelimiter() {
163 return lastDelimiter;
164 }
165
166 public char nextCharacter() throws IOException {
167 if (lastChar == '\0') {
168 lastChar = readCharacter();
169 }
170 return (char)lastChar;
171 }
172
173 public char readCharacter() throws IOException {
174
175 skipSpace();
176
177 char ch = read();
178
179 while (hasComments && (ch == startComment || ch == lineComment)) {
180 skipComments(ch);
181 skipSpace();
182 ch = read();
183 }
184
185 return ch;
186 }
187
188 public void unreadCharacter(char ch) {
189 lastChar = ch;
190 }
191
192 public char next() throws IOException {
193 if (lastChar == '\0') {
194 lastChar = read();
195 }
196 return (char)lastChar;
197 }
198
199 public char read() throws IOException {
200 int ch;
201
202 if (lastChar == '\0') {
203 ch = reader.read();
204 if (ch <= 0) {
205 throw new EOFException();
206 }
207 } else {
208 ch = lastChar;
209 lastChar = '\0';
210 }
211
212 return (char)ch;
213 }
214
215 /**
216 * Reads a line, skipping over any comments.
217 */
218 public String readLine() throws IOException {
219
220 StringBuffer line = new StringBuffer();
221
222 char ch = read();
223
224 try {
225
226 while (ch != '\n' && ch != '\r') {
227
228 if (hasComments) {
229 if (ch == lineComment) {
230 skipComments(ch);
231 break;
232 }
233 if (ch == startComment) {
234 skipComments(ch);
235 ch = read();
236 }
237 }
238
239 line.append(ch);
240 ch = read();
241 }
242
243 // accommodate DOS line endings..
244 if (ch == '\r') {
245 if (next() == '\n') read();
246 }
247
248 lastDelimiter = ch;
249
250 } catch (EOFException e) {
251 // We catch an EOF and return the line we have so far
252 }
253
254 return line.toString();
255 }
256
257 /**
258 * Reads sequences, skipping over any comments and filtering using dataType.
259 * @param sequence a StringBuffer into which the sequences is put
260 * @param dataType the dataType of the sequences
261 * @param delimiters list of characters that will stop the reading
262 * @param maxSites maximum number of sites to read
263 */
264 public void readSequence(StringBuffer sequence, DataType dataType,
265 String delimiters, int maxSites,
266 String gapCharacters, String missingCharacters,
267 String matchCharacters, String matchSequence) throws IOException, ImportException {
268
269 char ch = read();
270
271 try {
272 int n = 0;
273
274 while (n < maxSites && delimiters.indexOf(ch) == -1) {
275
276 if (hasComments && (ch == startComment || ch == lineComment)) {
277 skipComments(ch);
278 ch = read();
279 }
280
281 if (!Character.isWhitespace(ch)) {
282
283 char ch1 = ch;
284
285 if (gapCharacters.indexOf(ch) != -1) {
286 ch1 = DataType.GAP_CHARACTER;
287 } else if (missingCharacters.indexOf(ch) != -1) {
288 ch1 = DataType.UNKNOWN_CHARACTER;
289 } else if (matchCharacters.indexOf(ch) != -1) {
290 if (matchSequence == null) {
291 throw new ImportException("Match character in first sequences");
292 }
293 if (n >= matchSequence.length()) {
294 throw new ImportException("Match sequences too short");
295 }
296
297 ch1 = matchSequence.charAt(n);
298 }
299
300 sequence.append(ch1);
301
302 n++;
303 }
304
305 ch = read();
306 }
307
308 lastDelimiter = ch;
309
310 if (Character.isWhitespace((char)lastDelimiter)) {
311 ch = nextCharacter();
312 if (delimiters.indexOf(ch) != -1) {
313 lastDelimiter = readCharacter();
314 }
315 }
316
317 } catch (EOFException e) {
318 // We catch an EOF and return the sequences we have so far
319 }
320 }
321
322 /**
323 * Reads a line of sequences, skipping over any comments and filtering using dataType.
324 * @param sequence a StringBuffer into which the sequences is put
325 * @param dataType the dataType of the sequences
326 * @param delimiters list of characters that will stop the reading
327 */
328 public void readSequenceLine(StringBuffer sequence, DataType dataType,
329 String delimiters,
330 String gapCharacters, String missingCharacters,
331 String matchCharacters, String matchSequence) throws IOException, ImportException {
332
333 char ch = read();
334
335 try {
336 int n = 0;
337
338 while (ch != '\r' && ch != '\n' && delimiters.indexOf(ch) == -1) {
339
340 if (hasComments) {
341 if (ch == lineComment) {
342 skipComments(ch);
343 break;
344 }
345 if (ch == startComment) {
346 skipComments(ch);
347 ch = read();
348 }
349 }
350
351 if (ch != ' ' && ch != '\t') {
352 char ch1 = ch;
353
354 if (gapCharacters.indexOf(ch) != -1) {
355 ch1 = DataType.GAP_CHARACTER;
356 } else if (missingCharacters.indexOf(ch) != -1) {
357 ch1 = DataType.UNKNOWN_CHARACTER;
358 } else if (matchCharacters.indexOf(ch) != -1) {
359 if (matchSequence == null) {
360 throw new ImportException("Match character in first sequences");
361 }
362 if (n >= matchSequence.length()) {
363 throw new ImportException("Match sequences too short");
364 }
365
366 ch1 = matchSequence.charAt(n);
367 }
368
369 sequence.append(ch1);
370
371 n++;
372 }
373
374 ch = read();
375 }
376
377 if (ch == '\r') {
378 if (next() == '\n') read();
379 }
380
381 lastDelimiter = ch;
382
383 if (Character.isWhitespace((char)lastDelimiter)) {
384 ch = nextCharacter();
385 if (delimiters.indexOf(ch) != -1) {
386 lastDelimiter = readCharacter();
387 }
388 }
389
390 } catch (EOFException e) {
391 // We catch an EOF and return the sequences we have so far
392 }
393 }
394
395 /**
396 * Attempts to read and parse an integer delimited by whitespace.
397 */
398 public int readInteger() throws IOException, ImportException {
399 String token = readToken();
400 try {
401 return Integer.parseInt(token);
402 } catch (NumberFormatException nfe) {
403 throw new ImportException("Number format error: " + nfe.getMessage());
404 }
405 }
406
407 /**
408 * Attempts to read and parse an integer delimited by whitespace or by
409 * any character in delimiters.
410 */
411 public int readInteger(String delimiters) throws IOException, ImportException {
412 String token = readToken(delimiters);
413 try {
414 return Integer.parseInt(token);
415 } catch (NumberFormatException nfe) {
416 throw new ImportException("Number format error: " + nfe.getMessage());
417 }
418 }
419
420 /**
421 * Attempts to read and parse a double delimited by whitespace.
422 */
423 public double readDouble() throws IOException, ImportException {
424 String token = readToken();
425 try {
426 return Double.parseDouble(token);
427 } catch (NumberFormatException nfe) {
428 throw new ImportException("Number format error: " + nfe.getMessage());
429 }
430 }
431
432 /**
433 * Attempts to read and parse a double delimited by whitespace or by
434 * any character in delimiters.
435 */
436 public double readDouble(String delimiters) throws IOException, ImportException {
437 String token = readToken(delimiters);
438 try {
439 return Double.parseDouble(token);
440 } catch (NumberFormatException nfe) {
441 throw new ImportException("Number format error: " + nfe.getMessage());
442 }
443 }
444
445 /**
446 * Reads a token stopping when any whitespace or a comment is found.
447 * If the token begins with a quote char then all characters will be
448 * included in token until a matching quote is found (including whitespace or comments).
449 */
450 public String readToken() throws IOException {
451 return readToken("");
452 }
453
454 /**
455 * Reads a token stopping when any whitespace, a comment or when any character
456 * in delimiters is found. If the token begins with a quote char
457 * then all characters will be included in token until a matching
458 * quote is found (including whitespace or comments).
459 */
460 public String readToken(String delimiters) throws IOException {
461 int space = 0;
462 char ch, ch2, quoteChar = '\0';
463 boolean done = false, first = true, quoted = false, isSpace;
464
465 nextCharacter();
466
467 StringBuffer token = new StringBuffer();
468
469 while (!done) {
470 ch = read();
471
472 try {
473 isSpace = Character.isWhitespace(ch);
474
475 if (quoted && ch == quoteChar) { // Found the closing quote
476 ch2 = read();
477
478 if (ch == ch2) {
479 // A repeated quote character so add this to the token
480 token.append(ch);
481 } else {
482 // otherwise it terminates the token
483
484 lastDelimiter = ' ';
485 unreadCharacter(ch2);
486 done = true;
487 quoted = false;
488 }
489 } else if (first && (ch == '\'' || ch == '"')) {
490 // if the opening character is a quote
491 // read everything up to the closing quote
492 quoted = true;
493 quoteChar = ch;
494 first = false;
495 space = 0;
496 } else if ( ch == startComment || ch == lineComment ) {
497 skipComments(ch);
498 lastDelimiter = ' ';
499 done = true;
500 } else {
501 if (quoted) {
502 // compress multiple spaces into one
503 if (isSpace) {
504 space++;
505 ch = ' ';
506 } else {
507 space = 0;
508 }
509
510 if (space < 2) {
511 token.append(ch);
512 }
513 } else if (isSpace) {
514 lastDelimiter = ' ';
515 done = true;
516 } else if (delimiters.indexOf(ch) != -1) {
517 done = true;
518 lastDelimiter = ch;
519 } else {
520 token.append(ch);
521 first = false;
522 }
523 }
524 } catch (EOFException e) {
525 // We catch an EOF and return the token we have so far
526 done = true;
527 }
528 }
529
530 if (Character.isWhitespace((char)lastDelimiter)) {
531 ch = nextCharacter();
532 while (Character.isWhitespace(ch)) {
533 read();
534 ch = nextCharacter();
535 }
536
537 if (delimiters.indexOf(ch) != -1) {
538 lastDelimiter = readCharacter();
539 }
540 }
541
542 return token.toString();
543 }
544
545 /**
546 * Skips over any comments. The opening comment delimiter is passed.
547 */
548 protected void skipComments(char delimiter) throws IOException {
549
550 char ch;
551 int n=1;
552 boolean write = false;
553 StringBuffer meta = null;
554
555 if (nextCharacter() == writeComment) {
556 read();
557 write = true;
558 } else if (nextCharacter() == metaComment) {
559 read();
560 // combine two consecutive meta comments
561 meta = lastMetaComment!= null ? new StringBuffer(lastMetaComment + ";") : new StringBuffer();
562 }
563
564 lastMetaComment = null;
565
566 if (delimiter == lineComment) {
567 String line = readLine();
568 if (write && commentWriter != null) {
569 commentWriter.write(line, 0, line.length());
570 commentWriter.newLine();
571 } else if (meta != null) {
572 meta.append(line);
573 }
574 } else {
575 do {
576 ch = read();
577 if (ch == startComment) {
578 n++;
579 } else if (ch == stopComment) {
580 if (write && commentWriter != null) {
581 commentWriter.newLine();
582 }
583 n--;
584 } else if (write && commentWriter != null) {
585 commentWriter.write(ch);
586 } else if (meta != null) {
587 meta.append(ch);
588 }
589 } while (n > 0);
590 }
591
592 if (meta != null) {
593 lastMetaComment = meta.toString();
594 }
595 }
596
597 /**
598 * Skips to the end of the line. If a comment is found then this is read.
599 */
600 public void skipToEndOfLine() throws IOException {
601
602 char ch;
603
604 do {
605 ch = read();
606 if (hasComments) {
607 if (ch == lineComment) {
608 skipComments(ch);
609 break;
610 }
611 if (ch == startComment) {
612 skipComments(ch);
613 ch = read();
614 }
615 }
616
617 } while (ch != '\n' && ch != '\r');
618
619 if (ch == '\r') {
620 if (nextCharacter() == '\n') read();
621 }
622 }
623
624 /**
625 * Skips char any contiguous characters in skip. Will also skip
626 * comments.
627 */
628 public void skipWhile(String skip) throws IOException {
629
630 char ch;
631
632 do {
633 ch = read();
634 } while ( skip.indexOf(ch) > -1 );
635
636 unreadCharacter(ch);
637 }
638
639 /**
640 * Skips over any space (plus tabs and returns) in the file. Will also skip
641 * comments.
642 */
643 public void skipSpace() throws IOException {
644 skipWhile(" \t\r\n");
645 }
646
647 /**
648 * Skips over any contiguous characters in skip. Will also skip
649 * comments and space.
650 */
651 public void skipCharacters(String skip) throws IOException {
652 skipWhile(skip + " \t\r\n");
653 }
654
655 /**
656 * Skips over the file until a character from delimiters is found. Returns
657 * the delimiter found. Will skip comments and will ignore delimiters within
658 * comments.
659 */
660 public char skipUntil(String skip) throws IOException {
661 char ch;
662
663 do {
664 ch = readCharacter();
665 } while ( skip.indexOf(ch) == -1 );
666
667 return ch;
668 }
669
670 public String getLastMetaComment() {
671 return lastMetaComment;
672 }
673
674 public void clearLastMetaComment() {
675 lastMetaComment = null;
676 }
677
678 // Private stuff
679
680 private LineNumberReader reader;
681 private BufferedWriter commentWriter = null;
682
683 private int lastChar = '\0';
684 private int lastDelimiter = '\0';
685
686 private boolean hasComments = false;
687 private char startComment = (char)-1;
688 private char stopComment = (char)-1;
689 private char lineComment = (char)-1;
690
691 private char writeComment = (char)-1;
692 private char metaComment = (char)-1;
693
694 private String lastMetaComment = null;
695 }