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();
278 if ( getInputType() == NHXParser.BUFFERED_READER ) {
279 final int ci = ( ( BufferedReader ) getNhxSource() ).read();
288 if ( i >= getSourceLength() ) {
292 switch ( getInputType() ) {
294 c = ( ( String ) getNhxSource() ).charAt( i );
297 c = ( ( StringBuffer ) getNhxSource() ).charAt( i );
300 c = ( ( char[] ) getNhxSource() )[ i ];
305 if ( !in_single_quote && !in_double_quote ) {
309 else if ( !( ( c < 33 ) || ( c > 126 ) ) && saw_colon
310 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
313 if ( in_open_bracket && ( c == ']' ) ) {
314 in_open_bracket = false;
317 // \n\t is always ignored,
318 // as is " (34) and ' (39) (space is 32):
319 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
320 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
323 else if ( ( c == 32 ) && ( !in_single_quote && !in_double_quote ) ) {
326 else if ( in_comment ) {
331 else if ( in_double_quote ) {
333 in_double_quote = false;
336 getCurrentAnotation().append( c );
339 else if ( c == '"' ) {
340 in_double_quote = true;
342 else if ( in_single_quote ) {
344 in_single_quote = false;
347 getCurrentAnotation().append( c );
350 else if ( c == 39 ) {
351 in_single_quote = true;
353 else if ( c == '[' ) {
354 saw_open_bracket = true;
355 in_open_bracket = true;
357 else if ( saw_open_bracket ) {
359 // everything not starting with "[&" is considered a comment
360 // unless ":digits and/or . [bootstrap]":
362 getCurrentAnotation().append( "[&" );
364 else if ( saw_colon ) {
365 getCurrentAnotation().append( "[" + c );
371 // comment consisting just of "[]":
372 saw_open_bracket = false;
374 else if ( ( c == '(' ) && !in_open_bracket ) {
377 else if ( ( c == ')' ) && !in_open_bracket ) {
380 else if ( ( c == ',' ) && !in_open_bracket ) {
384 getCurrentAnotation().append( c );
388 if ( getCladeLevel() != 0 ) {
389 setPhylogenies( null );
390 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
392 if ( getCurrentPhylogeny() != null ) {
395 else if ( getCurrentAnotation().length() > 0 ) {
396 finishSingleNodePhylogeny();
398 else if ( getPhylogenies().size() < 1 ) {
399 getPhylogenies().add( new Phylogeny() );
401 return getPhylogeniesAsArray();
404 public Phylogeny parseNext() throws IOException, NHXFormatException {
409 * Called if a closing paren is encountered.
411 * @throws PhylogenyParserException
412 * @throws NHXFormatException
413 * @throws PhyloXmlDataFormatException
415 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
416 decreaseCladeLevel();
417 if ( !isSawClosingParen() ) {
418 final PhylogenyNode new_node = new PhylogenyNode();
419 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
420 newCurrentAnotation();
421 getCurrentNode().addAsChild( new_node );
424 parseNHX( getCurrentAnotation().toString(),
425 getCurrentNode().getLastChildNode(),
426 getTaxonomyExtraction(),
427 isReplaceUnderscores() );
428 newCurrentAnotation();
430 if ( !getCurrentNode().isRoot() ) {
431 setCurrentNode( getCurrentNode().getParent() );
433 setSawClosingParen( true );
434 } // processCloseParen()
437 * Called if a comma is encountered.
439 * @throws PhylogenyParserException
440 * @throws NHXFormatException
441 * @throws PhyloXmlDataFormatException
443 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
444 if ( !isSawClosingParen() ) {
445 final PhylogenyNode new_node = new PhylogenyNode();
446 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
447 if ( getCurrentNode() == null ) {
448 throw new NHXFormatException( "format might not be NH or NHX" );
450 getCurrentNode().addAsChild( new_node );
453 parseNHX( getCurrentAnotation().toString(),
454 getCurrentNode().getLastChildNode(),
455 getTaxonomyExtraction(),
456 isReplaceUnderscores() );
458 newCurrentAnotation();
459 setSawClosingParen( false );
463 * Called if a opening paren is encountered.
465 * @throws PhylogenyParserException
466 * @throws NHXFormatException
467 * @throws PhyloXmlDataFormatException
469 private void processOpenParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
470 final PhylogenyNode new_node = new PhylogenyNode();
471 if ( getCladeLevel() == 0 ) {
472 if ( getCurrentPhylogeny() != null ) {
476 newCurrentAnotation();
477 setCurrentPhylogeny( new Phylogeny() );
478 getCurrentPhylogeny().setRoot( new_node );
481 increaseCladeLevel();
482 getCurrentNode().addAsChild( new_node );
484 setCurrentNode( new_node );
485 setSawClosingParen( false );
488 private void setCladeLevel( final int clade_level ) {
489 if ( clade_level < 0 ) {
490 throw new IllegalArgumentException( "Attempt to set clade level to a number smaller than zero." );
492 _clade_level = clade_level;
495 private void setCurrentAnotation( final StringBuilder current_anotation ) {
496 _current_anotation = current_anotation;
499 private void setCurrentNode( final PhylogenyNode current_node ) {
500 _current_node = current_node;
503 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
504 _current_phylogeny = current_phylogeny;
507 public void setGuessRootedness( final boolean guess_rootedness ) {
508 _guess_rootedness = guess_rootedness;
511 private void setHasNext( final boolean has_next ) {
512 _has_next = has_next;
515 public void setIgnoreQuotes( final boolean ignore_quotes ) {
516 _ignore_quotes = ignore_quotes;
519 private void setInputType( final byte input_type ) {
520 _input_type = input_type;
523 private void setNhxSource( final Object nhx_source ) {
524 _nhx_source = nhx_source;
527 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
528 _phylogenies = phylogenies;
531 public void setReplaceUnderscores( final boolean replace_underscores ) {
532 _replace_underscores = replace_underscores;
535 private void setSawClosingParen( final boolean saw_closing_paren ) {
536 _saw_closing_paren = saw_closing_paren;
540 * This sets the source to be parsed. The source can be: String,
541 * StringBuffer, char[], File, or InputStream. The source can contain more
542 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
543 * Extended (NHX) format. There is no need to separate phylogenies with any
544 * special character. White space is always ignored, as are semicolons
545 * inbetween phylogenies. Example of a source describing two phylogenies
546 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
547 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
548 * character other than '&' and ']' is considered a comment and ignored
549 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
550 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
551 * info]" is ignored, too (at the PhylogenyNode level, though).
552 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
555 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
557 * the source to be parsed (String, StringBuffer, char[], File,
559 * @throws IOException
560 * @throws PhylogenyParserException
563 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
564 if ( nhx_source == null ) {
565 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
567 else if ( nhx_source instanceof String ) {
568 setInputType( NHXParser.STRING );
569 setSourceLength( ( ( String ) nhx_source ).length() );
570 setNhxSource( nhx_source );
572 else if ( nhx_source instanceof StringBuffer ) {
573 setInputType( NHXParser.STRING_BUFFER );
574 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
575 setNhxSource( nhx_source );
577 else if ( nhx_source instanceof char[] ) {
578 setInputType( NHXParser.CHAR_ARRAY );
579 setSourceLength( ( ( char[] ) nhx_source ).length );
580 setNhxSource( nhx_source );
582 else if ( nhx_source instanceof File ) {
583 setInputType( NHXParser.BUFFERED_READER );
584 setSourceLength( 0 );
585 final File f = ( File ) nhx_source;
586 final String error = ForesterUtil.isReadableFile( f );
587 if ( !ForesterUtil.isEmpty( error ) ) {
588 throw new PhylogenyParserException( error );
590 setNhxSource( new BufferedReader( new FileReader( f ) ) );
592 else if ( nhx_source instanceof InputStream ) {
593 setInputType( NHXParser.BUFFERED_READER );
594 setSourceLength( 0 );
595 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
596 setNhxSource( new BufferedReader( isr ) );
599 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
600 + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
601 + nhx_source.getClass() + "]." );
606 private void setSourceLength( final int source_length ) {
607 _source_length = source_length;
610 public void setTaxonomyExtraction( final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction ) {
611 _taxonomy_extraction = taxonomy_extraction;
614 private static double doubleValue( final String str ) throws NHXFormatException {
616 return Double.valueOf( str ).doubleValue();
618 catch ( final NumberFormatException ex ) {
619 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from :" + "\"" + str
624 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
625 final PhylogenyNodeIterator it = p.iteratorExternalForward();
626 final double d0 = it.next().getDistanceToParent();
627 if ( ( d0 < 10 ) || !it.hasNext() ) {
630 while ( it.hasNext() ) {
631 final double d = it.next().getDistanceToParent();
632 if ( ( d != d0 ) || ( d < 10 ) ) {
639 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
640 final PhylogenyNodeIterator it = p.iteratorPostorder();
641 while ( it.hasNext() ) {
642 final PhylogenyNode n = it.next();
643 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
644 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
648 public static void parseNHX( String s,
649 final PhylogenyNode node_to_annotate,
650 final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction,
651 final boolean replace_underscores ) throws NHXFormatException,
652 PhyloXmlDataFormatException {
653 if ( ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
654 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
656 if ( ( s != null ) && ( s.length() > 0 ) ) {
657 if ( replace_underscores ) {
658 s = s.replaceAll( "_+", " " );
660 boolean is_nhx = false;
661 final int ob = s.indexOf( "[" );
665 final int cb = s.indexOf( "]" );
667 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
669 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
670 b = s.substring( ob + 6, cb );
673 // No &&NHX and digits only: is likely to be a support value.
674 final String bracketed = s.substring( ob + 1, cb );
675 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
676 if ( numbers_only.matches() ) {
677 b = ":" + NHXtags.SUPPORT + bracketed;
679 else if ( s.indexOf( "prob=" ) > -1 ) {
680 processMrBayes3Data( s, node_to_annotate );
683 s = s.substring( 0, ob ) + b;
684 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
685 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
688 final StringTokenizer t = new StringTokenizer( s, ":" );
689 if ( t.countTokens() > 0 ) {
690 if ( !s.startsWith( ":" ) ) {
691 node_to_annotate.setName( t.nextToken() );
692 if ( !replace_underscores
693 && ( !is_nhx && ( taxonomy_extraction != PhylogenyMethods.TAXONOMY_EXTRACTION.NO ) ) ) {
694 final String tax = ParserUtils.extractTaxonomyCodeFromNodeName( node_to_annotate.getName(),
695 taxonomy_extraction );
696 if ( !ForesterUtil.isEmpty( tax ) ) {
697 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
698 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
700 node_to_annotate.getNodeData().getTaxonomy().setTaxonomyCode( tax );
704 while ( t.hasMoreTokens() ) {
706 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
707 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
708 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
710 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
712 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.ANNOTATION ) ) {
713 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
714 node_to_annotate.getNodeData().setSequence( new Sequence() );
716 final Annotation annotation = new Annotation( "_:_" );
717 annotation.setDesc( s.substring( 3 ) );
718 node_to_annotate.getNodeData().getSequence().addAnnotation( annotation );
720 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
721 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
722 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
724 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
725 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
727 else if ( s.charAt( 2 ) == '?' ) {
728 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
731 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
734 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
735 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
737 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
738 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
739 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
741 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
743 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
744 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
746 else if ( s.startsWith( NHXtags.COLOR ) ) {
747 final Color c = NHXParser.stringToColor( s.substring( 2 ) );
749 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
752 else if ( s.startsWith( NHXtags.CUSTOM_DATA_ON_NODE ) ) {
753 if ( !node_to_annotate.getNodeData().isHasProperties() ) {
754 node_to_annotate.getNodeData().setProperties( new PropertiesMap() );
756 node_to_annotate.getNodeData().getProperties().addProperty( Property.createFromNhxString( s ) );
758 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
759 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
760 node_to_annotate.getNodeData().setSequence( new Sequence() );
762 node_to_annotate.getNodeData().getSequence()
763 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
765 else if ( s.startsWith( NHXtags.NODE_IDENTIFIER ) ) {
766 node_to_annotate.getNodeData().setNodeIdentifier( new Identifier( s.substring( 3 ) ) );
768 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
769 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
770 node_to_annotate.getNodeData().setSequence( new Sequence() );
772 node_to_annotate.getNodeData().getSequence()
773 .setAccession( new Accession( s.substring( 3 ), "?" ) );
775 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
776 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
777 node_to_annotate.getNodeData().setSequence( new Sequence() );
779 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
781 else if ( s.startsWith( NHXtags.GENE_NAME_SYNONYM ) ) {
782 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
783 node_to_annotate.getNodeData().setSequence( new Sequence() );
785 node_to_annotate.getNodeData().getSequence().setName( s.substring( 2 ) );
787 else if ( s.indexOf( '=' ) < 0 ) {
788 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
789 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
792 node_to_annotate.setDistanceToParent( doubleValue( s ) );
794 } // while ( t.hasMoreTokens() )
799 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
800 throws NHXFormatException {
802 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
803 if ( mb_prob_sd_matcher.find() ) {
805 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
807 catch ( final NumberFormatException e ) {
808 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
812 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
813 if ( mb_prob_matcher.find() ) {
816 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
818 catch ( final NumberFormatException e ) {
819 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
823 node_to_annotate.getBranchData()
824 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
827 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
831 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
832 if ( mb_bl_matcher.find() ) {
835 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
837 catch ( final NumberFormatException e ) {
838 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
842 node_to_annotate.setDistanceToParent( bl );
848 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
849 * and blue and returns the corresponding Color.
851 private static Color stringToColor( final String s ) {
852 final StringTokenizer st = new StringTokenizer( s, "." );
853 if ( st.countTokens() != 3 ) {
854 throw new IllegalArgumentException( "illegal format for color: " + s );
856 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
857 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
858 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
859 return new Color( red, green, blu );