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