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: https://sites.google.com/site/cmzmasek/home/software/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.StringTokenizer;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
39 import org.forester.io.parsers.PhylogenyParser;
40 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
41 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
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.Confidence;
49 import org.forester.phylogeny.data.DomainArchitecture;
50 import org.forester.phylogeny.data.Event;
51 import org.forester.phylogeny.data.Identifier;
52 import org.forester.phylogeny.data.PhylogenyDataUtil;
53 import org.forester.phylogeny.data.Sequence;
54 import org.forester.phylogeny.data.Taxonomy;
55 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
56 import org.forester.util.ForesterUtil;
58 public final class NHXParser2 implements PhylogenyParser {
60 public static final TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION_DEFAULT = TAXONOMY_EXTRACTION.NO;
61 final static private boolean GUESS_ROOTEDNESS_DEFAULT = true;
62 final static private boolean GUESS_IF_SUPPORT_VALUES = true;
63 final static private boolean IGNORE_QUOTES_DEFAULT = false;
64 final static public boolean REPLACE_UNDERSCORES_DEFAULT = false;
65 private boolean _saw_closing_paren;
66 final static private byte STRING = 0;
67 final static private byte STRING_BUFFER = 1;
68 final static private byte CHAR_ARRAY = 2;
69 final static private byte BUFFERED_READER = 3;
70 final static private byte STRING_BUILDER = 4;
71 private boolean _guess_rootedness;
72 private boolean _has_next;
73 private boolean _ignore_quotes;
74 private byte _input_type;
75 private int _source_length;
76 private PhylogenyNode _current_node;
77 private StringBuilder _current_anotation;
78 private Object _nhx_source;
79 private int _clade_level;
80 private Phylogeny _current_phylogeny;
81 private TAXONOMY_EXTRACTION _taxonomy_extraction;
82 private boolean _replace_underscores;
83 public final static Pattern UC_LETTERS_NUMBERS_PATTERN = Pattern.compile( "^[A-Z0-9]+$" );
84 public final static Pattern NUMBERS_ONLY_PATTERN = Pattern.compile( "^[0-9\\.]+$" );
85 public final static Pattern MB_PROB_PATTERN = Pattern.compile( "prob=([^,]+)" );
86 public final static Pattern MB_PROB_SD_PATTERN = Pattern.compile( "prob_stddev=([^,]+)" );
87 public final static Pattern MB_BL_PATTERN = Pattern.compile( "length_median=([^,]+)" );
88 boolean _in_comment = false;
89 boolean _saw_colon = false;
90 boolean _saw_open_bracket = false;
91 boolean _in_open_bracket = false;
92 boolean _in_double_quote = false;
93 boolean _in_single_quote = false;
94 String _my_source_str = null;
95 StringBuffer _my_source_sbuff = null;
96 StringBuilder _my_source_sbuil = null;
97 char[] _my_source_charary = null;
98 BufferedReader _my_source_br = null;
101 public NHXParser2() {
105 public Phylogeny getNext() throws IOException, NHXFormatException {
108 if ( getInputType() == BUFFERED_READER ) {
109 final int ci = _my_source_br.read();
118 if ( _i >= getSourceLength() ) {
122 switch ( getInputType() ) {
124 c = _my_source_str.charAt( _i );
127 c = _my_source_sbuff.charAt( _i );
130 c = _my_source_sbuil.charAt( _i );
133 c = _my_source_charary[ _i ];
138 if ( !_in_single_quote && !_in_double_quote ) {
142 else if ( !( ( c < 33 ) || ( c > 126 ) ) && _saw_colon
143 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
146 if ( _in_open_bracket && ( c == ']' ) ) {
147 _in_open_bracket = false;
150 // \n\t is always ignored,
151 // as is " (34) and ' (39) (space is 32):
152 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
153 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
156 else if ( ( c == 32 ) && ( !_in_single_quote && !_in_double_quote ) ) {
159 else if ( _in_comment ) {
164 else if ( _in_double_quote ) {
166 _in_double_quote = false;
169 getCurrentAnotation().append( c );
172 else if ( c == '"' ) {
173 _in_double_quote = true;
175 else if ( _in_single_quote ) {
177 _in_single_quote = false;
180 getCurrentAnotation().append( c );
183 else if ( c == 39 ) {
184 _in_single_quote = true;
186 else if ( c == '[' ) {
187 _saw_open_bracket = true;
188 _in_open_bracket = true;
190 else if ( _saw_open_bracket ) {
192 // everything not starting with "[&" is considered a comment
193 // unless ":digits and/or . [bootstrap]":
195 getCurrentAnotation().append( "[&" );
197 else if ( _saw_colon ) {
198 getCurrentAnotation().append( "[" + c );
204 // comment consisting just of "[]":
205 _saw_open_bracket = false;
207 else if ( ( c == '(' ) && !_in_open_bracket ) {
208 Phylogeny phy = processOpenParen2();
214 else if ( ( c == ')' ) && !_in_open_bracket ) {
217 else if ( ( c == ',' ) && !_in_open_bracket ) {
221 getCurrentAnotation().append( c );
225 System.out.println( "done with loop" );
226 if ( getCladeLevel() != 0 ) {
227 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of open parens does not equal number of close parens" );
229 if ( getCurrentPhylogeny() != null ) {
230 return finishPhylogeny2();
232 else if ( getCurrentAnotation().length() > 0 ) {
233 System.out.println( "1node=" + getCurrentAnotation() );
234 return finishSingleNodePhylogeny2();
241 public TAXONOMY_EXTRACTION getTaxonomyExtraction() {
242 return _taxonomy_extraction;
245 public boolean hasNext() {
249 public void setGuessRootedness( final boolean guess_rootedness ) {
250 _guess_rootedness = guess_rootedness;
253 public void setIgnoreQuotes( final boolean ignore_quotes ) {
254 _ignore_quotes = ignore_quotes;
257 public void setReplaceUnderscores( final boolean replace_underscores ) {
258 _replace_underscores = replace_underscores;
262 * This sets the source to be parsed. The source can be: String,
263 * StringBuffer, char[], File, or InputStream. The source can contain more
264 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
265 * Extended (NHX) format. There is no need to separate phylogenies with any
266 * special character. White space is always ignored, as are semicolons
267 * inbetween phylogenies. Example of a source describing two phylogenies
268 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
269 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
270 * character other than '&' and ']' is considered a comment and ignored
271 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
272 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
273 * info]" is ignored, too (at the PhylogenyNode level, though).
274 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
277 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
279 * the source to be parsed (String, StringBuffer, char[], File,
281 * @throws IOException
282 * @throws PhylogenyParserException
285 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
286 if ( nhx_source == null ) {
287 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
289 else if ( nhx_source instanceof String ) {
290 setInputType( NHXParser2.STRING );
291 setSourceLength( ( ( String ) nhx_source ).length() );
292 setNhxSource( nhx_source );
294 else if ( nhx_source instanceof StringBuilder ) {
295 setInputType( NHXParser2.STRING_BUILDER );
296 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
297 setNhxSource( nhx_source );
299 else if ( nhx_source instanceof StringBuffer ) {
300 setInputType( NHXParser2.STRING_BUFFER );
301 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
302 setNhxSource( nhx_source );
304 else if ( nhx_source instanceof StringBuilder ) {
305 setInputType( NHXParser2.STRING_BUILDER );
306 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
307 setNhxSource( nhx_source );
309 else if ( nhx_source instanceof char[] ) {
310 setInputType( NHXParser2.CHAR_ARRAY );
311 setSourceLength( ( ( char[] ) nhx_source ).length );
312 setNhxSource( nhx_source );
314 else if ( nhx_source instanceof File ) {
315 setInputType( NHXParser2.BUFFERED_READER );
316 setSourceLength( 0 );
317 final File f = ( File ) nhx_source;
318 final String error = ForesterUtil.isReadableFile( f );
319 if ( !ForesterUtil.isEmpty( error ) ) {
320 throw new PhylogenyParserException( error );
322 setNhxSource( new BufferedReader( new FileReader( f ) ) );
324 else if ( nhx_source instanceof InputStream ) {
325 setInputType( NHXParser2.BUFFERED_READER );
326 setSourceLength( 0 );
327 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
328 setNhxSource( new BufferedReader( isr ) );
331 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
332 + " StringBuffer, char[], File," + " or InputStream " + " [attempt to parse object of "
333 + nhx_source.getClass() + "]." );
339 public void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
340 _taxonomy_extraction = taxonomy_extraction;
343 public void reset() {
348 _saw_open_bracket = false;
349 _in_open_bracket = false;
350 _in_double_quote = false;
351 _in_single_quote = false;
353 newCurrentAnotation();
354 setCurrentPhylogeny( null );
355 setCurrentNode( null );
356 _my_source_str = null;
357 _my_source_sbuff = null;
358 _my_source_sbuil = null;
359 _my_source_charary = null;
360 _my_source_br = null;
361 switch ( getInputType() ) {
363 _my_source_str = ( String ) getNhxSource();
366 _my_source_sbuff = ( StringBuffer ) getNhxSource();
369 _my_source_sbuil = ( StringBuilder ) getNhxSource();
372 _my_source_charary = ( char[] ) getNhxSource();
374 case BUFFERED_READER:
375 _my_source_br = ( BufferedReader ) getNhxSource();
378 throw new RuntimeException( "unknown input type" );
383 * Decreases the clade level by one.
385 * @throws PhylogenyParserException
386 * if level goes below zero.
388 private void decreaseCladeLevel() throws PhylogenyParserException {
389 if ( getCladeLevel() < 0 ) {
390 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
395 private Phylogeny finishPhylogeny2() throws PhylogenyParserException, NHXFormatException,
396 PhyloXmlDataFormatException {
397 //setCladeLevel( 0 );
398 if ( getCurrentPhylogeny() != null ) {
399 System.out.println( "cp=" + getCurrentPhylogeny() );
400 System.out.println( "ca=" + getCurrentAnotation().toString() );
401 parseNHX( getCurrentAnotation().toString(),
402 getCurrentPhylogeny().getRoot(),
403 getTaxonomyExtraction(),
404 isReplaceUnderscores() );
405 if ( GUESS_IF_SUPPORT_VALUES ) {
406 if ( isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
407 moveBranchLengthsToConfidenceValues( getCurrentPhylogeny() );
410 if ( isGuessRootedness() ) {
411 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
412 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
413 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
414 getCurrentPhylogeny().setRooted( true );
417 return getCurrentPhylogeny();
422 private Phylogeny finishSingleNodePhylogeny2() throws PhylogenyParserException, NHXFormatException,
423 PhyloXmlDataFormatException {
424 // setCladeLevel( 0 );
425 final PhylogenyNode new_node = new PhylogenyNode();
426 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
427 setCurrentPhylogeny( new Phylogeny() );
428 getCurrentPhylogeny().setRoot( new_node );
429 return getCurrentPhylogeny();
432 private int getCladeLevel() {
436 private StringBuilder getCurrentAnotation() {
437 return _current_anotation;
440 private PhylogenyNode getCurrentNode() {
441 return _current_node;
444 private Phylogeny getCurrentPhylogeny() {
445 return _current_phylogeny;
448 private byte getInputType() {
452 private Object getNhxSource() {
456 private int getSourceLength() {
457 return _source_length;
460 private void increaseCladeLevel() {
464 private void init() {
465 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
466 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
467 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
468 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
472 private boolean isGuessRootedness() {
473 return _guess_rootedness;
476 private boolean isIgnoreQuotes() {
477 return _ignore_quotes;
480 private boolean isReplaceUnderscores() {
481 return _replace_underscores;
484 private boolean isSawClosingParen() {
485 return _saw_closing_paren;
489 * Replaces the current annotation with a new StringBuffer.
491 private void newCurrentAnotation() {
492 setCurrentAnotation( new StringBuilder() );
496 * Called if a closing paren is encountered.
498 * @throws PhylogenyParserException
499 * @throws NHXFormatException
500 * @throws PhyloXmlDataFormatException
502 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
503 decreaseCladeLevel();
504 if ( !isSawClosingParen() ) {
505 final PhylogenyNode new_node = new PhylogenyNode();
506 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
507 newCurrentAnotation();
508 getCurrentNode().addAsChild( new_node );
511 parseNHX( getCurrentAnotation().toString(),
512 getCurrentNode().getLastChildNode(),
513 getTaxonomyExtraction(),
514 isReplaceUnderscores() );
515 newCurrentAnotation();
517 if ( !getCurrentNode().isRoot() ) {
518 setCurrentNode( getCurrentNode().getParent() );
520 setSawClosingParen( true );
524 * Called if a comma is encountered.
526 * @throws PhylogenyParserException
527 * @throws NHXFormatException
528 * @throws PhyloXmlDataFormatException
530 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
531 if ( !isSawClosingParen() ) {
532 final PhylogenyNode new_node = new PhylogenyNode();
533 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
534 if ( getCurrentNode() == null ) {
535 throw new NHXFormatException( "format might not be NH or NHX" );
537 getCurrentNode().addAsChild( new_node );
540 parseNHX( getCurrentAnotation().toString(),
541 getCurrentNode().getLastChildNode(),
542 getTaxonomyExtraction(),
543 isReplaceUnderscores() );
545 newCurrentAnotation();
546 setSawClosingParen( false );
549 private Phylogeny processOpenParen2() throws PhylogenyParserException, NHXFormatException,
550 PhyloXmlDataFormatException {
551 Phylogeny phy = null;
552 final PhylogenyNode new_node = new PhylogenyNode();
553 if ( getCladeLevel() == 0 ) {
554 if ( getCurrentPhylogeny() != null ) {
555 phy = finishPhylogeny2();
558 newCurrentAnotation();
559 setCurrentPhylogeny( new Phylogeny() );
560 getCurrentPhylogeny().setRoot( new_node );
563 increaseCladeLevel();
564 getCurrentNode().addAsChild( new_node );
566 setCurrentNode( new_node );
567 setSawClosingParen( false );
571 private void setCladeLevel( final int clade_level ) {
572 if ( clade_level < 0 ) {
573 throw new IllegalArgumentException( "attempt to set clade level to a number smaller than zero" );
575 _clade_level = clade_level;
578 private void setCurrentAnotation( final StringBuilder current_anotation ) {
579 _current_anotation = current_anotation;
582 private void setCurrentNode( final PhylogenyNode current_node ) {
583 _current_node = current_node;
586 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
587 _current_phylogeny = current_phylogeny;
590 private void setHasNext( final boolean has_next ) {
591 _has_next = has_next;
594 private void setInputType( final byte input_type ) {
595 _input_type = input_type;
598 private void setNhxSource( final Object nhx_source ) {
599 _nhx_source = nhx_source;
602 private void setSawClosingParen( final boolean saw_closing_paren ) {
603 _saw_closing_paren = saw_closing_paren;
606 private void setSourceLength( final int source_length ) {
607 _source_length = source_length;
610 public static void parseNHX( String s,
611 final PhylogenyNode node_to_annotate,
612 final TAXONOMY_EXTRACTION taxonomy_extraction,
613 final boolean replace_underscores ) throws NHXFormatException,
614 PhyloXmlDataFormatException {
615 if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
616 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
618 if ( ( s != null ) && ( s.length() > 0 ) ) {
619 if ( replace_underscores ) {
620 s = s.replaceAll( "_+", " " );
622 boolean is_nhx = false;
623 final int ob = s.indexOf( "[" );
627 final int cb = s.indexOf( "]" );
629 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
631 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
632 b = s.substring( ob + 6, cb );
635 // No &&NHX and digits only: is likely to be a support value.
636 final String bracketed = s.substring( ob + 1, cb );
637 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
638 if ( numbers_only.matches() ) {
639 b = ":" + NHXtags.SUPPORT + bracketed;
641 else if ( s.indexOf( "prob=" ) > -1 ) {
642 processMrBayes3Data( s, node_to_annotate );
645 s = s.substring( 0, ob ) + b;
646 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
647 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
650 final StringTokenizer t = new StringTokenizer( s, ":" );
651 if ( t.countTokens() > 0 ) {
652 if ( !s.startsWith( ":" ) ) {
653 node_to_annotate.setName( t.nextToken() );
654 if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
655 ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
658 while ( t.hasMoreTokens() ) {
660 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
661 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
662 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
664 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
666 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
667 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
668 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
670 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
671 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
673 else if ( s.charAt( 2 ) == '?' ) {
674 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
677 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
680 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
681 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
683 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
684 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
685 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
687 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
689 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
690 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
692 else if ( s.startsWith( NHXtags.COLOR ) ) {
693 final Color c = NHXParser2.stringToColor( s.substring( 2 ) );
695 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
698 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
699 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
700 node_to_annotate.getNodeData().setSequence( new Sequence() );
702 node_to_annotate.getNodeData().getSequence()
703 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
705 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
706 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
707 node_to_annotate.getNodeData().setSequence( new Sequence() );
709 node_to_annotate.getNodeData().getSequence()
710 .setAccession( new Accession( s.substring( 3 ), "?" ) );
712 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
713 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
714 node_to_annotate.getNodeData().setSequence( new Sequence() );
716 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
718 else if ( s.indexOf( '=' ) < 0 ) {
719 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
720 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
723 node_to_annotate.setDistanceToParent( doubleValue( s ) );
725 } // while ( t.hasMoreTokens() )
730 private static double doubleValue( final String str ) throws NHXFormatException {
732 return Double.valueOf( str ).doubleValue();
734 catch ( final NumberFormatException ex ) {
735 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
740 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
741 final PhylogenyNodeIterator it = p.iteratorExternalForward();
742 final double d0 = it.next().getDistanceToParent();
743 if ( ( d0 < 10 ) || !it.hasNext() ) {
746 while ( it.hasNext() ) {
747 final double d = it.next().getDistanceToParent();
748 if ( ( d != d0 ) || ( d < 10 ) ) {
755 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
756 final PhylogenyNodeIterator it = p.iteratorPostorder();
757 while ( it.hasNext() ) {
758 final PhylogenyNode n = it.next();
759 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
760 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
764 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
765 throws NHXFormatException {
767 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
768 if ( mb_prob_sd_matcher.find() ) {
770 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
772 catch ( final NumberFormatException e ) {
773 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
777 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
778 if ( mb_prob_matcher.find() ) {
781 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
783 catch ( final NumberFormatException e ) {
784 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
788 node_to_annotate.getBranchData()
789 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
792 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
796 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
797 if ( mb_bl_matcher.find() ) {
800 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
802 catch ( final NumberFormatException e ) {
803 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
807 node_to_annotate.setDistanceToParent( bl );
813 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
814 * and blue and returns the corresponding Color.
816 private static Color stringToColor( final String s ) {
817 final StringTokenizer st = new StringTokenizer( s, "." );
818 if ( st.countTokens() != 3 ) {
819 throw new IllegalArgumentException( "illegal format for color: " + s );
821 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
822 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
823 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
824 return new Color( red, green, blu );
828 public Phylogeny[] parse() throws IOException {
829 // TODO Auto-generated method stub