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