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