2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
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.
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.
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
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
26 package org.forester.io.parsers.nhx;
28 import java.awt.Color;
29 import java.io.BufferedReader;
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;
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.Confidence;
50 import org.forester.phylogeny.data.DomainArchitecture;
51 import org.forester.phylogeny.data.Event;
52 import org.forester.phylogeny.data.Identifier;
53 import org.forester.phylogeny.data.PhylogenyDataUtil;
54 import org.forester.phylogeny.data.Sequence;
55 import org.forester.phylogeny.data.Taxonomy;
56 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
57 import org.forester.util.ForesterUtil;
59 public final class NHXParser implements PhylogenyParser {
61 public static final TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION_DEFAULT = TAXONOMY_EXTRACTION.NO;
62 final static private boolean GUESS_ROOTEDNESS_DEFAULT = true;
63 final static private boolean GUESS_IF_SUPPORT_VALUES = true;
64 final static private boolean IGNORE_QUOTES_DEFAULT = false;
65 final static public boolean REPLACE_UNDERSCORES_DEFAULT = false;
66 private boolean _saw_closing_paren;
67 final static private byte STRING = 0;
68 final static private byte STRING_BUFFER = 1;
69 final static private byte CHAR_ARRAY = 2;
70 final static private byte BUFFERED_READER = 3;
71 final static private byte STRING_BUILDER = 4;
72 private boolean _guess_rootedness;
73 private boolean _has_next;
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 List<Phylogeny> _phylogenies;
82 private Phylogeny _current_phylogeny;
83 private TAXONOMY_EXTRACTION _taxonomy_extraction;
84 private boolean _replace_underscores;
85 public final static Pattern UC_LETTERS_NUMBERS_PATTERN = Pattern.compile( "^[A-Z0-9]+$" );
86 public final static Pattern NUMBERS_ONLY_PATTERN = Pattern.compile( "^[0-9\\.]+$" );
87 public final static Pattern MB_PROB_PATTERN = Pattern.compile( "prob=([^,]+)" );
88 public final static Pattern MB_PROB_SD_PATTERN = Pattern.compile( "prob_stddev=([^,]+)" );
89 public final static Pattern MB_BL_PATTERN = Pattern.compile( "length_median=([^,]+)" );
95 public NHXParser.TAXONOMY_EXTRACTION getTaxonomyExtraction() {
96 return _taxonomy_extraction;
99 public boolean hasNext() {
104 * Parses the source set with setSource( final Object nhx_source ). Returns
105 * the Phylogenies found in the source as Phylogeny[].
106 * Everything between [ and ] is considered comment and ignored,
110 * ":digits and/or.[bootstrap]"
112 * @see #setSource( final Object nhx_source )
113 * @see org.forester.io.parsers.PhylogenyParser#parse()
114 * @return Phylogeny[]
115 * @throws IOException
116 * @throws NHXFormatException
117 * @throws PhylogenyParserException
120 public Phylogeny[] parse() throws IOException, NHXFormatException {
122 boolean in_comment = false;
123 boolean saw_colon = false;
124 boolean saw_open_bracket = false;
125 boolean in_open_bracket = false;
126 boolean in_double_quote = false;
127 boolean in_single_quote = false;
128 setPhylogenies( new ArrayList<Phylogeny>() );
130 newCurrentAnotation();
131 setCurrentPhylogeny( null );
132 setCurrentNode( null );
134 String my_source_str = null;
135 StringBuffer my_source_sbuff = null;
136 StringBuilder my_source_sbuil = null;
137 char[] my_source_charary = null;
138 BufferedReader my_source_br = null;
139 switch ( getInputType() ) {
141 my_source_str = ( String ) getNhxSource();
144 my_source_sbuff = ( StringBuffer ) getNhxSource();
147 my_source_sbuil = ( StringBuilder ) getNhxSource();
150 my_source_charary = ( char[] ) getNhxSource();
152 case BUFFERED_READER:
153 my_source_br = ( BufferedReader ) getNhxSource();
156 throw new RuntimeException( "unknown input type" );
160 if ( getInputType() == NHXParser.BUFFERED_READER ) {
161 final int ci = my_source_br.read();
170 if ( i >= getSourceLength() ) {
174 switch ( getInputType() ) {
176 c = my_source_str.charAt( i );
179 c = my_source_sbuff.charAt( i );
182 c = my_source_sbuil.charAt( i );
185 c = my_source_charary[ i ];
190 if ( !in_single_quote && !in_double_quote ) {
194 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
195 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
198 if ( in_open_bracket && ( c == ']' ) ) {
199 in_open_bracket = false;
202 // \n\t is always ignored,
203 // as is " (34) and ' (39) (space is 32):
204 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
205 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
208 else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
211 else if ( in_comment ) {
216 else if ( in_double_quote ) {
218 in_double_quote = false;
221 getCurrentAnotation().append( c );
224 else if ( c == '"' ) {
225 in_double_quote = true;
227 else if ( in_single_quote ) {
229 in_single_quote = false;
232 getCurrentAnotation().append( c );
235 else if ( c == 39 ) {
236 in_single_quote = true;
238 else if ( c == '[' ) {
239 saw_open_bracket = true;
240 in_open_bracket = true;
242 else if ( saw_open_bracket ) {
244 // everything not starting with "[&" is considered a comment
245 // unless ":digits and/or . [bootstrap]":
247 getCurrentAnotation().append( "[&" );
249 else if ( saw_colon ) {
250 getCurrentAnotation().append( "[" + c );
256 // comment consisting just of "[]":
257 saw_open_bracket = false;
259 else if ( ( c == '(' ) && !in_open_bracket ) {
262 else if ( ( c == ')' ) && !in_open_bracket ) {
265 else if ( ( c == ',' ) && !in_open_bracket ) {
269 getCurrentAnotation().append( c );
273 if ( getCladeLevel() != 0 ) {
274 setPhylogenies( null );
275 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
277 if ( getCurrentPhylogeny() != null ) {
280 else if ( getCurrentAnotation().length() > 0 ) {
281 finishSingleNodePhylogeny();
283 else if ( getPhylogenies().size() < 1 ) {
284 getPhylogenies().add( new Phylogeny() );
286 return getPhylogeniesAsArray();
289 public void setGuessRootedness( final boolean guess_rootedness ) {
290 _guess_rootedness = guess_rootedness;
293 public void setIgnoreQuotes( final boolean ignore_quotes ) {
294 _ignore_quotes = ignore_quotes;
297 public void setReplaceUnderscores( final boolean replace_underscores ) {
298 _replace_underscores = replace_underscores;
302 * This sets the source to be parsed. The source can be: String,
303 * StringBuffer, char[], File, or InputStream. The source can contain more
304 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
305 * Extended (NHX) format. There is no need to separate phylogenies with any
306 * special character. White space is always ignored, as are semicolons
307 * inbetween phylogenies. Example of a source describing two phylogenies
308 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
309 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
310 * character other than '&' and ']' is considered a comment and ignored
311 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
312 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
313 * info]" is ignored, too (at the PhylogenyNode level, though).
314 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
317 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
319 * the source to be parsed (String, StringBuffer, char[], File,
321 * @throws IOException
322 * @throws PhylogenyParserException
325 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
326 if ( nhx_source == null ) {
327 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
329 else if ( nhx_source instanceof String ) {
330 setInputType( NHXParser.STRING );
331 setSourceLength( ( ( String ) nhx_source ).length() );
332 setNhxSource( nhx_source );
334 else if ( nhx_source instanceof StringBuilder ) {
335 setInputType( NHXParser.STRING_BUILDER );
336 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
337 setNhxSource( nhx_source );
339 else if ( nhx_source instanceof StringBuffer ) {
340 setInputType( NHXParser.STRING_BUFFER );
341 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
342 setNhxSource( nhx_source );
344 else if ( nhx_source instanceof StringBuilder ) {
345 setInputType( NHXParser.STRING_BUILDER );
346 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
347 setNhxSource( nhx_source );
349 else if ( nhx_source instanceof char[] ) {
350 setInputType( NHXParser.CHAR_ARRAY );
351 setSourceLength( ( ( char[] ) nhx_source ).length );
352 setNhxSource( nhx_source );
354 else if ( nhx_source instanceof File ) {
355 setInputType( NHXParser.BUFFERED_READER );
356 setSourceLength( 0 );
357 final File f = ( File ) nhx_source;
358 final String error = ForesterUtil.isReadableFile( f );
359 if ( !ForesterUtil.isEmpty( error ) ) {
360 throw new PhylogenyParserException( error );
362 setNhxSource( new BufferedReader( new FileReader( f ) ) );
364 else if ( nhx_source instanceof InputStream ) {
365 setInputType( NHXParser.BUFFERED_READER );
366 setSourceLength( 0 );
367 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
368 setNhxSource( new BufferedReader( isr ) );
371 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
372 + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
373 + nhx_source.getClass() + "]." );
378 public void setTaxonomyExtraction( final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction ) {
379 _taxonomy_extraction = taxonomy_extraction;
383 * Decreases the clade level by one.
385 * @throws PhylogenyParserException
386 * if level goes below zero.
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" );
396 * Finishes the current Phylogeny and adds it to the list of Phylogenies
399 * @throws PhylogenyParserException
400 * @throws NHXFormatException
401 * @throws PhyloXmlDataFormatException
403 private void finishPhylogeny() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
405 if ( getCurrentPhylogeny() != null ) {
406 parseNHX( getCurrentAnotation().toString(),
407 getCurrentPhylogeny().getRoot(),
408 getTaxonomyExtraction(),
409 isReplaceUnderscores() );
410 if ( NHXParser.GUESS_IF_SUPPORT_VALUES ) {
411 if ( NHXParser.isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
412 NHXParser.moveBranchLengthsToConfidenceValues( getCurrentPhylogeny() );
415 if ( isGuessRootedness() ) {
416 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
417 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
418 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
419 getCurrentPhylogeny().setRooted( true );
422 getPhylogenies().add( getCurrentPhylogeny() );
426 private void finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
427 PhyloXmlDataFormatException {
429 final PhylogenyNode new_node = new PhylogenyNode();
430 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
431 setCurrentPhylogeny( new Phylogeny() );
432 getCurrentPhylogeny().setRoot( new_node );
433 getPhylogenies().add( getCurrentPhylogeny() );
436 private int getCladeLevel() {
440 private StringBuilder getCurrentAnotation() {
441 return _current_anotation;
444 private PhylogenyNode getCurrentNode() {
445 return _current_node;
448 private Phylogeny getCurrentPhylogeny() {
449 return _current_phylogeny;
452 private byte getInputType() {
456 private Object getNhxSource() {
460 private List<Phylogeny> getPhylogenies() {
465 * Returns the Phylogenies created as Array.
467 * @return the Phylogenies created as Array
469 private Phylogeny[] getPhylogeniesAsArray() {
470 final Phylogeny[] p = new Phylogeny[ getPhylogenies().size() ];
471 for( int i = 0; i < getPhylogenies().size(); ++i ) {
472 p[ i ] = getPhylogenies().get( i );
477 private int getSourceLength() {
478 return _source_length;
482 * Increases the clade level by one.
484 private void increaseCladeLevel() {
488 private void init() {
489 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
490 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
491 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
492 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
496 private boolean isGuessRootedness() {
497 return _guess_rootedness;
500 private boolean isIgnoreQuotes() {
501 return _ignore_quotes;
504 private boolean isReplaceUnderscores() {
505 return _replace_underscores;
508 private boolean isSawClosingParen() {
509 return _saw_closing_paren;
513 * Replaces the current annotation with a new StringBuffer.
515 private void newCurrentAnotation() {
516 setCurrentAnotation( new StringBuilder() );
520 * Called if a closing paren is encountered.
522 * @throws PhylogenyParserException
523 * @throws NHXFormatException
524 * @throws PhyloXmlDataFormatException
526 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
527 decreaseCladeLevel();
528 if ( !isSawClosingParen() ) {
529 final PhylogenyNode new_node = new PhylogenyNode();
530 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
531 newCurrentAnotation();
532 getCurrentNode().addAsChild( new_node );
535 parseNHX( getCurrentAnotation().toString(),
536 getCurrentNode().getLastChildNode(),
537 getTaxonomyExtraction(),
538 isReplaceUnderscores() );
539 newCurrentAnotation();
541 if ( !getCurrentNode().isRoot() ) {
542 setCurrentNode( getCurrentNode().getParent() );
544 setSawClosingParen( true );
545 } // processCloseParen()
548 * Called if a comma is encountered.
550 * @throws PhylogenyParserException
551 * @throws NHXFormatException
552 * @throws PhyloXmlDataFormatException
554 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
555 if ( !isSawClosingParen() ) {
556 final PhylogenyNode new_node = new PhylogenyNode();
557 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
558 if ( getCurrentNode() == null ) {
559 throw new NHXFormatException( "format might not be NH or NHX" );
561 getCurrentNode().addAsChild( new_node );
564 parseNHX( getCurrentAnotation().toString(),
565 getCurrentNode().getLastChildNode(),
566 getTaxonomyExtraction(),
567 isReplaceUnderscores() );
569 newCurrentAnotation();
570 setSawClosingParen( false );
574 * Called if a opening paren is encountered.
576 * @throws PhylogenyParserException
577 * @throws NHXFormatException
578 * @throws PhyloXmlDataFormatException
580 private void processOpenParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
581 final PhylogenyNode new_node = new PhylogenyNode();
582 if ( getCladeLevel() == 0 ) {
583 if ( getCurrentPhylogeny() != null ) {
587 newCurrentAnotation();
588 setCurrentPhylogeny( new Phylogeny() );
589 getCurrentPhylogeny().setRoot( new_node );
592 increaseCladeLevel();
593 getCurrentNode().addAsChild( new_node );
595 setCurrentNode( new_node );
596 setSawClosingParen( false );
599 private void setCladeLevel( final int clade_level ) {
600 if ( clade_level < 0 ) {
601 throw new IllegalArgumentException( "Attempt to set clade level to a number smaller than zero." );
603 _clade_level = clade_level;
606 private void setCurrentAnotation( final StringBuilder current_anotation ) {
607 _current_anotation = current_anotation;
610 private void setCurrentNode( final PhylogenyNode current_node ) {
611 _current_node = current_node;
614 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
615 _current_phylogeny = current_phylogeny;
618 private void setHasNext( final boolean has_next ) {
619 _has_next = has_next;
622 private void setInputType( final byte input_type ) {
623 _input_type = input_type;
626 private void setNhxSource( final Object nhx_source ) {
627 _nhx_source = nhx_source;
630 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
631 _phylogenies = phylogenies;
634 private void setSawClosingParen( final boolean saw_closing_paren ) {
635 _saw_closing_paren = saw_closing_paren;
638 private void setSourceLength( final int source_length ) {
639 _source_length = source_length;
642 public static void parseNHX( String s,
643 final PhylogenyNode node_to_annotate,
644 final TAXONOMY_EXTRACTION taxonomy_extraction,
645 final boolean replace_underscores ) throws NHXFormatException,
646 PhyloXmlDataFormatException {
647 if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
648 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
650 if ( ( s != null ) && ( s.length() > 0 ) ) {
651 if ( replace_underscores ) {
652 s = s.replaceAll( "_+", " " );
654 boolean is_nhx = false;
655 final int ob = s.indexOf( "[" );
659 final int cb = s.indexOf( "]" );
661 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
663 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
664 b = s.substring( ob + 6, cb );
667 // No &&NHX and digits only: is likely to be a support value.
668 final String bracketed = s.substring( ob + 1, cb );
669 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
670 if ( numbers_only.matches() ) {
671 b = ":" + NHXtags.SUPPORT + bracketed;
673 else if ( s.indexOf( "prob=" ) > -1 ) {
674 processMrBayes3Data( s, node_to_annotate );
677 s = s.substring( 0, ob ) + b;
678 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
679 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
682 final StringTokenizer t = new StringTokenizer( s, ":" );
683 if ( t.countTokens() > 0 ) {
684 if ( !s.startsWith( ":" ) ) {
685 node_to_annotate.setName( t.nextToken() );
686 if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
687 ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
690 while ( t.hasMoreTokens() ) {
692 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
693 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
694 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
696 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
698 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
699 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
700 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
702 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
703 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
705 else if ( s.charAt( 2 ) == '?' ) {
706 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
709 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
712 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
713 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
715 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
716 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
717 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
719 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
721 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
722 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
724 else if ( s.startsWith( NHXtags.COLOR ) ) {
725 final Color c = NHXParser.stringToColor( s.substring( 2 ) );
727 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
730 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
731 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
732 node_to_annotate.getNodeData().setSequence( new Sequence() );
734 node_to_annotate.getNodeData().getSequence()
735 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
737 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
738 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
739 node_to_annotate.getNodeData().setSequence( new Sequence() );
741 node_to_annotate.getNodeData().getSequence()
742 .setAccession( new Accession( s.substring( 3 ), "?" ) );
744 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
745 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
746 node_to_annotate.getNodeData().setSequence( new Sequence() );
748 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
750 else if ( s.indexOf( '=' ) < 0 ) {
751 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
752 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
755 node_to_annotate.setDistanceToParent( doubleValue( s ) );
757 } // while ( t.hasMoreTokens() )
762 private static double doubleValue( final String str ) throws NHXFormatException {
764 return Double.valueOf( str ).doubleValue();
766 catch ( final NumberFormatException ex ) {
767 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
772 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
773 final PhylogenyNodeIterator it = p.iteratorExternalForward();
774 final double d0 = it.next().getDistanceToParent();
775 if ( ( d0 < 10 ) || !it.hasNext() ) {
778 while ( it.hasNext() ) {
779 final double d = it.next().getDistanceToParent();
780 if ( ( d != d0 ) || ( d < 10 ) ) {
787 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
788 final PhylogenyNodeIterator it = p.iteratorPostorder();
789 while ( it.hasNext() ) {
790 final PhylogenyNode n = it.next();
791 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
792 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
796 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
797 throws NHXFormatException {
799 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
800 if ( mb_prob_sd_matcher.find() ) {
802 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
804 catch ( final NumberFormatException e ) {
805 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
809 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
810 if ( mb_prob_matcher.find() ) {
813 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
815 catch ( final NumberFormatException e ) {
816 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
820 node_to_annotate.getBranchData()
821 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
824 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
828 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
829 if ( mb_bl_matcher.find() ) {
832 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
834 catch ( final NumberFormatException e ) {
835 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
839 node_to_annotate.setDistanceToParent( bl );
845 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
846 * and blue and returns the corresponding Color.
848 private static Color stringToColor( final String s ) {
849 final StringTokenizer st = new StringTokenizer( s, "." );
850 if ( st.countTokens() != 3 ) {
851 throw new IllegalArgumentException( "illegal format for color: " + s );
853 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
854 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
855 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
856 return new Color( red, green, blu );
859 public static enum TAXONOMY_EXTRACTION {
860 NO, YES, PFAM_STYLE_ONLY;