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