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.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;
62 public final class NHXParser implements PhylogenyParser {
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=([^,]+)" );
98 public NHXParser.TAXONOMY_EXTRACTION getTaxonomyExtraction() {
99 return _taxonomy_extraction;
102 public boolean hasNext() {
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,
113 * ":digits and/or.[bootstrap]"
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
123 public Phylogeny[] parse() throws IOException, NHXFormatException {
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>() );
133 newCurrentAnotation();
134 setCurrentPhylogeny( null );
135 setCurrentNode( null );
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() ) {
144 my_source_str = ( String ) getNhxSource();
147 my_source_sbuff = ( StringBuffer ) getNhxSource();
150 my_source_sbuil = ( StringBuilder ) getNhxSource();
153 my_source_charary = ( char[] ) getNhxSource();
155 case BUFFERED_READER:
156 my_source_br = ( BufferedReader ) getNhxSource();
159 throw new RuntimeException( "unknown input type" );
163 if ( getInputType() == NHXParser.BUFFERED_READER ) {
164 final int ci = my_source_br.read();
173 if ( i >= getSourceLength() ) {
177 switch ( getInputType() ) {
179 c = my_source_str.charAt( i );
182 c = my_source_sbuff.charAt( i );
185 c = my_source_sbuil.charAt( i );
188 c = my_source_charary[ i ];
193 if ( !in_single_quote && !in_double_quote ) {
197 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
198 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
201 if ( in_open_bracket && ( c == ']' ) ) {
202 in_open_bracket = false;
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 == ';' ) ) ) ) ) {
211 else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
214 else if ( in_comment ) {
219 else if ( in_double_quote ) {
221 in_double_quote = false;
224 getCurrentAnotation().append( c );
227 else if ( c == '"' ) {
228 in_double_quote = true;
230 else if ( in_single_quote ) {
232 in_single_quote = false;
235 getCurrentAnotation().append( c );
238 else if ( c == 39 ) {
239 in_single_quote = true;
241 else if ( c == '[' ) {
242 saw_open_bracket = true;
243 in_open_bracket = true;
245 else if ( saw_open_bracket ) {
247 // everything not starting with "[&" is considered a comment
248 // unless ":digits and/or . [bootstrap]":
250 getCurrentAnotation().append( "[&" );
252 else if ( saw_colon ) {
253 getCurrentAnotation().append( "[" + c );
259 // comment consisting just of "[]":
260 saw_open_bracket = false;
262 else if ( ( c == '(' ) && !in_open_bracket ) {
265 else if ( ( c == ')' ) && !in_open_bracket ) {
268 else if ( ( c == ',' ) && !in_open_bracket ) {
272 getCurrentAnotation().append( c );
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" );
280 if ( getCurrentPhylogeny() != null ) {
283 else if ( getCurrentAnotation().length() > 0 ) {
284 finishSingleNodePhylogeny();
286 else if ( getPhylogenies().size() < 1 ) {
287 getPhylogenies().add( new Phylogeny() );
289 return getPhylogeniesAsArray();
292 public void setGuessRootedness( final boolean guess_rootedness ) {
293 _guess_rootedness = guess_rootedness;
296 public void setIgnoreQuotes( final boolean ignore_quotes ) {
297 _ignore_quotes = ignore_quotes;
300 public void setReplaceUnderscores( final boolean replace_underscores ) {
301 _replace_underscores = replace_underscores;
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.
320 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
322 * the source to be parsed (String, StringBuffer, char[], File,
324 * @throws IOException
325 * @throws PhylogenyParserException
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." );
332 else if ( nhx_source instanceof String ) {
333 setInputType( NHXParser.STRING );
334 setSourceLength( ( ( String ) nhx_source ).length() );
335 setNhxSource( nhx_source );
337 else if ( nhx_source instanceof StringBuilder ) {
338 setInputType( NHXParser.STRING_BUILDER );
339 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
340 setNhxSource( nhx_source );
342 else if ( nhx_source instanceof StringBuffer ) {
343 setInputType( NHXParser.STRING_BUFFER );
344 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
345 setNhxSource( nhx_source );
347 else if ( nhx_source instanceof StringBuilder ) {
348 setInputType( NHXParser.STRING_BUILDER );
349 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
350 setNhxSource( nhx_source );
352 else if ( nhx_source instanceof char[] ) {
353 setInputType( NHXParser.CHAR_ARRAY );
354 setSourceLength( ( ( char[] ) nhx_source ).length );
355 setNhxSource( nhx_source );
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 );
365 setNhxSource( new BufferedReader( new FileReader( f ) ) );
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 ) );
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() + "]." );
381 public void setTaxonomyExtraction( final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction ) {
382 _taxonomy_extraction = taxonomy_extraction;
386 * Decreases the clade level by one.
388 * @throws PhylogenyParserException
389 * if level goes below zero.
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" );
399 * Finishes the current Phylogeny and adds it to the list of Phylogenies
402 * @throws PhylogenyParserException
403 * @throws NHXFormatException
404 * @throws PhyloXmlDataFormatException
406 private void finishPhylogeny() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
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() );
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 );
425 getPhylogenies().add( getCurrentPhylogeny() );
429 private void finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
430 PhyloXmlDataFormatException {
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() );
439 private int getCladeLevel() {
443 private StringBuilder getCurrentAnotation() {
444 return _current_anotation;
447 private PhylogenyNode getCurrentNode() {
448 return _current_node;
451 private Phylogeny getCurrentPhylogeny() {
452 return _current_phylogeny;
455 private byte getInputType() {
459 private Object getNhxSource() {
463 private List<Phylogeny> getPhylogenies() {
468 * Returns the Phylogenies created as Array.
470 * @return the Phylogenies created as Array
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 );
480 private int getSourceLength() {
481 return _source_length;
485 * Increases the clade level by one.
487 private void increaseCladeLevel() {
491 private void init() {
492 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
493 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
494 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
495 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
499 private boolean isGuessRootedness() {
500 return _guess_rootedness;
503 private boolean isIgnoreQuotes() {
504 return _ignore_quotes;
507 private boolean isReplaceUnderscores() {
508 return _replace_underscores;
511 private boolean isSawClosingParen() {
512 return _saw_closing_paren;
516 * Replaces the current annotation with a new StringBuffer.
518 private void newCurrentAnotation() {
519 setCurrentAnotation( new StringBuilder() );
523 * Called if a closing paren is encountered.
525 * @throws PhylogenyParserException
526 * @throws NHXFormatException
527 * @throws PhyloXmlDataFormatException
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 );
538 parseNHX( getCurrentAnotation().toString(),
539 getCurrentNode().getLastChildNode(),
540 getTaxonomyExtraction(),
541 isReplaceUnderscores() );
542 newCurrentAnotation();
544 if ( !getCurrentNode().isRoot() ) {
545 setCurrentNode( getCurrentNode().getParent() );
547 setSawClosingParen( true );
548 } // processCloseParen()
551 * Called if a comma is encountered.
553 * @throws PhylogenyParserException
554 * @throws NHXFormatException
555 * @throws PhyloXmlDataFormatException
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" );
564 getCurrentNode().addAsChild( new_node );
567 parseNHX( getCurrentAnotation().toString(),
568 getCurrentNode().getLastChildNode(),
569 getTaxonomyExtraction(),
570 isReplaceUnderscores() );
572 newCurrentAnotation();
573 setSawClosingParen( false );
577 * Called if a opening paren is encountered.
579 * @throws PhylogenyParserException
580 * @throws NHXFormatException
581 * @throws PhyloXmlDataFormatException
583 private void processOpenParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
584 final PhylogenyNode new_node = new PhylogenyNode();
585 if ( getCladeLevel() == 0 ) {
586 if ( getCurrentPhylogeny() != null ) {
590 newCurrentAnotation();
591 setCurrentPhylogeny( new Phylogeny() );
592 getCurrentPhylogeny().setRoot( new_node );
595 increaseCladeLevel();
596 getCurrentNode().addAsChild( new_node );
598 setCurrentNode( new_node );
599 setSawClosingParen( false );
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." );
606 _clade_level = clade_level;
609 private void setCurrentAnotation( final StringBuilder current_anotation ) {
610 _current_anotation = current_anotation;
613 private void setCurrentNode( final PhylogenyNode current_node ) {
614 _current_node = current_node;
617 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
618 _current_phylogeny = current_phylogeny;
621 private void setHasNext( final boolean has_next ) {
622 _has_next = has_next;
625 private void setInputType( final byte input_type ) {
626 _input_type = input_type;
629 private void setNhxSource( final Object nhx_source ) {
630 _nhx_source = nhx_source;
633 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
634 _phylogenies = phylogenies;
637 private void setSawClosingParen( final boolean saw_closing_paren ) {
638 _saw_closing_paren = saw_closing_paren;
641 private void setSourceLength( final int source_length ) {
642 _source_length = source_length;
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" );
653 if ( ( s != null ) && ( s.length() > 0 ) ) {
654 if ( replace_underscores ) {
655 s = s.replaceAll( "_+", " " );
657 boolean is_nhx = false;
658 final int ob = s.indexOf( "[" );
662 final int cb = s.indexOf( "]" );
664 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
666 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
667 b = s.substring( ob + 6, cb );
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;
676 else if ( s.indexOf( "prob=" ) > -1 ) {
677 processMrBayes3Data( s, node_to_annotate );
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 \"[\"" );
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 );
693 while ( t.hasMoreTokens() ) {
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() );
699 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
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() );
705 final Annotation annotation = new Annotation( "_:_" );
706 annotation.setDesc( s.substring( 3 ) );
707 node_to_annotate.getNodeData().getSequence().addAnnotation( annotation );
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() );
713 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
714 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
716 else if ( s.charAt( 2 ) == '?' ) {
717 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
720 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
723 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
724 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
726 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
727 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
728 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
730 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
732 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
733 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
735 else if ( s.startsWith( NHXtags.COLOR ) ) {
736 final Color c = NHXParser.stringToColor( s.substring( 2 ) );
738 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
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() );
745 node_to_annotate.getNodeData().getProperties().addProperty( Property.createFromNhxString( s ) );
747 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
748 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
749 node_to_annotate.getNodeData().setSequence( new Sequence() );
751 node_to_annotate.getNodeData().getSequence()
752 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
754 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
755 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
756 node_to_annotate.getNodeData().setSequence( new Sequence() );
758 node_to_annotate.getNodeData().getSequence()
759 .setAccession( new Accession( s.substring( 3 ), "?" ) );
761 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
762 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
763 node_to_annotate.getNodeData().setSequence( new Sequence() );
765 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
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:"
772 node_to_annotate.setDistanceToParent( doubleValue( s ) );
774 } // while ( t.hasMoreTokens() )
779 private static double doubleValue( final String str ) throws NHXFormatException {
781 return Double.valueOf( str ).doubleValue();
783 catch ( final NumberFormatException ex ) {
784 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
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() ) {
795 while ( it.hasNext() ) {
796 final double d = it.next().getDistanceToParent();
797 if ( ( d != d0 ) || ( d < 10 ) ) {
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 );
813 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
814 throws NHXFormatException {
816 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
817 if ( mb_prob_sd_matcher.find() ) {
819 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
821 catch ( final NumberFormatException e ) {
822 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
826 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
827 if ( mb_prob_matcher.find() ) {
830 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
832 catch ( final NumberFormatException e ) {
833 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
837 node_to_annotate.getBranchData()
838 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
841 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
845 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
846 if ( mb_bl_matcher.find() ) {
849 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
851 catch ( final NumberFormatException e ) {
852 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
856 node_to_annotate.setDistanceToParent( bl );
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.
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 );
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 );
876 public static enum TAXONOMY_EXTRACTION {
877 NO, YES, PFAM_STYLE_ONLY;