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