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