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