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 _ignore_quotes;
74 private byte _input_type;
75 private int _source_length;
76 private PhylogenyNode _current_node;
77 private StringBuilder _current_anotation;
78 private Object _nhx_source;
79 private int _clade_level;
80 private List<Phylogeny> _phylogenies;
81 private Phylogeny _current_phylogeny;
82 private TAXONOMY_EXTRACTION _taxonomy_extraction;
83 private boolean _replace_underscores;
84 public final static Pattern UC_LETTERS_NUMBERS_PATTERN = Pattern.compile( "^[A-Z0-9]+$" );
85 public final static Pattern NUMBERS_ONLY_PATTERN = Pattern.compile( "^[0-9\\.]+$" );
86 public final static Pattern MB_PROB_PATTERN = Pattern.compile( "prob=([^,]+)" );
87 public final static Pattern MB_PROB_SD_PATTERN = Pattern.compile( "prob_stddev=([^,]+)" );
88 public final static Pattern MB_BL_PATTERN = Pattern.compile( "length_median=([^,]+)" );
94 public NHXParser.TAXONOMY_EXTRACTION getTaxonomyExtraction() {
95 return _taxonomy_extraction;
99 * Parses the source set with setSource( final Object nhx_source ). Returns
100 * the Phylogenies found in the source as Phylogeny[].
101 * Everything between [ and ] is considered comment and ignored,
105 * ":digits and/or.[bootstrap]"
107 * @see #setSource( final Object nhx_source )
108 * @see org.forester.io.parsers.PhylogenyParser#parse()
109 * @return Phylogeny[]
110 * @throws IOException
111 * @throws NHXFormatException
112 * @throws PhylogenyParserException
115 public Phylogeny[] parse() throws IOException, NHXFormatException {
116 boolean in_comment = false;
117 boolean saw_colon = false;
118 boolean saw_open_bracket = false;
119 boolean in_open_bracket = false;
120 boolean in_double_quote = false;
121 boolean in_single_quote = false;
122 setPhylogenies( new ArrayList<Phylogeny>() );
124 newCurrentAnotation();
125 setCurrentPhylogeny( null );
126 setCurrentNode( null );
128 String my_source_str = null;
129 StringBuffer my_source_sbuff = null;
130 StringBuilder my_source_sbuil = null;
131 char[] my_source_charary = null;
132 BufferedReader my_source_br = null;
133 switch ( getInputType() ) {
135 my_source_str = ( String ) getNhxSource();
138 my_source_sbuff = ( StringBuffer ) getNhxSource();
141 my_source_sbuil = ( StringBuilder ) getNhxSource();
144 my_source_charary = ( char[] ) getNhxSource();
146 case BUFFERED_READER:
147 my_source_br = ( BufferedReader ) getNhxSource();
150 throw new RuntimeException( "unknown input type" );
154 if ( getInputType() == NHXParser.BUFFERED_READER ) {
155 final int ci = my_source_br.read();
164 if ( i >= getSourceLength() ) {
168 switch ( getInputType() ) {
170 c = my_source_str.charAt( i );
173 c = my_source_sbuff.charAt( i );
176 c = my_source_sbuil.charAt( i );
179 c = my_source_charary[ i ];
184 if ( !in_single_quote && !in_double_quote ) {
188 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
189 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
192 if ( in_open_bracket && ( c == ']' ) ) {
193 in_open_bracket = false;
196 // \n\t is always ignored,
197 // as is " (34) and ' (39) (space is 32):
198 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
199 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
202 else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
205 else if ( in_comment ) {
210 else if ( in_double_quote ) {
212 in_double_quote = false;
215 getCurrentAnotation().append( c );
218 else if ( c == '"' ) {
219 in_double_quote = true;
221 else if ( in_single_quote ) {
223 in_single_quote = false;
226 getCurrentAnotation().append( c );
229 else if ( c == 39 ) {
230 in_single_quote = true;
232 else if ( c == '[' ) {
233 saw_open_bracket = true;
234 in_open_bracket = true;
236 else if ( saw_open_bracket ) {
238 // everything not starting with "[&" is considered a comment
239 // unless ":digits and/or . [bootstrap]":
241 getCurrentAnotation().append( "[&" );
243 else if ( saw_colon ) {
244 getCurrentAnotation().append( "[" + c );
250 // comment consisting just of "[]":
251 saw_open_bracket = false;
253 else if ( ( c == '(' ) && !in_open_bracket ) {
256 else if ( ( c == ')' ) && !in_open_bracket ) {
259 else if ( ( c == ',' ) && !in_open_bracket ) {
263 getCurrentAnotation().append( c );
267 if ( getCladeLevel() != 0 ) {
268 setPhylogenies( null );
269 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
271 if ( getCurrentPhylogeny() != null ) {
274 else if ( getCurrentAnotation().length() > 0 ) {
275 finishSingleNodePhylogeny();
277 else if ( getPhylogenies().size() < 1 ) {
278 getPhylogenies().add( new Phylogeny() );
280 return getPhylogeniesAsArray();
283 public void setGuessRootedness( final boolean guess_rootedness ) {
284 _guess_rootedness = guess_rootedness;
287 public void setIgnoreQuotes( final boolean ignore_quotes ) {
288 _ignore_quotes = ignore_quotes;
291 public void setReplaceUnderscores( final boolean replace_underscores ) {
292 _replace_underscores = replace_underscores;
296 * This sets the source to be parsed. The source can be: String,
297 * StringBuffer, char[], File, or InputStream. The source can contain more
298 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
299 * Extended (NHX) format. There is no need to separate phylogenies with any
300 * special character. White space is always ignored, as are semicolons
301 * inbetween phylogenies. Example of a source describing two phylogenies
302 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
303 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
304 * character other than '&' and ']' is considered a comment and ignored
305 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
306 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
307 * info]" is ignored, too (at the PhylogenyNode level, though).
308 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
311 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
313 * the source to be parsed (String, StringBuffer, char[], File,
315 * @throws IOException
316 * @throws PhylogenyParserException
319 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
320 if ( nhx_source == null ) {
321 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
323 else if ( nhx_source instanceof String ) {
324 setInputType( NHXParser.STRING );
325 setSourceLength( ( ( String ) nhx_source ).length() );
326 setNhxSource( nhx_source );
328 else if ( nhx_source instanceof StringBuilder ) {
329 setInputType( NHXParser.STRING_BUILDER );
330 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
331 setNhxSource( nhx_source );
333 else if ( nhx_source instanceof StringBuffer ) {
334 setInputType( NHXParser.STRING_BUFFER );
335 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
336 setNhxSource( nhx_source );
338 else if ( nhx_source instanceof StringBuilder ) {
339 setInputType( NHXParser.STRING_BUILDER );
340 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
341 setNhxSource( nhx_source );
343 else if ( nhx_source instanceof char[] ) {
344 setInputType( NHXParser.CHAR_ARRAY );
345 setSourceLength( ( ( char[] ) nhx_source ).length );
346 setNhxSource( nhx_source );
348 else if ( nhx_source instanceof File ) {
349 setInputType( NHXParser.BUFFERED_READER );
350 setSourceLength( 0 );
351 final File f = ( File ) nhx_source;
352 final String error = ForesterUtil.isReadableFile( f );
353 if ( !ForesterUtil.isEmpty( error ) ) {
354 throw new PhylogenyParserException( error );
356 setNhxSource( new BufferedReader( new FileReader( f ) ) );
358 else if ( nhx_source instanceof InputStream ) {
359 setInputType( NHXParser.BUFFERED_READER );
360 setSourceLength( 0 );
361 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
362 setNhxSource( new BufferedReader( isr ) );
365 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
366 + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
367 + nhx_source.getClass() + "]." );
371 public void setTaxonomyExtraction( final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction ) {
372 _taxonomy_extraction = taxonomy_extraction;
376 * Decreases the clade level by one.
378 * @throws PhylogenyParserException
379 * if level goes below zero.
381 private void decreaseCladeLevel() throws PhylogenyParserException {
382 if ( getCladeLevel() < 0 ) {
383 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
389 * Finishes the current Phylogeny and adds it to the list of Phylogenies
392 * @throws PhylogenyParserException
393 * @throws NHXFormatException
394 * @throws PhyloXmlDataFormatException
396 private void finishPhylogeny() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
398 if ( getCurrentPhylogeny() != null ) {
399 parseNHX( getCurrentAnotation().toString(),
400 getCurrentPhylogeny().getRoot(),
401 getTaxonomyExtraction(),
402 isReplaceUnderscores() );
403 if ( NHXParser.GUESS_IF_SUPPORT_VALUES ) {
404 if ( NHXParser.isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
405 NHXParser.moveBranchLengthsToConfidenceValues( getCurrentPhylogeny() );
408 if ( isGuessRootedness() ) {
409 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
410 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
411 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
412 getCurrentPhylogeny().setRooted( true );
415 getPhylogenies().add( getCurrentPhylogeny() );
419 private void finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
420 PhyloXmlDataFormatException {
422 final PhylogenyNode new_node = new PhylogenyNode();
423 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
424 setCurrentPhylogeny( new Phylogeny() );
425 getCurrentPhylogeny().setRoot( new_node );
426 getPhylogenies().add( getCurrentPhylogeny() );
429 private int getCladeLevel() {
433 private StringBuilder getCurrentAnotation() {
434 return _current_anotation;
437 private PhylogenyNode getCurrentNode() {
438 return _current_node;
441 private Phylogeny getCurrentPhylogeny() {
442 return _current_phylogeny;
445 private byte getInputType() {
449 private Object getNhxSource() {
453 private List<Phylogeny> getPhylogenies() {
458 * Returns the Phylogenies created as Array.
460 * @return the Phylogenies created as Array
462 private Phylogeny[] getPhylogeniesAsArray() {
463 final Phylogeny[] p = new Phylogeny[ getPhylogenies().size() ];
464 for( int i = 0; i < getPhylogenies().size(); ++i ) {
465 p[ i ] = getPhylogenies().get( i );
470 private int getSourceLength() {
471 return _source_length;
475 * Increases the clade level by one.
477 private void increaseCladeLevel() {
481 private void init() {
482 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
483 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
484 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
485 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
488 private boolean isGuessRootedness() {
489 return _guess_rootedness;
492 private boolean isIgnoreQuotes() {
493 return _ignore_quotes;
496 private boolean isReplaceUnderscores() {
497 return _replace_underscores;
500 private boolean isSawClosingParen() {
501 return _saw_closing_paren;
505 * Replaces the current annotation with a new StringBuffer.
507 private void newCurrentAnotation() {
508 setCurrentAnotation( new StringBuilder() );
512 * Called if a closing paren is encountered.
514 * @throws PhylogenyParserException
515 * @throws NHXFormatException
516 * @throws PhyloXmlDataFormatException
518 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
519 decreaseCladeLevel();
520 if ( !isSawClosingParen() ) {
521 final PhylogenyNode new_node = new PhylogenyNode();
522 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
523 newCurrentAnotation();
524 getCurrentNode().addAsChild( new_node );
527 parseNHX( getCurrentAnotation().toString(),
528 getCurrentNode().getLastChildNode(),
529 getTaxonomyExtraction(),
530 isReplaceUnderscores() );
531 newCurrentAnotation();
533 if ( !getCurrentNode().isRoot() ) {
534 setCurrentNode( getCurrentNode().getParent() );
536 setSawClosingParen( true );
537 } // processCloseParen()
540 * Called if a comma is encountered.
542 * @throws PhylogenyParserException
543 * @throws NHXFormatException
544 * @throws PhyloXmlDataFormatException
546 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
547 if ( !isSawClosingParen() ) {
548 final PhylogenyNode new_node = new PhylogenyNode();
549 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
550 if ( getCurrentNode() == null ) {
551 throw new NHXFormatException( "format might not be NH or NHX" );
553 getCurrentNode().addAsChild( new_node );
556 parseNHX( getCurrentAnotation().toString(),
557 getCurrentNode().getLastChildNode(),
558 getTaxonomyExtraction(),
559 isReplaceUnderscores() );
561 newCurrentAnotation();
562 setSawClosingParen( false );
566 * Called if a opening paren is encountered.
568 * @throws PhylogenyParserException
569 * @throws NHXFormatException
570 * @throws PhyloXmlDataFormatException
572 private void processOpenParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
573 final PhylogenyNode new_node = new PhylogenyNode();
574 if ( getCladeLevel() == 0 ) {
575 if ( getCurrentPhylogeny() != null ) {
579 newCurrentAnotation();
580 setCurrentPhylogeny( new Phylogeny() );
581 getCurrentPhylogeny().setRoot( new_node );
584 increaseCladeLevel();
585 getCurrentNode().addAsChild( new_node );
587 setCurrentNode( new_node );
588 setSawClosingParen( false );
591 private void setCladeLevel( final int clade_level ) {
592 if ( clade_level < 0 ) {
593 throw new IllegalArgumentException( "Attempt to set clade level to a number smaller than zero." );
595 _clade_level = clade_level;
598 private void setCurrentAnotation( final StringBuilder current_anotation ) {
599 _current_anotation = current_anotation;
602 private void setCurrentNode( final PhylogenyNode current_node ) {
603 _current_node = current_node;
606 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
607 _current_phylogeny = current_phylogeny;
610 private void setInputType( final byte input_type ) {
611 _input_type = input_type;
614 private void setNhxSource( final Object nhx_source ) {
615 _nhx_source = nhx_source;
618 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
619 _phylogenies = phylogenies;
622 private void setSawClosingParen( final boolean saw_closing_paren ) {
623 _saw_closing_paren = saw_closing_paren;
626 private void setSourceLength( final int source_length ) {
627 _source_length = source_length;
630 public static void parseNHX( String s,
631 final PhylogenyNode node_to_annotate,
632 final TAXONOMY_EXTRACTION taxonomy_extraction,
633 final boolean replace_underscores ) throws NHXFormatException,
634 PhyloXmlDataFormatException {
635 if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
636 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
638 if ( ( s != null ) && ( s.length() > 0 ) ) {
639 if ( replace_underscores ) {
640 s = s.replaceAll( "_+", " " );
642 boolean is_nhx = false;
643 final int ob = s.indexOf( "[" );
647 final int cb = s.indexOf( "]" );
649 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
651 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
652 b = s.substring( ob + 6, cb );
655 // No &&NHX and digits only: is likely to be a support value.
656 final String bracketed = s.substring( ob + 1, cb );
657 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
658 if ( numbers_only.matches() ) {
659 b = ":" + NHXtags.SUPPORT + bracketed;
661 else if ( s.indexOf( "prob=" ) > -1 ) {
662 processMrBayes3Data( s, node_to_annotate );
665 s = s.substring( 0, ob ) + b;
666 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
667 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
670 final StringTokenizer t = new StringTokenizer( s, ":" );
671 if ( t.countTokens() > 0 ) {
672 if ( !s.startsWith( ":" ) ) {
673 node_to_annotate.setName( t.nextToken() );
674 if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
675 ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
678 while ( t.hasMoreTokens() ) {
680 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
681 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
682 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
684 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
686 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
687 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
688 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
690 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
691 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
693 else if ( s.charAt( 2 ) == '?' ) {
694 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
697 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
700 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
701 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
703 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
704 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
705 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
707 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
709 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
710 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
712 else if ( s.startsWith( NHXtags.COLOR ) ) {
713 final Color c = NHXParser.stringToColor( s.substring( 2 ) );
715 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
718 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
719 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
720 node_to_annotate.getNodeData().setSequence( new Sequence() );
722 node_to_annotate.getNodeData().getSequence()
723 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
725 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
726 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
727 node_to_annotate.getNodeData().setSequence( new Sequence() );
729 node_to_annotate.getNodeData().getSequence()
730 .setAccession( new Accession( s.substring( 3 ), "?" ) );
732 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
733 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
734 node_to_annotate.getNodeData().setSequence( new Sequence() );
736 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
738 else if ( s.indexOf( '=' ) < 0 ) {
739 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
740 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
743 node_to_annotate.setDistanceToParent( doubleValue( s ) );
745 } // while ( t.hasMoreTokens() )
750 private static double doubleValue( final String str ) throws NHXFormatException {
752 return Double.valueOf( str ).doubleValue();
754 catch ( final NumberFormatException ex ) {
755 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
760 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
761 final PhylogenyNodeIterator it = p.iteratorExternalForward();
762 final double d0 = it.next().getDistanceToParent();
763 if ( ( d0 < 10 ) || !it.hasNext() ) {
766 while ( it.hasNext() ) {
767 final double d = it.next().getDistanceToParent();
768 if ( ( d != d0 ) || ( d < 10 ) ) {
775 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
776 final PhylogenyNodeIterator it = p.iteratorPostorder();
777 while ( it.hasNext() ) {
778 final PhylogenyNode n = it.next();
779 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
780 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
784 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
785 throws NHXFormatException {
787 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
788 if ( mb_prob_sd_matcher.find() ) {
790 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
792 catch ( final NumberFormatException e ) {
793 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
797 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
798 if ( mb_prob_matcher.find() ) {
801 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
803 catch ( final NumberFormatException e ) {
804 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
808 node_to_annotate.getBranchData()
809 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
812 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
816 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
817 if ( mb_bl_matcher.find() ) {
820 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
822 catch ( final NumberFormatException e ) {
823 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
827 node_to_annotate.setDistanceToParent( bl );
833 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
834 * and blue and returns the corresponding Color.
836 private static Color stringToColor( final String s ) {
837 final StringTokenizer st = new StringTokenizer( s, "." );
838 if ( st.countTokens() != 3 ) {
839 throw new IllegalArgumentException( "illegal format for color: " + s );
841 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
842 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
843 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
844 return new Color( red, green, blu );
847 public static enum TAXONOMY_EXTRACTION {
848 NO, YES, PFAM_STYLE_ONLY;