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