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