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;
121 public final Phylogeny[] parse() throws IOException {
123 final List<Phylogeny> l = new ArrayList<Phylogeny>();
124 while ( hasNext() ) {
127 final Phylogeny[] p = new Phylogeny[ l.size() ];
128 for( int i = 0; i < l.size(); ++i ) {
135 public final void reset() throws NHXFormatException, IOException {
140 _saw_open_bracket = false;
141 _in_open_bracket = false;
142 _in_double_quote = false;
143 _in_single_quote = false;
145 _current_anotation = new StringBuilder();
146 _current_phylogeny = null;
147 _current_node = null;
148 _my_source_str = null;
149 _my_source_sbuff = null;
150 _my_source_sbuil = null;
151 _my_source_charary = null;
152 _my_source_br = null;
153 determineSourceType( _source );
154 switch ( _input_type ) {
156 _my_source_str = ( String ) _nhx_source;
159 _my_source_sbuff = ( StringBuffer ) _nhx_source;
162 _my_source_sbuil = ( StringBuilder ) _nhx_source;
165 _my_source_charary = ( char[] ) _nhx_source;
167 case BUFFERED_READER:
168 if ( _my_source_br != null ) {
170 _my_source_br.close();
172 catch ( final IOException e ) {
176 _my_source_br = ( BufferedReader ) _nhx_source;
179 throw new RuntimeException( "unknown input type" );
184 public final void setGuessRootedness( final boolean guess_rootedness ) {
185 _guess_rootedness = guess_rootedness;
188 public final void setIgnoreQuotes( final boolean ignore_quotes ) {
189 _ignore_quotes = ignore_quotes;
192 public final void setReplaceUnderscores( final boolean replace_underscores ) {
193 _replace_underscores = replace_underscores;
197 public final void setSource( final Object nhx_source ) throws NHXFormatException, IOException {
198 _source = nhx_source;
202 public final void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
203 _taxonomy_extraction = taxonomy_extraction;
206 private final void determineSourceType( final Object nhx_source ) throws PhylogenyParserException,
207 FileNotFoundException {
208 if ( nhx_source == null ) {
209 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
211 else if ( nhx_source instanceof String ) {
212 _input_type = NHXParser.STRING;
213 _source_length = ( ( String ) nhx_source ).length();
214 _nhx_source = nhx_source;
216 else if ( nhx_source instanceof StringBuilder ) {
217 _input_type = NHXParser.STRING_BUILDER;
218 _source_length = ( ( StringBuilder ) nhx_source ).length();
219 _nhx_source = nhx_source;
221 else if ( nhx_source instanceof StringBuffer ) {
222 _input_type = NHXParser.STRING_BUFFER;
223 _source_length = ( ( StringBuffer ) nhx_source ).length();
224 _nhx_source = nhx_source;
226 else if ( nhx_source instanceof StringBuilder ) {
227 _input_type = NHXParser.STRING_BUILDER;
228 _source_length = ( ( StringBuilder ) nhx_source ).length();
229 _nhx_source = nhx_source;
231 else if ( nhx_source instanceof char[] ) {
232 _input_type = NHXParser.CHAR_ARRAY;
233 _source_length = ( ( char[] ) nhx_source ).length;
234 _nhx_source = nhx_source;
236 else if ( nhx_source instanceof File ) {
237 _input_type = NHXParser.BUFFERED_READER;
239 final File f = ( File ) nhx_source;
240 final String error = ForesterUtil.isReadableFile( f );
241 if ( !ForesterUtil.isEmpty( error ) ) {
242 throw new PhylogenyParserException( error );
244 _nhx_source = new BufferedReader( new FileReader( f ) );
246 else if ( nhx_source instanceof InputStream ) {
247 _input_type = NHXParser.BUFFERED_READER;
249 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
250 _nhx_source = new BufferedReader( isr );
253 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
254 + " StringBuffer, StringBuilder, char[], File," + " or InputStream "
255 + " [attempt to parse object of " + nhx_source.getClass() + "]." );
259 private final Phylogeny finishPhylogeny() throws PhylogenyParserException, NHXFormatException,
260 PhyloXmlDataFormatException {
261 if ( _current_phylogeny != null ) {
262 parseNHX( _current_anotation != null ? _current_anotation.toString() : "",
263 _current_phylogeny.getRoot(),
264 getTaxonomyExtraction(),
265 isReplaceUnderscores() );
266 if ( GUESS_IF_SUPPORT_VALUES ) {
267 if ( isBranchLengthsLikeBootstrapValues( _current_phylogeny ) ) {
268 moveBranchLengthsToConfidenceValues( _current_phylogeny );
271 if ( isGuessRootedness() ) {
272 final PhylogenyNode root = _current_phylogeny.getRoot();
273 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
274 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
275 _current_phylogeny.setRooted( true );
278 return _current_phylogeny;
283 private final Phylogeny finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
284 PhyloXmlDataFormatException {
285 final PhylogenyNode new_node = new PhylogenyNode();
286 parseNHX( _current_anotation.toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
287 _current_phylogeny = new Phylogeny();
288 _current_phylogeny.setRoot( new_node );
289 return _current_phylogeny;
292 private final void getNext() throws IOException, NHXFormatException {
293 if ( _source == null ) {
294 throw new IOException( "source is not set" );
298 if ( _input_type == BUFFERED_READER ) {
299 final int ci = _my_source_br.read();
308 if ( _i >= _source_length ) {
312 switch ( _input_type ) {
314 c = _my_source_str.charAt( _i );
317 c = _my_source_sbuff.charAt( _i );
320 c = _my_source_sbuil.charAt( _i );
323 c = _my_source_charary[ _i ];
328 if ( !_in_single_quote && !_in_double_quote ) {
332 else if ( !( ( c < 33 ) || ( c > 126 ) ) && _saw_colon
333 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
336 if ( _in_open_bracket && ( c == ']' ) ) {
337 _in_open_bracket = false;
340 // \n\t is always ignored,
341 // as is " (34) and ' (39) (space is 32):
342 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( _clade_level == 0 ) && ( c == ';' ) ) ) )
343 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( _clade_level == 0 ) && ( c == ';' ) ) ) ) ) {
346 else if ( ( c == 32 ) && ( !_in_single_quote && !_in_double_quote ) ) {
349 else if ( _in_comment ) {
354 else if ( _in_double_quote ) {
356 _in_double_quote = false;
359 _current_anotation.append( c );
362 else if ( c == '"' ) {
363 _in_double_quote = true;
365 else if ( _in_single_quote ) {
367 _in_single_quote = false;
370 _current_anotation.append( c );
373 else if ( c == 39 ) {
374 _in_single_quote = true;
376 else if ( c == '[' ) {
377 _saw_open_bracket = true;
378 _in_open_bracket = true;
380 else if ( _saw_open_bracket ) {
382 // everything not starting with "[&" is considered a comment
383 // unless ":digits and/or . [bootstrap]":
385 _current_anotation.append( "[&" );
387 else if ( _saw_colon ) {
388 _current_anotation.append( "[" + c );
394 // comment consisting just of "[]":
395 _saw_open_bracket = false;
397 else if ( ( c == '(' ) && !_in_open_bracket ) {
398 final Phylogeny phy = processOpenParen();
406 else if ( ( c == ')' ) && !_in_open_bracket ) {
409 else if ( ( c == ',' ) && !_in_open_bracket ) {
413 _current_anotation.append( c );
417 if ( _clade_level != 0 ) {
418 throw new PhylogenyParserException( "error in NH (Newick) formatted data: most likely cause: number of open parens does not equal number of close parens" );
420 if ( _current_phylogeny != null ) {
421 _next = finishPhylogeny();
422 _current_phylogeny = null;
423 _current_anotation = null;
425 else if ( ( _current_anotation != null ) && ( _current_anotation.length() > 0 ) ) {
426 _next = finishSingleNodePhylogeny();
427 _current_anotation = null;
434 private final void init() {
435 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
436 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
437 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
438 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
441 private final boolean isGuessRootedness() {
442 return _guess_rootedness;
445 private final boolean isIgnoreQuotes() {
446 return _ignore_quotes;
449 private final boolean isReplaceUnderscores() {
450 return _replace_underscores;
453 private final void processCloseParen() throws PhylogenyParserException, NHXFormatException,
454 PhyloXmlDataFormatException {
455 if ( _clade_level < 0 ) {
456 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
459 if ( !_saw_closing_paren ) {
460 final PhylogenyNode new_node = new PhylogenyNode();
461 parseNHX( _current_anotation.toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
462 _current_anotation = new StringBuilder();
463 _current_node.addAsChild( new_node );
466 parseNHX( _current_anotation.toString(),
467 _current_node.getLastChildNode(),
468 getTaxonomyExtraction(),
469 isReplaceUnderscores() );
470 _current_anotation = new StringBuilder();
472 if ( !_current_node.isRoot() ) {
473 _current_node = _current_node.getParent();
475 _saw_closing_paren = true;
478 private final void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
479 if ( !_saw_closing_paren ) {
480 final PhylogenyNode new_node = new PhylogenyNode();
481 parseNHX( _current_anotation.toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
482 if ( _current_node == null ) {
483 throw new NHXFormatException( "format might not be NH or NHX" );
485 _current_node.addAsChild( new_node );
488 parseNHX( _current_anotation.toString(),
489 _current_node.getLastChildNode(),
490 getTaxonomyExtraction(),
491 isReplaceUnderscores() );
493 _current_anotation = new StringBuilder();
494 _saw_closing_paren = false;
497 private final Phylogeny processOpenParen() throws PhylogenyParserException, NHXFormatException,
498 PhyloXmlDataFormatException {
499 Phylogeny phy = null;
500 final PhylogenyNode new_node = new PhylogenyNode();
501 if ( _clade_level == 0 ) {
502 if ( _current_phylogeny != null ) {
503 phy = finishPhylogeny();
506 _current_anotation = new StringBuilder();
507 _current_phylogeny = new Phylogeny();
508 _current_phylogeny.setRoot( new_node );
512 _current_node.addAsChild( new_node );
514 _current_node = new_node;
515 _saw_closing_paren = false;
519 public final static void parseNHX( String s,
520 final PhylogenyNode node_to_annotate,
521 final TAXONOMY_EXTRACTION taxonomy_extraction,
522 final boolean replace_underscores ) throws NHXFormatException,
523 PhyloXmlDataFormatException {
524 if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
525 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
527 if ( ( s != null ) && ( s.length() > 0 ) ) {
528 if ( replace_underscores ) {
529 s = s.replaceAll( "_+", " " );
531 boolean is_nhx = false;
532 final int ob = s.indexOf( "[" );
536 final int cb = s.indexOf( "]" );
538 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
540 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
541 b = s.substring( ob + 6, cb );
544 // No &&NHX and digits only: is likely to be a support value.
545 final String bracketed = s.substring( ob + 1, cb );
546 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
547 if ( numbers_only.matches() ) {
548 b = ":" + NHXtags.SUPPORT + bracketed;
550 else if ( s.indexOf( "prob=" ) > -1 ) {
551 processMrBayes3Data( s, node_to_annotate );
554 s = s.substring( 0, ob ) + b;
555 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
556 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
559 final StringTokenizer t = new StringTokenizer( s, ":" );
560 if ( t.countTokens() > 0 ) {
561 if ( !s.startsWith( ":" ) ) {
562 node_to_annotate.setName( t.nextToken() );
563 if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
564 ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
567 while ( t.hasMoreTokens() ) {
569 if ( s.startsWith( NHXtags.SPECIES_NAME ) ) {
570 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
571 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
573 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
575 else if ( s.startsWith( NHXtags.IS_DUPLICATION ) ) {
576 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
577 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
579 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
580 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
582 else if ( s.charAt( 2 ) == '?' ) {
583 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
586 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
589 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
590 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
592 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
593 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
594 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
596 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
598 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
599 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
600 node_to_annotate.getNodeData().setSequence( new Sequence() );
602 node_to_annotate.getNodeData().getSequence()
603 .setAccession( new Accession( s.substring( 3 ), "?" ) );
605 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
606 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
607 node_to_annotate.getNodeData().setSequence( new Sequence() );
609 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
611 else if ( s.indexOf( '=' ) < 0 ) {
612 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
613 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
616 node_to_annotate.setDistanceToParent( doubleValue( s ) );
618 } // while ( t.hasMoreTokens() )
623 private final static double doubleValue( final String str ) throws NHXFormatException {
625 return Double.valueOf( str ).doubleValue();
627 catch ( final NumberFormatException ex ) {
628 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
633 private final static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
634 final PhylogenyNodeIterator it = p.iteratorExternalForward();
635 final double d0 = it.next().getDistanceToParent();
636 if ( ( d0 < 10 ) || !it.hasNext() ) {
639 while ( it.hasNext() ) {
640 final double d = it.next().getDistanceToParent();
641 if ( ( d != d0 ) || ( d < 10 ) ) {
648 private final static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
649 final PhylogenyNodeIterator it = p.iteratorPostorder();
650 while ( it.hasNext() ) {
651 final PhylogenyNode n = it.next();
652 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
653 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
657 private final static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
658 throws NHXFormatException {
660 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
661 if ( mb_prob_sd_matcher.find() ) {
663 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
665 catch ( final NumberFormatException e ) {
666 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
670 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
671 if ( mb_prob_matcher.find() ) {
674 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
676 catch ( final NumberFormatException e ) {
677 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
681 node_to_annotate.getBranchData()
682 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
685 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
689 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
690 if ( mb_bl_matcher.find() ) {
693 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
695 catch ( final NumberFormatException e ) {
696 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
700 node_to_annotate.setDistanceToParent( bl );
705 public static enum TAXONOMY_EXTRACTION {
706 NO, PFAM_STYLE_RELAXED, PFAM_STYLE_STRICT, AGGRESSIVE;