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