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