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.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.nhx.NHXParser.TAXONOMY_EXTRACTION;
43 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
44 import org.forester.io.parsers.util.ParserUtils;
45 import org.forester.io.parsers.util.PhylogenyParserException;
46 import org.forester.phylogeny.Phylogeny;
47 import org.forester.phylogeny.PhylogenyMethods;
48 import org.forester.phylogeny.PhylogenyNode;
49 import org.forester.phylogeny.data.Accession;
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.Sequence;
56 import org.forester.phylogeny.data.Taxonomy;
57 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
58 import org.forester.util.ForesterUtil;
60 public final class NHXParser2 implements PhylogenyParser {
62 public static final TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION_DEFAULT = TAXONOMY_EXTRACTION.NO;
63 final static private boolean GUESS_ROOTEDNESS_DEFAULT = true;
64 final static private boolean GUESS_IF_SUPPORT_VALUES = true;
65 final static private boolean IGNORE_QUOTES_DEFAULT = false;
66 final static public boolean REPLACE_UNDERSCORES_DEFAULT = false;
67 private boolean _saw_closing_paren;
68 final static private byte STRING = 0;
69 final static private byte STRING_BUFFER = 1;
70 final static private byte CHAR_ARRAY = 2;
71 final static private byte BUFFERED_READER = 3;
72 final static private byte STRING_BUILDER = 4;
73 private boolean _guess_rootedness;
74 private boolean _ignore_quotes;
75 private byte _input_type;
76 private int _source_length;
77 private PhylogenyNode _current_node;
78 private StringBuilder _current_anotation;
79 private Object _nhx_source;
80 private int _clade_level;
81 private Phylogeny _current_phylogeny;
82 private TAXONOMY_EXTRACTION _taxonomy_extraction;
83 private boolean _replace_underscores;
84 public final static Pattern UC_LETTERS_NUMBERS_PATTERN = Pattern.compile( "^[A-Z0-9]+$" );
85 public final static Pattern NUMBERS_ONLY_PATTERN = Pattern.compile( "^[0-9\\.]+$" );
86 public final static Pattern MB_PROB_PATTERN = Pattern.compile( "prob=([^,]+)" );
87 public final static Pattern MB_PROB_SD_PATTERN = Pattern.compile( "prob_stddev=([^,]+)" );
88 public final static Pattern MB_BL_PATTERN = Pattern.compile( "length_median=([^,]+)" );
89 boolean _in_comment = false;
90 boolean _saw_colon = false;
91 boolean _saw_open_bracket = false;
92 boolean _in_open_bracket = false;
93 boolean _in_double_quote = false;
94 boolean _in_single_quote = false;
95 String _my_source_str = null;
96 StringBuffer _my_source_sbuff = null;
97 StringBuilder _my_source_sbuil = null;
98 char[] _my_source_charary = null;
99 BufferedReader _my_source_br = null;
101 private Phylogeny _next;
103 public NHXParser2() {
107 public TAXONOMY_EXTRACTION getTaxonomyExtraction() {
108 return _taxonomy_extraction;
111 public boolean hasNext() {
112 return _next != null;
115 public Phylogeny next() throws NHXFormatException, IOException {
116 final Phylogeny phy = _next;
122 public Phylogeny[] parse() throws IOException {
124 List<Phylogeny> l = new ArrayList<Phylogeny>();
125 while ( hasNext() ) {
128 final Phylogeny[] p = new Phylogeny[ l.size() ];
129 for( int i = 0; i < l.size(); ++i ) {
135 public void reset() throws NHXFormatException, IOException {
139 _saw_open_bracket = false;
140 _in_open_bracket = false;
141 _in_double_quote = false;
142 _in_single_quote = false;
144 newCurrentAnotation();
145 setCurrentPhylogeny( null );
146 setCurrentNode( null );
147 _my_source_str = null;
148 _my_source_sbuff = null;
149 _my_source_sbuil = null;
150 _my_source_charary = null;
151 _my_source_br = null;
152 switch ( getInputType() ) {
154 _my_source_str = ( String ) getNhxSource();
157 _my_source_sbuff = ( StringBuffer ) getNhxSource();
160 _my_source_sbuil = ( StringBuilder ) getNhxSource();
163 _my_source_charary = ( char[] ) getNhxSource();
165 case BUFFERED_READER:
166 _my_source_br = ( BufferedReader ) getNhxSource();
169 throw new RuntimeException( "unknown input type" );
174 public void setGuessRootedness( final boolean guess_rootedness ) {
175 _guess_rootedness = guess_rootedness;
178 public void setIgnoreQuotes( final boolean ignore_quotes ) {
179 _ignore_quotes = ignore_quotes;
182 public void setReplaceUnderscores( final boolean replace_underscores ) {
183 _replace_underscores = replace_underscores;
187 * This sets the source to be parsed. The source can be: String,
188 * StringBuffer, char[], File, or InputStream. The source can contain more
189 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
190 * Extended (NHX) format. There is no need to separate phylogenies with any
191 * special character. White space is always ignored, as are semicolons
192 * inbetween phylogenies. Example of a source describing two phylogenies
193 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
194 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
195 * character other than '&' and ']' is considered a comment and ignored
196 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
197 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
198 * info]" is ignored, too (at the PhylogenyNode level, though).
199 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
202 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
204 * the source to be parsed (String, StringBuffer, char[], File,
206 * @throws IOException
207 * @throws PhylogenyParserException
210 public void setSource( final Object nhx_source ) throws PhylogenyParserException, IOException {
211 if ( nhx_source == null ) {
212 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
214 else if ( nhx_source instanceof String ) {
215 setInputType( NHXParser2.STRING );
216 setSourceLength( ( ( String ) nhx_source ).length() );
217 setNhxSource( nhx_source );
219 else if ( nhx_source instanceof StringBuilder ) {
220 setInputType( NHXParser2.STRING_BUILDER );
221 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
222 setNhxSource( nhx_source );
224 else if ( nhx_source instanceof StringBuffer ) {
225 setInputType( NHXParser2.STRING_BUFFER );
226 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
227 setNhxSource( nhx_source );
229 else if ( nhx_source instanceof StringBuilder ) {
230 setInputType( NHXParser2.STRING_BUILDER );
231 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
232 setNhxSource( nhx_source );
234 else if ( nhx_source instanceof char[] ) {
235 setInputType( NHXParser2.CHAR_ARRAY );
236 setSourceLength( ( ( char[] ) nhx_source ).length );
237 setNhxSource( nhx_source );
239 else if ( nhx_source instanceof File ) {
240 setInputType( NHXParser2.BUFFERED_READER );
241 setSourceLength( 0 );
242 final File f = ( File ) nhx_source;
243 final String error = ForesterUtil.isReadableFile( f );
244 if ( !ForesterUtil.isEmpty( error ) ) {
245 throw new PhylogenyParserException( error );
247 setNhxSource( new BufferedReader( new FileReader( f ) ) );
249 else if ( nhx_source instanceof InputStream ) {
250 setInputType( NHXParser2.BUFFERED_READER );
251 setSourceLength( 0 );
252 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
253 setNhxSource( new BufferedReader( isr ) );
256 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
257 + " StringBuffer, StringBuilder, char[], File," + " or InputStream "
258 + " [attempt to parse object of " + nhx_source.getClass() + "]." );
263 public void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
264 _taxonomy_extraction = taxonomy_extraction;
268 * Decreases the clade level by one.
270 * @throws PhylogenyParserException
271 * if level goes below zero.
273 private void decreaseCladeLevel() throws PhylogenyParserException {
274 if ( getCladeLevel() < 0 ) {
275 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
280 private Phylogeny finishPhylogeny2() throws PhylogenyParserException, NHXFormatException,
281 PhyloXmlDataFormatException {
282 //setCladeLevel( 0 );
283 if ( getCurrentPhylogeny() != null ) {
284 System.out.println( "cp=" + getCurrentPhylogeny() );
285 if ( getCurrentAnotation() != null ) {
286 System.out.println( "ca=" + getCurrentAnotation().toString() );
289 System.out.println( "ca=null" );
291 parseNHX( getCurrentAnotation() != null ? getCurrentAnotation().toString() : "", getCurrentPhylogeny()
292 .getRoot(), getTaxonomyExtraction(), isReplaceUnderscores() );
293 if ( GUESS_IF_SUPPORT_VALUES ) {
294 if ( isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
295 moveBranchLengthsToConfidenceValues( getCurrentPhylogeny() );
298 if ( isGuessRootedness() ) {
299 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
300 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
301 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
302 getCurrentPhylogeny().setRooted( true );
305 return getCurrentPhylogeny();
310 private Phylogeny finishSingleNodePhylogeny2() throws PhylogenyParserException, NHXFormatException,
311 PhyloXmlDataFormatException {
312 // setCladeLevel( 0 );
313 final PhylogenyNode new_node = new PhylogenyNode();
314 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
315 setCurrentPhylogeny( new Phylogeny() );
316 getCurrentPhylogeny().setRoot( new_node );
317 return getCurrentPhylogeny();
320 private int getCladeLevel() {
324 private StringBuilder getCurrentAnotation() {
325 return _current_anotation;
328 private PhylogenyNode getCurrentNode() {
329 return _current_node;
332 private Phylogeny getCurrentPhylogeny() {
333 return _current_phylogeny;
336 private byte getInputType() {
340 private void getNext() throws IOException, NHXFormatException {
343 if ( getInputType() == BUFFERED_READER ) {
344 final int ci = _my_source_br.read();
353 if ( _i >= getSourceLength() ) {
357 switch ( getInputType() ) {
359 c = _my_source_str.charAt( _i );
362 c = _my_source_sbuff.charAt( _i );
365 c = _my_source_sbuil.charAt( _i );
368 c = _my_source_charary[ _i ];
373 if ( !_in_single_quote && !_in_double_quote ) {
377 else if ( !( ( c < 33 ) || ( c > 126 ) ) && _saw_colon
378 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
381 if ( _in_open_bracket && ( c == ']' ) ) {
382 _in_open_bracket = false;
385 // \n\t is always ignored,
386 // as is " (34) and ' (39) (space is 32):
387 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
388 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
391 else if ( ( c == 32 ) && ( !_in_single_quote && !_in_double_quote ) ) {
394 else if ( _in_comment ) {
399 else if ( _in_double_quote ) {
401 _in_double_quote = false;
404 getCurrentAnotation().append( c );
407 else if ( c == '"' ) {
408 _in_double_quote = true;
410 else if ( _in_single_quote ) {
412 _in_single_quote = false;
415 getCurrentAnotation().append( c );
418 else if ( c == 39 ) {
419 _in_single_quote = true;
421 else if ( c == '[' ) {
422 _saw_open_bracket = true;
423 _in_open_bracket = true;
425 else if ( _saw_open_bracket ) {
427 // everything not starting with "[&" is considered a comment
428 // unless ":digits and/or . [bootstrap]":
430 getCurrentAnotation().append( "[&" );
432 else if ( _saw_colon ) {
433 getCurrentAnotation().append( "[" + c );
439 // comment consisting just of "[]":
440 _saw_open_bracket = false;
442 else if ( ( c == '(' ) && !_in_open_bracket ) {
443 final Phylogeny phy = processOpenParen2();
451 else if ( ( c == ')' ) && !_in_open_bracket ) {
454 else if ( ( c == ',' ) && !_in_open_bracket ) {
458 getCurrentAnotation().append( c );
462 System.out.println( "done with loop" );
463 if ( getCladeLevel() != 0 ) {
464 throw new PhylogenyParserException( "error in NH (Newick) formatted data: most likely cause: number of open parens does not equal number of close parens" );
466 if ( getCurrentPhylogeny() != null ) {
467 System.out.println( "current=" + getCurrentPhylogeny() );
468 _next = finishPhylogeny2();
469 setCurrentPhylogeny( null );
470 //return finishPhylogeny2();
472 else if ( ( getCurrentAnotation() != null ) && ( getCurrentAnotation().length() > 0 ) ) {
473 System.out.println( "1node=" + getCurrentAnotation() );
474 _next = finishSingleNodePhylogeny2();
475 setCurrentAnotation( null );
476 //return finishSingleNodePhylogeny2();
484 private Object getNhxSource() {
488 private int getSourceLength() {
489 return _source_length;
492 private void increaseCladeLevel() {
496 private void init() {
497 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
498 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
499 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
500 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
503 private boolean isGuessRootedness() {
504 return _guess_rootedness;
507 private boolean isIgnoreQuotes() {
508 return _ignore_quotes;
511 private boolean isReplaceUnderscores() {
512 return _replace_underscores;
515 private boolean isSawClosingParen() {
516 return _saw_closing_paren;
520 * Replaces the current annotation with a new StringBuffer.
522 private void newCurrentAnotation() {
523 setCurrentAnotation( new StringBuilder() );
527 * Called if a closing paren is encountered.
529 * @throws PhylogenyParserException
530 * @throws NHXFormatException
531 * @throws PhyloXmlDataFormatException
533 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
534 decreaseCladeLevel();
535 if ( !isSawClosingParen() ) {
536 final PhylogenyNode new_node = new PhylogenyNode();
537 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
538 newCurrentAnotation();
539 getCurrentNode().addAsChild( new_node );
542 parseNHX( getCurrentAnotation().toString(),
543 getCurrentNode().getLastChildNode(),
544 getTaxonomyExtraction(),
545 isReplaceUnderscores() );
546 newCurrentAnotation();
548 if ( !getCurrentNode().isRoot() ) {
549 setCurrentNode( getCurrentNode().getParent() );
551 setSawClosingParen( true );
555 * Called if a comma is encountered.
557 * @throws PhylogenyParserException
558 * @throws NHXFormatException
559 * @throws PhyloXmlDataFormatException
561 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
562 if ( !isSawClosingParen() ) {
563 final PhylogenyNode new_node = new PhylogenyNode();
564 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
565 if ( getCurrentNode() == null ) {
566 throw new NHXFormatException( "format might not be NH or NHX" );
568 getCurrentNode().addAsChild( new_node );
571 parseNHX( getCurrentAnotation().toString(),
572 getCurrentNode().getLastChildNode(),
573 getTaxonomyExtraction(),
574 isReplaceUnderscores() );
576 newCurrentAnotation();
577 setSawClosingParen( false );
580 private Phylogeny processOpenParen2() throws PhylogenyParserException, NHXFormatException,
581 PhyloXmlDataFormatException {
582 Phylogeny phy = null;
583 final PhylogenyNode new_node = new PhylogenyNode();
584 if ( getCladeLevel() == 0 ) {
585 if ( getCurrentPhylogeny() != null ) {
586 phy = finishPhylogeny2();
589 newCurrentAnotation();
590 setCurrentPhylogeny( new Phylogeny() );
591 getCurrentPhylogeny().setRoot( new_node );
594 increaseCladeLevel();
595 getCurrentNode().addAsChild( new_node );
597 setCurrentNode( new_node );
598 setSawClosingParen( false );
602 private void setCladeLevel( final int clade_level ) {
603 if ( clade_level < 0 ) {
604 throw new IllegalArgumentException( "attempt to set clade level to a number smaller than zero" );
606 _clade_level = clade_level;
609 private void setCurrentAnotation( final StringBuilder current_anotation ) {
610 _current_anotation = current_anotation;
613 private void setCurrentNode( final PhylogenyNode current_node ) {
614 _current_node = current_node;
617 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
618 _current_phylogeny = current_phylogeny;
621 private void setInputType( final byte input_type ) {
622 _input_type = input_type;
625 private void setNhxSource( final Object nhx_source ) {
626 _nhx_source = nhx_source;
629 private void setSawClosingParen( final boolean saw_closing_paren ) {
630 _saw_closing_paren = saw_closing_paren;
633 private void setSourceLength( final int source_length ) {
634 _source_length = source_length;
637 public static void parseNHX( String s,
638 final PhylogenyNode node_to_annotate,
639 final TAXONOMY_EXTRACTION taxonomy_extraction,
640 final boolean replace_underscores ) throws NHXFormatException,
641 PhyloXmlDataFormatException {
642 if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
643 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
645 if ( ( s != null ) && ( s.length() > 0 ) ) {
646 if ( replace_underscores ) {
647 s = s.replaceAll( "_+", " " );
649 boolean is_nhx = false;
650 final int ob = s.indexOf( "[" );
654 final int cb = s.indexOf( "]" );
656 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
658 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
659 b = s.substring( ob + 6, cb );
662 // No &&NHX and digits only: is likely to be a support value.
663 final String bracketed = s.substring( ob + 1, cb );
664 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
665 if ( numbers_only.matches() ) {
666 b = ":" + NHXtags.SUPPORT + bracketed;
668 else if ( s.indexOf( "prob=" ) > -1 ) {
669 processMrBayes3Data( s, node_to_annotate );
672 s = s.substring( 0, ob ) + b;
673 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
674 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
677 final StringTokenizer t = new StringTokenizer( s, ":" );
678 if ( t.countTokens() > 0 ) {
679 if ( !s.startsWith( ":" ) ) {
680 node_to_annotate.setName( t.nextToken() );
681 if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
682 ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
685 while ( t.hasMoreTokens() ) {
687 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
688 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
689 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
691 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
693 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
694 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
695 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
697 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
698 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
700 else if ( s.charAt( 2 ) == '?' ) {
701 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
704 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
707 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
708 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
710 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
711 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
712 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
714 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
716 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
717 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
719 else if ( s.startsWith( NHXtags.COLOR ) ) {
720 final Color c = NHXParser2.stringToColor( s.substring( 2 ) );
722 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
725 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
726 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
727 node_to_annotate.getNodeData().setSequence( new Sequence() );
729 node_to_annotate.getNodeData().getSequence()
730 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
732 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
733 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
734 node_to_annotate.getNodeData().setSequence( new Sequence() );
736 node_to_annotate.getNodeData().getSequence()
737 .setAccession( new Accession( s.substring( 3 ), "?" ) );
739 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
740 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
741 node_to_annotate.getNodeData().setSequence( new Sequence() );
743 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
745 else if ( s.indexOf( '=' ) < 0 ) {
746 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
747 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
750 node_to_annotate.setDistanceToParent( doubleValue( s ) );
752 } // while ( t.hasMoreTokens() )
757 private static double doubleValue( final String str ) throws NHXFormatException {
759 return Double.valueOf( str ).doubleValue();
761 catch ( final NumberFormatException ex ) {
762 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
767 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
768 final PhylogenyNodeIterator it = p.iteratorExternalForward();
769 final double d0 = it.next().getDistanceToParent();
770 if ( ( d0 < 10 ) || !it.hasNext() ) {
773 while ( it.hasNext() ) {
774 final double d = it.next().getDistanceToParent();
775 if ( ( d != d0 ) || ( d < 10 ) ) {
782 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
783 final PhylogenyNodeIterator it = p.iteratorPostorder();
784 while ( it.hasNext() ) {
785 final PhylogenyNode n = it.next();
786 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
787 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
791 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
792 throws NHXFormatException {
794 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
795 if ( mb_prob_sd_matcher.find() ) {
797 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
799 catch ( final NumberFormatException e ) {
800 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
804 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
805 if ( mb_prob_matcher.find() ) {
808 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
810 catch ( final NumberFormatException e ) {
811 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
815 node_to_annotate.getBranchData()
816 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
819 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
823 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
824 if ( mb_bl_matcher.find() ) {
827 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
829 catch ( final NumberFormatException e ) {
830 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
834 node_to_annotate.setDistanceToParent( bl );
840 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
841 * and blue and returns the corresponding Color.
843 private static Color stringToColor( final String s ) {
844 final StringTokenizer st = new StringTokenizer( s, "." );
845 if ( st.countTokens() != 3 ) {
846 throw new IllegalArgumentException( "illegal format for color: " + s );
848 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
849 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
850 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
851 return new Color( red, green, blu );