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