Debian Codegraph @

src/dr/evolution/io/NexusImporter.java

raw symbols SCIP
1 /*
2 * NexusImporter.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.alignment.Alignment;
29 import dr.evolution.alignment.SimpleAlignment;
30 import dr.evolution.datatype.AminoAcids;
31 import dr.evolution.datatype.DataType;
32 import dr.evolution.datatype.Nucleotides;
33 import dr.evolution.datatype.TwoStates;
34 import dr.evolution.sequence.Sequence;
35 import dr.evolution.sequence.SequenceList;
36 import dr.evolution.sequence.Sequences;
37 import dr.evolution.tree.FlexibleNode;
38 import dr.evolution.tree.FlexibleTree;
39 import dr.evolution.tree.Tree;
40 import dr.evolution.tree.TreeUtils;
41 import dr.evolution.util.*;
42 import dr.util.Attributable;
43
44 import java.awt.*;
45 import java.io.*;
46 import java.util.ArrayList;
47 import java.util.HashMap;
48 import java.util.Map;
49 import java.util.regex.Matcher;
50 import java.util.regex.Pattern;
51
52 /**
53 * Class for importing NEXUS file format
54 *
55 * @author Andrew Rambaut
56 * @author Alexei Drummond
57 * @version $Id: NexusImporter.java,v 1.30 2006/04/25 14:39:37 rambaut Exp $
58 */
59 public class NexusImporter extends Importer implements SequenceImporter, TreeImporter {
60
61 public static final NexusBlock UNKNOWN_BLOCK = new NexusBlock("unknown");
62 public static final NexusBlock TAXA_BLOCK = new NexusBlock("TAXA");
63 public static final NexusBlock CHARACTERS_BLOCK = new NexusBlock("CHARACTERS");
64 public static final NexusBlock DATA_BLOCK = new NexusBlock("DATA");
65 public static final NexusBlock UNALIGNED_BLOCK = new NexusBlock("UNALIGNED");
66 public static final NexusBlock DISTANCES_BLOCK = new NexusBlock("DISTANCES");
67 public static final NexusBlock TREES_BLOCK = new NexusBlock("TREES");
68 public static final NexusBlock CALIBRATION_BLOCK = new NexusBlock("CALIBRATION");
69
70 public static boolean suppressWarnings = false;
71
72 private final boolean ignoreMetaComments;
73
74 public static void setSuppressWarnings(boolean sw) {
75 suppressWarnings = sw;
76 }
77
78 // NEXUS specific ImportException classes
79 public static class MissingBlockException extends ImportException {
80 /**
81 *
82 */
83 private static final long serialVersionUID = -6287423449717453999L;
84
85 public MissingBlockException() {
86 super();
87 }
88
89 public MissingBlockException(String message) {
90 super(message);
91 }
92 }
93
94 public static class NexusBlock {
95 private final String name;
96
97 public NexusBlock(String name) {
98 this.name = name;
99 }
100
101 public String toString() {
102 return name;
103 }
104 }
105
106 /**
107 * Constructor
108 */
109 public NexusImporter(Reader reader) {
110 super(reader);
111 this.ignoreMetaComments = false;
112 setCommentDelimiters('[', ']', '\0', '\0', '&');
113 }
114
115 public NexusImporter(Reader reader, boolean ignoreMetaComments) {
116 super(reader);
117 this.ignoreMetaComments = ignoreMetaComments;
118 setCommentDelimiters('[', ']', '\0', '!', '&');
119 }
120
121 public NexusImporter(Reader reader, Writer commentWriter) {
122 super(reader, commentWriter);
123 this.ignoreMetaComments = false;
124 setCommentDelimiters('[', ']', '\0', '!', '&');
125 }
126
127 /**
128 * This function returns an integer to specify what the
129 * next block in the file is. The internal variable nextBlock is also set to this
130 * value. This should be overridden to provide support for other blocks. Once
131 * the block is read in, nextBlock is automatically set to UNKNOWN_BLOCK by
132 * findEndBlock.
133 */
134 public NexusBlock findNextBlock() throws IOException {
135 findToken("BEGIN", true);
136 String blockName = readToken(";");
137 return findBlockName(blockName);
138 }
139
140 /**
141 * This function returns an enum class to specify what the
142 * block given by blockName is.
143 */
144 public NexusBlock findBlockName(String blockName) {
145 if (blockName.equalsIgnoreCase(TAXA_BLOCK.toString())) {
146 nextBlock = TAXA_BLOCK;
147 } else if (blockName.equalsIgnoreCase(CHARACTERS_BLOCK.toString())) {
148 nextBlock = CHARACTERS_BLOCK;
149 } else if (blockName.equalsIgnoreCase(DATA_BLOCK.toString())) {
150 nextBlock = DATA_BLOCK;
151 } else if (blockName.equalsIgnoreCase(UNALIGNED_BLOCK.toString())) {
152 nextBlock = UNALIGNED_BLOCK;
153 } else if (blockName.equalsIgnoreCase(DISTANCES_BLOCK.toString())) {
154 nextBlock = DISTANCES_BLOCK;
155 } else if (blockName.equalsIgnoreCase(TREES_BLOCK.toString())) {
156 nextBlock = TREES_BLOCK;
157 } else if (blockName.equalsIgnoreCase(CALIBRATION_BLOCK.toString())) {
158 nextBlock = CALIBRATION_BLOCK;
159 }
160
161 return nextBlock;
162 }
163
164 /**
165 * Parses a 'TAXA' block.
166 */
167 public TaxonList parseTaxaBlock() throws ImportException, IOException {
168 return readTaxaBlock();
169 }
170
171 /**
172 * Parses a 'CHARACTERS' block.
173 */
174 public Alignment parseCharactersBlock(TaxonList taxonList) throws ImportException, IOException {
175 return readCharactersBlock(taxonList);
176 }
177
178 /**
179 * Parses a 'DATA' block.
180 */
181 public Alignment parseDataBlock(TaxonList taxonList) throws ImportException, IOException {
182 return readDataBlock(/*taxonList*/);
183 }
184
185 /**
186 * Parses a 'TREES' block.
187 */
188 public Tree[] parseTreesBlock(TaxonList taxonList) throws ImportException, IOException {
189 return readTreesBlock(taxonList, false);
190 }
191
192 /**
193 * Parses a 'CALIBRATION' block putting the dates into the appropriate taxa
194 */
195 public dr.evolution.util.Date[] parseCalibrationBlock(TaxonList taxonList) throws ImportException, IOException {
196 return readCalibrationBlock(taxonList);
197 }
198
199 // **************************************************************
200 // SequenceImporter IMPLEMENTATION
201 // **************************************************************
202
203 /**
204 * importAlignment.
205 */
206 public Alignment importAlignment() throws IOException, Importer.ImportException {
207 boolean done = false;
208
209 TaxonList taxonList = null;
210 Alignment alignment = null;
211
212 while (!done) {
213 try {
214
215 NexusImporter.NexusBlock block = findNextBlock();
216
217 if (block == NexusImporter.TAXA_BLOCK) {
218
219 taxonList = readTaxaBlock();
220
221 } else if (block == NexusImporter.CALIBRATION_BLOCK) {
222 if (taxonList == null) {
223 throw new MissingBlockException("TAXA block is missing");
224 }
225
226 readCalibrationBlock(taxonList);
227
228 } else if (block == NexusImporter.CHARACTERS_BLOCK) {
229
230 if (taxonList == null) {
231 throw new MissingBlockException("TAXA block is missing");
232 }
233
234 alignment = readCharactersBlock(taxonList);
235 done = true;
236
237 } else if (block == NexusImporter.DATA_BLOCK) {
238
239 // A data block doesn't need a taxon block before it
240 // but if one exists then it will use it.
241 alignment = readDataBlock(/*taxonList*/);
242 done = true;
243
244 } else {
245 // Ignore the block..
246 }
247
248 } catch (EOFException ex) {
249 done = true;
250 }
251 }
252
253 if (alignment == null) {
254 throw new MissingBlockException("DATA or CHARACTERS block is missing");
255 }
256
257 return alignment;
258 }
259
260 /**
261 * importSequences.
262 */
263 public SequenceList importSequences() throws IOException, ImportException {
264 return importAlignment();
265 }
266
267 // **************************************************************
268 // TreeImporter IMPLEMENTATION
269 // **************************************************************
270
271 private boolean isReadingTreesBlock = false;
272 private HashMap<String, Taxon> translationList = null;
273 private Tree nextTree = null;
274 private final String[] lastToken = new String[1];
275
276 /**
277 * import a single tree.
278 */
279 public Tree importTree(TaxonList taxonList) throws IOException, ImportException {
280 return importTree(taxonList, false);
281 }
282
283 public Tree importTree(TaxonList taxonList, boolean useTaxonListNumbering) throws IOException, ImportException {
284 isReadingTreesBlock = false;
285 TaxonList[] aTaxonList = new TaxonList[1];
286 aTaxonList[0] = taxonList;
287 if (!startReadingTrees(aTaxonList)) {
288 throw new MissingBlockException("TREES block is missing");
289 }
290 translationList = readTranslationList(aTaxonList[0], lastToken);
291 return readNextTree(translationList, lastToken, useTaxonListNumbering ? taxonList : null);
292 }
293
294 /**
295 * import an array of all trees.
296 */
297 public Tree[] importTrees(TaxonList taxonList) throws IOException, ImportException {
298 return importTrees(taxonList, false);
299 }
300
301 public Tree[] importTrees(TaxonList taxonList, boolean useTaxonListNumbering) throws IOException, ImportException {
302 isReadingTreesBlock = false;
303 TaxonList[] aTaxonList = new TaxonList[1];
304 aTaxonList[0] = taxonList;
305 if (!startReadingTrees(aTaxonList)) {
306 throw new MissingBlockException("TREES block is missing");
307 }
308 return readTreesBlock(aTaxonList[0], useTaxonListNumbering);
309 }
310
311 /**
312 * return whether another tree is available.
313 */
314 public boolean hasTree() throws IOException, ImportException {
315 if (!isReadingTreesBlock) {
316 TaxonList[] taxonList = new TaxonList[1];
317 taxonList[0] = null;
318 isReadingTreesBlock = startReadingTrees(taxonList);
319 if (!isReadingTreesBlock) return false;
320
321 translationList = readTranslationList(taxonList[0], lastToken);
322 }
323
324 if (nextTree == null) {
325 nextTree = readNextTree(translationList, lastToken, null);
326 }
327
328 return (nextTree != null);
329 }
330
331
332 /**
333 * import the next tree.
334 * return the tree or null if no more trees are available
335 */
336 public Tree importNextTree() throws IOException, ImportException {
337 // call hasTree to do the hard work...
338 if (!hasTree()) {
339 isReadingTreesBlock = false;
340 return null;
341 }
342
343 Tree tree = nextTree;
344 nextTree = null;
345
346 return tree;
347 }
348
349 public boolean startReadingTrees(TaxonList[] taxonList) throws IOException, ImportException {
350 boolean done = false;
351
352 while (!done) {
353 try {
354
355 NexusImporter.NexusBlock block = findNextBlock();
356
357 if (block == NexusImporter.TAXA_BLOCK && taxonList[0] == null) {
358 // only read the taxon list if one hasn't been set already...
359 taxonList[0] = readTaxaBlock();
360
361 } else if (block == NexusImporter.TREES_BLOCK) {
362
363 return true;
364 } else {
365 // Ignore the block..
366 }
367
368 } catch (EOFException ex) {
369 done = true;
370 }
371 }
372
373 return false;
374 }
375
376 /**
377 * Finds the end of the current block.
378 */
379 private void findToken(String query, boolean ignoreCase) throws IOException {
380 String token;
381 boolean found = false;
382
383 do {
384
385 token = readToken();
386
387 if ((ignoreCase && token.equalsIgnoreCase(query)) || token.equals(query)) {
388 found = true;
389 }
390 } while (!found);
391 }
392
393 /**
394 * Finds the end of the current block.
395 */
396 public void findEndBlock() throws IOException {
397 try {
398 String token;
399
400 do {
401 token = readToken(";");
402 } while (!token.equalsIgnoreCase("END") && !token.equalsIgnoreCase("ENDBLOCK"));
403 } catch (EOFException e) {
404 // Doesn't matter if the End is missing
405 }
406
407 nextBlock = UNKNOWN_BLOCK;
408 }
409
410 /**
411 * Reads the header information for a 'DATA', 'CHARACTERS' or 'TAXA' block.
412 */
413 private void readDataBlockHeader(String tokenToLookFor, NexusBlock block) throws ImportException, IOException {
414
415 boolean dim = false, ttl = false, fmt = false;
416 String token;
417
418 do {
419 token = readToken();
420
421 if (token.equalsIgnoreCase("TITLE")) {
422 if (ttl) {
423 throw new DuplicateFieldException("TITLE");
424 }
425
426 ttl = true;
427 } else if (token.equalsIgnoreCase("DIMENSIONS")) {
428
429 if (dim) {
430 throw new DuplicateFieldException("DIMENSIONS");
431 }
432
433 boolean nchar = (block == TAXA_BLOCK);
434 boolean ntax = (block == CHARACTERS_BLOCK);
435
436 do {
437 String token2 = readToken("=;");
438
439 if (getLastDelimiter() != '=') {
440 throw new BadFormatException("Unknown subcommand, '" + token2 + "', or missing '=' in DIMENSIONS command");
441 }
442
443 if (token2.equalsIgnoreCase("NTAX")) {
444
445 if (block == CHARACTERS_BLOCK) {
446 throw new BadFormatException("NTAX subcommand in CHARACTERS block");
447 }
448
449 taxonCount = readInteger(";");
450 ntax = true;
451
452 } else if (token2.equalsIgnoreCase("NCHAR")) {
453
454 if (block == TAXA_BLOCK) {
455 throw new BadFormatException("NCHAR subcommand in TAXA block");
456 }
457
458 siteCount = readInteger(";");
459 nchar = true;
460
461 } else {
462 throw new BadFormatException("Unknown subcommand, '" + token2 + "', in DIMENSIONS command");
463 }
464
465 } while (getLastDelimiter() != ';');
466
467 if (!ntax) {
468 throw new BadFormatException("NTAX subcommand missing from DIMENSIONS command");
469 }
470 if (!nchar) {
471 throw new BadFormatException("NCHAR subcommand missing from DIMENSIONS command");
472 }
473 dim = true;
474
475 } else if (token.equalsIgnoreCase("FORMAT")) {
476
477 if (fmt) {
478 throw new DuplicateFieldException("FORMAT");
479 }
480
481 dataType = null;
482
483 do {
484 String token2 = readToken("=;");
485
486 if (token2.equalsIgnoreCase("GAP")) {
487
488 if (getLastDelimiter() != '=') {
489 throw new BadFormatException("Expecting '=' after GAP subcommand in FORMAT command");
490 }
491
492 gapCharacters = readToken(";");
493
494 } else if (token2.equalsIgnoreCase("MISSING")) {
495
496 if (getLastDelimiter() != '=') {
497 throw new BadFormatException("Expecting '=' after MISSING subcommand in FORMAT command");
498 }
499
500 missingCharacters = readToken(";");
501
502 } else if (token2.equalsIgnoreCase("MATCHCHAR")) {
503
504 if (getLastDelimiter() != '=') {
505 throw new BadFormatException("Expecting '=' after MATCHCHAR subcommand in FORMAT command");
506 }
507
508 matchCharacters = readToken(";");
509
510 } else if (token2.equalsIgnoreCase("DATATYPE")) {
511
512 if (getLastDelimiter() != '=') {
513 throw new BadFormatException("Expecting '=' after DATATYPE subcommand in FORMAT command");
514 }
515
516 String token3 = readToken(";");
517 if (token3.equalsIgnoreCase("NUCLEOTIDE") ||
518 token3.equalsIgnoreCase("DNA") ||
519 token3.equalsIgnoreCase("RNA")) {
520
521 dataType = Nucleotides.INSTANCE;
522
523 } else if (token3.equalsIgnoreCase("STANDARD") || token3.equalsIgnoreCase("BINARY")) {
524
525 dataType = TwoStates.INSTANCE;
526
527 } else if (token3.equalsIgnoreCase("PROTEIN")) {
528
529 dataType = AminoAcids.INSTANCE;
530
531 } else if (token3.equalsIgnoreCase("CONTINUOUS")) {
532
533 throw new UnparsableDataException("Continuous data cannot be parsed at present");
534
535 }
536 } else if (token2.equalsIgnoreCase("INTERLEAVE")) {
537 isInterleaved = true;
538 }
539
540 } while (getLastDelimiter() != ';');
541
542 fmt = true;
543 }
544 } while (!token.equalsIgnoreCase(tokenToLookFor));
545
546 if (!dim) {
547 throw new MissingFieldException("DIMENSIONS");
548 }
549 if (block != TAXA_BLOCK && dataType == null) {
550 throw new MissingFieldException("DATATYPE");
551 }
552 }
553
554 /**
555 * Reads sequences in a 'DATA' or 'CHARACTERS' block.
556 */
557 private void readSequenceData(Sequences sequences, TaxonList taxonList) throws ImportException, IOException {
558 int n, i;
559 String firstSequence = null;
560
561 if (isInterleaved) {
562 boolean firstLoop = true;
563
564 int readCount = 0;
565 while (readCount < siteCount) {
566
567 n = -1;
568
569 for (i = 0; i < taxonCount; i++) {
570
571 String token = readToken().trim();
572
573 Sequence sequence;
574
575 if (firstLoop) {
576
577 sequence = new Sequence();
578 sequence.setDataType(dataType);
579 sequences.addSequence(sequence);
580
581 Taxon taxon;
582
583 if (taxonList != null) {
584 int index = taxonList.getTaxonIndex(token.trim());
585 if (index == -1) {
586 // taxon not found in taxon list...
587 // ...perhaps it is a numerical taxon reference?
588 throw new UnknownTaxonException(token);
589 } else {
590 taxon = taxonList.getTaxon(index);
591 }
592 } else {
593 taxon = new Taxon(token.trim());
594 }
595
596 sequence.setTaxon(taxon);
597
598 } else {
599
600 sequence = sequences.getSequence(i);
601 Taxon taxon = sequence.getTaxon();
602 if (!taxon.getId().equals(token)) {
603 throw new UnknownTaxonException("Unknown taxon label: expecting '" +
604 taxon.getId() + "', found '" + token + "'");
605 }
606 }
607
608 StringBuffer buffer = new StringBuffer();
609 readSequenceLine(buffer, dataType, ";", gapCharacters, missingCharacters,
610 matchCharacters, firstSequence);
611 String seqString = buffer.toString();
612 sequence.appendSequenceString(seqString);
613 if (i == 0) {
614 firstSequence = seqString;
615 }
616
617 if (getLastDelimiter() == ';') {
618 if (i < taxonCount - 1) {
619 throw new TooFewTaxaException();
620 }
621 if (readCount + n < siteCount) {
622 throw new ShortSequenceException(sequence.getTaxon().getId());
623 }
624 }
625
626 if (n == -1) {
627 n = seqString.length();
628 }
629
630 if (n != seqString.length()) {
631 throw new ShortSequenceException(sequence.getTaxon().getId());
632 }
633 }
634
635 firstLoop = false;
636 readCount += n;
637
638 }
639 if (getLastDelimiter() != ';') {
640 throw new BadFormatException("Expecting ';' after sequences data");
641 }
642
643 } else {
644
645 for (i = 0; i < taxonCount; i++) {
646 String token = readToken().trim();
647
648 Sequence sequence = new Sequence();
649 sequence.setDataType(dataType);
650 sequences.addSequence(sequence);
651
652 Taxon taxon;
653
654 if (taxonList != null) {
655 int index = taxonList.getTaxonIndex(token);
656 if (index == -1) {
657 // taxon not found in taxon list...
658 // ...perhaps it is a numerical taxon reference?
659 throw new UnknownTaxonException(token);
660 } else {
661 taxon = taxonList.getTaxon(index);
662 }
663 } else {
664 taxon = new Taxon(token);
665 }
666
667 sequence.setTaxon(taxon);
668
669 StringBuffer buffer = new StringBuffer();
670 readSequence(buffer, dataType, ";", siteCount, gapCharacters,
671 missingCharacters, matchCharacters, firstSequence);
672 String seqString = buffer.toString();
673 if (seqString.length() != siteCount) {
674 throw new ShortSequenceException(sequence.getTaxon().getId());
675 }
676
677 sequence.appendSequenceString(seqString);
678 if (i == 0) {
679 firstSequence = seqString;
680 }
681
682 if (getLastDelimiter() == ';' && i < taxonCount - 1) {
683 throw new TooFewTaxaException();
684 }
685
686 }
687
688 if (getLastDelimiter() != ';') {
689 throw new BadFormatException("Expecting ';' after sequences data, has '"
690 + (char) getLastDelimiter() + "' in line " + getLineNumber());
691 }
692
693 }
694 }
695
696
697 /**
698 * Reads a 'TAXA' block.
699 */
700 private TaxonList readTaxaBlock() throws ImportException, IOException, IllegalArgumentException {
701
702 taxonCount = 0;
703
704 readDataBlockHeader("TAXLABELS", TAXA_BLOCK);
705
706 if (taxonCount == 0) {
707 throw new MissingFieldException("NTAXA");
708 }
709
710 Taxa taxa = new Taxa();
711
712 do {
713 String name = readToken(";").trim();
714 if (name.length() > 0) {
715 Taxon taxon = new Taxon(name);
716 taxa.addTaxon(taxon);
717 }
718 } while (getLastDelimiter() != ';');
719
720 if (taxa.getTaxonCount() != taxonCount) {
721 throw new BadFormatException("Number of taxa doesn't match NTAXA field");
722 }
723
724 findEndBlock();
725
726 int duplicateTaxon = TaxonList.Utils.findDuplicateTaxon(taxa);
727 if (duplicateTaxon >= 0)
728 throw new IllegalArgumentException("Tree contains duplicate taxon name: " + taxa.getTaxon(duplicateTaxon).getId() +
729 "!\nAll taxon names should be unique.");
730
731 return taxa;
732 }
733
734 /**
735 * Reads a 'CHARACTERS' block.
736 */
737 private Alignment readCharactersBlock(TaxonList taxonList) throws ImportException, IOException {
738
739 siteCount = 0;
740 dataType = null;
741
742 readDataBlockHeader("MATRIX", CHARACTERS_BLOCK);
743
744 SimpleAlignment alignment = new SimpleAlignment();
745 readSequenceData(alignment, taxonList);
746 alignment.updateSiteCount();
747
748 findEndBlock();
749
750 return alignment;
751 }
752
753 /**
754 * Reads a 'DATA' block.
755 */
756 private Alignment readDataBlock(/*TaxonList taxonList*/) throws ImportException, IOException {
757
758 taxonCount = 0;
759 siteCount = 0;
760 dataType = null;
761
762 readDataBlockHeader("MATRIX", DATA_BLOCK);
763
764 SimpleAlignment alignment = new SimpleAlignment();
765 readSequenceData(alignment, null);
766 alignment.updateSiteCount();
767
768 findEndBlock();
769
770 return alignment;
771 }
772
773
774 /**
775 * Reads a 'TREES' block.
776 */
777 private Tree[] readTreesBlock(TaxonList taxonList, boolean useTaxonListNumbering) throws ImportException, IOException {
778 ArrayList<Tree> trees = new ArrayList<Tree>();
779
780 String[] lastToken = new String[1];
781 HashMap<String, Taxon> translationList = readTranslationList(taxonList, lastToken);
782
783 boolean done = false;
784 do {
785
786 Tree tree = readNextTree(translationList, lastToken, useTaxonListNumbering ? taxonList : null);
787
788 if (tree != null) {
789 trees.add(tree);
790 } else {
791 done = true;
792 }
793 } while (!done);
794
795 if (trees.size() == 0) {
796 throw new BadFormatException("No trees defined in TREES block");
797 }
798
799 Tree[] treeArray = new Tree[trees.size()];
800 trees.toArray(treeArray);
801
802 nextBlock = UNKNOWN_BLOCK;
803
804 return treeArray;
805 }
806
807 private HashMap<String, Taxon> readTranslationList(TaxonList taxonList, String[] lastToken) throws ImportException, IOException {
808 HashMap<String, Taxon> translationList = new HashMap<String, Taxon>();
809
810 String token = readToken(";");
811
812 if (token.equalsIgnoreCase("TRANSLATE")) {
813
814 do {
815 String token2 = readToken(",;");
816
817 if (getLastDelimiter() == ',' || getLastDelimiter() == ';') {
818 throw new BadFormatException("Missing taxon label in TRANSLATE command of TREES block");
819 }
820
821 String token3 = readToken(",;");
822 Taxon taxon;
823
824 if (getLastDelimiter() != ',' && getLastDelimiter() != ';') {
825 throw new BadFormatException("Expecting ',' or ';' after taxon label in TRANSLATE command of TREES block");
826 }
827
828 if (taxonList != null) {
829 int index = taxonList.getTaxonIndex(token3);
830 if (index == -1) {
831 // taxon not found in taxon list...
832 // ...perhaps it is a numerical taxon reference?
833 throw new UnknownTaxonException(token3);
834 } else {
835 taxon = taxonList.getTaxon(index);
836 }
837 } else {
838 taxon = new Taxon(token3);
839 }
840
841 if (translationList.containsKey(token2)) {
842 throw new BadFormatException("Translation list uses the key, " + token2 + ", more than once.");
843 }
844 translationList.put(token2, taxon);
845
846 } while (getLastDelimiter() != ';');
847
848 token = readToken(";");
849 } else if (taxonList != null) {
850 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
851 Taxon taxon = taxonList.getTaxon(i);
852 translationList.put(taxon.getId(), taxon);
853 }
854 }
855
856 lastToken[0] = token;
857
858 return translationList;
859 }
860
861 private Tree readNextTree(HashMap<String, Taxon> translationList, String[] lastToken, TaxonList taxonList) throws ImportException, IOException {
862 try {
863 Tree tree = null;
864 String token = lastToken[0];
865
866 if (token.equalsIgnoreCase("UTREE") || token.equalsIgnoreCase("TREE")) {
867
868 if (nextCharacter() == '*') {
869 // Star is used to specify a default tree - ignore it
870 readCharacter();
871 }
872
873 String token2 = readToken("=;");
874 // Save tree comment and attach it later
875 final String comment = getLastMetaComment();
876 clearLastMetaComment();
877
878 if (getLastDelimiter() != '=') {
879 throw new BadFormatException("Missing label for tree'" + token2 + "' or missing '=' in TREE command of TREES block");
880 }
881
882 try {
883 if (nextCharacter() != '(') {
884 throw new BadFormatException("Missing tree definition in TREE command of TREES block");
885 }
886
887 // tree special comments
888 final String scomment = getLastMetaComment();
889 clearLastMetaComment();
890
891 FlexibleNode root = readInternalNode(translationList);
892
893 if (translationList != null) {
894 // this ensures that if a translation list is used, the external node numbers
895 // of the trees correspond as well.
896
897 Map<Taxon, Integer> taxonNumberMap = new HashMap<Taxon, Integer>();
898 int count = 0;
899 for (String label : translationList.keySet()) {
900 Taxon taxon = translationList.get(label);
901 int number;
902
903 if (taxonList != null) { // Map back to original numbering from TaxonList
904 number = taxonList.getTaxonIndex(taxon);
905 } else { // Old functionality
906 try {
907 number = Integer.parseInt(label) - 1;
908 } catch (NumberFormatException nfe) {
909 number = count;
910 }
911 }
912
913 taxonNumberMap.put(taxon, number);
914 count++;
915 }
916
917 tree = new FlexibleTree(root, false, true, taxonNumberMap);
918 } else {
919 tree = new FlexibleTree(root, false, true, null);
920 }
921
922 tree.setId(token2);
923
924 if (getLastDelimiter() == ':') {
925 // in case the root has a branch length, skip it
926 readToken(";");
927
928 if (getLastMetaComment() != null) {
929 // There was a meta-comment which should be in the form:
930 // \[&label[=value][,label[=value]>[,/..]]\]
931 try {
932 parseMetaCommentPairs(getLastMetaComment(), root);
933 } catch (BadFormatException bfe) {
934 // ignore it
935 }
936 clearLastMetaComment();
937 }
938 }
939
940 if (getLastDelimiter() != ';') {
941 throw new BadFormatException("Expecting ';' after tree, '" + token2 + "', TREE command of TREES block");
942 }
943
944 if (scomment != null) {
945 // below is correct only if [&W] appears on it own
946 String c = scomment;
947 while (c.length() > 0) {
948 final char ch = c.charAt(0);
949 if (ch == ';') {
950 c = c.substring(1);
951 continue;
952 }
953 if (ch == 'R') {
954 // we only have rooted trees anyway
955 c = c.substring(1);
956 } else if (ch == 'W') {
957 int e = c.indexOf(';');
958 if (e < 0) e = c.length();
959
960 try {
961 final Float value = new Float(c.substring(2, e));
962 tree.setAttribute("weight", value);
963 } catch (NumberFormatException ex) {
964 // don't fail, ignore
965 }
966 c = c.substring(e);
967 } else {
968 c = c.substring(1);
969 }
970 }
971 }
972
973 if (comment != null) {
974 try {
975 parseMetaCommentPairs(comment, tree);
976 } catch (Importer.BadFormatException e) {
977 // set generic comment attribute
978 tree.setAttribute("comment", comment);
979 }
980 }
981
982 } catch (EOFException e) {
983 // If we reach EOF we may as well return what we have?
984 return tree;
985 }
986
987 token = readToken(";");
988 } else if (token.equalsIgnoreCase("ENDBLOCK") || token.equalsIgnoreCase("END")) {
989 return null;
990 } else {
991 throw new BadFormatException("Unknown command '" + token + "' in TREES block");
992 }
993
994 //added this to escape readNextTree loop correctly -- AJD
995 lastToken[0] = token;
996
997 return tree;
998
999 } catch (EOFException e) {
1000 return null;
1001 }
1002 }
1003
1004 /**
1005 * Reads a branch in. This could be a node or a tip (calls readNode or readTip
1006 * accordingly). It then reads the branch length and SimpleNode that will
1007 * point at the new node or tip.
1008 */
1009 FlexibleNode readBranch(HashMap<String, Taxon> translationList) throws IOException, ImportException {
1010 double length = 0.0;
1011 FlexibleNode branch;
1012
1013 clearLastMetaComment();
1014
1015 if (nextCharacter() == '(') {
1016 // is an internal node
1017 branch = readInternalNode(translationList);
1018
1019 } else {
1020 // is an external node
1021 branch = readExternalNode(translationList);
1022 }
1023
1024 if (getLastDelimiter() != ':' && getLastDelimiter() != ',' && getLastDelimiter() != ')') {
1025 String label = readToken(",():;");
1026 if (label.length() > 0) {
1027 branch.setAttribute("label", label);
1028 }
1029 }
1030
1031 if (getLastDelimiter() == ':') {
1032 length = readDouble(",():;");
1033
1034 if (getLastMetaComment() != null) {
1035 if (!ignoreMetaComments) {
1036 // There was a meta-comment which should be in the form:
1037 // \[&label[=value][,label[=value]>[,/..]]\]
1038 try {
1039 parseMetaCommentPairs(getLastMetaComment(), branch);
1040 } catch (BadFormatException bfe) {
1041 // ignore it
1042 }
1043 }
1044 clearLastMetaComment();
1045 }
1046
1047 }
1048
1049 branch.setLength(length);
1050
1051 return branch;
1052 }
1053
1054 /**
1055 * Reads a node in. This could be a polytomy. Calls readBranch on each branch
1056 * in the node.
1057 */
1058 FlexibleNode readInternalNode(HashMap<String, Taxon> translationList) throws IOException, ImportException {
1059 FlexibleNode node = new FlexibleNode();
1060
1061 // read the opening '('
1062 readCharacter();
1063
1064 // read the first child
1065 node.addChild(readBranch(translationList));
1066
1067 if (getLastDelimiter() != ',' && !suppressWarnings) {
1068 java.util.logging.Logger.getLogger("dr.evolution.io").warning("Internal node only has a single child.");
1069 }
1070
1071 // this allows one or more children
1072 while(getLastDelimiter()==',') {
1073 node.addChild(readBranch(translationList));
1074 }
1075
1076 // should have had a closing ')'
1077 if (getLastDelimiter() != ')') {
1078 throw new BadFormatException("Missing closing ')' in tree in TREES block");
1079 }
1080
1081 readToken(":(),;");
1082
1083 if (getLastMetaComment() != null) {
1084 if (!ignoreMetaComments) {
1085 // There was a meta-comment which should be in the form:
1086 // \[&label[=value][,label[=value]>[,/..]]\]
1087 try {
1088 parseMetaCommentPairs(getLastMetaComment(), node);
1089 } catch (BadFormatException bfe) {
1090 // ignore it
1091 }
1092 }
1093 clearLastMetaComment();
1094 }
1095
1096 // find the next delimiter
1097 return node;
1098 }
1099
1100 // private void labelNode(FlexibleNode node, String label, String value) {
1101 // // Attempt to format the value as a number
1102 // Number number = null;
1103 // try {
1104 // number = Integer.valueOf(value);
1105 // } catch (NumberFormatException nfe1) {
1106 // try {
1107 // number = Double.valueOf(value);
1108 // } catch (NumberFormatException nfe2) {
1109 // //
1110 // }
1111 // }
1112 // if (number != null) {
1113 // node.setAttribute(label, number);
1114 // } else {
1115 // node.setAttribute(label, value);
1116 // }
1117 // }
1118
1119 /**
1120 * Reads an external node in.
1121 */
1122 FlexibleNode readExternalNode(HashMap<String, Taxon> translationList) throws ImportException, IOException {
1123 FlexibleNode node = new FlexibleNode();
1124
1125 String label = readToken(":(),;");
1126
1127 Taxon taxon;
1128
1129 if (translationList.size() > 0) {
1130 taxon = translationList.get(label);
1131
1132 if (taxon == null) {
1133 // taxon not found in taxon list...
1134 throw new UnknownTaxonException("Taxon in tree, '" + label + "' is unknown");
1135 }
1136 } else {
1137 taxon = new Taxon(label);
1138 }
1139
1140 if (getLastMetaComment() != null) {
1141 if (!ignoreMetaComments) {
1142 // There was a meta-comment which should be in the form:
1143 // \[&label[=value][,label[=value]>[,/..]]\]
1144 try {
1145 parseMetaCommentPairs(getLastMetaComment(), node);
1146 } catch (BadFormatException bfe) {
1147 // ignore it
1148 }
1149 }
1150 clearLastMetaComment();
1151 }
1152
1153 node.setTaxon(taxon);
1154 return node;
1155 }
1156
1157 /**
1158 * Reads a 'CALIBRATION' block.
1159 */
1160 private dr.evolution.util.Date[] readCalibrationBlock(TaxonList taxonList) throws ImportException, IOException {
1161 double origin = 0.0;
1162 boolean isBackwards = false;
1163 Units.Type units = Units.Type.YEARS;
1164 ArrayList<Date> dates = new ArrayList<Date>();
1165
1166 String token;
1167
1168 boolean done = false;
1169 do {
1170 token = readToken(";");
1171
1172 if (token.equalsIgnoreCase("OPTIONS")) {
1173
1174 do {
1175 String token2 = readToken("=;");
1176
1177 if (getLastDelimiter() != '=') {
1178 throw new BadFormatException("Unknown subcommand, '" + token2 + "', or missing '=' in OPTIONS command of CALIBRATION block");
1179 }
1180
1181 if (token2.equalsIgnoreCase("SCALE")) {
1182
1183 String token3 = readToken(";");
1184 if (token3.equalsIgnoreCase("DAYS")) {
1185
1186 units = Units.Type.DAYS;
1187
1188 } else if (token3.equalsIgnoreCase("MONTHS")) {
1189
1190 units = Units.Type.MONTHS;
1191
1192 } else if (token3.equalsIgnoreCase("YEARS")) {
1193
1194 units = Units.Type.YEARS;
1195
1196 } else {
1197 throw new BadFormatException("SCALE in OPTIONS command of CALIBRATION block must be one of DAYS, MONTHS or YEARS");
1198 }
1199
1200 } else if (token2.equalsIgnoreCase("ORIGIN")) {
1201
1202 origin = readDouble(";");
1203
1204 } else if (token2.equalsIgnoreCase("DIRECTION")) {
1205
1206 String token3 = readToken(";");
1207 if (token3.equalsIgnoreCase("FORWARDS")) {
1208
1209 isBackwards = false;
1210
1211 } else if (token3.equalsIgnoreCase("BACKWARDS")) {
1212
1213 isBackwards = true;
1214
1215 } else {
1216 throw new BadFormatException("DIRECTION in OPTIONS command of CALIBRATION block must be either FORWARDS or BACKWARDS");
1217 }
1218
1219
1220 } else {
1221 throw new BadFormatException("Unknown subcommand, '" + token2 + "', in OPTIONS command of CALIBRATION block");
1222 }
1223
1224 } while (getLastDelimiter() != ';');
1225
1226 } else if (token.equalsIgnoreCase("TIPCALIBRATION")) {
1227
1228 do {
1229 String token2 = readToken("=;");
1230
1231 if (getLastDelimiter() != '=') {
1232 throw new BadFormatException("Missing date for label '" + token2 + "' or missing '=' in TIPCALIBRATION command of CALIBRATION block");
1233 }
1234
1235 double value = readDouble(":;");
1236
1237 if (getLastDelimiter() != ':') {
1238 throw new BadFormatException("Missing taxon list for label '" + token2 + "' or missing ':' in TIPCALIBRATION command of CALIBRATION block");
1239 }
1240
1241 dr.evolution.util.Date date;
1242 if (isBackwards) {
1243 date = dr.evolution.util.Date.createTimeAgoFromOrigin(value, units, origin);
1244 } else {
1245 date = dr.evolution.util.Date.createTimeSinceOrigin(value, units, origin);
1246 }
1247
1248 dates.add(date);
1249
1250 do {
1251 String token3 = readToken(",;");
1252 Taxon taxon;
1253
1254 int index = taxonList.getTaxonIndex(token3);
1255 if (index == -1) {
1256 // taxon not found in taxon list...
1257 throw new UnknownTaxonException("Unknown taxon '" + token3 + "' for label '" + token2 + "' in TIPCALIBRATION command of CALIBRATION block");
1258 } else {
1259 taxon = taxonList.getTaxon(index);
1260 }
1261
1262 taxon.setAttribute("date", date);
1263
1264 } while (getLastDelimiter() != ',' && getLastDelimiter() != ';');
1265
1266 } while (getLastDelimiter() == ',');
1267
1268 } else if (token.equalsIgnoreCase("NODECALIBRATION")) {
1269 throw new BadFormatException("NODECALIBRATION not suppored in CALIBRATION block");
1270 } else if (token.equalsIgnoreCase("ENDBLOCK") || token.equalsIgnoreCase("END")) {
1271 done = true;
1272 } else {
1273 throw new BadFormatException("Unknown command '" + token + "' in CALIBRATION block");
1274 }
1275 } while (!done);
1276
1277 dr.evolution.util.Date[] dateArray = new dr.evolution.util.Date[dates.size()];
1278 dates.toArray(dateArray);
1279
1280 nextBlock = UNKNOWN_BLOCK;
1281
1282 return dateArray;
1283 }
1284
1285 static void parseMetaCommentPairs(String meta, Attributable item) throws Importer.BadFormatException {
1286 if (meta.startsWith("B ")) {
1287 // a MrBayes annotation
1288 String[] parts = meta.split(" ");
1289 if (parts.length == 3 && parts[1].length() > 0 && parts[2].length() > 0) {
1290 item.setAttribute(parts[1], parseValue(parts[2]));
1291 } else if (parts.length == 2 && parts[1].length() > 0) {
1292 item.setAttribute(parts[1], Boolean.TRUE);
1293 } else {
1294 throw new Importer.BadFormatException("Badly formatted attribute: '" + meta + "'");
1295 }
1296 return;
1297 }
1298
1299 // This regex should match key=value pairs, separated by commas
1300 // This can match the following types of meta comment pairs:
1301 // value=number, value="string", value={item1, item2, item3}
1302 // (label must be quoted if it contains spaces (i.e. "my label"=label)
1303
1304 // TODO MAS Minor change in line below for nested arrays may cause other unforeseen bugs
1305 Pattern pattern = Pattern.compile("(\"[^\"]*\"+|[^,=\\s]+)\\s*(=\\s*(\\{[^=]*\\}|\"[^\"]*\"+|[^,]+))?");
1306 Matcher matcher = pattern.matcher(meta);
1307
1308 while (matcher.find()) {
1309 String label = matcher.group(1);
1310 if (label.charAt(0) == '\"') {
1311 label = label.substring(1, label.length() - 1);
1312 }
1313 if (label == null || label.trim().length() == 0) {
1314 throw new Importer.BadFormatException("Badly formatted attribute: '" + matcher.group() + "'");
1315 }
1316 final String value = matcher.group(2);
1317 if (value != null && value.trim().length() > 0) {
1318 // there is a specified value so try to parse it
1319 item.setAttribute(label, parseValue(value.substring(1)));
1320 } else {
1321 item.setAttribute(label, Boolean.TRUE);
1322 }
1323 }
1324 }
1325
1326 public static boolean isInt(String str)
1327 {
1328 if (str == null) {
1329 return false;
1330 }
1331 int length = str.length();
1332 if (length == 0) {
1333 return false;
1334 }
1335 int i = 0;
1336 if (str.charAt(0) == '-') {
1337 if (length == 1) {
1338 return false;
1339 }
1340 i = 1;
1341 }
1342 for (; i < length; i++) {
1343 char c = str.charAt(i);
1344 if (c <= '/' || c >= ':') {
1345 return false;
1346 }
1347 }
1348 return true;
1349 }
1350
1351 /**
1352 * This method takes a string and tries to decode it returning the object
1353 * that best fits the data. It will recognize comma delimited lists enclosed
1354 * in {..} and call parseValue() on each element. It will also recognize Boolean,
1355 * Integer and Double. If the value starts with a # then it will attempt to decode
1356 * the following integer as an RGB colour - see Color.decode(). If nothing else fits
1357 * then the value will be returned as a string but trimmed of leading and trailing
1358 * white space.
1359 *
1360 * @param value the string
1361 * @return the object
1362 */
1363 public static Serializable parseValue(String value) {
1364
1365 value = value.trim();
1366
1367 if (value.startsWith("{")) {
1368 // the value is a list so recursively parse the elements
1369 // and return an array
1370 String inside = value.substring(1, value.length() - 1);
1371
1372 if (inside.length() == 0) {
1373 return null;
1374 }
1375
1376 // Determine depth of further nesting
1377 int depth = 0;
1378 while (inside.charAt(depth) == '{') {
1379 depth++;
1380 }
1381
1382 StringBuilder split;
1383 if (depth == 0) {
1384 split = new StringBuilder(",");
1385 } else {
1386 StringBuilder rightBookEnd = new StringBuilder("(?<=");
1387 StringBuilder leftBookEnd = new StringBuilder("(?=");
1388 for (int i = 0; i < depth; ++i) {
1389 rightBookEnd.append("\\}");
1390 leftBookEnd.append("\\{");
1391 }
1392 leftBookEnd.append(")");
1393 rightBookEnd.append(")");
1394 split = rightBookEnd.append(",").append(leftBookEnd);
1395 }
1396
1397 // Non-destructive split
1398 String[] elements = inside.split(split.toString());
1399 Object[] values = new Object[elements.length];
1400 for (int i = 0; i < elements.length; i++) {
1401 values[i] = parseValue(elements[i]);
1402 }
1403 return values;
1404 }
1405
1406 if (value.startsWith("#")) {
1407 // I am not sure whether this is a good idea but
1408 // I am going to assume that a # denotes an RGB colour
1409 try {
1410 return Color.decode(value.substring(1));
1411 } catch (NumberFormatException nfe1) {
1412 // not a colour
1413 }
1414 }
1415
1416 if (value.equalsIgnoreCase("TRUE") || value.equalsIgnoreCase("FALSE")) {
1417 return Boolean.valueOf(value);
1418 }
1419
1420 // Attempt to format the value as an integer
1421 // try {
1422 // return new Integer(value);
1423 // } catch (NumberFormatException nfe1) {
1424 // // not an integer
1425 // }
1426 // throwing exception to test for an integer is slow
1427 if (isInt(value)) {
1428 return Integer.valueOf(value);
1429 }
1430
1431 // Attempt to format the value as a double
1432 try {
1433 return new Double(value);
1434 } catch (NumberFormatException nfe2) {
1435 // not a double
1436 }
1437
1438 // return the trimmed string
1439 return value;
1440 }
1441
1442 // private stuff
1443
1444 private NexusBlock nextBlock = null;
1445
1446 private int taxonCount = 0, siteCount = 0;
1447 private DataType dataType = null;
1448 private String gapCharacters = "-";
1449 private String matchCharacters = ".";
1450 private String missingCharacters = "?";
1451 private boolean isInterleaved = false;
1452
1453 public static void main(String[] args) throws IOException, ImportException {
1454
1455 if (args.length > 3) {
1456
1457 int sampleFrequency = Integer.parseInt(args[1]);
1458 boolean includeBranchLengths = Boolean.getBoolean(args[2]);
1459 boolean isNexus = Boolean.getBoolean(args[3]);
1460
1461 NexusImporter nexusImporter = null;
1462
1463 BufferedReader reader = null;
1464
1465 if (isNexus) {
1466 nexusImporter = new NexusImporter(new FileReader(args[0]));
1467 } else {
1468 reader = new BufferedReader(new FileReader(args[0]));
1469 }
1470
1471
1472 int index = 0;
1473 int count = 0;
1474 String line = null;
1475 if (!isNexus) line = reader.readLine();
1476 while (line != null || (isNexus && nexusImporter.hasTree())) {
1477
1478 Tree tree;
1479 if (isNexus) {
1480 tree = nexusImporter.importNextTree();
1481 } else {
1482 String treeString = line.substring(line.indexOf('(')).trim();
1483
1484 java.io.Reader stringReader = new java.io.StringReader(treeString);
1485 NewickImporter importer = new NewickImporter(stringReader);
1486 tree = importer.importNextTree();
1487 }
1488
1489
1490 if (index % sampleFrequency == 0) {
1491 if (includeBranchLengths) {
1492 System.out.println(TreeUtils.newick(tree));
1493 } else {
1494 System.out.println(TreeUtils.newickNoLengths(tree));
1495 count += 1;
1496 }
1497 }
1498 index += 1;
1499 if (!isNexus) line = reader.readLine();
1500 }
1501 System.out.println(count + " trees");
1502
1503 } else {
1504 System.err.println("usage: filterTrees <tree-file-name> <sample-frequency> <include-branch-lengths>");
1505 }
1506
1507
1508 }
1509
1510 }