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