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