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