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