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