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