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.util.ParserUtils;
43 import org.forester.io.parsers.util.PhylogenyParserException;
44 import org.forester.phylogeny.Phylogeny;
45 import org.forester.phylogeny.PhylogenyMethods;
46 import org.forester.phylogeny.PhylogenyNode;
47 import org.forester.phylogeny.data.Accession;
48 import org.forester.phylogeny.data.Annotation;
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.PropertiesMap;
55 import org.forester.phylogeny.data.Property;
56 import org.forester.phylogeny.data.Sequence;
57 import org.forester.phylogeny.data.Taxonomy;
58 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
59 import org.forester.util.ForesterUtil;
61 public final class NHXParser implements PhylogenyParser {
63 public static final boolean LIMIT_SPECIES_NAMES_TO_FIVE_CHARS = true;
64 public static final PhylogenyMethods.TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION_DEFAULT = PhylogenyMethods.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 PhylogenyMethods.TAXONOMY_EXTRACTION _taxonomy_extraction;
86 private boolean _replace_underscores;
87 public final static Pattern UC_LETTERS_NUMBERS_PATTERN = Pattern
88 .compile( "^[A-Z0-9]+$" );
89 public final static Pattern NUMBERS_ONLY_PATTERN = Pattern
90 .compile( "^[0-9\\.]+$" );
91 public final static Pattern MB_PROB_PATTERN = Pattern
92 .compile( "prob=([^,]+)" );
93 public final static Pattern MB_PROB_SD_PATTERN = Pattern
94 .compile( "prob_stddev=([^,]+)" );
95 public final static Pattern MB_BL_PATTERN = Pattern
96 .compile( "length_median=([^,]+)" );
103 * Decreases the clade level by one.
105 * @throws PhylogenyParserException
106 * if level goes below zero.
108 private void decreaseCladeLevel() throws PhylogenyParserException {
109 if ( getCladeLevel() < 0 ) {
110 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
116 * Finishes the current Phylogeny and adds it to the list of Phylogenies
119 * @throws PhylogenyParserException
120 * @throws NHXFormatException
122 private void finishPhylogeny() throws PhylogenyParserException, NHXFormatException {
124 if ( getCurrentPhylogeny() != null ) {
125 parseNHX( getCurrentAnotation().toString(),
126 getCurrentPhylogeny().getRoot(),
127 getTaxonomyExtraction(),
128 isReplaceUnderscores() );
129 if ( NHXParser.GUESS_IF_SUPPORT_VALUES ) {
130 if ( NHXParser.isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
131 NHXParser.moveBranchLengthsToBootstrapValues( getCurrentPhylogeny() );
134 if ( isGuessRootedness() ) {
135 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
136 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
137 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
138 getCurrentPhylogeny().setRooted( true );
141 getPhylogenies().add( getCurrentPhylogeny() );
145 private void finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException {
147 final PhylogenyNode new_node = new PhylogenyNode();
148 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
149 setCurrentPhylogeny( new Phylogeny() );
150 getCurrentPhylogeny().setRoot( new_node );
151 getPhylogenies().add( getCurrentPhylogeny() );
154 private int getCladeLevel() {
158 private StringBuilder getCurrentAnotation() {
159 return _current_anotation;
162 private PhylogenyNode getCurrentNode() {
163 return _current_node;
166 private Phylogeny getCurrentPhylogeny() {
167 return _current_phylogeny;
170 private byte getInputType() {
174 private Object getNhxSource() {
178 private List<Phylogeny> getPhylogenies() {
183 * Returns the Phylogenies created as Array.
185 * @return the Phylogenies created as Array
187 private Phylogeny[] getPhylogeniesAsArray() {
188 final Phylogeny[] p = new Phylogeny[ getPhylogenies().size() ];
189 for( int i = 0; i < getPhylogenies().size(); ++i ) {
190 p[ i ] = getPhylogenies().get( i );
195 private int getSourceLength() {
196 return _source_length;
199 public PhylogenyMethods.TAXONOMY_EXTRACTION getTaxonomyExtraction() {
200 return _taxonomy_extraction;
203 public boolean hasNext() {
208 * Increases the clade level by one.
210 private void increaseCladeLevel() {
214 private void init() {
215 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
216 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
217 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
218 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
222 private boolean isGuessRootedness() {
223 return _guess_rootedness;
226 private boolean isIgnoreQuotes() {
227 return _ignore_quotes;
230 private boolean isReplaceUnderscores() {
231 return _replace_underscores;
234 private boolean isSawClosingParen() {
235 return _saw_closing_paren;
239 * Replaces the current annotation with a new StringBuffer.
241 private void newCurrentAnotation() {
242 setCurrentAnotation( new StringBuilder() );
246 * Parses the source set with setSource( final Object nhx_source ). Returns
247 * the Phylogenies found in the source as Phylogeny[].
248 * Everything between [ and ] is considered comment and ignored,
252 * ":digits and/or.[bootstrap]"
254 * @see #setSource( final Object nhx_source )
255 * @see org.forester.io.parsers.PhylogenyParser#parse()
256 * @return Phylogeny[]
257 * @throws IOException
258 * @throws NHXFormatException
259 * @throws PhylogenyParserException
262 public Phylogeny[] parse() throws IOException, NHXFormatException {
264 boolean in_comment = false;
265 boolean saw_colon = false;
266 boolean saw_open_bracket = false;
267 boolean in_open_bracket = false;
268 boolean in_double_quote = false;
269 boolean in_single_quote = false;
270 setPhylogenies( new ArrayList<Phylogeny>() );
272 newCurrentAnotation();
276 if ( getInputType() == NHXParser.BUFFERED_READER ) {
277 final int ci = ( ( BufferedReader ) getNhxSource() ).read();
286 if ( i >= getSourceLength() ) {
290 switch ( getInputType() ) {
292 c = ( ( String ) getNhxSource() ).charAt( i );
295 c = ( ( StringBuffer ) getNhxSource() ).charAt( i );
298 c = ( ( char[] ) getNhxSource() )[ i ];
303 if ( !in_single_quote && !in_double_quote ) {
307 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
308 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
311 if ( in_open_bracket && ( c == ']' ) ) {
312 in_open_bracket = false;
315 // \n\t is always ignored,
316 // as is " (34) and ' (39) (space is 32):
317 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
318 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
321 else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
324 else if ( in_comment ) {
329 else if ( in_double_quote ) {
331 in_double_quote = false;
334 getCurrentAnotation().append( c );
337 else if ( c == '"' ) {
338 in_double_quote = true;
340 else if ( in_single_quote ) {
342 in_single_quote = false;
345 getCurrentAnotation().append( c );
348 else if ( c == 39 ) {
349 in_single_quote = true;
351 else if ( c == '[' ) {
352 saw_open_bracket = true;
353 in_open_bracket = true;
355 else if ( saw_open_bracket ) {
357 // everything not starting with "[&" is considered a comment
358 // unless ":digits and/or . [bootstrap]":
360 getCurrentAnotation().append( "[&" );
362 else if ( saw_colon ) {
363 getCurrentAnotation().append( "[" + c );
369 // comment consisting just of "[]":
370 saw_open_bracket = false;
372 else if ( ( c == '(' ) && !in_open_bracket ) {
375 else if ( ( c == ')' ) && !in_open_bracket ) {
378 else if ( ( c == ',' ) && !in_open_bracket ) {
382 getCurrentAnotation().append( c );
386 if ( getCladeLevel() != 0 ) {
387 setPhylogenies( null );
388 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
390 if ( getCurrentPhylogeny() != null ) {
393 else if ( getCurrentAnotation().length() > 0 ) {
394 finishSingleNodePhylogeny();
396 else if ( getPhylogenies().size() < 1 ) {
397 getPhylogenies().add( new Phylogeny() );
399 return getPhylogeniesAsArray();
402 public Phylogeny parseNext() throws IOException, NHXFormatException {
407 * Called if a closing paren is encountered.
409 * @throws PhylogenyParserException
410 * @throws NHXFormatException
412 private void processCloseParen() throws PhylogenyParserException, NHXFormatException {
413 decreaseCladeLevel();
414 if ( !isSawClosingParen() ) {
415 final PhylogenyNode new_node = new PhylogenyNode();
416 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
417 newCurrentAnotation();
418 getCurrentNode().addAsChild( new_node );
421 parseNHX( getCurrentAnotation().toString(),
422 getCurrentNode().getLastChildNode(),
423 getTaxonomyExtraction(),
424 isReplaceUnderscores() );
425 newCurrentAnotation();
427 if ( !getCurrentNode().isRoot() ) {
428 setCurrentNode( getCurrentNode().getParent() );
430 setSawClosingParen( true );
431 } // processCloseParen()
434 * Called if a comma is encountered.
436 * @throws PhylogenyParserException
437 * @throws NHXFormatException
439 private void processComma() throws PhylogenyParserException, NHXFormatException {
440 if ( !isSawClosingParen() ) {
441 final PhylogenyNode new_node = new PhylogenyNode();
442 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
443 if ( getCurrentNode() == null ) {
444 throw new NHXFormatException( "format might not be NH or NHX" );
446 getCurrentNode().addAsChild( new_node );
449 parseNHX( getCurrentAnotation().toString(),
450 getCurrentNode().getLastChildNode(),
451 getTaxonomyExtraction(),
452 isReplaceUnderscores() );
454 newCurrentAnotation();
455 setSawClosingParen( false );
459 * Called if a opening paren is encountered.
461 * @throws PhylogenyParserException
462 * @throws NHXFormatException
464 private void processOpenParen() throws PhylogenyParserException, NHXFormatException {
465 final PhylogenyNode new_node = new PhylogenyNode();
466 if ( getCladeLevel() == 0 ) {
467 if ( getCurrentPhylogeny() != null ) {
471 newCurrentAnotation();
472 setCurrentPhylogeny( new Phylogeny() );
473 getCurrentPhylogeny().setRoot( new_node );
476 increaseCladeLevel();
477 getCurrentNode().addAsChild( new_node );
479 setCurrentNode( new_node );
480 setSawClosingParen( false );
483 private void setCladeLevel( final int clade_level ) {
484 if ( clade_level < 0 ) {
485 throw new IllegalArgumentException( "Attempt to set clade level to a number smaller than zero." );
487 _clade_level = clade_level;
490 private void setCurrentAnotation( final StringBuilder current_anotation ) {
491 _current_anotation = current_anotation;
494 private void setCurrentNode( final PhylogenyNode current_node ) {
495 _current_node = current_node;
498 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
499 _current_phylogeny = current_phylogeny;
502 public void setGuessRootedness( final boolean guess_rootedness ) {
503 _guess_rootedness = guess_rootedness;
506 private void setHasNext( final boolean has_next ) {
507 _has_next = has_next;
510 public void setIgnoreQuotes( final boolean ignore_quotes ) {
511 _ignore_quotes = ignore_quotes;
514 private void setInputType( final byte input_type ) {
515 _input_type = input_type;
518 private void setNhxSource( final Object nhx_source ) {
519 _nhx_source = nhx_source;
522 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
523 _phylogenies = phylogenies;
526 public void setReplaceUnderscores( final boolean replace_underscores ) {
527 _replace_underscores = replace_underscores;
530 private void setSawClosingParen( final boolean saw_closing_paren ) {
531 _saw_closing_paren = saw_closing_paren;
535 * This sets the source to be parsed. The source can be: String,
536 * StringBuffer, char[], File, or InputStream. The source can contain more
537 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
538 * Extended (NHX) format. There is no need to separate phylogenies with any
539 * special character. White space is always ignored, as are semicolons
540 * inbetween phylogenies. Example of a source describing two phylogenies
541 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
542 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
543 * character other than '&' and ']' is considered a comment and ignored
544 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
545 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
546 * info]" is ignored, too (at the PhylogenyNode level, though).
547 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
550 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
552 * the source to be parsed (String, StringBuffer, char[], File,
554 * @throws IOException
555 * @throws PhylogenyParserException
558 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
559 if ( nhx_source == null ) {
560 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
562 else if ( nhx_source instanceof String ) {
563 setInputType( NHXParser.STRING );
564 setSourceLength( ( ( String ) nhx_source ).length() );
565 setNhxSource( nhx_source );
567 else if ( nhx_source instanceof StringBuffer ) {
568 setInputType( NHXParser.STRING_BUFFER );
569 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
570 setNhxSource( nhx_source );
572 else if ( nhx_source instanceof char[] ) {
573 setInputType( NHXParser.CHAR_ARRAY );
574 setSourceLength( ( ( char[] ) nhx_source ).length );
575 setNhxSource( nhx_source );
577 else if ( nhx_source instanceof File ) {
578 setInputType( NHXParser.BUFFERED_READER );
579 setSourceLength( 0 );
580 final File f = ( File ) nhx_source;
581 final String error = ForesterUtil.isReadableFile( f );
582 if ( !ForesterUtil.isEmpty( error ) ) {
583 throw new PhylogenyParserException( error );
585 setNhxSource( new BufferedReader( new FileReader( f ) ) );
587 else if ( nhx_source instanceof InputStream ) {
588 setInputType( NHXParser.BUFFERED_READER );
589 setSourceLength( 0 );
590 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
591 setNhxSource( new BufferedReader( isr ) );
594 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
595 + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
596 + nhx_source.getClass() + "]." );
601 private void setSourceLength( final int source_length ) {
602 _source_length = source_length;
605 public void setTaxonomyExtraction( final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction ) {
606 _taxonomy_extraction = taxonomy_extraction;
609 private static double doubleValue( final String str ) throws NHXFormatException {
611 return Double.valueOf( str ).doubleValue();
613 catch ( final NumberFormatException ex ) {
614 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from :" + "\"" + str
619 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
620 final PhylogenyNodeIterator it = p.iteratorExternalForward();
621 final double d0 = it.next().getDistanceToParent();
622 if ( ( d0 < 10 ) || !it.hasNext() ) {
625 while ( it.hasNext() ) {
626 final double d = it.next().getDistanceToParent();
627 if ( ( d != d0 ) || ( d < 10 ) ) {
634 private static void moveBranchLengthsToBootstrapValues( final Phylogeny p ) {
635 final PhylogenyNodeIterator it = p.iteratorPostorder();
636 while ( it.hasNext() ) {
637 final PhylogenyNode n = it.next();
638 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
639 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
643 public static void parseNHX( String s,
644 final PhylogenyNode node_to_annotate,
645 final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction,
646 final boolean replace_underscores ) throws NHXFormatException {
647 if ( ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
648 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
650 if ( ( s != null ) && ( s.length() > 0 ) ) {
651 if ( replace_underscores ) {
652 s = s.replaceAll( "_+", " " );
654 boolean is_nhx = false;
655 final int ob = s.indexOf( "[" );
659 final int cb = s.indexOf( "]" );
661 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
663 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
664 b = s.substring( ob + 6, cb );
667 // No &&NHX and digits only: is likely to be a support value.
668 final String bracketed = s.substring( ob + 1, cb );
669 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
670 if ( numbers_only.matches() ) {
671 b = ":" + NHXtags.SUPPORT + bracketed;
673 else if ( s.indexOf( "prob=" ) > -1 ) {
674 processMrBayes3Data( s, node_to_annotate );
677 s = s.substring( 0, ob ) + b;
678 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
679 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
682 final StringTokenizer t = new StringTokenizer( s, ":" );
683 if ( t.countTokens() > 0 ) {
684 if ( !s.startsWith( ":" ) ) {
685 node_to_annotate.setName( t.nextToken() );
686 if ( !replace_underscores
687 && ( !is_nhx && ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.NO ) ) ) {
688 final String tax = ParserUtils
689 .extractTaxonomyCodeFromNodeName( node_to_annotate.getName(),
690 LIMIT_SPECIES_NAMES_TO_FIVE_CHARS,
691 taxonomy_extraction );
692 if ( !ForesterUtil.isEmpty( tax ) ) {
693 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
694 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
696 node_to_annotate.getNodeData().getTaxonomy().setTaxonomyCode( tax );
700 while ( t.hasMoreTokens() ) {
702 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
703 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
704 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
706 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
708 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.ANNOTATION ) ) {
709 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
710 node_to_annotate.getNodeData().setSequence( new Sequence() );
712 final Annotation annotation = new Annotation( "_:_" );
713 annotation.setDesc( s.substring( 3 ) );
714 node_to_annotate.getNodeData().getSequence().addAnnotation( annotation );
716 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
717 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
718 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
720 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
721 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
723 else if ( s.charAt( 2 ) == '?' ) {
724 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
727 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
730 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
731 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
733 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
734 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
735 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
737 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
739 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
740 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
742 else if ( s.startsWith( NHXtags.COLOR ) ) {
743 final Color c = NHXParser.stringToColor( s.substring( 2 ) );
745 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
748 else if ( s.startsWith( NHXtags.CUSTOM_DATA_ON_NODE ) ) {
749 if ( !node_to_annotate.getNodeData().isHasProperties() ) {
750 node_to_annotate.getNodeData().setProperties( new PropertiesMap() );
752 node_to_annotate.getNodeData().getProperties().addProperty( Property.createFromNhxString( s ) );
754 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
755 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
756 node_to_annotate.getNodeData().setSequence( new Sequence() );
758 node_to_annotate.getNodeData().getSequence()
759 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
761 else if ( s.startsWith( NHXtags.NODE_IDENTIFIER ) ) {
762 node_to_annotate.getNodeData().setNodeIdentifier( new Identifier( s.substring( 3 ) ) );
764 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
765 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
766 node_to_annotate.getNodeData().setSequence( new Sequence() );
768 node_to_annotate.getNodeData().getSequence()
769 .setAccession( new Accession( s.substring( 3 ), "?" ) );
771 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
772 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
773 node_to_annotate.getNodeData().setSequence( new Sequence() );
775 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
777 else if ( s.startsWith( NHXtags.GENE_NAME_SYNONYM ) ) {
778 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
779 node_to_annotate.getNodeData().setSequence( new Sequence() );
781 node_to_annotate.getNodeData().getSequence().setName( s.substring( 2 ) );
783 else if ( s.indexOf( '=' ) < 0 ) {
784 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
785 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
788 node_to_annotate.setDistanceToParent( doubleValue( s ) );
790 } // while ( t.hasMoreTokens() )
795 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
796 throws NHXFormatException {
798 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
799 if ( mb_prob_sd_matcher.find() ) {
801 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
803 catch ( final NumberFormatException e ) {
804 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
808 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
809 if ( mb_prob_matcher.find() ) {
812 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
814 catch ( final NumberFormatException e ) {
815 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
819 node_to_annotate.getBranchData()
820 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
823 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
827 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
828 if ( mb_bl_matcher.find() ) {
831 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
833 catch ( final NumberFormatException e ) {
834 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
838 node_to_annotate.setDistanceToParent( bl );
844 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
845 * and blue and returns the corresponding Color.
847 private static Color stringToColor( final String s ) {
848 final StringTokenizer st = new StringTokenizer( s, "." );
849 if ( st.countTokens() != 3 ) {
850 throw new IllegalArgumentException( "illegal format for color: " + s );
852 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
853 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
854 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
855 return new Color( red, green, blu );