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 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
121 * @throws PhyloXmlDataFormatException
123 private void finishPhylogeny() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
125 if ( getCurrentPhylogeny() != null ) {
126 parseNHX( getCurrentAnotation().toString(),
127 getCurrentPhylogeny().getRoot(),
128 getTaxonomyExtraction(),
129 isReplaceUnderscores() );
130 if ( NHXParser.GUESS_IF_SUPPORT_VALUES ) {
131 if ( NHXParser.isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
132 NHXParser.moveBranchLengthsToConfidenceValues( getCurrentPhylogeny() );
135 if ( isGuessRootedness() ) {
136 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
137 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
138 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
139 getCurrentPhylogeny().setRooted( true );
142 getPhylogenies().add( getCurrentPhylogeny() );
146 private void finishSingleNodePhylogeny() throws PhylogenyParserException, NHXFormatException,
147 PhyloXmlDataFormatException {
149 final PhylogenyNode new_node = new PhylogenyNode();
150 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
151 setCurrentPhylogeny( new Phylogeny() );
152 getCurrentPhylogeny().setRoot( new_node );
153 getPhylogenies().add( getCurrentPhylogeny() );
156 private int getCladeLevel() {
160 private StringBuilder getCurrentAnotation() {
161 return _current_anotation;
164 private PhylogenyNode getCurrentNode() {
165 return _current_node;
168 private Phylogeny getCurrentPhylogeny() {
169 return _current_phylogeny;
172 private byte getInputType() {
176 private Object getNhxSource() {
180 private List<Phylogeny> getPhylogenies() {
185 * Returns the Phylogenies created as Array.
187 * @return the Phylogenies created as Array
189 private Phylogeny[] getPhylogeniesAsArray() {
190 final Phylogeny[] p = new Phylogeny[ getPhylogenies().size() ];
191 for( int i = 0; i < getPhylogenies().size(); ++i ) {
192 p[ i ] = getPhylogenies().get( i );
197 private int getSourceLength() {
198 return _source_length;
201 public PhylogenyMethods.TAXONOMY_EXTRACTION getTaxonomyExtraction() {
202 return _taxonomy_extraction;
205 public boolean hasNext() {
210 * Increases the clade level by one.
212 private void increaseCladeLevel() {
216 private void init() {
217 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
218 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
219 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
220 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
224 private boolean isGuessRootedness() {
225 return _guess_rootedness;
228 private boolean isIgnoreQuotes() {
229 return _ignore_quotes;
232 private boolean isReplaceUnderscores() {
233 return _replace_underscores;
236 private boolean isSawClosingParen() {
237 return _saw_closing_paren;
241 * Replaces the current annotation with a new StringBuffer.
243 private void newCurrentAnotation() {
244 setCurrentAnotation( new StringBuilder() );
248 * Parses the source set with setSource( final Object nhx_source ). Returns
249 * the Phylogenies found in the source as Phylogeny[].
250 * Everything between [ and ] is considered comment and ignored,
254 * ":digits and/or.[bootstrap]"
256 * @see #setSource( final Object nhx_source )
257 * @see org.forester.io.parsers.PhylogenyParser#parse()
258 * @return Phylogeny[]
259 * @throws IOException
260 * @throws NHXFormatException
261 * @throws PhylogenyParserException
264 public Phylogeny[] parse() throws IOException, NHXFormatException {
266 boolean in_comment = false;
267 boolean saw_colon = false;
268 boolean saw_open_bracket = false;
269 boolean in_open_bracket = false;
270 boolean in_double_quote = false;
271 boolean in_single_quote = false;
272 setPhylogenies( new ArrayList<Phylogeny>() );
274 newCurrentAnotation();
275 setCurrentPhylogeny( null );
276 setCurrentNode( null );
280 if ( getInputType() == NHXParser.BUFFERED_READER ) {
281 final int ci = ( ( BufferedReader ) getNhxSource() ).read();
290 if ( i >= getSourceLength() ) {
294 switch ( getInputType() ) {
296 c = ( ( String ) getNhxSource() ).charAt( i );
299 c = ( ( StringBuffer ) getNhxSource() ).charAt( i );
302 c = ( ( char[] ) getNhxSource() )[ i ];
307 if ( !in_single_quote && !in_double_quote ) {
311 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
312 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
315 if ( in_open_bracket && ( c == ']' ) ) {
316 in_open_bracket = false;
319 // \n\t is always ignored,
320 // as is " (34) and ' (39) (space is 32):
321 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
322 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
325 else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
328 else if ( in_comment ) {
333 else if ( in_double_quote ) {
335 in_double_quote = false;
338 getCurrentAnotation().append( c );
341 else if ( c == '"' ) {
342 in_double_quote = true;
344 else if ( in_single_quote ) {
346 in_single_quote = false;
349 getCurrentAnotation().append( c );
352 else if ( c == 39 ) {
353 in_single_quote = true;
355 else if ( c == '[' ) {
356 saw_open_bracket = true;
357 in_open_bracket = true;
359 else if ( saw_open_bracket ) {
361 // everything not starting with "[&" is considered a comment
362 // unless ":digits and/or . [bootstrap]":
364 getCurrentAnotation().append( "[&" );
366 else if ( saw_colon ) {
367 getCurrentAnotation().append( "[" + c );
373 // comment consisting just of "[]":
374 saw_open_bracket = false;
376 else if ( ( c == '(' ) && !in_open_bracket ) {
379 else if ( ( c == ')' ) && !in_open_bracket ) {
382 else if ( ( c == ',' ) && !in_open_bracket ) {
386 getCurrentAnotation().append( c );
390 if ( getCladeLevel() != 0 ) {
391 setPhylogenies( null );
392 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
394 if ( getCurrentPhylogeny() != null ) {
397 else if ( getCurrentAnotation().length() > 0 ) {
398 finishSingleNodePhylogeny();
400 else if ( getPhylogenies().size() < 1 ) {
401 getPhylogenies().add( new Phylogeny() );
403 return getPhylogeniesAsArray();
407 * Called if a closing paren is encountered.
409 * @throws PhylogenyParserException
410 * @throws NHXFormatException
411 * @throws PhyloXmlDataFormatException
413 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
414 decreaseCladeLevel();
415 if ( !isSawClosingParen() ) {
416 final PhylogenyNode new_node = new PhylogenyNode();
417 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
418 newCurrentAnotation();
419 getCurrentNode().addAsChild( new_node );
422 parseNHX( getCurrentAnotation().toString(),
423 getCurrentNode().getLastChildNode(),
424 getTaxonomyExtraction(),
425 isReplaceUnderscores() );
426 newCurrentAnotation();
428 if ( !getCurrentNode().isRoot() ) {
429 setCurrentNode( getCurrentNode().getParent() );
431 setSawClosingParen( true );
432 } // processCloseParen()
435 * Called if a comma is encountered.
437 * @throws PhylogenyParserException
438 * @throws NHXFormatException
439 * @throws PhyloXmlDataFormatException
441 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
442 if ( !isSawClosingParen() ) {
443 final PhylogenyNode new_node = new PhylogenyNode();
444 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
445 if ( getCurrentNode() == null ) {
446 throw new NHXFormatException( "format might not be NH or NHX" );
448 getCurrentNode().addAsChild( new_node );
451 parseNHX( getCurrentAnotation().toString(),
452 getCurrentNode().getLastChildNode(),
453 getTaxonomyExtraction(),
454 isReplaceUnderscores() );
456 newCurrentAnotation();
457 setSawClosingParen( false );
461 * Called if a opening paren is encountered.
463 * @throws PhylogenyParserException
464 * @throws NHXFormatException
465 * @throws PhyloXmlDataFormatException
467 private void processOpenParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
468 final PhylogenyNode new_node = new PhylogenyNode();
469 if ( getCladeLevel() == 0 ) {
470 if ( getCurrentPhylogeny() != null ) {
474 newCurrentAnotation();
475 setCurrentPhylogeny( new Phylogeny() );
476 getCurrentPhylogeny().setRoot( new_node );
479 increaseCladeLevel();
480 getCurrentNode().addAsChild( new_node );
482 setCurrentNode( new_node );
483 setSawClosingParen( false );
486 private void setCladeLevel( final int clade_level ) {
487 if ( clade_level < 0 ) {
488 throw new IllegalArgumentException( "Attempt to set clade level to a number smaller than zero." );
490 _clade_level = clade_level;
493 private void setCurrentAnotation( final StringBuilder current_anotation ) {
494 _current_anotation = current_anotation;
497 private void setCurrentNode( final PhylogenyNode current_node ) {
498 _current_node = current_node;
501 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
502 _current_phylogeny = current_phylogeny;
505 public void setGuessRootedness( final boolean guess_rootedness ) {
506 _guess_rootedness = guess_rootedness;
509 private void setHasNext( final boolean has_next ) {
510 _has_next = has_next;
513 public void setIgnoreQuotes( final boolean ignore_quotes ) {
514 _ignore_quotes = ignore_quotes;
517 private void setInputType( final byte input_type ) {
518 _input_type = input_type;
521 private void setNhxSource( final Object nhx_source ) {
522 _nhx_source = nhx_source;
525 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
526 _phylogenies = phylogenies;
529 public void setReplaceUnderscores( final boolean replace_underscores ) {
530 _replace_underscores = replace_underscores;
533 private void setSawClosingParen( final boolean saw_closing_paren ) {
534 _saw_closing_paren = saw_closing_paren;
538 * This sets the source to be parsed. The source can be: String,
539 * StringBuffer, char[], File, or InputStream. The source can contain more
540 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
541 * Extended (NHX) format. There is no need to separate phylogenies with any
542 * special character. White space is always ignored, as are semicolons
543 * inbetween phylogenies. Example of a source describing two phylogenies
544 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
545 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
546 * character other than '&' and ']' is considered a comment and ignored
547 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
548 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
549 * info]" is ignored, too (at the PhylogenyNode level, though).
550 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
553 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
555 * the source to be parsed (String, StringBuffer, char[], File,
557 * @throws IOException
558 * @throws PhylogenyParserException
561 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
562 if ( nhx_source == null ) {
563 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
565 else if ( nhx_source instanceof String ) {
566 setInputType( NHXParser.STRING );
567 setSourceLength( ( ( String ) nhx_source ).length() );
568 setNhxSource( nhx_source );
570 else if ( nhx_source instanceof StringBuffer ) {
571 setInputType( NHXParser.STRING_BUFFER );
572 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
573 setNhxSource( nhx_source );
575 else if ( nhx_source instanceof char[] ) {
576 setInputType( NHXParser.CHAR_ARRAY );
577 setSourceLength( ( ( char[] ) nhx_source ).length );
578 setNhxSource( nhx_source );
580 else if ( nhx_source instanceof File ) {
581 setInputType( NHXParser.BUFFERED_READER );
582 setSourceLength( 0 );
583 final File f = ( File ) nhx_source;
584 final String error = ForesterUtil.isReadableFile( f );
585 if ( !ForesterUtil.isEmpty( error ) ) {
586 throw new PhylogenyParserException( error );
588 setNhxSource( new BufferedReader( new FileReader( f ) ) );
590 else if ( nhx_source instanceof InputStream ) {
591 setInputType( NHXParser.BUFFERED_READER );
592 setSourceLength( 0 );
593 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
594 setNhxSource( new BufferedReader( isr ) );
597 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
598 + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
599 + nhx_source.getClass() + "]." );
604 private void setSourceLength( final int source_length ) {
605 _source_length = source_length;
608 public void setTaxonomyExtraction( final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction ) {
609 _taxonomy_extraction = taxonomy_extraction;
612 private static double doubleValue( final String str ) throws NHXFormatException {
614 return Double.valueOf( str ).doubleValue();
616 catch ( final NumberFormatException ex ) {
617 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
622 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
623 final PhylogenyNodeIterator it = p.iteratorExternalForward();
624 final double d0 = it.next().getDistanceToParent();
625 if ( ( d0 < 10 ) || !it.hasNext() ) {
628 while ( it.hasNext() ) {
629 final double d = it.next().getDistanceToParent();
630 if ( ( d != d0 ) || ( d < 10 ) ) {
637 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
638 final PhylogenyNodeIterator it = p.iteratorPostorder();
639 while ( it.hasNext() ) {
640 final PhylogenyNode n = it.next();
641 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
642 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
646 public static void parseNHX( String s,
647 final PhylogenyNode node_to_annotate,
648 final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction,
649 final boolean replace_underscores ) throws NHXFormatException,
650 PhyloXmlDataFormatException {
651 if ( ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
652 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
654 if ( ( s != null ) && ( s.length() > 0 ) ) {
655 if ( replace_underscores ) {
656 s = s.replaceAll( "_+", " " );
658 boolean is_nhx = false;
659 final int ob = s.indexOf( "[" );
663 final int cb = s.indexOf( "]" );
665 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
667 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
668 b = s.substring( ob + 6, cb );
671 // No &&NHX and digits only: is likely to be a support value.
672 final String bracketed = s.substring( ob + 1, cb );
673 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
674 if ( numbers_only.matches() ) {
675 b = ":" + NHXtags.SUPPORT + bracketed;
677 else if ( s.indexOf( "prob=" ) > -1 ) {
678 processMrBayes3Data( s, node_to_annotate );
681 s = s.substring( 0, ob ) + b;
682 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
683 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
686 final StringTokenizer t = new StringTokenizer( s, ":" );
687 if ( t.countTokens() > 0 ) {
688 if ( !s.startsWith( ":" ) ) {
689 node_to_annotate.setName( t.nextToken() );
690 if ( !replace_underscores
691 && ( !is_nhx && ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.NO ) ) ) {
692 final String tax = ParserUtils.extractTaxonomyCodeFromNodeName( node_to_annotate.getName(),
693 taxonomy_extraction );
694 if ( !ForesterUtil.isEmpty( tax ) ) {
695 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
696 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
698 node_to_annotate.getNodeData().getTaxonomy().setTaxonomyCode( tax );
702 while ( t.hasMoreTokens() ) {
704 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
705 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
706 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
708 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
710 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.ANNOTATION ) ) {
711 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
712 node_to_annotate.getNodeData().setSequence( new Sequence() );
714 final Annotation annotation = new Annotation( "_:_" );
715 annotation.setDesc( s.substring( 3 ) );
716 node_to_annotate.getNodeData().getSequence().addAnnotation( annotation );
718 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
719 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
720 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
722 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
723 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
725 else if ( s.charAt( 2 ) == '?' ) {
726 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
729 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
732 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
733 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
735 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
736 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
737 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
739 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
741 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
742 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
744 else if ( s.startsWith( NHXtags.COLOR ) ) {
745 final Color c = NHXParser.stringToColor( s.substring( 2 ) );
747 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
750 else if ( s.startsWith( NHXtags.CUSTOM_DATA_ON_NODE ) ) {
751 if ( !node_to_annotate.getNodeData().isHasProperties() ) {
752 node_to_annotate.getNodeData().setProperties( new PropertiesMap() );
754 node_to_annotate.getNodeData().getProperties().addProperty( Property.createFromNhxString( s ) );
756 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
757 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
758 node_to_annotate.getNodeData().setSequence( new Sequence() );
760 node_to_annotate.getNodeData().getSequence()
761 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
763 else if ( s.startsWith( NHXtags.NODE_IDENTIFIER ) ) {
764 node_to_annotate.getNodeData().setNodeIdentifier( new Identifier( s.substring( 3 ) ) );
766 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
767 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
768 node_to_annotate.getNodeData().setSequence( new Sequence() );
770 node_to_annotate.getNodeData().getSequence()
771 .setAccession( new Accession( s.substring( 3 ), "?" ) );
773 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
774 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
775 node_to_annotate.getNodeData().setSequence( new Sequence() );
777 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
779 else if ( s.startsWith( NHXtags.GENE_NAME_SYNONYM ) ) {
780 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
781 node_to_annotate.getNodeData().setSequence( new Sequence() );
783 node_to_annotate.getNodeData().getSequence().setName( s.substring( 2 ) );
785 else if ( s.indexOf( '=' ) < 0 ) {
786 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
787 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
790 node_to_annotate.setDistanceToParent( doubleValue( s ) );
792 } // while ( t.hasMoreTokens() )
797 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
798 throws NHXFormatException {
800 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
801 if ( mb_prob_sd_matcher.find() ) {
803 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
805 catch ( final NumberFormatException e ) {
806 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
810 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
811 if ( mb_prob_matcher.find() ) {
814 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
816 catch ( final NumberFormatException e ) {
817 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
821 node_to_annotate.getBranchData()
822 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
825 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
829 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
830 if ( mb_bl_matcher.find() ) {
833 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
835 catch ( final NumberFormatException e ) {
836 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
840 node_to_annotate.setDistanceToParent( bl );
846 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
847 * and blue and returns the corresponding Color.
849 private static Color stringToColor( final String s ) {
850 final StringTokenizer st = new StringTokenizer( s, "." );
851 if ( st.countTokens() != 3 ) {
852 throw new IllegalArgumentException( "illegal format for color: " + s );
854 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
855 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
856 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
857 return new Color( red, green, blu );