2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2013 Christian M. Zmasek
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Lesser General Public
9 // License as published by the Free Software Foundation; either
10 // version 2.1 of the License, or (at your option) any later version.
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // Lesser General Public License for more details.
17 // You should have received a copy of the GNU Lesser General Public
18 // License along with this library; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 // Contact: phylosoft @ gmail . com
22 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
24 package org.forester.io.parsers.nhx;
26 import java.io.BufferedReader;
28 import java.io.FileNotFoundException;
29 import java.io.FileReader;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.InputStreamReader;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.StringTokenizer;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
39 import org.forester.io.parsers.IteratingPhylogenyParser;
40 import org.forester.io.parsers.PhylogenyParser;
41 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
42 import org.forester.io.parsers.util.ParserUtils;
43 import org.forester.io.parsers.util.PhylogenyParserException;
44 import org.forester.phylogeny.Phylogeny;
45 import org.forester.phylogeny.PhylogenyMethods;
46 import org.forester.phylogeny.PhylogenyNode;
47 import org.forester.phylogeny.data.Accession;
48 import org.forester.phylogeny.data.Confidence;
49 import org.forester.phylogeny.data.Event;
50 import org.forester.phylogeny.data.Identifier;
51 import org.forester.phylogeny.data.PhylogenyDataUtil;
52 import org.forester.phylogeny.data.Sequence;
53 import org.forester.phylogeny.data.Taxonomy;
54 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
55 import org.forester.util.ForesterUtil;
57 public final class NHXParser implements PhylogenyParser, IteratingPhylogenyParser {
59 public static final TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION_DEFAULT = TAXONOMY_EXTRACTION.NO;
60 public final static Pattern NUMBERS_ONLY_PATTERN = Pattern.compile( "^[0-9\\.]+$" );
61 public final static Pattern MB_PROB_PATTERN = Pattern.compile( "prob=([^,]+)" );
62 public final static Pattern MB_PROB_SD_PATTERN = Pattern.compile( "prob_stddev=([^,]+)" );
63 public final static Pattern MB_BL_PATTERN = Pattern.compile( "length_median=([^,]+)" );
64 final static private boolean GUESS_ROOTEDNESS_DEFAULT = true;
65 final static private boolean GUESS_IF_SUPPORT_VALUES = true;
66 final static private boolean IGNORE_QUOTES_DEFAULT = false;
67 final static public boolean REPLACE_UNDERSCORES_DEFAULT = false;
68 final static private byte STRING = 0;
69 final static private byte STRING_BUFFER = 1;
70 final static private byte CHAR_ARRAY = 2;
71 final static private byte BUFFERED_READER = 3;
72 final static private byte STRING_BUILDER = 4;
73 private boolean _guess_rootedness;
74 private boolean _ignore_quotes;
75 private byte _input_type;
76 private int _source_length;
77 private PhylogenyNode _current_node;
78 private StringBuilder _current_anotation;
79 private Object _nhx_source;
80 private int _clade_level;
81 private Phylogeny _current_phylogeny;
82 private TAXONOMY_EXTRACTION _taxonomy_extraction;
83 private boolean _replace_underscores;
84 private boolean _in_comment = false;
85 private boolean _saw_colon = false;
86 private boolean _saw_closing_paren;
87 private boolean _saw_open_bracket = false;
88 private boolean _in_open_bracket = false;
89 private boolean _in_double_quote = false;
90 private boolean _in_single_quote = false;
91 private String _my_source_str = null;
92 private StringBuffer _my_source_sbuff = null;
93 private StringBuilder _my_source_sbuil = null;
94 private char[] _my_source_charary = null;
95 private BufferedReader _my_source_br = null;
97 private Phylogeny _next;
98 private Object _source;
104 public final TAXONOMY_EXTRACTION getTaxonomyExtraction() {
105 return _taxonomy_extraction;
109 public final boolean hasNext() {
110 return _next != null;
114 public final Phylogeny next() throws NHXFormatException, IOException {
115 final Phylogeny phy = _next;
122 public final Phylogeny[] parse() throws IOException {
124 final List<Phylogeny> l = new ArrayList<Phylogeny>();
126 while ( hasNext() ) {
131 final Phylogeny[] p = new Phylogeny[ l.size() ];
132 for( int i = 0; i < l.size(); ++i ) {
141 public final void reset() throws NHXFormatException, IOException {
146 _saw_open_bracket = false;
147 _in_open_bracket = false;
148 _in_double_quote = false;
149 _in_single_quote = false;
151 _current_anotation = new StringBuilder();
152 _current_phylogeny = null;
153 _current_node = null;
154 _my_source_str = null;
155 _my_source_sbuff = null;
156 _my_source_sbuil = null;
157 _my_source_charary = null;
158 _my_source_br = null;
159 determineSourceType( _source );
160 switch ( _input_type ) {
162 _my_source_str = ( String ) _nhx_source;
165 _my_source_sbuff = ( StringBuffer ) _nhx_source;
168 _my_source_sbuil = ( StringBuilder ) _nhx_source;
171 _my_source_charary = ( char[] ) _nhx_source;
173 case BUFFERED_READER:
175 // if ( _my_source_br != null ) {
177 // _my_source_br.close();
179 // catch ( final IOException e ) {
183 _my_source_br = ( BufferedReader ) _nhx_source;
186 throw new RuntimeException( "unknown input type" );
191 public final void setGuessRootedness( final boolean guess_rootedness ) {
192 _guess_rootedness = guess_rootedness;
195 public final void setIgnoreQuotes( final boolean ignore_quotes ) {
196 _ignore_quotes = ignore_quotes;
199 public final void setReplaceUnderscores( final boolean replace_underscores ) {
200 _replace_underscores = replace_underscores;
204 public final void setSource( final Object nhx_source ) throws NHXFormatException, IOException {
205 _source = nhx_source;
209 public final void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
210 _taxonomy_extraction = taxonomy_extraction;
213 private final void determineSourceType( final Object nhx_source ) throws PhylogenyParserException,
214 FileNotFoundException {
215 if ( nhx_source == null ) {
216 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
218 else if ( nhx_source instanceof String ) {
219 _input_type = NHXParser.STRING;
220 _source_length = ( ( String ) nhx_source ).length();
221 _nhx_source = nhx_source;
223 else if ( nhx_source instanceof StringBuilder ) {
224 _input_type = NHXParser.STRING_BUILDER;
225 _source_length = ( ( StringBuilder ) nhx_source ).length();
226 _nhx_source = nhx_source;
228 else if ( nhx_source instanceof StringBuffer ) {
229 _input_type = NHXParser.STRING_BUFFER;
230 _source_length = ( ( StringBuffer ) nhx_source ).length();
231 _nhx_source = nhx_source;
233 else if ( nhx_source instanceof StringBuilder ) {
234 _input_type = NHXParser.STRING_BUILDER;
235 _source_length = ( ( StringBuilder ) nhx_source ).length();
236 _nhx_source = nhx_source;
238 else if ( nhx_source instanceof char[] ) {
239 _input_type = NHXParser.CHAR_ARRAY;
240 _source_length = ( ( char[] ) nhx_source ).length;
241 _nhx_source = nhx_source;
243 else if ( nhx_source instanceof File ) {
244 _input_type = NHXParser.BUFFERED_READER;
246 final File f = ( File ) nhx_source;
247 final String error = ForesterUtil.isReadableFile( f );
248 if ( !ForesterUtil.isEmpty( error ) ) {
249 throw new PhylogenyParserException( error );
251 _nhx_source = new BufferedReader( new FileReader( f ) );
253 else if ( nhx_source instanceof InputStream ) {
254 _input_type = NHXParser.BUFFERED_READER;
256 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
257 _nhx_source = new BufferedReader( isr );
260 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
261 + " StringBuffer, StringBuilder, char[], File," + " or InputStream "
262 + " [attempt to parse object of " + nhx_source.getClass() + "]." );
266 private final Phylogeny finishPhylogeny() throws PhylogenyParserException, NHXFormatException,
267 PhyloXmlDataFormatException {
268 if ( _current_phylogeny != null ) {
269 parseNHX( _current_anotation != null ? _current_anotation.toString() : "",
270 _current_phylogeny.getRoot(),
271 getTaxonomyExtraction(),
272 isReplaceUnderscores() );
273 if ( GUESS_IF_SUPPORT_VALUES ) {
274 if ( isBranchLengthsLikeBootstrapValues( _current_phylogeny ) ) {
275 moveBranchLengthsToConfidenceValues( _current_phylogeny );
278 if ( isGuessRootedness() ) {
279 final PhylogenyNode root = _current_phylogeny.getRoot();
280 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
281 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
282 _current_phylogeny.setRooted( true );
286 return _current_phylogeny;
291 private final Phylogeny finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
292 PhyloXmlDataFormatException {
293 final PhylogenyNode new_node = new PhylogenyNode();
294 parseNHX( _current_anotation.toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
295 _current_phylogeny = new Phylogeny();
296 _current_phylogeny.setRoot( new_node );
297 return _current_phylogeny;
300 private final void getNext() throws IOException, NHXFormatException {
301 if ( _source == null ) {
302 throw new IOException( "source is not set" );
306 if ( _input_type == BUFFERED_READER ) {
307 final int ci = _my_source_br.read();
316 if ( _i >= _source_length ) {
320 switch ( _input_type ) {
322 c = _my_source_str.charAt( _i );
325 c = _my_source_sbuff.charAt( _i );
328 c = _my_source_sbuil.charAt( _i );
331 c = _my_source_charary[ _i ];
337 if ( !_in_single_quote && !_in_double_quote ) {
341 else if ( !( ( c < 33 ) || ( c > 126 ) ) && _saw_colon
342 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
345 if ( _in_open_bracket && ( c == ']' ) ) {
346 _in_open_bracket = false;
349 // \n\t is always ignored,
350 // as is " (34) and ' (39) (space is 32):
351 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( _clade_level == 0 ) && ( c == ';' ) ) ) )
352 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( _clade_level == 0 ) && ( c == ';' ) ) ) ) ) {
355 else if ( ( c == 32 ) && ( !_in_single_quote && !_in_double_quote ) ) {
358 else if ( _in_comment ) {
363 else if ( _in_double_quote ) {
365 _in_double_quote = false;
368 _current_anotation.append( c );
371 else if ( c == '"' ) {
372 _in_double_quote = true;
374 else if ( _in_single_quote ) {
376 _in_single_quote = false;
379 _current_anotation.append( c );
382 else if ( c == 39 ) {
383 _in_single_quote = true;
385 else if ( c == '[' ) {
386 _saw_open_bracket = true;
387 _in_open_bracket = true;
389 else if ( _saw_open_bracket ) {
391 // everything not starting with "[&" is considered a comment
392 // unless ":digits and/or . [bootstrap]":
394 _current_anotation.append( "[&" );
396 else if ( _saw_colon ) {
397 _current_anotation.append( "[" + c );
403 // comment consisting just of "[]":
404 _saw_open_bracket = false;
406 else if ( ( c == '(' ) && !_in_open_bracket ) {
407 final Phylogeny phy = processOpenParen();
415 else if ( ( c == ')' ) && !_in_open_bracket ) {
418 else if ( ( c == ',' ) && !_in_open_bracket ) {
422 _current_anotation.append( c );
426 if ( _clade_level != 0 ) {
427 throw new PhylogenyParserException( "error in NH (Newick) formatted data: most likely cause: number of open parens does not equal number of close parens" );
429 if ( _current_phylogeny != null ) {
431 _next = finishPhylogeny();
432 _current_phylogeny = null;
433 _current_anotation = null;
435 else if ( ( _current_anotation != null ) && ( _current_anotation.length() > 0 ) ) {
436 _next = finishSingleNodePhylogeny();
437 _current_anotation = null;
444 private final void init() {
445 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
446 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
447 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
448 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
451 private final boolean isGuessRootedness() {
452 return _guess_rootedness;
455 private final boolean isIgnoreQuotes() {
456 return _ignore_quotes;
459 private final boolean isReplaceUnderscores() {
460 return _replace_underscores;
463 private final void processCloseParen() throws PhylogenyParserException, NHXFormatException,
464 PhyloXmlDataFormatException {
465 if ( _clade_level < 0 ) {
466 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
469 if ( !_saw_closing_paren ) {
470 final PhylogenyNode new_node = new PhylogenyNode();
471 parseNHX( _current_anotation.toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
472 _current_anotation = new StringBuilder();
473 _current_node.addAsChild( new_node );
476 parseNHX( _current_anotation.toString(),
477 _current_node.getLastChildNode(),
478 getTaxonomyExtraction(),
479 isReplaceUnderscores() );
480 _current_anotation = new StringBuilder();
482 if ( !_current_node.isRoot() ) {
483 _current_node = _current_node.getParent();
485 _saw_closing_paren = true;
488 private final void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
489 if ( !_saw_closing_paren ) {
490 final PhylogenyNode new_node = new PhylogenyNode();
491 parseNHX( _current_anotation.toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
492 if ( _current_node == null ) {
493 throw new NHXFormatException( "format might not be NH or NHX" );
495 _current_node.addAsChild( new_node );
498 parseNHX( _current_anotation.toString(),
499 _current_node.getLastChildNode(),
500 getTaxonomyExtraction(),
501 isReplaceUnderscores() );
503 _current_anotation = new StringBuilder();
504 _saw_closing_paren = false;
507 private final Phylogeny processOpenParen() throws PhylogenyParserException, NHXFormatException,
508 PhyloXmlDataFormatException {
509 Phylogeny phy = null;
510 final PhylogenyNode new_node = new PhylogenyNode();
511 if ( _clade_level == 0 ) {
512 if ( _current_phylogeny != null ) {
514 phy = finishPhylogeny();
517 _current_anotation = new StringBuilder();
518 _current_phylogeny = new Phylogeny();
519 _current_phylogeny.setRoot( new_node );
523 _current_node.addAsChild( new_node );
525 _current_node = new_node;
526 _saw_closing_paren = false;
530 public final static void parseNHX( String s,
531 final PhylogenyNode node_to_annotate,
532 final TAXONOMY_EXTRACTION taxonomy_extraction,
533 final boolean replace_underscores ) throws NHXFormatException,
534 PhyloXmlDataFormatException {
535 if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
536 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
538 if ( ( s != null ) && ( s.length() > 0 ) ) {
539 if ( replace_underscores ) {
540 s = s.replaceAll( "_+", " " );
542 boolean is_nhx = false;
543 final int ob = s.indexOf( "[" );
547 final int cb = s.indexOf( "]" );
549 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
551 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
552 b = s.substring( ob + 6, cb );
555 // No &&NHX and digits only: is likely to be a support value.
556 final String bracketed = s.substring( ob + 1, cb );
557 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
558 if ( numbers_only.matches() ) {
559 b = ":" + NHXtags.SUPPORT + bracketed;
561 else if ( s.indexOf( "prob=" ) > -1 ) {
562 processMrBayes3Data( s, node_to_annotate );
565 s = s.substring( 0, ob ) + b;
566 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
567 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
570 final StringTokenizer t = new StringTokenizer( s, ":" );
571 if ( t.countTokens() > 0 ) {
572 if ( !s.startsWith( ":" ) ) {
573 node_to_annotate.setName( t.nextToken() );
574 if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
575 ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
578 while ( t.hasMoreTokens() ) {
580 if ( s.startsWith( NHXtags.SPECIES_NAME ) ) {
581 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
582 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
584 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
586 else if ( s.startsWith( NHXtags.IS_DUPLICATION ) ) {
587 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
588 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
590 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
591 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
593 else if ( s.charAt( 2 ) == '?' ) {
594 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
597 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
600 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
601 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
603 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
604 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
605 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
607 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
609 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
610 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
611 node_to_annotate.getNodeData().setSequence( new Sequence() );
613 node_to_annotate.getNodeData().getSequence()
614 .setAccession( new Accession( s.substring( 3 ), "?" ) );
616 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
617 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
618 node_to_annotate.getNodeData().setSequence( new Sequence() );
620 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
622 else if ( s.indexOf( '=' ) < 0 ) {
623 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
624 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
627 node_to_annotate.setDistanceToParent( doubleValue( s ) );
629 } // while ( t.hasMoreTokens() )
634 private final static double doubleValue( final String str ) throws NHXFormatException {
636 return Double.valueOf( str ).doubleValue();
638 catch ( final NumberFormatException ex ) {
639 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
644 private final static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
645 final PhylogenyNodeIterator it = p.iteratorExternalForward();
646 final double d0 = it.next().getDistanceToParent();
647 if ( ( d0 < 10 ) || !it.hasNext() ) {
650 while ( it.hasNext() ) {
651 final double d = it.next().getDistanceToParent();
652 if ( ( d != d0 ) || ( d < 10 ) ) {
659 private final static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
660 final PhylogenyNodeIterator it = p.iteratorPostorder();
661 while ( it.hasNext() ) {
662 final PhylogenyNode n = it.next();
663 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
664 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
668 private final static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
669 throws NHXFormatException {
671 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
672 if ( mb_prob_sd_matcher.find() ) {
674 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
676 catch ( final NumberFormatException e ) {
677 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
681 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
682 if ( mb_prob_matcher.find() ) {
685 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
687 catch ( final NumberFormatException e ) {
688 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
692 node_to_annotate.getBranchData()
693 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
696 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
700 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
701 if ( mb_bl_matcher.find() ) {
704 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
706 catch ( final NumberFormatException e ) {
707 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
711 node_to_annotate.setDistanceToParent( bl );
717 public String getName() {
718 return "NN/NHX Parser";
721 public static enum TAXONOMY_EXTRACTION {
722 NO, PFAM_STYLE_RELAXED, PFAM_STYLE_STRICT, AGGRESSIVE;