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