clean up
[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     @Override
253     public Phylogeny[] parse() throws IOException, NHXFormatException {
254         setHasNext( false );
255         boolean in_comment = false;
256         boolean saw_colon = false;
257         boolean saw_open_bracket = false;
258         boolean in_double_quote = false;
259         boolean in_single_quote = false;
260         setPhylogenies( new ArrayList<Phylogeny>() );
261         setCladeLevel( 0 );
262         newCurrentAnotation();
263         int i = 0;
264         while ( true ) {
265             char c = '\b';
266             if ( getInputType() == NHXParser.BUFFERED_READER ) {
267                 final int ci = ( ( BufferedReader ) getNhxSource() ).read();
268                 if ( ci >= 0 ) {
269                     c = ( char ) ci;
270                 }
271                 else {
272                     break;
273                 }
274             }
275             else {
276                 if ( i >= getSourceLength() ) {
277                     break;
278                 }
279                 else {
280                     switch ( getInputType() ) {
281                         case STRING:
282                             c = ( ( String ) getNhxSource() ).charAt( i );
283                             break;
284                         case STRING_BUFFER:
285                             c = ( ( StringBuffer ) getNhxSource() ).charAt( i );
286                             break;
287                         case CHAR_ARRAY:
288                             c = ( ( char[] ) getNhxSource() )[ i ];
289                             break;
290                     }
291                 }
292             }
293             if ( !in_single_quote && !in_double_quote ) {
294                 if ( c == ':' ) {
295                     saw_colon = true;
296                 }
297                 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
298                         && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
299                     saw_colon = false;
300                 }
301             }
302             // \n\t is always ignored,
303             // as is " (34) and ' (39) (space is 32):
304             if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
305                     || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
306                 // Do nothing.
307             }
308             else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
309                 // Do nothing.
310             }
311             else if ( in_comment ) {
312                 if ( c == ']' ) {
313                     in_comment = false;
314                 }
315             }
316             else if ( in_double_quote ) {
317                 if ( c == '"' ) {
318                     in_double_quote = false;
319                 }
320                 else {
321                     getCurrentAnotation().append( c );
322                 }
323             }
324             else if ( c == '"' ) {
325                 in_double_quote = true;
326             }
327             else if ( in_single_quote ) {
328                 if ( c == 39 ) {
329                     in_single_quote = false;
330                 }
331                 else {
332                     getCurrentAnotation().append( c );
333                 }
334             }
335             else if ( c == 39 ) {
336                 in_single_quote = true;
337             }
338             else if ( c == '[' ) {
339                 saw_open_bracket = true;
340             }
341             else if ( saw_open_bracket ) {
342                 if ( c != ']' ) {
343                     // everything not starting with "[&" is considered a comment
344                     // unless ":digits and/or . [bootstrap]":
345                     if ( c == '&' ) {
346                         getCurrentAnotation().append( "[&" );
347                     }
348                     else if ( saw_colon ) {
349                         getCurrentAnotation().append( "[" + c );
350                     }
351                     else {
352                         in_comment = true;
353                     }
354                 }
355                 // comment consisting just of "[]":
356                 saw_open_bracket = false;
357             }
358             else if ( c == '(' ) {
359                 processOpenParen();
360             }
361             else if ( c == ')' ) {
362                 processCloseParen();
363             }
364             else if ( c == ',' ) {
365                 processComma();
366             }
367             else {
368                 getCurrentAnotation().append( c );
369             }
370             ++i;
371         }
372         if ( getCladeLevel() != 0 ) {
373             setPhylogenies( null );
374             throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
375         }
376         if ( getCurrentPhylogeny() != null ) {
377             finishPhylogeny();
378         }
379         else if ( getCurrentAnotation().length() > 0 ) {
380             finishSingleNodePhylogeny();
381         }
382         else if ( getPhylogenies().size() < 1 ) {
383             getPhylogenies().add( new Phylogeny() );
384         }
385         return getPhylogeniesAsArray();
386     } // parse()
387
388     public Phylogeny parseNext() throws IOException, NHXFormatException {
389         return null;
390     }
391
392     /**
393      * Called if a closing paren is encountered.
394      * 
395      * @throws PhylogenyParserException
396      * @throws NHXFormatException
397      */
398     private void processCloseParen() throws PhylogenyParserException, NHXFormatException {
399         decreaseCladeLevel();
400         if ( !isSawClosingParen() ) {
401             final PhylogenyNode new_node = new PhylogenyNode();
402             parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
403             newCurrentAnotation();
404             getCurrentNode().addAsChild( new_node );
405         }
406         else {
407             parseNHX( getCurrentAnotation().toString(),
408                       getCurrentNode().getLastChildNode(),
409                       getTaxonomyExtraction(),
410                       isReplaceUnderscores() );
411             newCurrentAnotation();
412         }
413         if ( !getCurrentNode().isRoot() ) {
414             setCurrentNode( getCurrentNode().getParent() );
415         }
416         setSawClosingParen( true );
417     } // processCloseParen()
418
419     /**
420      * Called if a comma is encountered.
421      * 
422      * @throws PhylogenyParserException
423      * @throws NHXFormatException
424      */
425     private void processComma() throws PhylogenyParserException, NHXFormatException {
426         if ( !isSawClosingParen() ) {
427             final PhylogenyNode new_node = new PhylogenyNode();
428             parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
429             if ( getCurrentNode() == null ) {
430                 throw new NHXFormatException( "format might not be NH or NHX" );
431             }
432             getCurrentNode().addAsChild( new_node );
433         }
434         else {
435             parseNHX( getCurrentAnotation().toString(),
436                       getCurrentNode().getLastChildNode(),
437                       getTaxonomyExtraction(),
438                       isReplaceUnderscores() );
439         }
440         newCurrentAnotation();
441         setSawClosingParen( false );
442     } // processComma()
443
444     /**
445      * Called if a opening paren is encountered.
446      * 
447      * @throws PhylogenyParserException
448      * @throws NHXFormatException
449      */
450     private void processOpenParen() throws PhylogenyParserException, NHXFormatException {
451         final PhylogenyNode new_node = new PhylogenyNode();
452         if ( getCladeLevel() == 0 ) {
453             if ( getCurrentPhylogeny() != null ) {
454                 finishPhylogeny();
455             }
456             setCladeLevel( 1 );
457             newCurrentAnotation();
458             setCurrentPhylogeny( new Phylogeny() );
459             getCurrentPhylogeny().setRoot( new_node );
460         }
461         else {
462             increaseCladeLevel();
463             getCurrentNode().addAsChild( new_node );
464         }
465         setCurrentNode( new_node );
466         setSawClosingParen( false );
467     }
468
469     private void setCladeLevel( final int clade_level ) {
470         if ( clade_level < 0 ) {
471             throw new IllegalArgumentException( "Attempt to set clade level to a number smaller than zero." );
472         }
473         _clade_level = clade_level;
474     }
475
476     private void setCurrentAnotation( final StringBuilder current_anotation ) {
477         _current_anotation = current_anotation;
478     }
479
480     private void setCurrentNode( final PhylogenyNode current_node ) {
481         _current_node = current_node;
482     }
483
484     private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
485         _current_phylogeny = current_phylogeny;
486     }
487
488     public void setGuessRootedness( final boolean guess_rootedness ) {
489         _guess_rootedness = guess_rootedness;
490     }
491
492     private void setHasNext( final boolean has_next ) {
493         _has_next = has_next;
494     }
495
496     public void setIgnoreQuotes( final boolean ignore_quotes ) {
497         _ignore_quotes = ignore_quotes;
498     }
499
500     private void setInputType( final byte input_type ) {
501         _input_type = input_type;
502     }
503
504     private void setNhxSource( final Object nhx_source ) {
505         _nhx_source = nhx_source;
506     }
507
508     private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
509         _phylogenies = phylogenies;
510     }
511
512     public void setReplaceUnderscores( final boolean replace_underscores ) {
513         _replace_underscores = replace_underscores;
514     }
515
516     private void setSawClosingParen( final boolean saw_closing_paren ) {
517         _saw_closing_paren = saw_closing_paren;
518     }
519
520     /**
521      * This sets the source to be parsed. The source can be: String,
522      * StringBuffer, char[], File, or InputStream. The source can contain more
523      * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
524      * Extended (NHX) format. There is no need to separate phylogenies with any
525      * special character. White space is always ignored, as are semicolons
526      * inbetween phylogenies. Example of a source describing two phylogenies
527      * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
528      * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
529      * character other than '&' and ']' is considered a comment and ignored
530      * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
531      * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
532      * info]" is ignored, too (at the PhylogenyNode level, though).
533      * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
534      * 
535      * @see #parse()
536      * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
537      * @param nhx_source
538      *            the source to be parsed (String, StringBuffer, char[], File,
539      *            or InputStream)
540      * @throws IOException
541      * @throws PhylogenyParserException
542      */
543     @Override
544     public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
545         if ( nhx_source == null ) {
546             throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
547         }
548         else if ( nhx_source instanceof String ) {
549             setInputType( NHXParser.STRING );
550             setSourceLength( ( ( String ) nhx_source ).length() );
551             setNhxSource( nhx_source );
552         }
553         else if ( nhx_source instanceof StringBuffer ) {
554             setInputType( NHXParser.STRING_BUFFER );
555             setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
556             setNhxSource( nhx_source );
557         }
558         else if ( nhx_source instanceof char[] ) {
559             setInputType( NHXParser.CHAR_ARRAY );
560             setSourceLength( ( ( char[] ) nhx_source ).length );
561             setNhxSource( nhx_source );
562         }
563         else if ( nhx_source instanceof File ) {
564             setInputType( NHXParser.BUFFERED_READER );
565             setSourceLength( 0 );
566             final File f = ( File ) nhx_source;
567             final String error = ForesterUtil.isReadableFile( f );
568             if ( !ForesterUtil.isEmpty( error ) ) {
569                 throw new PhylogenyParserException( error );
570             }
571             setNhxSource( new BufferedReader( new FileReader( f ) ) );
572         }
573         else if ( nhx_source instanceof InputStream ) {
574             setInputType( NHXParser.BUFFERED_READER );
575             setSourceLength( 0 );
576             final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
577             setNhxSource( new BufferedReader( isr ) );
578         }
579         else {
580             throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
581                     + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
582                     + nhx_source.getClass() + "]." );
583         }
584         setHasNext( true );
585     }
586
587     private void setSourceLength( final int source_length ) {
588         _source_length = source_length;
589     }
590
591     public void setTaxonomyExtraction( final ForesterUtil.TAXONOMY_EXTRACTION taxonomy_extraction ) {
592         _taxonomy_extraction = taxonomy_extraction;
593     }
594
595     private static double doubleValue( final String str ) throws NHXFormatException {
596         try {
597             return Double.valueOf( str ).doubleValue();
598         }
599         catch ( final NumberFormatException ex ) {
600             throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from :" + "\"" + str
601                     + "\"" );
602         }
603     }
604
605     private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
606         final PhylogenyNodeIterator it = p.iteratorExternalForward();
607         final double d0 = it.next().getDistanceToParent();
608         if ( ( d0 < 10 ) || !it.hasNext() ) {
609             return false;
610         }
611         while ( it.hasNext() ) {
612             final double d = it.next().getDistanceToParent();
613             if ( ( d != d0 ) || ( d < 10 ) ) {
614                 return false;
615             }
616         }
617         return true;
618     }
619
620     private static void moveBranchLengthsToBootstrapValues( final Phylogeny p ) {
621         final PhylogenyNodeIterator it = p.iteratorPostorder();
622         while ( it.hasNext() ) {
623             final PhylogenyNode n = it.next();
624             PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
625             n.setDistanceToParent( PhylogenyNode.DISTANCE_DEFAULT );
626         }
627     }
628
629     public static void parseNHX( String s,
630                                  final PhylogenyNode node_to_annotate,
631                                  final ForesterUtil.TAXONOMY_EXTRACTION taxonomy_extraction,
632                                  final boolean replace_underscores ) throws NHXFormatException {
633         if ( ( taxonomy_extraction != ForesterUtil.TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
634             throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
635         }
636         if ( ( s != null ) && ( s.length() > 0 ) ) {
637             if ( replace_underscores ) {
638                 s = s.replaceAll( "_+", " " );
639             }
640             int ob = 0;
641             int cb = 0;
642             String a = "";
643             String b = "";
644             StringTokenizer t = null;
645             boolean is_nhx = false;
646             ob = s.indexOf( "[" );
647             cb = s.indexOf( "]" );
648             if ( ob > -1 ) {
649                 a = "";
650                 b = "";
651                 is_nhx = true;
652                 if ( cb < 0 ) {
653                     throw new NHXFormatException( "error in NHX formatted data: no closing \"]\"" );
654                 }
655                 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
656                     b = s.substring( ob + 6, cb );
657                 }
658                 else {
659                     // No &&NHX and digits only: is likely to be a support value.
660                     final String bracketed = s.substring( ob + 1, cb );
661                     final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
662                     if ( numbers_only.matches() ) {
663                         b = ":" + NHXtags.SUPPORT + bracketed;
664                     }
665                 }
666                 a = s.substring( 0, ob );
667                 s = a + b;
668                 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
669                     throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
670                 }
671             }
672             t = new StringTokenizer( s, ":" );
673             if ( t.countTokens() >= 1 ) {
674                 if ( !s.startsWith( ":" ) ) {
675                     node_to_annotate.setName( t.nextToken() );
676                     if ( !replace_underscores
677                             && ( !is_nhx && ( taxonomy_extraction != ForesterUtil.TAXONOMY_EXTRACTION.NO ) ) ) {
678                         final String tax = ForesterUtil
679                                 .extractTaxonomyCodeFromNodeName( node_to_annotate.getName(),
680                                                                   LIMIT_SPECIES_NAMES_TO_FIVE_CHARS,
681                                                                   taxonomy_extraction );
682                         if ( !ForesterUtil.isEmpty( tax ) ) {
683                             if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
684                                 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
685                             }
686                             node_to_annotate.getNodeData().getTaxonomy().setTaxonomyCode( tax );
687                         }
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.ANNOTATION ) ) {
699                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
700                             node_to_annotate.getNodeData().setSequence( new Sequence() );
701                         }
702                         final Annotation annotation = new Annotation( "_:_" );
703                         annotation.setDesc( s.substring( 3 ) );
704                         node_to_annotate.getNodeData().getSequence().addAnnotation( annotation );
705                     }
706                     else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
707                         if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
708                             node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
709                         }
710                         else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
711                             node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
712                         }
713                         else if ( s.charAt( 2 ) == '?' ) {
714                             node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
715                         }
716                         else {
717                             throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
718                         }
719                     }
720                     else if ( s.startsWith( NHXtags.SUPPORT ) ) {
721                         PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
722                     }
723                     else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
724                         if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
725                             node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
726                         }
727                         node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
728                     }
729                     else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
730                         PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
731                     }
732                     else if ( s.startsWith( NHXtags.COLOR ) ) {
733                         final Color c = NHXParser.stringToColor( s.substring( 2 ) );
734                         if ( c != null ) {
735                             PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
736                         }
737                     }
738                     else if ( s.startsWith( NHXtags.CUSTOM_DATA_ON_NODE ) ) {
739                         if ( !node_to_annotate.getNodeData().isHasProperties() ) {
740                             node_to_annotate.getNodeData().setProperties( new PropertiesMap() );
741                         }
742                         node_to_annotate.getNodeData().getProperties().addProperty( Property.createFromNhxString( s ) );
743                     }
744                     else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
745                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
746                             node_to_annotate.getNodeData().setSequence( new Sequence() );
747                         }
748                         node_to_annotate.getNodeData().getSequence()
749                                 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
750                     }
751                     else if ( s.startsWith( NHXtags.NODE_IDENTIFIER ) ) {
752                         node_to_annotate.getNodeData().setNodeIdentifier( new Identifier( s.substring( 3 ) ) );
753                     }
754                     else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
755                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
756                             node_to_annotate.getNodeData().setSequence( new Sequence() );
757                         }
758                         node_to_annotate.getNodeData().getSequence()
759                                 .setAccession( new Accession( s.substring( 3 ), "?" ) );
760                     }
761                     else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
762                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
763                             node_to_annotate.getNodeData().setSequence( new Sequence() );
764                         }
765                         node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
766                     }
767                     else if ( s.startsWith( NHXtags.GENE_NAME_SYNONYM ) ) {
768                         if ( !node_to_annotate.getNodeData().isHasSequence() ) {
769                             node_to_annotate.getNodeData().setSequence( new Sequence() );
770                         }
771                         node_to_annotate.getNodeData().getSequence().setName( s.substring( 2 ) );
772                     }
773                     else if ( s.indexOf( '=' ) < 0 ) {
774                         if ( node_to_annotate.getDistanceToParent() != PhylogenyNode.DISTANCE_DEFAULT ) {
775                             throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
776                                     + "\"" + s + "\"" );
777                         }
778                         node_to_annotate.setDistanceToParent( doubleValue( s ) );
779                     }
780                 } // while ( t.hasMoreTokens() ) 
781             }
782         }
783     }
784
785     /**
786      * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
787      * and blue and returns the corresponding Color.
788      */
789     private static Color stringToColor( final String s ) {
790         final StringTokenizer st = new StringTokenizer( s, "." );
791         if ( st.countTokens() != 3 ) {
792             throw new IllegalArgumentException( "illegal format for color: " + s );
793         }
794         final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
795         final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
796         final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
797         return new Color( red, green, blu );
798     }
799 }