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