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 boolean LIMIT_SPECIES_NAMES_TO_FIVE_CHARS = false;
65 public static final PhylogenyMethods.TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION_DEFAULT = PhylogenyMethods.TAXONOMY_EXTRACTION.NO;
66 final static private boolean GUESS_ROOTEDNESS_DEFAULT = true;
67 final static private boolean GUESS_IF_SUPPORT_VALUES = true;
68 final static private boolean IGNORE_QUOTES_DEFAULT = false;
69 final static public boolean REPLACE_UNDERSCORES_DEFAULT = false;
70 private boolean _saw_closing_paren;
71 final static private byte STRING = 0;
72 final static private byte STRING_BUFFER = 1;
73 final static private byte CHAR_ARRAY = 2;
74 final static private byte BUFFERED_READER = 3;
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 PhylogenyMethods.TAXONOMY_EXTRACTION _taxonomy_extraction;
87 private boolean _replace_underscores;
88 public final static Pattern UC_LETTERS_NUMBERS_PATTERN = Pattern
89 .compile( "^[A-Z0-9]+$" );
90 public final static Pattern NUMBERS_ONLY_PATTERN = Pattern
91 .compile( "^[0-9\\.]+$" );
92 public final static Pattern MB_PROB_PATTERN = Pattern
93 .compile( "prob=([^,]+)" );
94 public final static Pattern MB_PROB_SD_PATTERN = Pattern
95 .compile( "prob_stddev=([^,]+)" );
96 public final static Pattern MB_BL_PATTERN = Pattern
97 .compile( "length_median=([^,]+)" );
104 * Decreases the clade level by one.
106 * @throws PhylogenyParserException
107 * if level goes below zero.
109 private void decreaseCladeLevel() throws PhylogenyParserException {
110 if ( getCladeLevel() < 0 ) {
111 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
117 * Finishes the current Phylogeny and adds it to the list of Phylogenies
120 * @throws PhylogenyParserException
121 * @throws NHXFormatException
122 * @throws PhyloXmlDataFormatException
124 private void finishPhylogeny() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
126 if ( getCurrentPhylogeny() != null ) {
127 parseNHX( getCurrentAnotation().toString(),
128 getCurrentPhylogeny().getRoot(),
129 getTaxonomyExtraction(),
130 isReplaceUnderscores() );
131 if ( NHXParser.GUESS_IF_SUPPORT_VALUES ) {
132 if ( NHXParser.isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
133 NHXParser.moveBranchLengthsToConfidenceValues( getCurrentPhylogeny() );
136 if ( isGuessRootedness() ) {
137 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
138 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
139 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
140 getCurrentPhylogeny().setRooted( true );
143 getPhylogenies().add( getCurrentPhylogeny() );
147 private void finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
148 PhyloXmlDataFormatException {
150 final PhylogenyNode new_node = new PhylogenyNode();
151 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
152 setCurrentPhylogeny( new Phylogeny() );
153 getCurrentPhylogeny().setRoot( new_node );
154 getPhylogenies().add( getCurrentPhylogeny() );
157 private int getCladeLevel() {
161 private StringBuilder getCurrentAnotation() {
162 return _current_anotation;
165 private PhylogenyNode getCurrentNode() {
166 return _current_node;
169 private Phylogeny getCurrentPhylogeny() {
170 return _current_phylogeny;
173 private byte getInputType() {
177 private Object getNhxSource() {
181 private List<Phylogeny> getPhylogenies() {
186 * Returns the Phylogenies created as Array.
188 * @return the Phylogenies created as Array
190 private Phylogeny[] getPhylogeniesAsArray() {
191 final Phylogeny[] p = new Phylogeny[ getPhylogenies().size() ];
192 for( int i = 0; i < getPhylogenies().size(); ++i ) {
193 p[ i ] = getPhylogenies().get( i );
198 private int getSourceLength() {
199 return _source_length;
202 public PhylogenyMethods.TAXONOMY_EXTRACTION getTaxonomyExtraction() {
203 return _taxonomy_extraction;
206 public boolean hasNext() {
211 * Increases the clade level by one.
213 private void increaseCladeLevel() {
217 private void init() {
218 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
219 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
220 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
221 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
225 private boolean isGuessRootedness() {
226 return _guess_rootedness;
229 private boolean isIgnoreQuotes() {
230 return _ignore_quotes;
233 private boolean isReplaceUnderscores() {
234 return _replace_underscores;
237 private boolean isSawClosingParen() {
238 return _saw_closing_paren;
242 * Replaces the current annotation with a new StringBuffer.
244 private void newCurrentAnotation() {
245 setCurrentAnotation( new StringBuilder() );
249 * Parses the source set with setSource( final Object nhx_source ). Returns
250 * the Phylogenies found in the source as Phylogeny[].
251 * Everything between [ and ] is considered comment and ignored,
255 * ":digits and/or.[bootstrap]"
257 * @see #setSource( final Object nhx_source )
258 * @see org.forester.io.parsers.PhylogenyParser#parse()
259 * @return Phylogeny[]
260 * @throws IOException
261 * @throws NHXFormatException
262 * @throws PhylogenyParserException
265 public Phylogeny[] parse() throws IOException, NHXFormatException {
267 boolean in_comment = false;
268 boolean saw_colon = false;
269 boolean saw_open_bracket = false;
270 boolean in_open_bracket = false;
271 boolean in_double_quote = false;
272 boolean in_single_quote = false;
273 setPhylogenies( new ArrayList<Phylogeny>() );
275 newCurrentAnotation();
279 if ( getInputType() == NHXParser.BUFFERED_READER ) {
280 final int ci = ( ( BufferedReader ) getNhxSource() ).read();
289 if ( i >= getSourceLength() ) {
293 switch ( getInputType() ) {
295 c = ( ( String ) getNhxSource() ).charAt( i );
298 c = ( ( StringBuffer ) getNhxSource() ).charAt( i );
301 c = ( ( char[] ) getNhxSource() )[ i ];
306 if ( !in_single_quote && !in_double_quote ) {
310 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
311 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
314 if ( in_open_bracket && ( c == ']' ) ) {
315 in_open_bracket = false;
318 // \n\t is always ignored,
319 // as is " (34) and ' (39) (space is 32):
320 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
321 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
324 else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
327 else if ( in_comment ) {
332 else if ( in_double_quote ) {
334 in_double_quote = false;
337 getCurrentAnotation().append( c );
340 else if ( c == '"' ) {
341 in_double_quote = true;
343 else if ( in_single_quote ) {
345 in_single_quote = false;
348 getCurrentAnotation().append( c );
351 else if ( c == 39 ) {
352 in_single_quote = true;
354 else if ( c == '[' ) {
355 saw_open_bracket = true;
356 in_open_bracket = true;
358 else if ( saw_open_bracket ) {
360 // everything not starting with "[&" is considered a comment
361 // unless ":digits and/or . [bootstrap]":
363 getCurrentAnotation().append( "[&" );
365 else if ( saw_colon ) {
366 getCurrentAnotation().append( "[" + c );
372 // comment consisting just of "[]":
373 saw_open_bracket = false;
375 else if ( ( c == '(' ) && !in_open_bracket ) {
378 else if ( ( c == ')' ) && !in_open_bracket ) {
381 else if ( ( c == ',' ) && !in_open_bracket ) {
385 getCurrentAnotation().append( c );
389 if ( getCladeLevel() != 0 ) {
390 setPhylogenies( null );
391 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
393 if ( getCurrentPhylogeny() != null ) {
396 else if ( getCurrentAnotation().length() > 0 ) {
397 finishSingleNodePhylogeny();
399 else if ( getPhylogenies().size() < 1 ) {
400 getPhylogenies().add( new Phylogeny() );
402 return getPhylogeniesAsArray();
405 public Phylogeny parseNext() throws IOException, NHXFormatException {
410 * Called if a closing paren is encountered.
412 * @throws PhylogenyParserException
413 * @throws NHXFormatException
414 * @throws PhyloXmlDataFormatException
416 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
417 decreaseCladeLevel();
418 if ( !isSawClosingParen() ) {
419 final PhylogenyNode new_node = new PhylogenyNode();
420 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
421 newCurrentAnotation();
422 getCurrentNode().addAsChild( new_node );
425 parseNHX( getCurrentAnotation().toString(),
426 getCurrentNode().getLastChildNode(),
427 getTaxonomyExtraction(),
428 isReplaceUnderscores() );
429 newCurrentAnotation();
431 if ( !getCurrentNode().isRoot() ) {
432 setCurrentNode( getCurrentNode().getParent() );
434 setSawClosingParen( true );
435 } // processCloseParen()
438 * Called if a comma is encountered.
440 * @throws PhylogenyParserException
441 * @throws NHXFormatException
442 * @throws PhyloXmlDataFormatException
444 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
445 if ( !isSawClosingParen() ) {
446 final PhylogenyNode new_node = new PhylogenyNode();
447 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
448 if ( getCurrentNode() == null ) {
449 throw new NHXFormatException( "format might not be NH or NHX" );
451 getCurrentNode().addAsChild( new_node );
454 parseNHX( getCurrentAnotation().toString(),
455 getCurrentNode().getLastChildNode(),
456 getTaxonomyExtraction(),
457 isReplaceUnderscores() );
459 newCurrentAnotation();
460 setSawClosingParen( false );
464 * Called if a opening paren is encountered.
466 * @throws PhylogenyParserException
467 * @throws NHXFormatException
468 * @throws PhyloXmlDataFormatException
470 private void processOpenParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
471 final PhylogenyNode new_node = new PhylogenyNode();
472 if ( getCladeLevel() == 0 ) {
473 if ( getCurrentPhylogeny() != null ) {
477 newCurrentAnotation();
478 setCurrentPhylogeny( new Phylogeny() );
479 getCurrentPhylogeny().setRoot( new_node );
482 increaseCladeLevel();
483 getCurrentNode().addAsChild( new_node );
485 setCurrentNode( new_node );
486 setSawClosingParen( false );
489 private void setCladeLevel( final int clade_level ) {
490 if ( clade_level < 0 ) {
491 throw new IllegalArgumentException( "Attempt to set clade level to a number smaller than zero." );
493 _clade_level = clade_level;
496 private void setCurrentAnotation( final StringBuilder current_anotation ) {
497 _current_anotation = current_anotation;
500 private void setCurrentNode( final PhylogenyNode current_node ) {
501 _current_node = current_node;
504 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
505 _current_phylogeny = current_phylogeny;
508 public void setGuessRootedness( final boolean guess_rootedness ) {
509 _guess_rootedness = guess_rootedness;
512 private void setHasNext( final boolean has_next ) {
513 _has_next = has_next;
516 public void setIgnoreQuotes( final boolean ignore_quotes ) {
517 _ignore_quotes = ignore_quotes;
520 private void setInputType( final byte input_type ) {
521 _input_type = input_type;
524 private void setNhxSource( final Object nhx_source ) {
525 _nhx_source = nhx_source;
528 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
529 _phylogenies = phylogenies;
532 public void setReplaceUnderscores( final boolean replace_underscores ) {
533 _replace_underscores = replace_underscores;
536 private void setSawClosingParen( final boolean saw_closing_paren ) {
537 _saw_closing_paren = saw_closing_paren;
541 * This sets the source to be parsed. The source can be: String,
542 * StringBuffer, char[], File, or InputStream. The source can contain more
543 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
544 * Extended (NHX) format. There is no need to separate phylogenies with any
545 * special character. White space is always ignored, as are semicolons
546 * inbetween phylogenies. Example of a source describing two phylogenies
547 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
548 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
549 * character other than '&' and ']' is considered a comment and ignored
550 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
551 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
552 * info]" is ignored, too (at the PhylogenyNode level, though).
553 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
556 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
558 * the source to be parsed (String, StringBuffer, char[], File,
560 * @throws IOException
561 * @throws PhylogenyParserException
564 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
565 if ( nhx_source == null ) {
566 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
568 else if ( nhx_source instanceof String ) {
569 setInputType( NHXParser.STRING );
570 setSourceLength( ( ( String ) nhx_source ).length() );
571 setNhxSource( nhx_source );
573 else if ( nhx_source instanceof StringBuffer ) {
574 setInputType( NHXParser.STRING_BUFFER );
575 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
576 setNhxSource( nhx_source );
578 else if ( nhx_source instanceof char[] ) {
579 setInputType( NHXParser.CHAR_ARRAY );
580 setSourceLength( ( ( char[] ) nhx_source ).length );
581 setNhxSource( nhx_source );
583 else if ( nhx_source instanceof File ) {
584 setInputType( NHXParser.BUFFERED_READER );
585 setSourceLength( 0 );
586 final File f = ( File ) nhx_source;
587 final String error = ForesterUtil.isReadableFile( f );
588 if ( !ForesterUtil.isEmpty( error ) ) {
589 throw new PhylogenyParserException( error );
591 setNhxSource( new BufferedReader( new FileReader( f ) ) );
593 else if ( nhx_source instanceof InputStream ) {
594 setInputType( NHXParser.BUFFERED_READER );
595 setSourceLength( 0 );
596 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
597 setNhxSource( new BufferedReader( isr ) );
600 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
601 + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
602 + nhx_source.getClass() + "]." );
607 private void setSourceLength( final int source_length ) {
608 _source_length = source_length;
611 public void setTaxonomyExtraction( final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction ) {
612 _taxonomy_extraction = taxonomy_extraction;
615 private static double doubleValue( final String str ) throws NHXFormatException {
617 return Double.valueOf( str ).doubleValue();
619 catch ( final NumberFormatException ex ) {
620 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from :" + "\"" + str
625 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
626 final PhylogenyNodeIterator it = p.iteratorExternalForward();
627 final double d0 = it.next().getDistanceToParent();
628 if ( ( d0 < 10 ) || !it.hasNext() ) {
631 while ( it.hasNext() ) {
632 final double d = it.next().getDistanceToParent();
633 if ( ( d != d0 ) || ( d < 10 ) ) {
640 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
641 final PhylogenyNodeIterator it = p.iteratorPostorder();
642 while ( it.hasNext() ) {
643 final PhylogenyNode n = it.next();
644 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
645 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
649 public static void parseNHX( String s,
650 final PhylogenyNode node_to_annotate,
651 final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction,
652 final boolean replace_underscores ) throws NHXFormatException,
653 PhyloXmlDataFormatException {
654 if ( ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
655 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
657 if ( ( s != null ) && ( s.length() > 0 ) ) {
658 if ( replace_underscores ) {
659 s = s.replaceAll( "_+", " " );
661 boolean is_nhx = false;
662 final int ob = s.indexOf( "[" );
666 final int cb = s.indexOf( "]" );
668 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
670 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
671 b = s.substring( ob + 6, cb );
674 // No &&NHX and digits only: is likely to be a support value.
675 final String bracketed = s.substring( ob + 1, cb );
676 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
677 if ( numbers_only.matches() ) {
678 b = ":" + NHXtags.SUPPORT + bracketed;
680 else if ( s.indexOf( "prob=" ) > -1 ) {
681 processMrBayes3Data( s, node_to_annotate );
684 s = s.substring( 0, ob ) + b;
685 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
686 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
689 final StringTokenizer t = new StringTokenizer( s, ":" );
690 if ( t.countTokens() > 0 ) {
691 if ( !s.startsWith( ":" ) ) {
692 node_to_annotate.setName( t.nextToken() );
693 if ( !replace_underscores
694 && ( !is_nhx && ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.NO ) ) ) {
695 final String tax = ParserUtils
696 .extractTaxonomyCodeFromNodeName( node_to_annotate.getName(),
697 LIMIT_SPECIES_NAMES_TO_FIVE_CHARS,
698 taxonomy_extraction );
699 if ( !ForesterUtil.isEmpty( tax ) ) {
700 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
701 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
703 node_to_annotate.getNodeData().getTaxonomy().setTaxonomyCode( tax );
707 while ( t.hasMoreTokens() ) {
709 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
710 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
711 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
713 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
715 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.ANNOTATION ) ) {
716 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
717 node_to_annotate.getNodeData().setSequence( new Sequence() );
719 final Annotation annotation = new Annotation( "_:_" );
720 annotation.setDesc( s.substring( 3 ) );
721 node_to_annotate.getNodeData().getSequence().addAnnotation( annotation );
723 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
724 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
725 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
727 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
728 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
730 else if ( s.charAt( 2 ) == '?' ) {
731 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
734 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
737 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
738 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
740 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
741 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
742 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
744 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
746 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
747 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
749 else if ( s.startsWith( NHXtags.COLOR ) ) {
750 final Color c = NHXParser.stringToColor( s.substring( 2 ) );
752 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
755 else if ( s.startsWith( NHXtags.CUSTOM_DATA_ON_NODE ) ) {
756 if ( !node_to_annotate.getNodeData().isHasProperties() ) {
757 node_to_annotate.getNodeData().setProperties( new PropertiesMap() );
759 node_to_annotate.getNodeData().getProperties().addProperty( Property.createFromNhxString( s ) );
761 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
762 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
763 node_to_annotate.getNodeData().setSequence( new Sequence() );
765 node_to_annotate.getNodeData().getSequence()
766 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
768 else if ( s.startsWith( NHXtags.NODE_IDENTIFIER ) ) {
769 node_to_annotate.getNodeData().setNodeIdentifier( new Identifier( s.substring( 3 ) ) );
771 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
772 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
773 node_to_annotate.getNodeData().setSequence( new Sequence() );
775 node_to_annotate.getNodeData().getSequence()
776 .setAccession( new Accession( s.substring( 3 ), "?" ) );
778 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
779 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
780 node_to_annotate.getNodeData().setSequence( new Sequence() );
782 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
784 else if ( s.startsWith( NHXtags.GENE_NAME_SYNONYM ) ) {
785 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
786 node_to_annotate.getNodeData().setSequence( new Sequence() );
788 node_to_annotate.getNodeData().getSequence().setName( s.substring( 2 ) );
790 else if ( s.indexOf( '=' ) < 0 ) {
791 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
792 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
795 node_to_annotate.setDistanceToParent( doubleValue( s ) );
797 } // while ( t.hasMoreTokens() )
802 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
803 throws NHXFormatException {
805 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
806 if ( mb_prob_sd_matcher.find() ) {
808 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
810 catch ( final NumberFormatException e ) {
811 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
815 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
816 if ( mb_prob_matcher.find() ) {
819 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
821 catch ( final NumberFormatException e ) {
822 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
826 node_to_annotate.getBranchData()
827 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
830 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
834 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
835 if ( mb_bl_matcher.find() ) {
838 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
840 catch ( final NumberFormatException e ) {
841 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
845 node_to_annotate.setDistanceToParent( bl );
851 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
852 * and blue and returns the corresponding Color.
854 private static Color stringToColor( final String s ) {
855 final StringTokenizer st = new StringTokenizer( s, "." );
856 if ( st.countTokens() != 3 ) {
857 throw new IllegalArgumentException( "illegal format for color: " + s );
859 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
860 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
861 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
862 return new Color( red, green, blu );