more tests for isDuplication() and isSpecation() added
[jalview.git] / forester / java / src / org / forester / io / parsers / nhx / NHXParser.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2013 Christian M. Zmasek
6 //
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Lesser General Public
9 // License as published by the Free Software Foundation; either
10 // version 2.1 of the License, or (at your option) any later version.
11 //
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // Lesser General Public License for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public
18 // License along with this library; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
20 //
21 // Contact: phylosoft @ gmail . com
22 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
23
24 package org.forester.io.parsers.nhx;
25
26 import java.io.BufferedReader;
27 import java.io.File;
28 import java.io.FileReader;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.net.URL;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.StringTokenizer;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38
39 import org.forester.io.parsers.IteratingPhylogenyParser;
40 import org.forester.io.parsers.PhylogenyParser;
41 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
42 import org.forester.io.parsers.util.ParserUtils;
43 import org.forester.io.parsers.util.PhylogenyParserException;
44 import org.forester.phylogeny.Phylogeny;
45 import org.forester.phylogeny.PhylogenyMethods;
46 import org.forester.phylogeny.PhylogenyNode;
47 import org.forester.phylogeny.data.Accession;
48 import org.forester.phylogeny.data.Confidence;
49 import org.forester.phylogeny.data.Event;
50 import org.forester.phylogeny.data.Identifier;
51 import org.forester.phylogeny.data.PhylogenyDataUtil;
52 import org.forester.phylogeny.data.Sequence;
53 import org.forester.phylogeny.data.Taxonomy;
54 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
55 import org.forester.util.ForesterUtil;
56
57 public final class NHXParser implements PhylogenyParser, IteratingPhylogenyParser {
58
59     public final static Pattern  MB_BL_PATTERN                              = Pattern.compile( "length.median=([^,]+)" );
60     public final static Pattern  MB_PROB_PATTERN                            = Pattern.compile( "prob=([^,]+)" );
61     public final static Pattern  MB_PROB_SD_PATTERN                         = Pattern.compile( "prob.stddev=([^,]+)" );
62     public final static Pattern  NUMBERS_ONLY_PATTERN                       = Pattern.compile( "^[0-9\\.]+$" );
63     final static public boolean  REPLACE_UNDERSCORES_DEFAULT                = false;
64     private static final boolean ALLOW_ERRORS_IN_DISTANCE_TO_PARENT_DEFAULT = false;
65     final static private byte    BUFFERED_READER                            = 3;
66     final static private byte    CHAR_ARRAY                                 = 2;
67     final static private boolean GUESS_IF_SUPPORT_VALUES                    = true;
68     final static private boolean GUESS_ROOTEDNESS_DEFAULT                   = true;
69     final static private boolean IGNORE_QUOTES_DEFAULT                      = false;
70     final static private byte    STRING                                     = 0;
71     final static private byte    STRING_BUFFER                              = 1;
72     final static private byte    STRING_BUILDER                             = 4;
73     final static private char    BELL                                       = 7;
74     private boolean              _allow_errors_in_distance_to_parent;
75     private int                  _clade_level;
76     private StringBuilder        _current_anotation;
77     private PhylogenyNode        _current_node;
78     private Phylogeny            _current_phylogeny;
79     private boolean              _guess_rootedness;
80     private int                  _i;
81     private boolean              _ignore_quotes;
82     private boolean              _in_comment                                = false;
83     private boolean              _in_double_quote                           = false;
84     private boolean              _in_open_bracket                           = false;
85     private boolean              _in_single_quote                           = false;
86     private byte                 _input_type;
87     private BufferedReader       _my_source_br                              = null;
88     private char[]               _my_source_charary                         = null;
89     private StringBuffer         _my_source_sbuff                           = null;
90     private StringBuilder        _my_source_sbuil                           = null;
91     private String               _my_source_str                             = null;
92     private Phylogeny            _next;
93     private Object               _nhx_source;
94     private boolean              _replace_underscores;
95     private boolean              _saw_closing_paren;
96     private boolean              _saw_colon                                 = false;
97     private boolean              _saw_open_bracket                          = false;
98     private Object               _source;
99     private int                  _source_length;
100     private TAXONOMY_EXTRACTION  _taxonomy_extraction;
101
102     public NHXParser() {
103         init();
104     }
105
106     @Override
107     public String getName() {
108         return "NH/NHX Parser";
109     }
110
111     public final TAXONOMY_EXTRACTION getTaxonomyExtraction() {
112         return _taxonomy_extraction;
113     }
114
115     @Override
116     public final boolean hasNext() {
117         return _next != null;
118     }
119
120     @Override
121     public final Phylogeny next() throws NHXFormatException, IOException {
122         final Phylogeny phy = _next;
123         parseNext();
124         return phy;
125     }
126
127     @Override
128     public final Phylogeny[] parse() throws IOException {
129         final List<Phylogeny> l = new ArrayList<Phylogeny>();
130         //int c = 0;
131         while ( hasNext() ) {
132             l.add( next() );
133             // c++;
134         }
135         final Phylogeny[] p = new Phylogeny[ l.size() ];
136         for( int i = 0; i < l.size(); ++i ) {
137             p[ i ] = l.get( i );
138         }
139         reset();
140         return p;
141     }
142
143     @Override
144     public final void reset() throws NHXFormatException, IOException {
145         _i = 0;
146         _next = null;
147         _in_comment = false;
148         _saw_colon = false;
149         _saw_open_bracket = false;
150         _in_open_bracket = false;
151         _in_double_quote = false;
152         _in_single_quote = false;
153         _clade_level = 0;
154         _current_anotation = new StringBuilder();
155         _current_phylogeny = null;
156         _current_node = null;
157         _my_source_str = null;
158         _my_source_sbuff = null;
159         _my_source_sbuil = null;
160         _my_source_charary = null;
161         determineAndProcessSourceType( _source );
162         switch ( _input_type ) {
163             case STRING:
164                 _my_source_br = null;
165                 _my_source_str = ( String ) _nhx_source;
166                 break;
167             case STRING_BUFFER:
168                 _my_source_br = null;
169                 _my_source_sbuff = ( StringBuffer ) _nhx_source;
170                 break;
171             case STRING_BUILDER:
172                 _my_source_br = null;
173                 _my_source_sbuil = ( StringBuilder ) _nhx_source;
174                 break;
175             case CHAR_ARRAY:
176                 _my_source_br = null;
177                 _my_source_charary = ( char[] ) _nhx_source;
178                 break;
179             case BUFFERED_READER:
180                 _my_source_br = ( BufferedReader ) _nhx_source;
181                 break;
182             default:
183                 throw new RuntimeException( "unknown input type" );
184         }
185         parseNext();
186     }
187
188     public final void setGuessRootedness( final boolean guess_rootedness ) {
189         _guess_rootedness = guess_rootedness;
190     }
191
192     public final void setIgnoreQuotes( final boolean ignore_quotes ) {
193         _ignore_quotes = ignore_quotes;
194     }
195
196     public final void setReplaceUnderscores( final boolean replace_underscores ) {
197         _replace_underscores = replace_underscores;
198     }
199
200     @Override
201     public final void setSource( final Object nhx_source ) throws NHXFormatException, IOException {
202         _source = nhx_source;
203         reset();
204     }
205
206     public final void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
207         _taxonomy_extraction = taxonomy_extraction;
208     }
209
210     public final void setAllowErrorsInDistanceToParent( final boolean allow_errors_in_distance_to_parent ) {
211         _allow_errors_in_distance_to_parent = allow_errors_in_distance_to_parent;
212     }
213
214     private final void determineAndProcessSourceType( final Object nhx_source ) throws IOException {
215         if ( nhx_source == null ) {
216             throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
217         }
218         else if ( nhx_source instanceof String ) {
219             _input_type = NHXParser.STRING;
220             _source_length = ( ( String ) nhx_source ).length();
221             _nhx_source = nhx_source;
222         }
223         else if ( nhx_source instanceof StringBuilder ) {
224             _input_type = NHXParser.STRING_BUILDER;
225             _source_length = ( ( StringBuilder ) nhx_source ).length();
226             _nhx_source = nhx_source;
227         }
228         else if ( nhx_source instanceof StringBuffer ) {
229             _input_type = NHXParser.STRING_BUFFER;
230             _source_length = ( ( StringBuffer ) nhx_source ).length();
231             _nhx_source = nhx_source;
232         }
233         else if ( nhx_source instanceof StringBuilder ) {
234             _input_type = NHXParser.STRING_BUILDER;
235             _source_length = ( ( StringBuilder ) nhx_source ).length();
236             _nhx_source = nhx_source;
237         }
238         else if ( nhx_source instanceof char[] ) {
239             _input_type = NHXParser.CHAR_ARRAY;
240             _source_length = ( ( char[] ) nhx_source ).length;
241             _nhx_source = nhx_source;
242         }
243         else if ( nhx_source instanceof File ) {
244             _input_type = NHXParser.BUFFERED_READER;
245             _source_length = 0;
246             if ( _my_source_br != null ) {
247                 //I am REALLY not sure if it is a "good" idea NOT to close the stream...
248                 //                try {
249                 //                    _my_source_br.close();
250                 //                }
251                 //                catch ( final IOException e ) {
252                 //                }
253             }
254             final File f = ( File ) nhx_source;
255             final String error = ForesterUtil.isReadableFile( f );
256             if ( !ForesterUtil.isEmpty( error ) ) {
257                 throw new PhylogenyParserException( error );
258             }
259             _nhx_source = new BufferedReader( new FileReader( f ) );
260         }
261         else if ( nhx_source instanceof URL ) {
262             _input_type = NHXParser.BUFFERED_READER;
263             _source_length = 0;
264             if ( _my_source_br != null ) {
265                 //I am REALLY not sure if it is a "good" idea NOT to close the stream...
266                 //                try {
267                 //                    _my_source_br.close();
268                 //                }
269                 //                catch ( final IOException e ) {
270                 //                }
271             }
272             final InputStreamReader isr = new InputStreamReader( ( ( URL ) nhx_source ).openStream() );
273             _nhx_source = new BufferedReader( isr );
274         }
275         else if ( nhx_source instanceof InputStream ) {
276             _input_type = NHXParser.BUFFERED_READER;
277             _source_length = 0;
278             if ( _my_source_br != null ) {
279                 //I am REALLY not sure if it is a "good" idea NOT to close the stream...
280                 //                try {
281                 //                    _my_source_br.close();
282                 //                }
283                 //                catch ( final IOException e ) {
284                 //                }
285             }
286             final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
287             _nhx_source = new BufferedReader( isr );
288         }
289         else {
290             throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
291                     + " StringBuffer, StringBuilder, char[], File, InputStream, or URL "
292                     + " [attempt to parse object of " + nhx_source.getClass() + "]." );
293         }
294     }
295
296     private final Phylogeny finishPhylogeny() throws PhylogenyParserException, NHXFormatException,
297     PhyloXmlDataFormatException {
298         if ( _current_phylogeny != null ) {
299             parseNHX( _current_anotation != null ? _current_anotation.toString() : "",
300                     _current_phylogeny.getRoot(),
301                     getTaxonomyExtraction(),
302                     isReplaceUnderscores(),
303                     isAllowErrorsInDistanceToParent(),
304                     true );
305             if ( GUESS_IF_SUPPORT_VALUES ) {
306                 if ( isBranchLengthsLikeBootstrapValues( _current_phylogeny ) ) {
307                     moveBranchLengthsToConfidenceValues( _current_phylogeny );
308                 }
309             }
310             if ( isGuessRootedness() ) {
311                 final PhylogenyNode root = _current_phylogeny.getRoot();
312                 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
313                         || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
314                     _current_phylogeny.setRooted( true );
315                 }
316             }
317             return _current_phylogeny;
318         }
319         return null;
320     }
321
322     private final Phylogeny finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
323     PhyloXmlDataFormatException {
324         final PhylogenyNode new_node = new PhylogenyNode();
325         parseNHX( _current_anotation.toString(),
326                   new_node,
327                   getTaxonomyExtraction(),
328                   isReplaceUnderscores(),
329                   isAllowErrorsInDistanceToParent(),
330                   true );
331         _current_phylogeny = new Phylogeny();
332         _current_phylogeny.setRoot( new_node );
333         return _current_phylogeny;
334     }
335
336     private final void init() {
337         setTaxonomyExtraction( TAXONOMY_EXTRACTION.NO );
338         setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
339         setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
340         setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
341         setAllowErrorsInDistanceToParent( ALLOW_ERRORS_IN_DISTANCE_TO_PARENT_DEFAULT );
342     }
343
344     private final boolean isAllowErrorsInDistanceToParent() {
345         return _allow_errors_in_distance_to_parent;
346     }
347
348     private final boolean isGuessRootedness() {
349         return _guess_rootedness;
350     }
351
352     private final boolean isIgnoreQuotes() {
353         return _ignore_quotes;
354     }
355
356     private final boolean isReplaceUnderscores() {
357         return _replace_underscores;
358     }
359
360     private final void parseNext() throws IOException, NHXFormatException {
361         if ( _source == null ) {
362             throw new IOException( "source is not set" );
363         }
364         while ( true ) {
365             char c = '\b';
366             if ( _input_type == BUFFERED_READER ) {
367                 final int ci = _my_source_br.read();
368                 if ( ci >= 0 ) {
369                     c = ( char ) ci;
370                 }
371                 else {
372                     break;
373                 }
374             }
375             else {
376                 if ( _i >= _source_length ) {
377                     break;
378                 }
379                 else {
380                     switch ( _input_type ) {
381                         case STRING:
382                             c = _my_source_str.charAt( _i );
383                             break;
384                         case STRING_BUFFER:
385                             c = _my_source_sbuff.charAt( _i );
386                             break;
387                         case STRING_BUILDER:
388                             c = _my_source_sbuil.charAt( _i );
389                             break;
390                         case CHAR_ARRAY:
391                             c = _my_source_charary[ _i ];
392                             break;
393                     }
394                 }
395             }
396             if ( !_in_single_quote && !_in_double_quote ) {
397                 if ( c == ':' ) {
398                     _saw_colon = true;
399                 }
400                 else if ( !( ( c < 33 ) || ( c > 126 ) ) && _saw_colon
401                         && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
402                     _saw_colon = false;
403                 }
404                 if ( _in_open_bracket && ( c == ']' ) ) {
405                     _in_open_bracket = false;
406                 }
407             }
408             // \n\t is always ignored,
409             // "=34  '=39 space=32
410             if ( ( c < 32 ) || ( c > 126 ) || ( isIgnoreQuotes() && ( ( c == 32 ) || ( c == 34 ) || ( c == 39 ) ) )
411                     || ( ( c == 32 ) && ( !_in_single_quote && !_in_double_quote ) )
412                     || ( ( _clade_level == 0 ) && ( c == ';' ) && ( !_in_single_quote && !_in_double_quote ) ) ) {
413                 //do nothing
414             }
415             else if ( _in_comment ) {
416                 if ( c == ']' ) {
417                     _in_comment = false;
418                 }
419             }
420             else if ( _in_double_quote ) {
421                 if ( c == '"' ) {
422                     _in_double_quote = false;
423                 }
424                 else {
425                     _current_anotation.append( changeCharInParens( c ) );
426                 }
427             }
428             else if ( ( c == '"' ) && !_in_single_quote ) {
429                 _in_double_quote = true;
430             }
431             else if ( _in_single_quote ) {
432                 if ( c == 39 ) {
433                     _in_single_quote = false;
434                 }
435                 else {
436                     _current_anotation.append( changeCharInParens( c ) );
437                 }
438             }
439             else if ( c == 39 ) {
440                 _in_single_quote = true;
441             }
442             else if ( c == '[' ) {
443                 _saw_open_bracket = true;
444                 _in_open_bracket = true;
445             }
446             else if ( _saw_open_bracket ) {
447                 if ( c != ']' ) {
448                     // everything not starting with "[&" is considered a comment
449                     // unless ":digits and/or . [bootstrap]":
450                     if ( c == '&' ) {
451                         _current_anotation.append( "[&" );
452                     }
453                     else if ( _saw_colon ) {
454                         _current_anotation.append( "[" + c );
455                     }
456                     else {
457                         _in_comment = true;
458                     }
459                 }
460                 // comment consisting just of "[]":
461                 _saw_open_bracket = false;
462             }
463             else if ( ( c == '(' ) && !_in_open_bracket ) {
464                 final Phylogeny phy = processOpenParen();
465                 if ( phy != null ) {
466                     ++_i;
467                     //  return phy;
468                     _next = phy;
469                     return;
470                 }
471             }
472             else if ( ( c == ')' ) && !_in_open_bracket ) {
473                 processCloseParen();
474             }
475             else if ( ( c == ',' ) && !_in_open_bracket ) {
476                 processComma();
477             }
478             else {
479                 _current_anotation.append( c );
480             }
481             ++_i;
482         } //  while ( true )
483         if ( _clade_level != 0 ) {
484             throw new PhylogenyParserException( "error in NH (Newick) formatted data: most likely cause: number of open parens does not equal number of close parens" );
485         }
486         if ( _current_phylogeny != null ) {
487             _next = finishPhylogeny();
488             _current_phylogeny = null;
489             _current_anotation = null;
490         }
491         else if ( ( _current_anotation != null ) && ( _current_anotation.length() > 0 ) ) {
492             _next = finishSingleNodePhylogeny();
493             _current_anotation = null;
494         }
495         else {
496             _next = null;
497         }
498     }
499
500     private final static char changeCharInParens( char c ) {
501         if ( c == ':' ) {
502             c = BELL;
503         }
504         else if ( c == '[' ) {
505             c = '{';
506         }
507         else if ( c == ']' ) {
508             c = '}';
509         }
510         return c;
511     }
512
513     private final void processCloseParen() throws PhylogenyParserException, NHXFormatException,
514     PhyloXmlDataFormatException {
515         if ( _clade_level < 0 ) {
516             throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
517         }
518         --_clade_level;
519         if ( !_saw_closing_paren ) {
520             final PhylogenyNode new_node = new PhylogenyNode();
521             parseNHX( _current_anotation.toString(),
522                       new_node,
523                       getTaxonomyExtraction(),
524                       isReplaceUnderscores(),
525                       isAllowErrorsInDistanceToParent(),
526                       true );
527             _current_anotation = new StringBuilder();
528             _current_node.addAsChild( new_node );
529         }
530         else {
531             parseNHX( _current_anotation.toString(),
532                       _current_node.getLastChildNode(),
533                       getTaxonomyExtraction(),
534                       isReplaceUnderscores(),
535                       isAllowErrorsInDistanceToParent(),
536                       true );
537             _current_anotation = new StringBuilder();
538         }
539         if ( !_current_node.isRoot() ) {
540             _current_node = _current_node.getParent();
541         }
542         _saw_closing_paren = true;
543     }
544
545     private final void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
546         if ( !_saw_closing_paren ) {
547             final PhylogenyNode new_node = new PhylogenyNode();
548             parseNHX( _current_anotation.toString(),
549                       new_node,
550                       getTaxonomyExtraction(),
551                       isReplaceUnderscores(),
552                       isAllowErrorsInDistanceToParent(),
553                       true );
554             if ( _current_node == null ) {
555                 throw new NHXFormatException( "format might not be NH or NHX" );
556             }
557             _current_node.addAsChild( new_node );
558         }
559         else {
560             parseNHX( _current_anotation.toString(),
561                       _current_node.getLastChildNode(),
562                       getTaxonomyExtraction(),
563                       isReplaceUnderscores(),
564                       isAllowErrorsInDistanceToParent(),
565                       true );
566         }
567         _current_anotation = new StringBuilder();
568         _saw_closing_paren = false;
569     }
570
571     private final Phylogeny processOpenParen() throws PhylogenyParserException, NHXFormatException,
572     PhyloXmlDataFormatException {
573         Phylogeny phy = null;
574         final PhylogenyNode new_node = new PhylogenyNode();
575         if ( _clade_level == 0 ) {
576             if ( _current_phylogeny != null ) {
577                 phy = finishPhylogeny();
578             }
579             _clade_level = 1;
580             _current_anotation = new StringBuilder();
581             _current_phylogeny = new Phylogeny();
582             _current_phylogeny.setRoot( new_node );
583         }
584         else {
585             ++_clade_level;
586             _current_node.addAsChild( new_node );
587         }
588         _current_node = new_node;
589         _saw_closing_paren = false;
590         return phy;
591     }
592
593     private final static NHXParser createInstance( final Object nhx_source ) throws NHXFormatException, IOException {
594         final NHXParser parser = new NHXParser();
595         parser.setSource( nhx_source );
596         return parser;
597     }
598
599     public final static Phylogeny[] parse( final Object nhx_source ) throws NHXFormatException, IOException {
600         return NHXParser.createInstance( nhx_source ).parse();
601     }
602
603     public final static void parseNHX( String s,
604                                        final PhylogenyNode node_to_annotate,
605                                        final TAXONOMY_EXTRACTION taxonomy_extraction,
606                                        final boolean replace_underscores,
607                                        final boolean allow_errors_in_distance_to_parent,
608                                        final boolean replace_bell ) throws NHXFormatException,
609                                        PhyloXmlDataFormatException {
610         if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
611             throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
612         }
613         if ( ( s != null ) && ( s.length() > 0 ) ) {
614             if ( replace_underscores ) {
615                 s = s.replaceAll( "_+", " " );
616             }
617             s = s.replaceAll( "\\s+", " " ).trim();
618             boolean is_nhx = false;
619             final int ob = s.indexOf( "[" );
620             if ( ob > -1 ) {
621                 String b = "";
622                 is_nhx = true;
623                 final int cb = s.indexOf( "]" );
624                 if ( cb < 0 ) {
625                     throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
626                 }
627                 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
628                     b = s.substring( ob + 6, cb );
629                 }
630                 else {
631                     // No &&NHX and digits only: is likely to be a support value.
632                     final String bracketed = s.substring( ob + 1, cb );
633                     final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
634                     if ( numbers_only.matches() ) {
635                         b = ":" + NHXtags.SUPPORT + bracketed;
636                     }
637                     else if ( s.indexOf( "prob=" ) > -1 ) {
638                         processMrBayes3Data( s, node_to_annotate );
639                     }
640                 }
641                 s = s.substring( 0, ob ) + b;
642                 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
643                     throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
644                 }
645             }
646             final StringTokenizer t = new StringTokenizer( s, ":" );
647             if ( t.countTokens() > 0 ) {
648                 if ( !s.startsWith( ":" ) ) {
649                     if ( ( s.indexOf( BELL ) <= -1 ) || !replace_bell ) {
650                         node_to_annotate.setName( t.nextToken() );
651                     }
652                     else {
653                         node_to_annotate.setName( t.nextToken().replace( BELL, ':' ) );
654                     }
655                     if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
656                         ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
657                     }
658                 }
659                 while ( t.hasMoreTokens() ) {
660                     s = t.nextToken();
661                     if ( ( s.indexOf( BELL ) > -1 ) && replace_bell ) {
662                         s = s.replace( BELL, ':' );
663                     }
664                     if ( s.indexOf( '=' ) < 0 ) {
665                         if ( ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT )
666                                 && !allow_errors_in_distance_to_parent ) {
667                             throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
668                                     + "\"" + s + "\"" );
669                         }
670                         node_to_annotate.setDistanceToParent( doubleValue( s, allow_errors_in_distance_to_parent ) );
671                     }
672                     else if ( s.startsWith( NHXtags.SPECIES_NAME ) ) {
673                         if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
674                             node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
675                         }
676                         node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
677                     }
678                     else if ( s.startsWith( NHXtags.IS_DUPLICATION ) ) {
679                         if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
680                             node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
681                         }
682                         else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
683                             node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
684                         }
685                         else if ( s.charAt( 2 ) == '?' ) {
686                             node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
687                         }
688                         else {
689                             throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
690                         }
691                     }
692                     else if ( s.startsWith( NHXtags.SUPPORT ) ) {
693                         PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ), false ) );
694                     }
695                     else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
696                         if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
697                             node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
698                         }
699                         node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
700                     }
701                     else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
702                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
703                             node_to_annotate.getNodeData().setSequence( new Sequence() );
704                         }
705                         node_to_annotate.getNodeData().getSequence()
706                         .setAccession( new Accession( s.substring( 3 ), "?" ) );
707                     }
708                     else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
709                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
710                             node_to_annotate.getNodeData().setSequence( new Sequence() );
711                         }
712                         node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
713                     }
714                 } // while ( t.hasMoreTokens() )
715             }
716         }
717     }
718
719     private final static double doubleValue( final String str, final boolean allow_errors ) throws NHXFormatException {
720         try {
721             return Double.valueOf( str ).doubleValue();
722         }
723         catch ( final NumberFormatException ex ) {
724             if ( !allow_errors ) {
725                 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\""
726                         + str + "\"" );
727             }
728         }
729         return 0.0;
730     }
731
732     private final static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
733         final PhylogenyNodeIterator it = p.iteratorExternalForward();
734         final double d0 = it.next().getDistanceToParent();
735         if ( ( d0 < 10 ) || !it.hasNext() ) {
736             return false;
737         }
738         while ( it.hasNext() ) {
739             final double d = it.next().getDistanceToParent();
740             if ( ( d != d0 ) || ( d < 10 ) ) {
741                 return false;
742             }
743         }
744         return true;
745     }
746
747     private final static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
748         final PhylogenyNodeIterator it = p.iteratorPostorder();
749         while ( it.hasNext() ) {
750             final PhylogenyNode n = it.next();
751             PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
752             n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
753         }
754     }
755
756     private final static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
757             throws NHXFormatException {
758         double sd = -1;
759         final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
760         if ( mb_prob_sd_matcher.find() ) {
761             try {
762                 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
763             }
764             catch ( final NumberFormatException e ) {
765                 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
766                         + s + "\"" );
767             }
768         }
769         final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
770         if ( mb_prob_matcher.find() ) {
771             double prob = -1;
772             try {
773                 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
774             }
775             catch ( final NumberFormatException e ) {
776                 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
777             }
778             if ( prob >= 0.0 ) {
779                 if ( sd >= 0.0 ) {
780                     node_to_annotate.getBranchData()
781                     .addConfidence( new Confidence( prob, "posterior probability", sd ) );
782                 }
783                 else {
784                     node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
785                 }
786             }
787         }
788         final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
789         if ( mb_bl_matcher.find() ) {
790             double bl = -1;
791             try {
792                 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
793             }
794             catch ( final NumberFormatException e ) {
795                 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
796                                               + "\"" );
797             }
798             if ( bl >= 0.0 ) {
799                 node_to_annotate.setDistanceToParent( bl );
800             }
801         }
802     }
803
804     public static enum TAXONOMY_EXTRACTION {
805         AGGRESSIVE, NO, PFAM_STYLE_RELAXED, PFAM_STYLE_STRICT;
806     }
807 }