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             // as is " (34) and ' (39) (space is 32):
407             if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( _clade_level == 0 ) && ( c == ';' ) ) ) )
408                     || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( _clade_level == 0 ) && ( c == ';' ) ) ) ) ) {
409                 //do nothing
410             }
411             else if ( ( c == 32 ) && ( !_in_single_quote && !_in_double_quote ) ) {
412                 //do nothing
413             }
414             else if ( _in_comment ) {
415                 if ( c == ']' ) {
416                     _in_comment = false;
417                 }
418             }
419             else if ( _in_double_quote ) {
420                 if ( c == '"' ) {
421                     _in_double_quote = false;
422                 }
423                 else {
424                     _current_anotation.append( c != ':' ? c : BELL );
425                 }
426             }
427             else if ( c == '"' ) {
428                 _in_double_quote = true;
429             }
430             else if ( _in_single_quote ) {
431                 if ( c == 39 ) {
432                     _in_single_quote = false;
433                 }
434                 else {
435                     _current_anotation.append( c != ':' ? c : BELL );
436                 }
437             }
438             else if ( c == 39 ) {
439                 _in_single_quote = true;
440             }
441             else if ( c == '[' ) {
442                 _saw_open_bracket = true;
443                 _in_open_bracket = true;
444             }
445             else if ( _saw_open_bracket ) {
446                 if ( c != ']' ) {
447                     // everything not starting with "[&" is considered a comment
448                     // unless ":digits and/or . [bootstrap]":
449                     if ( c == '&' ) {
450                         _current_anotation.append( "[&" );
451                     }
452                     else if ( _saw_colon ) {
453                         _current_anotation.append( "[" + c );
454                     }
455                     else {
456                         _in_comment = true;
457                     }
458                 }
459                 // comment consisting just of "[]":
460                 _saw_open_bracket = false;
461             }
462             else if ( ( c == '(' ) && !_in_open_bracket ) {
463                 final Phylogeny phy = processOpenParen();
464                 if ( phy != null ) {
465                     ++_i;
466                     //  return phy;
467                     _next = phy;
468                     return;
469                 }
470             }
471             else if ( ( c == ')' ) && !_in_open_bracket ) {
472                 processCloseParen();
473             }
474             else if ( ( c == ',' ) && !_in_open_bracket ) {
475                 processComma();
476             }
477             else {
478                 _current_anotation.append( c );
479             }
480             ++_i;
481         } //  while ( true ) 
482         if ( _clade_level != 0 ) {
483             throw new PhylogenyParserException( "error in NH (Newick) formatted data: most likely cause: number of open parens does not equal number of close parens" );
484         }
485         if ( _current_phylogeny != null ) {
486             _next = finishPhylogeny();
487             _current_phylogeny = null;
488             _current_anotation = null;
489         }
490         else if ( ( _current_anotation != null ) && ( _current_anotation.length() > 0 ) ) {
491             _next = finishSingleNodePhylogeny();
492             _current_anotation = null;
493         }
494         else {
495             _next = null;
496         }
497     }
498
499     private final void processCloseParen() throws PhylogenyParserException, NHXFormatException,
500             PhyloXmlDataFormatException {
501         if ( _clade_level < 0 ) {
502             throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
503         }
504         --_clade_level;
505         if ( !_saw_closing_paren ) {
506             final PhylogenyNode new_node = new PhylogenyNode();
507             parseNHX( _current_anotation.toString(),
508                       new_node,
509                       getTaxonomyExtraction(),
510                       isReplaceUnderscores(),
511                       isAllowErrorsInDistanceToParent(),
512                       true );
513             _current_anotation = new StringBuilder();
514             _current_node.addAsChild( new_node );
515         }
516         else {
517             parseNHX( _current_anotation.toString(),
518                       _current_node.getLastChildNode(),
519                       getTaxonomyExtraction(),
520                       isReplaceUnderscores(),
521                       isAllowErrorsInDistanceToParent(),
522                       true );
523             _current_anotation = new StringBuilder();
524         }
525         if ( !_current_node.isRoot() ) {
526             _current_node = _current_node.getParent();
527         }
528         _saw_closing_paren = true;
529     }
530
531     private final void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
532         if ( !_saw_closing_paren ) {
533             final PhylogenyNode new_node = new PhylogenyNode();
534             parseNHX( _current_anotation.toString(),
535                       new_node,
536                       getTaxonomyExtraction(),
537                       isReplaceUnderscores(),
538                       isAllowErrorsInDistanceToParent(),
539                       true );
540             if ( _current_node == null ) {
541                 throw new NHXFormatException( "format might not be NH or NHX" );
542             }
543             _current_node.addAsChild( new_node );
544         }
545         else {
546             parseNHX( _current_anotation.toString(),
547                       _current_node.getLastChildNode(),
548                       getTaxonomyExtraction(),
549                       isReplaceUnderscores(),
550                       isAllowErrorsInDistanceToParent(),
551                       true );
552         }
553         _current_anotation = new StringBuilder();
554         _saw_closing_paren = false;
555     }
556
557     private final Phylogeny processOpenParen() throws PhylogenyParserException, NHXFormatException,
558             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     public 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 ) throws NHXFormatException,
595             PhyloXmlDataFormatException {
596         if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
597             throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
598         }
599         if ( ( s != null ) && ( s.length() > 0 ) ) {
600             if ( replace_underscores ) {
601                 s = s.replaceAll( "_+", " " );
602             }
603             s = s.replaceAll( "\\s+", " " ).trim();
604             boolean is_nhx = false;
605             final int ob = s.indexOf( "[" );
606             if ( ob > -1 ) {
607                 String b = "";
608                 is_nhx = true;
609                 final int cb = s.indexOf( "]" );
610                 if ( cb < 0 ) {
611                     throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
612                 }
613                 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
614                     b = s.substring( ob + 6, cb );
615                 }
616                 else {
617                     // No &&NHX and digits only: is likely to be a support value.
618                     final String bracketed = s.substring( ob + 1, cb );
619                     final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
620                     if ( numbers_only.matches() ) {
621                         b = ":" + NHXtags.SUPPORT + bracketed;
622                     }
623                     else if ( s.indexOf( "prob=" ) > -1 ) {
624                         processMrBayes3Data( s, node_to_annotate );
625                     }
626                 }
627                 s = s.substring( 0, ob ) + b;
628                 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
629                     throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
630                 }
631             }
632             final StringTokenizer t = new StringTokenizer( s, ":" );
633             if ( t.countTokens() > 0 ) {
634                 if ( !s.startsWith( ":" ) ) {
635                     if ( ( s.indexOf( BELL ) <= -1 ) || !replace_bell ) {
636                         node_to_annotate.setName( t.nextToken() );
637                     }
638                     else {
639                         node_to_annotate.setName( t.nextToken().replace( BELL, ':' ) );
640                     }
641                     if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
642                         ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
643                     }
644                 }
645                 while ( t.hasMoreTokens() ) {
646                     s = t.nextToken();
647                     if ( ( s.indexOf( BELL ) > -1 ) && replace_bell ) {
648                         s = s.replace( BELL, ':' );
649                     }
650                     if ( s.indexOf( '=' ) < 0 ) {
651                         if ( ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT )
652                                 && !allow_errors_in_distance_to_parent ) {
653                             throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
654                                     + "\"" + s + "\"" );
655                         }
656                         node_to_annotate.setDistanceToParent( doubleValue( s, allow_errors_in_distance_to_parent ) );
657                     }
658                     else if ( s.startsWith( NHXtags.SPECIES_NAME ) ) {
659                         if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
660                             node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
661                         }
662                         node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
663                     }
664                     else if ( s.startsWith( NHXtags.IS_DUPLICATION ) ) {
665                         if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
666                             node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
667                         }
668                         else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
669                             node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
670                         }
671                         else if ( s.charAt( 2 ) == '?' ) {
672                             node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
673                         }
674                         else {
675                             throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
676                         }
677                     }
678                     else if ( s.startsWith( NHXtags.SUPPORT ) ) {
679                         PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ), false ) );
680                     }
681                     else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
682                         if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
683                             node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
684                         }
685                         node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
686                     }
687                     else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
688                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
689                             node_to_annotate.getNodeData().setSequence( new Sequence() );
690                         }
691                         node_to_annotate.getNodeData().getSequence()
692                                 .setAccession( new Accession( s.substring( 3 ), "?" ) );
693                     }
694                     else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
695                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
696                             node_to_annotate.getNodeData().setSequence( new Sequence() );
697                         }
698                         node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
699                     }
700                 } // while ( t.hasMoreTokens() ) 
701             }
702         }
703     }
704
705     private final static double doubleValue( final String str, final boolean allow_errors ) throws NHXFormatException {
706         try {
707             return Double.valueOf( str ).doubleValue();
708         }
709         catch ( final NumberFormatException ex ) {
710             if ( !allow_errors ) {
711                 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\""
712                         + str + "\"" );
713             }
714         }
715         return 0.0;
716     }
717
718     private final static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
719         final PhylogenyNodeIterator it = p.iteratorExternalForward();
720         final double d0 = it.next().getDistanceToParent();
721         if ( ( d0 < 10 ) || !it.hasNext() ) {
722             return false;
723         }
724         while ( it.hasNext() ) {
725             final double d = it.next().getDistanceToParent();
726             if ( ( d != d0 ) || ( d < 10 ) ) {
727                 return false;
728             }
729         }
730         return true;
731     }
732
733     private final static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
734         final PhylogenyNodeIterator it = p.iteratorPostorder();
735         while ( it.hasNext() ) {
736             final PhylogenyNode n = it.next();
737             PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
738             n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
739         }
740     }
741
742     private final static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
743             throws NHXFormatException {
744         double sd = -1;
745         final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
746         if ( mb_prob_sd_matcher.find() ) {
747             try {
748                 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
749             }
750             catch ( final NumberFormatException e ) {
751                 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
752                         + s + "\"" );
753             }
754         }
755         final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
756         if ( mb_prob_matcher.find() ) {
757             double prob = -1;
758             try {
759                 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
760             }
761             catch ( final NumberFormatException e ) {
762                 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
763             }
764             if ( prob >= 0.0 ) {
765                 if ( sd >= 0.0 ) {
766                     node_to_annotate.getBranchData()
767                             .addConfidence( new Confidence( prob, "posterior probability", sd ) );
768                 }
769                 else {
770                     node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
771                 }
772             }
773         }
774         final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
775         if ( mb_bl_matcher.find() ) {
776             double bl = -1;
777             try {
778                 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
779             }
780             catch ( final NumberFormatException e ) {
781                 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
782                         + "\"" );
783             }
784             if ( bl >= 0.0 ) {
785                 node_to_annotate.setDistanceToParent( bl );
786             }
787         }
788     }
789
790     public static enum TAXONOMY_EXTRACTION {
791         AGGRESSIVE, NO, PFAM_STYLE_RELAXED, PFAM_STYLE_STRICT;
792     }
793 }