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