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 = NHXParser.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 NHXParser.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=([^,]+)" );
98 * Decreases the clade level by one.
100 * @throws PhylogenyParserException
101 * if level goes below zero.
103 private void decreaseCladeLevel() throws PhylogenyParserException {
104 if ( getCladeLevel() < 0 ) {
105 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
111 * Finishes the current Phylogeny and adds it to the list of Phylogenies
114 * @throws PhylogenyParserException
115 * @throws NHXFormatException
116 * @throws PhyloXmlDataFormatException
118 private void finishPhylogeny() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
120 if ( getCurrentPhylogeny() != null ) {
121 parseNHX( getCurrentAnotation().toString(),
122 getCurrentPhylogeny().getRoot(),
123 getTaxonomyExtraction(),
124 isReplaceUnderscores() );
125 if ( NHXParser.GUESS_IF_SUPPORT_VALUES ) {
126 if ( NHXParser.isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
127 NHXParser.moveBranchLengthsToConfidenceValues( getCurrentPhylogeny() );
130 if ( isGuessRootedness() ) {
131 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
132 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
133 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
134 getCurrentPhylogeny().setRooted( true );
137 getPhylogenies().add( getCurrentPhylogeny() );
141 private void finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
142 PhyloXmlDataFormatException {
144 final PhylogenyNode new_node = new PhylogenyNode();
145 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
146 setCurrentPhylogeny( new Phylogeny() );
147 getCurrentPhylogeny().setRoot( new_node );
148 getPhylogenies().add( getCurrentPhylogeny() );
151 private int getCladeLevel() {
155 private StringBuilder getCurrentAnotation() {
156 return _current_anotation;
159 private PhylogenyNode getCurrentNode() {
160 return _current_node;
163 private Phylogeny getCurrentPhylogeny() {
164 return _current_phylogeny;
167 private byte getInputType() {
171 private Object getNhxSource() {
175 private List<Phylogeny> getPhylogenies() {
180 * Returns the Phylogenies created as Array.
182 * @return the Phylogenies created as Array
184 private Phylogeny[] getPhylogeniesAsArray() {
185 final Phylogeny[] p = new Phylogeny[ getPhylogenies().size() ];
186 for( int i = 0; i < getPhylogenies().size(); ++i ) {
187 p[ i ] = getPhylogenies().get( i );
192 private int getSourceLength() {
193 return _source_length;
196 public NHXParser.TAXONOMY_EXTRACTION getTaxonomyExtraction() {
197 return _taxonomy_extraction;
200 public boolean hasNext() {
205 * Increases the clade level by one.
207 private void increaseCladeLevel() {
211 private void init() {
212 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
213 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
214 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
215 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
219 private boolean isGuessRootedness() {
220 return _guess_rootedness;
223 private boolean isIgnoreQuotes() {
224 return _ignore_quotes;
227 private boolean isReplaceUnderscores() {
228 return _replace_underscores;
231 private boolean isSawClosingParen() {
232 return _saw_closing_paren;
236 * Replaces the current annotation with a new StringBuffer.
238 private void newCurrentAnotation() {
239 setCurrentAnotation( new StringBuilder() );
243 * Parses the source set with setSource( final Object nhx_source ). Returns
244 * the Phylogenies found in the source as Phylogeny[].
245 * Everything between [ and ] is considered comment and ignored,
249 * ":digits and/or.[bootstrap]"
251 * @see #setSource( final Object nhx_source )
252 * @see org.forester.io.parsers.PhylogenyParser#parse()
253 * @return Phylogeny[]
254 * @throws IOException
255 * @throws NHXFormatException
256 * @throws PhylogenyParserException
259 public Phylogeny[] parse() throws IOException, NHXFormatException {
261 boolean in_comment = false;
262 boolean saw_colon = false;
263 boolean saw_open_bracket = false;
264 boolean in_open_bracket = false;
265 boolean in_double_quote = false;
266 boolean in_single_quote = false;
267 setPhylogenies( new ArrayList<Phylogeny>() );
269 newCurrentAnotation();
270 setCurrentPhylogeny( null );
271 setCurrentNode( null );
275 if ( getInputType() == NHXParser.BUFFERED_READER ) {
276 final int ci = ( ( BufferedReader ) getNhxSource() ).read();
285 if ( i >= getSourceLength() ) {
289 switch ( getInputType() ) {
291 c = ( ( String ) getNhxSource() ).charAt( i );
294 c = ( ( StringBuffer ) getNhxSource() ).charAt( i );
297 c = ( ( char[] ) getNhxSource() )[ i ];
302 if ( !in_single_quote && !in_double_quote ) {
306 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
307 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
310 if ( in_open_bracket && ( c == ']' ) ) {
311 in_open_bracket = false;
314 // \n\t is always ignored,
315 // as is " (34) and ' (39) (space is 32):
316 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
317 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
320 else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
323 else if ( in_comment ) {
328 else if ( in_double_quote ) {
330 in_double_quote = false;
333 getCurrentAnotation().append( c );
336 else if ( c == '"' ) {
337 in_double_quote = true;
339 else if ( in_single_quote ) {
341 in_single_quote = false;
344 getCurrentAnotation().append( c );
347 else if ( c == 39 ) {
348 in_single_quote = true;
350 else if ( c == '[' ) {
351 saw_open_bracket = true;
352 in_open_bracket = true;
354 else if ( saw_open_bracket ) {
356 // everything not starting with "[&" is considered a comment
357 // unless ":digits and/or . [bootstrap]":
359 getCurrentAnotation().append( "[&" );
361 else if ( saw_colon ) {
362 getCurrentAnotation().append( "[" + c );
368 // comment consisting just of "[]":
369 saw_open_bracket = false;
371 else if ( ( c == '(' ) && !in_open_bracket ) {
374 else if ( ( c == ')' ) && !in_open_bracket ) {
377 else if ( ( c == ',' ) && !in_open_bracket ) {
381 getCurrentAnotation().append( c );
385 if ( getCladeLevel() != 0 ) {
386 setPhylogenies( null );
387 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
389 if ( getCurrentPhylogeny() != null ) {
392 else if ( getCurrentAnotation().length() > 0 ) {
393 finishSingleNodePhylogeny();
395 else if ( getPhylogenies().size() < 1 ) {
396 getPhylogenies().add( new Phylogeny() );
398 return getPhylogeniesAsArray();
402 * Called if a closing paren is encountered.
404 * @throws PhylogenyParserException
405 * @throws NHXFormatException
406 * @throws PhyloXmlDataFormatException
408 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
409 decreaseCladeLevel();
410 if ( !isSawClosingParen() ) {
411 final PhylogenyNode new_node = new PhylogenyNode();
412 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
413 newCurrentAnotation();
414 getCurrentNode().addAsChild( new_node );
417 parseNHX( getCurrentAnotation().toString(),
418 getCurrentNode().getLastChildNode(),
419 getTaxonomyExtraction(),
420 isReplaceUnderscores() );
421 newCurrentAnotation();
423 if ( !getCurrentNode().isRoot() ) {
424 setCurrentNode( getCurrentNode().getParent() );
426 setSawClosingParen( true );
427 } // processCloseParen()
430 * Called if a comma is encountered.
432 * @throws PhylogenyParserException
433 * @throws NHXFormatException
434 * @throws PhyloXmlDataFormatException
436 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
437 if ( !isSawClosingParen() ) {
438 final PhylogenyNode new_node = new PhylogenyNode();
439 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
440 if ( getCurrentNode() == null ) {
441 throw new NHXFormatException( "format might not be NH or NHX" );
443 getCurrentNode().addAsChild( new_node );
446 parseNHX( getCurrentAnotation().toString(),
447 getCurrentNode().getLastChildNode(),
448 getTaxonomyExtraction(),
449 isReplaceUnderscores() );
451 newCurrentAnotation();
452 setSawClosingParen( false );
456 * Called if a opening paren is encountered.
458 * @throws PhylogenyParserException
459 * @throws NHXFormatException
460 * @throws PhyloXmlDataFormatException
462 private void processOpenParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
463 final PhylogenyNode new_node = new PhylogenyNode();
464 if ( getCladeLevel() == 0 ) {
465 if ( getCurrentPhylogeny() != null ) {
469 newCurrentAnotation();
470 setCurrentPhylogeny( new Phylogeny() );
471 getCurrentPhylogeny().setRoot( new_node );
474 increaseCladeLevel();
475 getCurrentNode().addAsChild( new_node );
477 setCurrentNode( new_node );
478 setSawClosingParen( false );
481 private void setCladeLevel( final int clade_level ) {
482 if ( clade_level < 0 ) {
483 throw new IllegalArgumentException( "Attempt to set clade level to a number smaller than zero." );
485 _clade_level = clade_level;
488 private void setCurrentAnotation( final StringBuilder current_anotation ) {
489 _current_anotation = current_anotation;
492 private void setCurrentNode( final PhylogenyNode current_node ) {
493 _current_node = current_node;
496 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
497 _current_phylogeny = current_phylogeny;
500 public void setGuessRootedness( final boolean guess_rootedness ) {
501 _guess_rootedness = guess_rootedness;
504 private void setHasNext( final boolean has_next ) {
505 _has_next = has_next;
508 public void setIgnoreQuotes( final boolean ignore_quotes ) {
509 _ignore_quotes = ignore_quotes;
512 private void setInputType( final byte input_type ) {
513 _input_type = input_type;
516 private void setNhxSource( final Object nhx_source ) {
517 _nhx_source = nhx_source;
520 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
521 _phylogenies = phylogenies;
524 public void setReplaceUnderscores( final boolean replace_underscores ) {
525 _replace_underscores = replace_underscores;
528 private void setSawClosingParen( final boolean saw_closing_paren ) {
529 _saw_closing_paren = saw_closing_paren;
533 * This sets the source to be parsed. The source can be: String,
534 * StringBuffer, char[], File, or InputStream. The source can contain more
535 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
536 * Extended (NHX) format. There is no need to separate phylogenies with any
537 * special character. White space is always ignored, as are semicolons
538 * inbetween phylogenies. Example of a source describing two phylogenies
539 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
540 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
541 * character other than '&' and ']' is considered a comment and ignored
542 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
543 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
544 * info]" is ignored, too (at the PhylogenyNode level, though).
545 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
548 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
550 * the source to be parsed (String, StringBuffer, char[], File,
552 * @throws IOException
553 * @throws PhylogenyParserException
556 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
557 if ( nhx_source == null ) {
558 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
560 else if ( nhx_source instanceof String ) {
561 setInputType( NHXParser.STRING );
562 setSourceLength( ( ( String ) nhx_source ).length() );
563 setNhxSource( nhx_source );
565 else if ( nhx_source instanceof StringBuffer ) {
566 setInputType( NHXParser.STRING_BUFFER );
567 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
568 setNhxSource( nhx_source );
570 else if ( nhx_source instanceof char[] ) {
571 setInputType( NHXParser.CHAR_ARRAY );
572 setSourceLength( ( ( char[] ) nhx_source ).length );
573 setNhxSource( nhx_source );
575 else if ( nhx_source instanceof File ) {
576 setInputType( NHXParser.BUFFERED_READER );
577 setSourceLength( 0 );
578 final File f = ( File ) nhx_source;
579 final String error = ForesterUtil.isReadableFile( f );
580 if ( !ForesterUtil.isEmpty( error ) ) {
581 throw new PhylogenyParserException( error );
583 setNhxSource( new BufferedReader( new FileReader( f ) ) );
585 else if ( nhx_source instanceof InputStream ) {
586 setInputType( NHXParser.BUFFERED_READER );
587 setSourceLength( 0 );
588 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
589 setNhxSource( new BufferedReader( isr ) );
592 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
593 + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
594 + nhx_source.getClass() + "]." );
599 private void setSourceLength( final int source_length ) {
600 _source_length = source_length;
603 public void setTaxonomyExtraction( final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction ) {
604 _taxonomy_extraction = taxonomy_extraction;
607 private static double doubleValue( final String str ) throws NHXFormatException {
609 return Double.valueOf( str ).doubleValue();
611 catch ( final NumberFormatException ex ) {
612 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
617 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
618 final PhylogenyNodeIterator it = p.iteratorExternalForward();
619 final double d0 = it.next().getDistanceToParent();
620 if ( ( d0 < 10 ) || !it.hasNext() ) {
623 while ( it.hasNext() ) {
624 final double d = it.next().getDistanceToParent();
625 if ( ( d != d0 ) || ( d < 10 ) ) {
632 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
633 final PhylogenyNodeIterator it = p.iteratorPostorder();
634 while ( it.hasNext() ) {
635 final PhylogenyNode n = it.next();
636 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
637 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
641 public static void parseNHX( String s,
642 final PhylogenyNode node_to_annotate,
643 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction,
644 final boolean replace_underscores ) throws NHXFormatException,
645 PhyloXmlDataFormatException {
646 if ( ( taxonomy_extraction != NHXParser.TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
647 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
649 if ( ( s != null ) && ( s.length() > 0 ) ) {
650 if ( replace_underscores ) {
651 s = s.replaceAll( "_+", " " );
653 boolean is_nhx = false;
654 final int ob = s.indexOf( "[" );
658 final int cb = s.indexOf( "]" );
660 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
662 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
663 b = s.substring( ob + 6, cb );
666 // No &&NHX and digits only: is likely to be a support value.
667 final String bracketed = s.substring( ob + 1, cb );
668 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
669 if ( numbers_only.matches() ) {
670 b = ":" + NHXtags.SUPPORT + bracketed;
672 else if ( s.indexOf( "prob=" ) > -1 ) {
673 processMrBayes3Data( s, node_to_annotate );
676 s = s.substring( 0, ob ) + b;
677 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
678 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
681 final StringTokenizer t = new StringTokenizer( s, ":" );
682 if ( t.countTokens() > 0 ) {
683 if ( !s.startsWith( ":" ) ) {
684 node_to_annotate.setName( t.nextToken() );
685 if ( !replace_underscores
686 && ( !is_nhx && ( taxonomy_extraction != NHXParser.TAXONOMY_EXTRACTION.NO ) ) ) {
687 final String tax = ParserUtils.extractTaxonomyCodeFromNodeName( node_to_annotate.getName(),
688 taxonomy_extraction );
689 if ( !ForesterUtil.isEmpty( tax ) ) {
690 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
691 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
693 node_to_annotate.getNodeData().getTaxonomy().setTaxonomyCode( tax );
697 while ( t.hasMoreTokens() ) {
699 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
700 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
701 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
703 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
705 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.ANNOTATION ) ) {
706 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
707 node_to_annotate.getNodeData().setSequence( new Sequence() );
709 final Annotation annotation = new Annotation( "_:_" );
710 annotation.setDesc( s.substring( 3 ) );
711 node_to_annotate.getNodeData().getSequence().addAnnotation( annotation );
713 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
714 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
715 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
717 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
718 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
720 else if ( s.charAt( 2 ) == '?' ) {
721 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
724 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
727 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
728 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
730 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
731 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
732 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
734 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
736 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
737 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
739 else if ( s.startsWith( NHXtags.COLOR ) ) {
740 final Color c = NHXParser.stringToColor( s.substring( 2 ) );
742 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
745 else if ( s.startsWith( NHXtags.CUSTOM_DATA_ON_NODE ) ) {
746 if ( !node_to_annotate.getNodeData().isHasProperties() ) {
747 node_to_annotate.getNodeData().setProperties( new PropertiesMap() );
749 node_to_annotate.getNodeData().getProperties().addProperty( Property.createFromNhxString( s ) );
751 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
752 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
753 node_to_annotate.getNodeData().setSequence( new Sequence() );
755 node_to_annotate.getNodeData().getSequence()
756 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
758 else if ( s.startsWith( NHXtags.NODE_IDENTIFIER ) ) {
759 node_to_annotate.getNodeData().setNodeIdentifier( new Identifier( s.substring( 3 ) ) );
761 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
762 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
763 node_to_annotate.getNodeData().setSequence( new Sequence() );
765 node_to_annotate.getNodeData().getSequence()
766 .setAccession( new Accession( s.substring( 3 ), "?" ) );
768 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
769 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
770 node_to_annotate.getNodeData().setSequence( new Sequence() );
772 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
774 else if ( s.startsWith( NHXtags.GENE_NAME_SYNONYM ) ) {
775 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
776 node_to_annotate.getNodeData().setSequence( new Sequence() );
778 node_to_annotate.getNodeData().getSequence().setName( s.substring( 2 ) );
780 else if ( s.indexOf( '=' ) < 0 ) {
781 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
782 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
785 node_to_annotate.setDistanceToParent( doubleValue( s ) );
787 } // while ( t.hasMoreTokens() )
792 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
793 throws NHXFormatException {
795 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
796 if ( mb_prob_sd_matcher.find() ) {
798 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
800 catch ( final NumberFormatException e ) {
801 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
805 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
806 if ( mb_prob_matcher.find() ) {
809 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
811 catch ( final NumberFormatException e ) {
812 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
816 node_to_annotate.getBranchData()
817 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
820 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
824 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
825 if ( mb_bl_matcher.find() ) {
828 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
830 catch ( final NumberFormatException e ) {
831 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
835 node_to_annotate.setDistanceToParent( bl );
841 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
842 * and blue and returns the corresponding Color.
844 private static Color stringToColor( final String s ) {
845 final StringTokenizer st = new StringTokenizer( s, "." );
846 if ( st.countTokens() != 3 ) {
847 throw new IllegalArgumentException( "illegal format for color: " + s );
849 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
850 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
851 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
852 return new Color( red, green, blu );
855 public static enum TAXONOMY_EXTRACTION {
856 NO, YES, PFAM_STYLE_ONLY;