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