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: www.phylosoft.org/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 private boolean _guess_rootedness;
75 private boolean _has_next;
76 private boolean _ignore_quotes;
77 private byte _input_type;
78 private int _source_length;
79 private PhylogenyNode _current_node;
80 private StringBuilder _current_anotation;
81 private Object _nhx_source;
82 private int _clade_level;
83 private List<Phylogeny> _phylogenies;
84 private Phylogeny _current_phylogeny;
85 private TAXONOMY_EXTRACTION _taxonomy_extraction;
86 private boolean _replace_underscores;
87 public final static Pattern UC_LETTERS_NUMBERS_PATTERN = Pattern.compile( "^[A-Z0-9]+$" );
88 public final static Pattern NUMBERS_ONLY_PATTERN = Pattern.compile( "^[0-9\\.]+$" );
89 public final static Pattern MB_PROB_PATTERN = Pattern.compile( "prob=([^,]+)" );
90 public final static Pattern MB_PROB_SD_PATTERN = Pattern.compile( "prob_stddev=([^,]+)" );
91 public final static Pattern MB_BL_PATTERN = Pattern.compile( "length_median=([^,]+)" );
97 public NHXParser.TAXONOMY_EXTRACTION getTaxonomyExtraction() {
98 return _taxonomy_extraction;
101 public boolean hasNext() {
106 * Parses the source set with setSource( final Object nhx_source ). Returns
107 * the Phylogenies found in the source as Phylogeny[].
108 * Everything between [ and ] is considered comment and ignored,
112 * ":digits and/or.[bootstrap]"
114 * @see #setSource( final Object nhx_source )
115 * @see org.forester.io.parsers.PhylogenyParser#parse()
116 * @return Phylogeny[]
117 * @throws IOException
118 * @throws NHXFormatException
119 * @throws PhylogenyParserException
122 public Phylogeny[] parse() throws IOException, NHXFormatException {
124 boolean in_comment = false;
125 boolean saw_colon = false;
126 boolean saw_open_bracket = false;
127 boolean in_open_bracket = false;
128 boolean in_double_quote = false;
129 boolean in_single_quote = false;
130 setPhylogenies( new ArrayList<Phylogeny>() );
132 newCurrentAnotation();
133 setCurrentPhylogeny( null );
134 setCurrentNode( null );
138 if ( getInputType() == NHXParser.BUFFERED_READER ) {
139 final int ci = ( ( BufferedReader ) getNhxSource() ).read();
148 if ( i >= getSourceLength() ) {
152 switch ( getInputType() ) {
154 c = ( ( String ) getNhxSource() ).charAt( i );
157 c = ( ( StringBuffer ) getNhxSource() ).charAt( i );
160 c = ( ( char[] ) getNhxSource() )[ i ];
165 if ( !in_single_quote && !in_double_quote ) {
169 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
170 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
173 if ( in_open_bracket && ( c == ']' ) ) {
174 in_open_bracket = false;
177 // \n\t is always ignored,
178 // as is " (34) and ' (39) (space is 32):
179 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
180 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
183 else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
186 else if ( in_comment ) {
191 else if ( in_double_quote ) {
193 in_double_quote = false;
196 getCurrentAnotation().append( c );
199 else if ( c == '"' ) {
200 in_double_quote = true;
202 else if ( in_single_quote ) {
204 in_single_quote = false;
207 getCurrentAnotation().append( c );
210 else if ( c == 39 ) {
211 in_single_quote = true;
213 else if ( c == '[' ) {
214 saw_open_bracket = true;
215 in_open_bracket = true;
217 else if ( saw_open_bracket ) {
219 // everything not starting with "[&" is considered a comment
220 // unless ":digits and/or . [bootstrap]":
222 getCurrentAnotation().append( "[&" );
224 else if ( saw_colon ) {
225 getCurrentAnotation().append( "[" + c );
231 // comment consisting just of "[]":
232 saw_open_bracket = false;
234 else if ( ( c == '(' ) && !in_open_bracket ) {
237 else if ( ( c == ')' ) && !in_open_bracket ) {
240 else if ( ( c == ',' ) && !in_open_bracket ) {
244 getCurrentAnotation().append( c );
248 if ( getCladeLevel() != 0 ) {
249 setPhylogenies( null );
250 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
252 if ( getCurrentPhylogeny() != null ) {
255 else if ( getCurrentAnotation().length() > 0 ) {
256 finishSingleNodePhylogeny();
258 else if ( getPhylogenies().size() < 1 ) {
259 getPhylogenies().add( new Phylogeny() );
261 return getPhylogeniesAsArray();
264 public void setGuessRootedness( final boolean guess_rootedness ) {
265 _guess_rootedness = guess_rootedness;
268 public void setIgnoreQuotes( final boolean ignore_quotes ) {
269 _ignore_quotes = ignore_quotes;
272 public void setReplaceUnderscores( final boolean replace_underscores ) {
273 _replace_underscores = replace_underscores;
277 * This sets the source to be parsed. The source can be: String,
278 * StringBuffer, char[], File, or InputStream. The source can contain more
279 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
280 * Extended (NHX) format. There is no need to separate phylogenies with any
281 * special character. White space is always ignored, as are semicolons
282 * inbetween phylogenies. Example of a source describing two phylogenies
283 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
284 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
285 * character other than '&' and ']' is considered a comment and ignored
286 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
287 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
288 * info]" is ignored, too (at the PhylogenyNode level, though).
289 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
292 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
294 * the source to be parsed (String, StringBuffer, char[], File,
296 * @throws IOException
297 * @throws PhylogenyParserException
300 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
301 if ( nhx_source == null ) {
302 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
304 else if ( nhx_source instanceof String ) {
305 setInputType( NHXParser.STRING );
306 setSourceLength( ( ( String ) nhx_source ).length() );
307 setNhxSource( nhx_source );
309 else if ( nhx_source instanceof StringBuffer ) {
310 setInputType( NHXParser.STRING_BUFFER );
311 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
312 setNhxSource( nhx_source );
314 else if ( nhx_source instanceof char[] ) {
315 setInputType( NHXParser.CHAR_ARRAY );
316 setSourceLength( ( ( char[] ) nhx_source ).length );
317 setNhxSource( nhx_source );
319 else if ( nhx_source instanceof File ) {
320 setInputType( NHXParser.BUFFERED_READER );
321 setSourceLength( 0 );
322 final File f = ( File ) nhx_source;
323 final String error = ForesterUtil.isReadableFile( f );
324 if ( !ForesterUtil.isEmpty( error ) ) {
325 throw new PhylogenyParserException( error );
327 setNhxSource( new BufferedReader( new FileReader( f ) ) );
329 else if ( nhx_source instanceof InputStream ) {
330 setInputType( NHXParser.BUFFERED_READER );
331 setSourceLength( 0 );
332 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
333 setNhxSource( new BufferedReader( isr ) );
336 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
337 + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
338 + nhx_source.getClass() + "]." );
343 public void setTaxonomyExtraction( final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction ) {
344 _taxonomy_extraction = taxonomy_extraction;
348 * Decreases the clade level by one.
350 * @throws PhylogenyParserException
351 * if level goes below zero.
353 private void decreaseCladeLevel() throws PhylogenyParserException {
354 if ( getCladeLevel() < 0 ) {
355 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
361 * Finishes the current Phylogeny and adds it to the list of Phylogenies
364 * @throws PhylogenyParserException
365 * @throws NHXFormatException
366 * @throws PhyloXmlDataFormatException
368 private void finishPhylogeny() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
370 if ( getCurrentPhylogeny() != null ) {
371 parseNHX( getCurrentAnotation().toString(),
372 getCurrentPhylogeny().getRoot(),
373 getTaxonomyExtraction(),
374 isReplaceUnderscores() );
375 if ( NHXParser.GUESS_IF_SUPPORT_VALUES ) {
376 if ( NHXParser.isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
377 NHXParser.moveBranchLengthsToConfidenceValues( getCurrentPhylogeny() );
380 if ( isGuessRootedness() ) {
381 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
382 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
383 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
384 getCurrentPhylogeny().setRooted( true );
387 getPhylogenies().add( getCurrentPhylogeny() );
391 private void finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
392 PhyloXmlDataFormatException {
394 final PhylogenyNode new_node = new PhylogenyNode();
395 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
396 setCurrentPhylogeny( new Phylogeny() );
397 getCurrentPhylogeny().setRoot( new_node );
398 getPhylogenies().add( getCurrentPhylogeny() );
401 private int getCladeLevel() {
405 private StringBuilder getCurrentAnotation() {
406 return _current_anotation;
409 private PhylogenyNode getCurrentNode() {
410 return _current_node;
413 private Phylogeny getCurrentPhylogeny() {
414 return _current_phylogeny;
417 private byte getInputType() {
421 private Object getNhxSource() {
425 private List<Phylogeny> getPhylogenies() {
430 * Returns the Phylogenies created as Array.
432 * @return the Phylogenies created as Array
434 private Phylogeny[] getPhylogeniesAsArray() {
435 final Phylogeny[] p = new Phylogeny[ getPhylogenies().size() ];
436 for( int i = 0; i < getPhylogenies().size(); ++i ) {
437 p[ i ] = getPhylogenies().get( i );
442 private int getSourceLength() {
443 return _source_length;
447 * Increases the clade level by one.
449 private void increaseCladeLevel() {
453 private void init() {
454 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
455 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
456 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
457 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
461 private boolean isGuessRootedness() {
462 return _guess_rootedness;
465 private boolean isIgnoreQuotes() {
466 return _ignore_quotes;
469 private boolean isReplaceUnderscores() {
470 return _replace_underscores;
473 private boolean isSawClosingParen() {
474 return _saw_closing_paren;
478 * Replaces the current annotation with a new StringBuffer.
480 private void newCurrentAnotation() {
481 setCurrentAnotation( new StringBuilder() );
485 * Called if a closing paren is encountered.
487 * @throws PhylogenyParserException
488 * @throws NHXFormatException
489 * @throws PhyloXmlDataFormatException
491 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
492 decreaseCladeLevel();
493 if ( !isSawClosingParen() ) {
494 final PhylogenyNode new_node = new PhylogenyNode();
495 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
496 newCurrentAnotation();
497 getCurrentNode().addAsChild( new_node );
500 parseNHX( getCurrentAnotation().toString(),
501 getCurrentNode().getLastChildNode(),
502 getTaxonomyExtraction(),
503 isReplaceUnderscores() );
504 newCurrentAnotation();
506 if ( !getCurrentNode().isRoot() ) {
507 setCurrentNode( getCurrentNode().getParent() );
509 setSawClosingParen( true );
510 } // processCloseParen()
513 * Called if a comma is encountered.
515 * @throws PhylogenyParserException
516 * @throws NHXFormatException
517 * @throws PhyloXmlDataFormatException
519 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
520 if ( !isSawClosingParen() ) {
521 final PhylogenyNode new_node = new PhylogenyNode();
522 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
523 if ( getCurrentNode() == null ) {
524 throw new NHXFormatException( "format might not be NH or NHX" );
526 getCurrentNode().addAsChild( new_node );
529 parseNHX( getCurrentAnotation().toString(),
530 getCurrentNode().getLastChildNode(),
531 getTaxonomyExtraction(),
532 isReplaceUnderscores() );
534 newCurrentAnotation();
535 setSawClosingParen( false );
539 * Called if a opening paren is encountered.
541 * @throws PhylogenyParserException
542 * @throws NHXFormatException
543 * @throws PhyloXmlDataFormatException
545 private void processOpenParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
546 final PhylogenyNode new_node = new PhylogenyNode();
547 if ( getCladeLevel() == 0 ) {
548 if ( getCurrentPhylogeny() != null ) {
552 newCurrentAnotation();
553 setCurrentPhylogeny( new Phylogeny() );
554 getCurrentPhylogeny().setRoot( new_node );
557 increaseCladeLevel();
558 getCurrentNode().addAsChild( new_node );
560 setCurrentNode( new_node );
561 setSawClosingParen( false );
564 private void setCladeLevel( final int clade_level ) {
565 if ( clade_level < 0 ) {
566 throw new IllegalArgumentException( "Attempt to set clade level to a number smaller than zero." );
568 _clade_level = clade_level;
571 private void setCurrentAnotation( final StringBuilder current_anotation ) {
572 _current_anotation = current_anotation;
575 private void setCurrentNode( final PhylogenyNode current_node ) {
576 _current_node = current_node;
579 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
580 _current_phylogeny = current_phylogeny;
583 private void setHasNext( final boolean has_next ) {
584 _has_next = has_next;
587 private void setInputType( final byte input_type ) {
588 _input_type = input_type;
591 private void setNhxSource( final Object nhx_source ) {
592 _nhx_source = nhx_source;
595 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
596 _phylogenies = phylogenies;
599 private void setSawClosingParen( final boolean saw_closing_paren ) {
600 _saw_closing_paren = saw_closing_paren;
603 private void setSourceLength( final int source_length ) {
604 _source_length = source_length;
607 public static void parseNHX( String s,
608 final PhylogenyNode node_to_annotate,
609 final TAXONOMY_EXTRACTION taxonomy_extraction,
610 final boolean replace_underscores ) throws NHXFormatException,
611 PhyloXmlDataFormatException {
612 if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
613 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
615 if ( ( s != null ) && ( s.length() > 0 ) ) {
616 if ( replace_underscores ) {
617 s = s.replaceAll( "_+", " " );
619 boolean is_nhx = false;
620 final int ob = s.indexOf( "[" );
624 final int cb = s.indexOf( "]" );
626 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
628 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
629 b = s.substring( ob + 6, cb );
632 // No &&NHX and digits only: is likely to be a support value.
633 final String bracketed = s.substring( ob + 1, cb );
634 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
635 if ( numbers_only.matches() ) {
636 b = ":" + NHXtags.SUPPORT + bracketed;
638 else if ( s.indexOf( "prob=" ) > -1 ) {
639 processMrBayes3Data( s, node_to_annotate );
642 s = s.substring( 0, ob ) + b;
643 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
644 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
647 final StringTokenizer t = new StringTokenizer( s, ":" );
648 if ( t.countTokens() > 0 ) {
649 if ( !s.startsWith( ":" ) ) {
650 node_to_annotate.setName( t.nextToken() );
651 if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
652 final String tax = ParserUtils.extractTaxonomyCodeFromNodeName( node_to_annotate.getName(),
653 taxonomy_extraction );
654 if ( !ForesterUtil.isEmpty( tax ) ) {
655 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
656 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
658 node_to_annotate.getNodeData().getTaxonomy().setTaxonomyCode( tax );
662 while ( t.hasMoreTokens() ) {
664 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
665 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
666 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
668 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
670 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.ANNOTATION ) ) {
671 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
672 node_to_annotate.getNodeData().setSequence( new Sequence() );
674 final Annotation annotation = new Annotation( "_:_" );
675 annotation.setDesc( s.substring( 3 ) );
676 node_to_annotate.getNodeData().getSequence().addAnnotation( annotation );
678 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
679 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
680 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
682 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
683 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
685 else if ( s.charAt( 2 ) == '?' ) {
686 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
689 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
692 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
693 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
695 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
696 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
697 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
699 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
701 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
702 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
704 else if ( s.startsWith( NHXtags.COLOR ) ) {
705 final Color c = NHXParser.stringToColor( s.substring( 2 ) );
707 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
710 else if ( s.startsWith( NHXtags.CUSTOM_DATA_ON_NODE ) ) {
711 if ( !node_to_annotate.getNodeData().isHasProperties() ) {
712 node_to_annotate.getNodeData().setProperties( new PropertiesMap() );
714 node_to_annotate.getNodeData().getProperties().addProperty( Property.createFromNhxString( s ) );
716 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
717 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
718 node_to_annotate.getNodeData().setSequence( new Sequence() );
720 node_to_annotate.getNodeData().getSequence()
721 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
723 else if ( s.startsWith( NHXtags.NODE_IDENTIFIER ) ) {
724 node_to_annotate.getNodeData().setNodeIdentifier( new Identifier( s.substring( 3 ) ) );
726 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
727 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
728 node_to_annotate.getNodeData().setSequence( new Sequence() );
730 node_to_annotate.getNodeData().getSequence()
731 .setAccession( new Accession( s.substring( 3 ), "?" ) );
733 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
734 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
735 node_to_annotate.getNodeData().setSequence( new Sequence() );
737 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
739 else if ( s.startsWith( NHXtags.GENE_NAME_SYNONYM ) ) {
740 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
741 node_to_annotate.getNodeData().setSequence( new Sequence() );
743 node_to_annotate.getNodeData().getSequence().setName( s.substring( 2 ) );
745 else if ( s.indexOf( '=' ) < 0 ) {
746 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
747 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
750 node_to_annotate.setDistanceToParent( doubleValue( s ) );
752 } // while ( t.hasMoreTokens() )
757 private static double doubleValue( final String str ) throws NHXFormatException {
759 return Double.valueOf( str ).doubleValue();
761 catch ( final NumberFormatException ex ) {
762 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
767 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
768 final PhylogenyNodeIterator it = p.iteratorExternalForward();
769 final double d0 = it.next().getDistanceToParent();
770 if ( ( d0 < 10 ) || !it.hasNext() ) {
773 while ( it.hasNext() ) {
774 final double d = it.next().getDistanceToParent();
775 if ( ( d != d0 ) || ( d < 10 ) ) {
782 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
783 final PhylogenyNodeIterator it = p.iteratorPostorder();
784 while ( it.hasNext() ) {
785 final PhylogenyNode n = it.next();
786 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
787 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
791 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
792 throws NHXFormatException {
794 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
795 if ( mb_prob_sd_matcher.find() ) {
797 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
799 catch ( final NumberFormatException e ) {
800 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
804 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
805 if ( mb_prob_matcher.find() ) {
808 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
810 catch ( final NumberFormatException e ) {
811 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
815 node_to_annotate.getBranchData()
816 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
819 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
823 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
824 if ( mb_bl_matcher.find() ) {
827 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
829 catch ( final NumberFormatException e ) {
830 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
834 node_to_annotate.setDistanceToParent( bl );
840 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
841 * and blue and returns the corresponding Color.
843 private static Color stringToColor( final String s ) {
844 final StringTokenizer st = new StringTokenizer( s, "." );
845 if ( st.countTokens() != 3 ) {
846 throw new IllegalArgumentException( "illegal format for color: " + s );
848 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
849 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
850 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
851 return new Color( red, green, blu );
854 public static enum TAXONOMY_EXTRACTION {
855 NO, YES, PFAM_STYLE_ONLY;