in progress...
[jalview.git] / forester / java / src / org / forester / io / parsers / nhx / NHXParser.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2013 Christian M. Zmasek
6 //
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.
11 //
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.
16 //
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
20 //
21 // Contact: phylosoft @ gmail . com
22 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
23
24 package org.forester.io.parsers.nhx;
25
26 import java.awt.Color;
27 import java.io.BufferedReader;
28 import java.io.ByteArrayInputStream;
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.net.URL;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.StringTokenizer;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40
41 import org.forester.io.parsers.IteratingPhylogenyParser;
42 import org.forester.io.parsers.PhylogenyParser;
43 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
44 import org.forester.io.parsers.util.ParserUtils;
45 import org.forester.io.parsers.util.PhylogenyParserException;
46 import org.forester.phylogeny.Phylogeny;
47 import org.forester.phylogeny.PhylogenyMethods;
48 import org.forester.phylogeny.PhylogenyNode;
49 import org.forester.phylogeny.data.Accession;
50 import org.forester.phylogeny.data.BranchColor;
51 import org.forester.phylogeny.data.Confidence;
52 import org.forester.phylogeny.data.Event;
53 import org.forester.phylogeny.data.Identifier;
54 import org.forester.phylogeny.data.PhylogenyDataUtil;
55 import org.forester.phylogeny.data.Sequence;
56 import org.forester.phylogeny.data.Taxonomy;
57 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
58 import org.forester.util.ForesterConstants;
59 import org.forester.util.ForesterUtil;
60
61 public final class NHXParser implements PhylogenyParser, IteratingPhylogenyParser {
62
63     private final static Pattern MB_BL_PATTERN                              = Pattern
64             .compile( "length.median=([-+eE0-9\\.]+)" );
65     private final static Pattern MB_PROB_PATTERN                            = Pattern.compile( "prob=([-+eE0-9\\.]+)" );
66     private final static Pattern MB_PROB_SD_PATTERN                         = Pattern
67             .compile( "prob.stddev=([-+eE0-9\\.]+)" );
68     private final static Pattern NUMBERS_ONLY_PATTERN                       = Pattern.compile( "^[-+]?[0-9\\.]+$" );
69     private final static Pattern BEAST_STYLE_EXTENDED_BOOTSTRAP_PATTERN     = Pattern
70             .compile( "boot?strap=([\\d\\.]+)" );
71     private final static Pattern BEAST_STYLE_EXTENDED_COLOR_PATTERN         = Pattern
72             .compile( "colou?r=(#[\\da-fA-F]{6})" );
73     private final static Pattern ENDS_WITH_NUMBER_PATTERN                   = Pattern.compile( "(:[-+eE0-9\\.]+$)" );
74     public final static boolean  REPLACE_UNDERSCORES_DEFAULT                = false;
75     private final static boolean ALLOW_ERRORS_IN_DISTANCE_TO_PARENT_DEFAULT = false;
76     private final static byte    BUFFERED_READER                            = 3;
77     private final static byte    CHAR_ARRAY                                 = 2;
78     private final static boolean GUESS_IF_SUPPORT_VALUES                    = true;
79     private final static boolean GUESS_ROOTEDNESS_DEFAULT                   = true;
80     private final static boolean IGNORE_QUOTES_DEFAULT                      = false;
81     private final static char    BELL                                       = 7;
82     private final static String  ENCODING_DEFAULT                           = ForesterConstants.UTF_8;
83     private boolean              _allow_errors_in_distance_to_parent;
84     private int                  _clade_level;
85     private StringBuilder        _current_anotation;
86     private PhylogenyNode        _current_node;
87     private Phylogeny            _current_phylogeny;
88     private boolean              _guess_rootedness;
89     private int                  _i;
90     private boolean              _ignore_quotes;
91     private boolean              _in_comment                                = false;
92     private boolean              _in_double_quote                           = false;
93     private boolean              _in_open_bracket                           = false;
94     private boolean              _in_single_quote                           = false;
95     private byte                 _input_type;
96     private BufferedReader       _my_source_br                              = null;
97     private char[]               _my_source_charary                         = null;
98     private Phylogeny            _next;
99     private Object               _nhx_source;
100     private boolean              _replace_underscores;
101     private boolean              _saw_closing_paren;
102     private boolean              _saw_colon                                 = false;
103     private boolean              _saw_open_bracket                          = false;
104     private boolean              _after_close_paren                         = false;
105     private Object               _source;
106     private int                  _source_length;
107     private TAXONOMY_EXTRACTION  _taxonomy_extraction;
108     private boolean              _parse_beast_style_extended_tags           = false;
109     private final String         _encoding;
110
111     public NHXParser() {
112         _encoding = ENCODING_DEFAULT;
113         init();
114     }
115
116     public NHXParser( final String encoding ) {
117         _encoding = encoding;
118         init();
119     }
120
121     @Override
122     public String getName() {
123         return "NH/NHX Parser";
124     }
125
126     public final TAXONOMY_EXTRACTION getTaxonomyExtraction() {
127         return _taxonomy_extraction;
128     }
129
130     @Override
131     public final boolean hasNext() {
132         return _next != null;
133     }
134
135     @Override
136     public final Phylogeny next() throws NHXFormatException, IOException {
137         final Phylogeny phy = _next;
138         parseNext();
139         return phy;
140     }
141
142     @Override
143     public final Phylogeny[] parse() throws IOException {
144         final List<Phylogeny> l = new ArrayList<Phylogeny>();
145         while ( hasNext() ) {
146             l.add( next() );
147         }
148         final Phylogeny[] p = new Phylogeny[ l.size() ];
149         for( int i = 0; i < l.size(); ++i ) {
150             p[ i ] = l.get( i );
151         }
152         reset();
153         return p;
154     }
155
156     @Override
157     public final void reset() throws NHXFormatException, IOException {
158         _i = 0;
159         _next = null;
160         _in_comment = false;
161         _saw_colon = false;
162         _saw_open_bracket = false;
163         _in_open_bracket = false;
164         _in_double_quote = false;
165         _in_single_quote = false;
166         _after_close_paren = false;
167         _clade_level = 0;
168         _current_anotation = new StringBuilder();
169         _current_phylogeny = null;
170         _current_node = null;
171         _my_source_charary = null;
172         determineAndProcessSourceType( _source );
173         switch ( _input_type ) {
174             case CHAR_ARRAY:
175                 _my_source_br = null;
176                 _my_source_charary = ( char[] ) _nhx_source;
177                 break;
178             case BUFFERED_READER:
179                 _my_source_br = ( BufferedReader ) _nhx_source;
180                 break;
181             default:
182                 throw new RuntimeException( "unknown input type" );
183         }
184         parseNext();
185     }
186
187     public final void setGuessRootedness( final boolean guess_rootedness ) {
188         _guess_rootedness = guess_rootedness;
189     }
190
191     public final void setIgnoreQuotes( final boolean ignore_quotes ) {
192         _ignore_quotes = ignore_quotes;
193     }
194
195     public final void setReplaceUnderscores( final boolean replace_underscores ) {
196         _replace_underscores = replace_underscores;
197     }
198
199     @Override
200     public final void setSource( final Object nhx_source ) throws NHXFormatException, IOException {
201         _source = nhx_source;
202         reset();
203     }
204
205     public final void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
206         _taxonomy_extraction = taxonomy_extraction;
207     }
208
209     public final void setAllowErrorsInDistanceToParent( final boolean allow_errors_in_distance_to_parent ) {
210         _allow_errors_in_distance_to_parent = allow_errors_in_distance_to_parent;
211     }
212
213     private final void determineAndProcessSourceType( final Object nhx_source ) throws IOException {
214         if ( nhx_source == null ) {
215             throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
216         }
217         else if ( nhx_source instanceof String ) {
218             _nhx_source = nhx_source;
219             _input_type = NHXParser.BUFFERED_READER;
220             _source_length = 0;
221             final InputStream is = new ByteArrayInputStream( ( ( String ) nhx_source ).getBytes( getEncoding() ) );
222             final InputStreamReader isr = new InputStreamReader( is, getEncoding() );
223             _nhx_source = new BufferedReader( isr );
224         }
225         else if ( nhx_source instanceof char[] ) {
226             _input_type = NHXParser.CHAR_ARRAY;
227             _source_length = ( ( char[] ) nhx_source ).length;
228             _nhx_source = nhx_source;
229         }
230         else if ( nhx_source instanceof File ) {
231             _input_type = NHXParser.BUFFERED_READER;
232             _source_length = 0;
233             if ( _my_source_br != null ) {
234                 //I am REALLY not sure if it is a "good" idea NOT to close the stream...
235                 //                try {
236                 //                    _my_source_br.close();
237                 //                }
238                 //                catch ( final IOException e ) {
239                 //                }
240             }
241             final File f = ( File ) nhx_source;
242             final String error = ForesterUtil.isReadableFile( f );
243             if ( !ForesterUtil.isEmpty( error ) ) {
244                 throw new PhylogenyParserException( error );
245             }
246             final InputStream is = new FileInputStream( f );
247             final InputStreamReader isr = new InputStreamReader( is, getEncoding() );
248             _nhx_source = new BufferedReader( isr );
249         }
250         else if ( nhx_source instanceof URL ) {
251             _input_type = NHXParser.BUFFERED_READER;
252             _source_length = 0;
253             if ( _my_source_br != null ) {
254                 //I am REALLY not sure if it is a "good" idea NOT to close the stream...
255                 //                try {
256                 //                    _my_source_br.close();
257                 //                }
258                 //                catch ( final IOException e ) {
259                 //                }
260             }
261             final InputStream is = ( ( URL ) nhx_source ).openStream();
262             final InputStreamReader isr = new InputStreamReader( is, getEncoding() );
263             _nhx_source = new BufferedReader( isr );
264         }
265         else if ( nhx_source instanceof InputStream ) {
266             _input_type = NHXParser.BUFFERED_READER;
267             _source_length = 0;
268             if ( _my_source_br != null ) {
269                 //I am REALLY not sure if it is a "good" idea NOT to close the stream...
270                 //                try {
271                 //                    _my_source_br.close();
272                 //                }
273                 //                catch ( final IOException e ) {
274                 //                }
275             }
276             final InputStream is = ( InputStream ) nhx_source;
277             final InputStreamReader isr = new InputStreamReader( is, getEncoding() );
278             _nhx_source = new BufferedReader( isr );
279         }
280         else {
281             throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
282                     + " char[], File, InputStream, or URL " + " [attempt to parse object of " + nhx_source.getClass()
283                     + "]." );
284         }
285     }
286
287     private final Phylogeny finishPhylogeny()
288             throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
289         if ( _current_phylogeny != null ) {
290             parseNHX( _current_anotation != null ? _current_anotation.toString() : "",
291                       _current_phylogeny.getRoot(),
292                       getTaxonomyExtraction(),
293                       isReplaceUnderscores(),
294                       isAllowErrorsInDistanceToParent(),
295                       true,
296                       isParseBeastStyleExtendedTags() );
297             if ( GUESS_IF_SUPPORT_VALUES ) {
298                 if ( isBranchLengthsLikeBootstrapValues( _current_phylogeny ) ) {
299                     moveBranchLengthsToConfidenceValues( _current_phylogeny );
300                 }
301             }
302             if ( isGuessRootedness() ) {
303                 final PhylogenyNode root = _current_phylogeny.getRoot();
304                 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
305                         || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
306                     _current_phylogeny.setRooted( true );
307                 }
308             }
309             return _current_phylogeny;
310         }
311         return null;
312     }
313
314     private final Phylogeny finishSingleNodePhylogeny()
315             throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
316         final PhylogenyNode new_node = new PhylogenyNode();
317         parseNHX( _current_anotation.toString(),
318                   new_node,
319                   getTaxonomyExtraction(),
320                   isReplaceUnderscores(),
321                   isAllowErrorsInDistanceToParent(),
322                   true,
323                   isParseBeastStyleExtendedTags() );
324         _current_phylogeny = new Phylogeny();
325         _current_phylogeny.setRoot( new_node );
326         return _current_phylogeny;
327     }
328
329     private final void init() {
330         setTaxonomyExtraction( TAXONOMY_EXTRACTION.NO );
331         setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
332         setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
333         setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
334         setAllowErrorsInDistanceToParent( ALLOW_ERRORS_IN_DISTANCE_TO_PARENT_DEFAULT );
335         setParseBeastStyleExtendedTags( false );
336     }
337
338     private final boolean isAllowErrorsInDistanceToParent() {
339         return _allow_errors_in_distance_to_parent;
340     }
341
342     private final boolean isGuessRootedness() {
343         return _guess_rootedness;
344     }
345
346     private final boolean isIgnoreQuotes() {
347         return _ignore_quotes;
348     }
349
350     private final boolean isReplaceUnderscores() {
351         return _replace_underscores;
352     }
353
354     private final void parseNext() throws IOException, NHXFormatException {
355         if ( _source == null ) {
356             throw new IOException( "source is not set" );
357         }
358         while ( true ) {
359             char c = '\b';
360             if ( _input_type == BUFFERED_READER ) {
361                 final int ci = _my_source_br.read();
362                 if ( ci >= 0 ) {
363                     c = ( char ) ci;
364                 }
365                 else {
366                     break;
367                 }
368             }
369             else {
370                 if ( _i >= _source_length ) {
371                     break;
372                 }
373                 c = _my_source_charary[ _i ];
374             }
375             if ( !_in_single_quote && !_in_double_quote ) {
376                 if ( c == ':' ) {
377                     _saw_colon = true;
378                 }
379                 else if ( !( ( c < 33 ) || ( c == 127 ) ) && _saw_colon
380                         && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
381                     _saw_colon = false;
382                 }
383                 if ( _in_open_bracket && ( c == ']' ) ) {
384                     _in_open_bracket = false;
385                 }
386             }
387             // \n\t is always ignored,
388             // "=34  '=39 space=32
389             if ( ( c < 32 ) || ( c == 127 ) || ( isIgnoreQuotes() && ( ( c == 32 ) || ( c == 34 ) || ( c == 39 ) ) )
390                     || ( ( c == 32 ) && ( !_in_single_quote && !_in_double_quote ) )
391                     || ( ( _clade_level == 0 ) && ( c == ';' ) && ( !_in_single_quote && !_in_double_quote ) ) ) {
392                 //do nothing
393             }
394             else if ( _in_comment ) {
395                 if ( c == ']' ) {
396                     _in_comment = false;
397                 }
398             }
399             else if ( _in_double_quote ) {
400                 if ( c == '"' ) {
401                     _in_double_quote = false;
402                 }
403                 else {
404                     _current_anotation.append( changeCharInParens( c ) );
405                 }
406             }
407             else if ( ( c == '"' ) && !_in_single_quote ) {
408                 _in_double_quote = true;
409             }
410             else if ( _in_single_quote ) {
411                 if ( c == 39 ) {
412                     _in_single_quote = false;
413                 }
414                 else {
415                     _current_anotation.append( changeCharInParens( c ) );
416                 }
417             }
418             else if ( c == 39 ) {
419                 _in_single_quote = true;
420             }
421             else if ( c == '[' ) {
422                 _saw_open_bracket = true;
423                 _in_open_bracket = true;
424             }
425             else if ( _saw_open_bracket ) {
426                 if ( c != ']' ) {
427                     // everything not starting with "[&" is considered a comment
428                     // unless ":digits and/or . [bootstrap]":
429                     if ( c == '&' ) {
430                         _current_anotation.append( "[&" );
431                     }
432                     else if ( ( _saw_colon || _after_close_paren )
433                             && ( ( ( c > 47 ) && ( c < 58 ) ) || ( c == 46 ) || ( c == 45 ) || ( c == 43 ) ) ) {
434                         _current_anotation.append( "[" + c );
435                     }
436                     else {
437                         _in_comment = true;
438                     }
439                 }
440                 // comment consisting just of "[]":
441                 _saw_open_bracket = false;
442             }
443             else if ( ( c == '(' ) && !_in_open_bracket ) {
444                 _after_close_paren = false;
445                 final Phylogeny phy = processOpenParen();
446                 if ( phy != null ) {
447                     ++_i;
448                     _next = phy;
449                     return;
450                 }
451             }
452             else if ( ( c == ')' ) && !_in_open_bracket ) {
453                 _after_close_paren = true;
454                 processCloseParen();
455             }
456             else if ( ( c == ',' ) && !_in_open_bracket ) {
457                 _after_close_paren = false;
458                 processComma();
459             }
460             else {
461                 _current_anotation.append( c );
462             }
463             ++_i;
464         } //  while ( true )
465         if ( _clade_level != 0 ) {
466             throw new PhylogenyParserException( "error in NH (Newick) formatted data: most likely cause: number of open parens does not equal number of close parens" );
467         }
468         if ( _current_phylogeny != null ) {
469             _next = finishPhylogeny();
470             _current_phylogeny = null;
471             _current_anotation = null;
472         }
473         else if ( ( _current_anotation != null ) && ( _current_anotation.length() > 0 ) ) {
474             _next = finishSingleNodePhylogeny();
475             _current_anotation = null;
476         }
477         else {
478             _next = null;
479         }
480     }
481
482     private final static char changeCharInParens( char c ) {
483         if ( c == ':' ) {
484             c = BELL;
485         }
486         else if ( c == '[' ) {
487             c = '{';
488         }
489         else if ( c == ']' ) {
490             c = '}';
491         }
492         return c;
493     }
494
495     private final void processCloseParen()
496             throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
497         if ( _clade_level < 0 ) {
498             throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
499         }
500         --_clade_level;
501         if ( !_saw_closing_paren ) {
502             final PhylogenyNode new_node = new PhylogenyNode();
503             parseNHX( _current_anotation.toString(),
504                       new_node,
505                       getTaxonomyExtraction(),
506                       isReplaceUnderscores(),
507                       isAllowErrorsInDistanceToParent(),
508                       true,
509                       isParseBeastStyleExtendedTags() );
510             _current_anotation = new StringBuilder();
511             _current_node.addAsChild( new_node );
512         }
513         else {
514             parseNHX( _current_anotation.toString(),
515                       _current_node.getLastChildNode(),
516                       getTaxonomyExtraction(),
517                       isReplaceUnderscores(),
518                       isAllowErrorsInDistanceToParent(),
519                       true,
520                       isParseBeastStyleExtendedTags() );
521             _current_anotation = new StringBuilder();
522         }
523         if ( !_current_node.isRoot() ) {
524             _current_node = _current_node.getParent();
525         }
526         _saw_closing_paren = true;
527     }
528
529     private final void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
530         if ( !_saw_closing_paren ) {
531             final PhylogenyNode new_node = new PhylogenyNode();
532             parseNHX( _current_anotation.toString(),
533                       new_node,
534                       getTaxonomyExtraction(),
535                       isReplaceUnderscores(),
536                       isAllowErrorsInDistanceToParent(),
537                       true,
538                       isParseBeastStyleExtendedTags() );
539             if ( _current_node == null ) {
540                 throw new NHXFormatException( "format might not be NH or NHX" );
541             }
542             _current_node.addAsChild( new_node );
543         }
544         else {
545             parseNHX( _current_anotation.toString(),
546                       _current_node.getLastChildNode(),
547                       getTaxonomyExtraction(),
548                       isReplaceUnderscores(),
549                       isAllowErrorsInDistanceToParent(),
550                       true,
551                       isParseBeastStyleExtendedTags() );
552         }
553         _current_anotation = new StringBuilder();
554         _saw_closing_paren = false;
555     }
556
557     private final Phylogeny processOpenParen()
558             throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
559         Phylogeny phy = null;
560         final PhylogenyNode new_node = new PhylogenyNode();
561         if ( _clade_level == 0 ) {
562             if ( _current_phylogeny != null ) {
563                 phy = finishPhylogeny();
564             }
565             _clade_level = 1;
566             _current_anotation = new StringBuilder();
567             _current_phylogeny = new Phylogeny();
568             _current_phylogeny.setRoot( new_node );
569         }
570         else {
571             ++_clade_level;
572             _current_node.addAsChild( new_node );
573         }
574         _current_node = new_node;
575         _saw_closing_paren = false;
576         return phy;
577     }
578
579     private final static NHXParser createInstance( final Object nhx_source ) throws NHXFormatException, IOException {
580         final NHXParser parser = new NHXParser();
581         parser.setSource( nhx_source );
582         return parser;
583     }
584
585     public final static Phylogeny[] parse( final Object nhx_source ) throws NHXFormatException, IOException {
586         return NHXParser.createInstance( nhx_source ).parse();
587     }
588
589     public final static void parseNHX( String s,
590                                        final PhylogenyNode node_to_annotate,
591                                        final TAXONOMY_EXTRACTION taxonomy_extraction,
592                                        final boolean replace_underscores,
593                                        final boolean allow_errors_in_distance_to_parent,
594                                        final boolean replace_bell,
595                                        final boolean parse_beast_style_extended_tags )
596             throws NHXFormatException, PhyloXmlDataFormatException {
597         if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
598             throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
599         }
600         if ( ( s != null ) && ( s.length() > 0 ) ) {
601             if ( replace_underscores ) {
602                 s = s.replaceAll( "_+", " " );
603             }
604             s = s.replaceAll( "\\s+", " " ).trim();
605             boolean is_nhx = false;
606             final int ob = s.indexOf( "[" );
607             if ( ob > -1 ) {
608                 String b = "";
609                 is_nhx = true;
610                 final int cb = s.indexOf( "]" );
611                 if ( cb < 0 ) {
612                     throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
613                 }
614                 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
615                     b = s.substring( ob + 6, cb );
616                 }
617                 else {
618                     // No &&NHX and digits only: is likely to be a support value.
619                     final String bracketed = s.substring( ob + 1, cb );
620                     final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
621                     if ( numbers_only.matches() ) {
622                         b = ":" + NHXtags.SUPPORT + bracketed;
623                     }
624                     else if ( s.indexOf( "prob=" ) > -1 ) {
625                         processMrBayes3Data( s, node_to_annotate );
626                     }
627                     if ( parse_beast_style_extended_tags ) {
628                         processBeastStyleExtendedData( s, node_to_annotate );
629                     }
630                     final Matcher ewn_matcher = ENDS_WITH_NUMBER_PATTERN.matcher( s );
631                     if ( ewn_matcher.find() ) {
632                         b = b + ewn_matcher.group( 1 );
633                     }
634                 }
635                 s = s.substring( 0, ob ) + b;
636                 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
637                     throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
638                 }
639             }
640             final StringTokenizer t = new StringTokenizer( s, ":" );
641             if ( t.countTokens() > 0 ) {
642                 if ( !s.startsWith( ":" ) ) {
643                     if ( ( s.indexOf( BELL ) <= -1 ) || !replace_bell ) {
644                         node_to_annotate.setName( t.nextToken() );
645                     }
646                     else {
647                         node_to_annotate.setName( t.nextToken().replace( BELL, ':' ) );
648                     }
649                     if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
650                         ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
651                     }
652                 }
653                 while ( t.hasMoreTokens() ) {
654                     s = t.nextToken();
655                     if ( ( s.indexOf( BELL ) > -1 ) && replace_bell ) {
656                         s = s.replace( BELL, ':' );
657                     }
658                     if ( s.indexOf( '=' ) < 0 ) {
659                         if ( ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT )
660                                 && !allow_errors_in_distance_to_parent ) {
661                             throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
662                                     + "\"" + s + "\"" );
663                         }
664                         node_to_annotate.setDistanceToParent( doubleValue( s, allow_errors_in_distance_to_parent ) );
665                     }
666                     else if ( s.startsWith( NHXtags.SPECIES_NAME ) ) {
667                         if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
668                             node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
669                         }
670                         node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
671                     }
672                     else if ( s.startsWith( NHXtags.IS_DUPLICATION ) ) {
673                         if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
674                             node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
675                         }
676                         else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
677                             node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
678                         }
679                         else if ( s.charAt( 2 ) == '?' ) {
680                             node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
681                         }
682                         else {
683                             throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
684                         }
685                     }
686                     else if ( s.startsWith( NHXtags.SUPPORT ) ) {
687                         PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ), false ) );
688                     }
689                     else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
690                         if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
691                             node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
692                         }
693                         node_to_annotate.getNodeData().getTaxonomy()
694                                 .setIdentifier( new Identifier( s.substring( 2 ) ) );
695                     }
696                     else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
697                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
698                             node_to_annotate.getNodeData().setSequence( new Sequence() );
699                         }
700                         node_to_annotate.getNodeData().getSequence()
701                                 .setAccession( new Accession( s.substring( 3 ), "?" ) );
702                     }
703                     else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
704                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
705                             node_to_annotate.getNodeData().setSequence( new Sequence() );
706                         }
707                         node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
708                     }
709                 } // while ( t.hasMoreTokens() )
710             }
711         }
712     }
713
714     private final static double doubleValue( final String str, final boolean allow_errors ) throws NHXFormatException {
715         try {
716             return Double.valueOf( str ).doubleValue();
717         }
718         catch ( final NumberFormatException ex ) {
719             if ( !allow_errors ) {
720                 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\""
721                         + str + "\"" );
722             }
723         }
724         return 0.0;
725     }
726
727     private final static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
728         final PhylogenyNodeIterator it = p.iteratorExternalForward();
729         final double d0 = it.next().getDistanceToParent();
730         if ( ( d0 < 10 ) || !it.hasNext() ) {
731             return false;
732         }
733         while ( it.hasNext() ) {
734             final double d = it.next().getDistanceToParent();
735             if ( ( d != d0 ) || ( d < 10 ) ) {
736                 return false;
737             }
738         }
739         return true;
740     }
741
742     private final static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
743         final PhylogenyNodeIterator it = p.iteratorPostorder();
744         while ( it.hasNext() ) {
745             final PhylogenyNode n = it.next();
746             PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
747             n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
748         }
749     }
750
751     private final static void processBeastStyleExtendedData( final String s, final PhylogenyNode node_to_annotate )
752             throws NHXFormatException {
753         final Matcher ft_bs_matcher = BEAST_STYLE_EXTENDED_BOOTSTRAP_PATTERN.matcher( s );
754         double bs = -1;
755         if ( ft_bs_matcher.find() ) {
756             try {
757                 bs = Double.parseDouble( ft_bs_matcher.group( 1 ) );
758             }
759             catch ( final NumberFormatException e ) {
760                 throw new NHXFormatException( "failed to parse bootstrap support from \"" + s + "\"" );
761             }
762             if ( bs >= 0.0 ) {
763                 node_to_annotate.getBranchData().addConfidence( new Confidence( bs, "bootstrap" ) );
764             }
765         }
766         final Matcher ft_color_matcher = BEAST_STYLE_EXTENDED_COLOR_PATTERN.matcher( s );
767         Color c = null;
768         if ( ft_color_matcher.find() ) {
769             try {
770                 c = Color.decode( ft_color_matcher.group( 1 ) );
771             }
772             catch ( final NumberFormatException e ) {
773                 throw new NHXFormatException( "failed to parse color from \"" + s + "\"" );
774             }
775         }
776         if ( c != null ) {
777             node_to_annotate.getBranchData().setBranchColor( new BranchColor( c ) );
778         }
779     }
780
781     private final static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
782             throws NHXFormatException {
783         double sd = -1;
784         final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
785         if ( mb_prob_sd_matcher.find() ) {
786             try {
787                 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
788             }
789             catch ( final NumberFormatException e ) {
790                 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
791                         + s + "\"" );
792             }
793         }
794         final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
795         if ( mb_prob_matcher.find() ) {
796             double prob = -1;
797             try {
798                 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
799             }
800             catch ( final NumberFormatException e ) {
801                 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
802             }
803             if ( prob >= 0.0 ) {
804                 if ( sd >= 0.0 ) {
805                     node_to_annotate.getBranchData()
806                             .addConfidence( new Confidence( prob, "posterior probability", sd ) );
807                 }
808                 else {
809                     node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
810                 }
811             }
812         }
813         final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
814         if ( mb_bl_matcher.find() ) {
815             double bl = -1;
816             try {
817                 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
818             }
819             catch ( final NumberFormatException e ) {
820                 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
821                         + "\"" );
822             }
823             if ( bl >= 0.0 ) {
824                 node_to_annotate.setDistanceToParent( bl );
825             }
826         }
827     }
828
829     public String getEncoding() {
830         return _encoding;
831     }
832
833     private final boolean isParseBeastStyleExtendedTags() {
834         return _parse_beast_style_extended_tags;
835     }
836
837     public final void setParseBeastStyleExtendedTags( final boolean parse_beast_style_extended_tags ) {
838         _parse_beast_style_extended_tags = parse_beast_style_extended_tags;
839     }
840
841     public static enum TAXONOMY_EXTRACTION {
842                                             AGGRESSIVE,
843                                             NO,
844                                             PFAM_STYLE_RELAXED,
845                                             PFAM_STYLE_STRICT;
846     }
847 }