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