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.FileNotFoundException;
32 import java.io.FileReader;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.InputStreamReader;
36 import java.util.ArrayList;
37 import java.util.List;
38 import java.util.StringTokenizer;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
42 import org.forester.io.parsers.PhylogenyParser;
43 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
44 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
45 import org.forester.io.parsers.util.ParserUtils;
46 import org.forester.io.parsers.util.PhylogenyParserException;
47 import org.forester.phylogeny.Phylogeny;
48 import org.forester.phylogeny.PhylogenyMethods;
49 import org.forester.phylogeny.PhylogenyNode;
50 import org.forester.phylogeny.data.Accession;
51 import org.forester.phylogeny.data.Confidence;
52 import org.forester.phylogeny.data.DomainArchitecture;
53 import org.forester.phylogeny.data.Event;
54 import org.forester.phylogeny.data.Identifier;
55 import org.forester.phylogeny.data.PhylogenyDataUtil;
56 import org.forester.phylogeny.data.Sequence;
57 import org.forester.phylogeny.data.Taxonomy;
58 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
59 import org.forester.util.ForesterUtil;
61 public final class NHXParser2 implements PhylogenyParser {
63 public static final TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION_DEFAULT = TAXONOMY_EXTRACTION.NO;
64 final static private boolean GUESS_ROOTEDNESS_DEFAULT = true;
65 final static private boolean GUESS_IF_SUPPORT_VALUES = true;
66 final static private boolean IGNORE_QUOTES_DEFAULT = false;
67 final static public boolean REPLACE_UNDERSCORES_DEFAULT = false;
68 private boolean _saw_closing_paren;
69 final static private byte STRING = 0;
70 final static private byte STRING_BUFFER = 1;
71 final static private byte CHAR_ARRAY = 2;
72 final static private byte BUFFERED_READER = 3;
73 final static private byte STRING_BUILDER = 4;
74 private boolean _guess_rootedness;
75 private boolean _ignore_quotes;
76 private byte _input_type;
77 private int _source_length;
78 private PhylogenyNode _current_node;
79 private StringBuilder _current_anotation;
80 private Object _nhx_source;
81 private int _clade_level;
82 private Phylogeny _current_phylogeny;
83 private TAXONOMY_EXTRACTION _taxonomy_extraction;
84 private boolean _replace_underscores;
85 public final static Pattern UC_LETTERS_NUMBERS_PATTERN = Pattern.compile( "^[A-Z0-9]+$" );
86 public final static Pattern NUMBERS_ONLY_PATTERN = Pattern.compile( "^[0-9\\.]+$" );
87 public final static Pattern MB_PROB_PATTERN = Pattern.compile( "prob=([^,]+)" );
88 public final static Pattern MB_PROB_SD_PATTERN = Pattern.compile( "prob_stddev=([^,]+)" );
89 public final static Pattern MB_BL_PATTERN = Pattern.compile( "length_median=([^,]+)" );
90 boolean _in_comment = false;
91 boolean _saw_colon = false;
92 boolean _saw_open_bracket = false;
93 boolean _in_open_bracket = false;
94 boolean _in_double_quote = false;
95 boolean _in_single_quote = false;
96 String _my_source_str = null;
97 StringBuffer _my_source_sbuff = null;
98 StringBuilder _my_source_sbuil = null;
99 char[] _my_source_charary = null;
100 BufferedReader _my_source_br = null;
102 private Phylogeny _next;
103 private Object _source;
105 public NHXParser2() {
109 public TAXONOMY_EXTRACTION getTaxonomyExtraction() {
110 return _taxonomy_extraction;
113 public boolean hasNext() {
114 return _next != null;
117 public Phylogeny next() throws NHXFormatException, IOException {
118 final Phylogeny phy = _next;
124 public Phylogeny[] parse() throws IOException {
126 List<Phylogeny> l = new ArrayList<Phylogeny>();
127 System.out.println( ">> _next=" + _next );
128 while ( hasNext() ) {
129 Phylogeny n = next();
130 System.out.println( ">> going to add " + n );
133 final Phylogeny[] p = new Phylogeny[ l.size() ];
134 for( int i = 0; i < l.size(); ++i ) {
140 public void reset() throws NHXFormatException, IOException {
145 _saw_open_bracket = false;
146 _in_open_bracket = false;
147 _in_double_quote = false;
148 _in_single_quote = false;
150 newCurrentAnotation();
151 setCurrentPhylogeny( null );
152 setCurrentNode( null );
153 _my_source_str = null;
154 _my_source_sbuff = null;
155 _my_source_sbuil = null;
156 _my_source_charary = null;
157 _my_source_br = null;
158 determineSourceType( _source );
159 switch ( getInputType() ) {
161 _my_source_str = ( String ) getNhxSource();
164 _my_source_sbuff = ( StringBuffer ) getNhxSource();
167 _my_source_sbuil = ( StringBuilder ) getNhxSource();
170 _my_source_charary = ( char[] ) getNhxSource();
172 case BUFFERED_READER:
173 if ( _my_source_br != null ) {
175 _my_source_br.close();
177 catch ( IOException e ) {
181 _my_source_br = ( BufferedReader ) getNhxSource();
184 throw new RuntimeException( "unknown input type" );
189 public void setGuessRootedness( final boolean guess_rootedness ) {
190 _guess_rootedness = guess_rootedness;
193 public void setIgnoreQuotes( final boolean ignore_quotes ) {
194 _ignore_quotes = ignore_quotes;
197 public void setReplaceUnderscores( final boolean replace_underscores ) {
198 _replace_underscores = replace_underscores;
202 * This sets the source to be parsed. The source can be: String,
203 * StringBuffer, char[], File, or InputStream. The source can contain more
204 * than one phylogenies in either New Hamphshire (NH) or New Hamphshire
205 * Extended (NHX) format. There is no need to separate phylogenies with any
206 * special character. White space is always ignored, as are semicolons
207 * inbetween phylogenies. Example of a source describing two phylogenies
208 * (source is a String, in this example): "(A,(B,(C,(D,E)de)cde)bcde)abcde
209 * ((((A,B)ab,C)abc,D)abcd,E)abcde". Everything between a '[' followed by any
210 * character other than '&' and ']' is considered a comment and ignored
211 * (example: "[this is a comment]"). NHX tags are surrounded by '[&&NHX' and
212 * ']' (example: "[&&NHX:S=Varanus_storri]"). A sequence like "[& some
213 * info]" is ignored, too (at the PhylogenyNode level, though).
214 * Exception: numbers only between [ and ] (e.g. [90]) are interpreted as support values.
217 * @see org.forester.io.parsers.PhylogenyParser#setSource(java.lang.Object)
219 * the source to be parsed (String, StringBuffer, char[], File,
221 * @throws NHXFormatException
222 * @throws IOException
223 * @throws PhylogenyParserException
226 public void setSource( final Object nhx_source ) throws NHXFormatException, IOException {
227 _source = nhx_source;
231 private void determineSourceType( final Object nhx_source ) throws PhylogenyParserException, FileNotFoundException {
232 if ( nhx_source == null ) {
233 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
235 else if ( nhx_source instanceof String ) {
236 setInputType( NHXParser2.STRING );
237 setSourceLength( ( ( String ) nhx_source ).length() );
238 setNhxSource( nhx_source );
240 else if ( nhx_source instanceof StringBuilder ) {
241 setInputType( NHXParser2.STRING_BUILDER );
242 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
243 setNhxSource( nhx_source );
245 else if ( nhx_source instanceof StringBuffer ) {
246 setInputType( NHXParser2.STRING_BUFFER );
247 setSourceLength( ( ( StringBuffer ) nhx_source ).length() );
248 setNhxSource( nhx_source );
250 else if ( nhx_source instanceof StringBuilder ) {
251 setInputType( NHXParser2.STRING_BUILDER );
252 setSourceLength( ( ( StringBuilder ) nhx_source ).length() );
253 setNhxSource( nhx_source );
255 else if ( nhx_source instanceof char[] ) {
256 setInputType( NHXParser2.CHAR_ARRAY );
257 setSourceLength( ( ( char[] ) nhx_source ).length );
258 setNhxSource( nhx_source );
260 else if ( nhx_source instanceof File ) {
261 setInputType( NHXParser2.BUFFERED_READER );
262 setSourceLength( 0 );
263 final File f = ( File ) nhx_source;
264 final String error = ForesterUtil.isReadableFile( f );
265 if ( !ForesterUtil.isEmpty( error ) ) {
266 throw new PhylogenyParserException( error );
268 setNhxSource( new BufferedReader( new FileReader( f ) ) );
270 else if ( nhx_source instanceof InputStream ) {
271 setInputType( NHXParser2.BUFFERED_READER );
272 setSourceLength( 0 );
273 final InputStreamReader isr = new InputStreamReader( ( InputStream ) nhx_source );
274 setNhxSource( new BufferedReader( isr ) );
277 throw new IllegalArgumentException( getClass() + " can only parse objects of type String,"
278 + " StringBuffer, StringBuilder, char[], File," + " or InputStream "
279 + " [attempt to parse object of " + nhx_source.getClass() + "]." );
283 public void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
284 _taxonomy_extraction = taxonomy_extraction;
288 * Decreases the clade level by one.
290 * @throws PhylogenyParserException
291 * if level goes below zero.
293 private void decreaseCladeLevel() throws PhylogenyParserException {
294 if ( getCladeLevel() < 0 ) {
295 throw new PhylogenyParserException( "error in NH (Newick)/NHX formatted data: most likely cause: number of close parens is larger than number of open parens" );
300 private Phylogeny finishPhylogeny2() throws PhylogenyParserException, NHXFormatException,
301 PhyloXmlDataFormatException {
302 //setCladeLevel( 0 );
303 if ( getCurrentPhylogeny() != null ) {
304 System.out.println( "fp: cp=" + getCurrentPhylogeny() );
305 if ( getCurrentAnotation() != null ) {
306 System.out.println( "fp: ca=" + getCurrentAnotation().toString() );
309 System.out.println( "fp: ca=null" );
311 parseNHX( getCurrentAnotation() != null ? getCurrentAnotation().toString() : "", getCurrentPhylogeny()
312 .getRoot(), getTaxonomyExtraction(), isReplaceUnderscores() );
313 if ( GUESS_IF_SUPPORT_VALUES ) {
314 if ( isBranchLengthsLikeBootstrapValues( getCurrentPhylogeny() ) ) {
315 moveBranchLengthsToConfidenceValues( getCurrentPhylogeny() );
318 if ( isGuessRootedness() ) {
319 final PhylogenyNode root = getCurrentPhylogeny().getRoot();
320 if ( ( root.getDistanceToParent() >= 0.0 ) || !ForesterUtil.isEmpty( root.getName() )
321 || !ForesterUtil.isEmpty( PhylogenyMethods.getSpecies( root ) ) || root.isHasAssignedEvent() ) {
322 getCurrentPhylogeny().setRooted( true );
325 return getCurrentPhylogeny();
330 private Phylogeny finishSingleNodePhylogeny2() throws PhylogenyParserException, NHXFormatException,
331 PhyloXmlDataFormatException {
332 // setCladeLevel( 0 );
333 final PhylogenyNode new_node = new PhylogenyNode();
334 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
335 setCurrentPhylogeny( new Phylogeny() );
336 getCurrentPhylogeny().setRoot( new_node );
337 return getCurrentPhylogeny();
340 private int getCladeLevel() {
344 private StringBuilder getCurrentAnotation() {
345 return _current_anotation;
348 private PhylogenyNode getCurrentNode() {
349 return _current_node;
352 private Phylogeny getCurrentPhylogeny() {
353 return _current_phylogeny;
356 private byte getInputType() {
360 private void getNext() throws IOException, NHXFormatException {
363 if ( getInputType() == BUFFERED_READER ) {
364 final int ci = _my_source_br.read();
373 if ( _i >= getSourceLength() ) {
377 switch ( getInputType() ) {
379 c = _my_source_str.charAt( _i );
382 c = _my_source_sbuff.charAt( _i );
385 c = _my_source_sbuil.charAt( _i );
388 c = _my_source_charary[ _i ];
393 if ( !_in_single_quote && !_in_double_quote ) {
397 else if ( !( ( c < 33 ) || ( c > 126 ) ) && _saw_colon
398 && ( ( c != '[' ) && ( c != '.' ) && ( ( c < 48 ) || ( c > 57 ) ) ) ) {
401 if ( _in_open_bracket && ( c == ']' ) ) {
402 _in_open_bracket = false;
405 // \n\t is always ignored,
406 // as is " (34) and ' (39) (space is 32):
407 if ( ( isIgnoreQuotes() && ( ( c < 33 ) || ( c > 126 ) || ( c == 34 ) || ( c == 39 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) )
408 || ( !isIgnoreQuotes() && ( ( c < 32 ) || ( c > 126 ) || ( ( getCladeLevel() == 0 ) && ( c == ';' ) ) ) ) ) {
411 else if ( ( c == 32 ) && ( !_in_single_quote && !_in_double_quote ) ) {
414 else if ( _in_comment ) {
419 else if ( _in_double_quote ) {
421 _in_double_quote = false;
424 getCurrentAnotation().append( c );
427 else if ( c == '"' ) {
428 _in_double_quote = true;
430 else if ( _in_single_quote ) {
432 _in_single_quote = false;
435 getCurrentAnotation().append( c );
438 else if ( c == 39 ) {
439 _in_single_quote = true;
441 else if ( c == '[' ) {
442 _saw_open_bracket = true;
443 _in_open_bracket = true;
445 else if ( _saw_open_bracket ) {
447 // everything not starting with "[&" is considered a comment
448 // unless ":digits and/or . [bootstrap]":
450 getCurrentAnotation().append( "[&" );
452 else if ( _saw_colon ) {
453 getCurrentAnotation().append( "[" + c );
459 // comment consisting just of "[]":
460 _saw_open_bracket = false;
462 else if ( ( c == '(' ) && !_in_open_bracket ) {
463 final Phylogeny phy = processOpenParen2();
471 else if ( ( c == ')' ) && !_in_open_bracket ) {
474 else if ( ( c == ',' ) && !_in_open_bracket ) {
478 getCurrentAnotation().append( c );
482 System.out.println( "done with loop" );
483 if ( getCurrentPhylogeny() == null ) {
484 System.out.println( "... but is null" );
486 if ( getCladeLevel() != 0 ) {
487 throw new PhylogenyParserException( "error in NH (Newick) formatted data: most likely cause: number of open parens does not equal number of close parens" );
489 if ( getCurrentPhylogeny() != null ) {
490 System.out.println( "... and current=" + getCurrentPhylogeny() );
491 _next = finishPhylogeny2();
492 System.out.println( "... _next=" + _next );
493 setCurrentPhylogeny( null );
494 setCurrentAnotation( null );
495 //return finishPhylogeny2();
497 else if ( ( getCurrentAnotation() != null ) && ( getCurrentAnotation().length() > 0 ) ) {
498 System.out.println( "1node=" + getCurrentAnotation() );
499 _next = finishSingleNodePhylogeny2();
500 setCurrentAnotation( null );
501 //return finishSingleNodePhylogeny2();
509 private Object getNhxSource() {
513 private int getSourceLength() {
514 return _source_length;
517 private void increaseCladeLevel() {
521 private void init() {
522 setTaxonomyExtraction( TAXONOMY_EXTRACTION_DEFAULT );
523 setReplaceUnderscores( REPLACE_UNDERSCORES_DEFAULT );
524 setGuessRootedness( GUESS_ROOTEDNESS_DEFAULT );
525 setIgnoreQuotes( IGNORE_QUOTES_DEFAULT );
528 private boolean isGuessRootedness() {
529 return _guess_rootedness;
532 private boolean isIgnoreQuotes() {
533 return _ignore_quotes;
536 private boolean isReplaceUnderscores() {
537 return _replace_underscores;
540 private boolean isSawClosingParen() {
541 return _saw_closing_paren;
545 * Replaces the current annotation with a new StringBuffer.
547 private void newCurrentAnotation() {
548 setCurrentAnotation( new StringBuilder() );
552 * Called if a closing paren is encountered.
554 * @throws PhylogenyParserException
555 * @throws NHXFormatException
556 * @throws PhyloXmlDataFormatException
558 private void processCloseParen() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
559 decreaseCladeLevel();
560 if ( !isSawClosingParen() ) {
561 final PhylogenyNode new_node = new PhylogenyNode();
562 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
563 newCurrentAnotation();
564 getCurrentNode().addAsChild( new_node );
567 parseNHX( getCurrentAnotation().toString(),
568 getCurrentNode().getLastChildNode(),
569 getTaxonomyExtraction(),
570 isReplaceUnderscores() );
571 newCurrentAnotation();
573 if ( !getCurrentNode().isRoot() ) {
574 setCurrentNode( getCurrentNode().getParent() );
576 setSawClosingParen( true );
580 * Called if a comma is encountered.
582 * @throws PhylogenyParserException
583 * @throws NHXFormatException
584 * @throws PhyloXmlDataFormatException
586 private void processComma() throws PhylogenyParserException, NHXFormatException, PhyloXmlDataFormatException {
587 if ( !isSawClosingParen() ) {
588 final PhylogenyNode new_node = new PhylogenyNode();
589 parseNHX( getCurrentAnotation().toString(), new_node, getTaxonomyExtraction(), isReplaceUnderscores() );
590 if ( getCurrentNode() == null ) {
591 throw new NHXFormatException( "format might not be NH or NHX" );
593 getCurrentNode().addAsChild( new_node );
596 parseNHX( getCurrentAnotation().toString(),
597 getCurrentNode().getLastChildNode(),
598 getTaxonomyExtraction(),
599 isReplaceUnderscores() );
601 newCurrentAnotation();
602 setSawClosingParen( false );
605 private Phylogeny processOpenParen2() throws PhylogenyParserException, NHXFormatException,
606 PhyloXmlDataFormatException {
607 Phylogeny phy = null;
608 final PhylogenyNode new_node = new PhylogenyNode();
609 System.out.println( "level=" + getCladeLevel() );
610 if ( getCladeLevel() == 0 ) {
611 if ( getCurrentPhylogeny() != null ) {
612 phy = finishPhylogeny2();
615 newCurrentAnotation();
616 setCurrentPhylogeny( new Phylogeny() );
617 getCurrentPhylogeny().setRoot( new_node );
620 increaseCladeLevel();
621 getCurrentNode().addAsChild( new_node );
623 setCurrentNode( new_node );
624 setSawClosingParen( false );
626 System.out.println( "processOpenParen2 returns " + phy.toString() );
629 System.out.println( "processOpenParen2 returns null" );
634 private void setCladeLevel( final int clade_level ) {
635 if ( clade_level < 0 ) {
636 throw new IllegalArgumentException( "attempt to set clade level to a number smaller than zero" );
638 _clade_level = clade_level;
641 private void setCurrentAnotation( final StringBuilder current_anotation ) {
642 _current_anotation = current_anotation;
645 private void setCurrentNode( final PhylogenyNode current_node ) {
646 _current_node = current_node;
649 private void setCurrentPhylogeny( final Phylogeny current_phylogeny ) {
650 _current_phylogeny = current_phylogeny;
653 private void setInputType( final byte input_type ) {
654 _input_type = input_type;
657 private void setNhxSource( final Object nhx_source ) {
658 _nhx_source = nhx_source;
661 private void setSawClosingParen( final boolean saw_closing_paren ) {
662 _saw_closing_paren = saw_closing_paren;
665 private void setSourceLength( final int source_length ) {
666 _source_length = source_length;
669 public static void parseNHX( String s,
670 final PhylogenyNode node_to_annotate,
671 final TAXONOMY_EXTRACTION taxonomy_extraction,
672 final boolean replace_underscores ) throws NHXFormatException,
673 PhyloXmlDataFormatException {
674 if ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) && replace_underscores ) {
675 throw new IllegalArgumentException( "cannot extract taxonomies and replace under scores at the same time" );
677 if ( ( s != null ) && ( s.length() > 0 ) ) {
678 if ( replace_underscores ) {
679 s = s.replaceAll( "_+", " " );
681 boolean is_nhx = false;
682 final int ob = s.indexOf( "[" );
686 final int cb = s.indexOf( "]" );
688 throw new NHXFormatException( "error in NHX formatted data: no closing \"]\" in \"" + s + "\"" );
690 if ( s.indexOf( "&&NHX" ) == ( ob + 1 ) ) {
691 b = s.substring( ob + 6, cb );
694 // No &&NHX and digits only: is likely to be a support value.
695 final String bracketed = s.substring( ob + 1, cb );
696 final Matcher numbers_only = NUMBERS_ONLY_PATTERN.matcher( bracketed );
697 if ( numbers_only.matches() ) {
698 b = ":" + NHXtags.SUPPORT + bracketed;
700 else if ( s.indexOf( "prob=" ) > -1 ) {
701 processMrBayes3Data( s, node_to_annotate );
704 s = s.substring( 0, ob ) + b;
705 if ( ( s.indexOf( "[" ) > -1 ) || ( s.indexOf( "]" ) > -1 ) ) {
706 throw new NHXFormatException( "error in NHX formatted data: more than one \"]\" or \"[\"" );
709 final StringTokenizer t = new StringTokenizer( s, ":" );
710 if ( t.countTokens() > 0 ) {
711 if ( !s.startsWith( ":" ) ) {
712 node_to_annotate.setName( t.nextToken() );
713 if ( !replace_underscores && ( !is_nhx && ( taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
714 ParserUtils.extractTaxonomyDataFromNodeName( node_to_annotate, taxonomy_extraction );
717 while ( t.hasMoreTokens() ) {
719 if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.SPECIES_NAME ) ) {
720 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
721 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
723 node_to_annotate.getNodeData().getTaxonomy().setScientificName( s.substring( 2 ) );
725 else if ( s.startsWith( org.forester.io.parsers.nhx.NHXtags.IS_DUPLICATION ) ) {
726 if ( ( s.charAt( 2 ) == 'Y' ) || ( s.charAt( 2 ) == 'T' ) ) {
727 node_to_annotate.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
729 else if ( ( s.charAt( 2 ) == 'N' ) || ( s.charAt( 2 ) == 'F' ) ) {
730 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
732 else if ( s.charAt( 2 ) == '?' ) {
733 node_to_annotate.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
736 throw new NHXFormatException( "error in NHX formatted data: :D=Y or :D=N or :D=?" );
739 else if ( s.startsWith( NHXtags.SUPPORT ) ) {
740 PhylogenyMethods.setConfidence( node_to_annotate, doubleValue( s.substring( 2 ) ) );
742 else if ( s.startsWith( NHXtags.TAXONOMY_ID ) ) {
743 if ( !node_to_annotate.getNodeData().isHasTaxonomy() ) {
744 node_to_annotate.getNodeData().setTaxonomy( new Taxonomy() );
746 node_to_annotate.getNodeData().getTaxonomy().setIdentifier( new Identifier( s.substring( 2 ) ) );
748 else if ( s.startsWith( NHXtags.PARENT_BRANCH_WIDTH ) ) {
749 PhylogenyMethods.setBranchWidthValue( node_to_annotate, Integer.parseInt( s.substring( 2 ) ) );
751 else if ( s.startsWith( NHXtags.COLOR ) ) {
752 final Color c = NHXParser2.stringToColor( s.substring( 2 ) );
754 PhylogenyMethods.setBranchColorValue( node_to_annotate, c );
757 else if ( s.startsWith( NHXtags.DOMAIN_STRUCTURE ) ) {
758 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
759 node_to_annotate.getNodeData().setSequence( new Sequence() );
761 node_to_annotate.getNodeData().getSequence()
762 .setDomainArchitecture( new DomainArchitecture( s.substring( 3 ) ) );
764 else if ( s.startsWith( NHXtags.SEQUENCE_ACCESSION ) ) {
765 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
766 node_to_annotate.getNodeData().setSequence( new Sequence() );
768 node_to_annotate.getNodeData().getSequence()
769 .setAccession( new Accession( s.substring( 3 ), "?" ) );
771 else if ( s.startsWith( NHXtags.GENE_NAME ) ) {
772 if ( !node_to_annotate.getNodeData().isHasSequence() ) {
773 node_to_annotate.getNodeData().setSequence( new Sequence() );
775 node_to_annotate.getNodeData().getSequence().setName( s.substring( 3 ) );
777 else if ( s.indexOf( '=' ) < 0 ) {
778 if ( node_to_annotate.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
779 throw new NHXFormatException( "error in NHX formatted data: more than one distance to parent:"
782 node_to_annotate.setDistanceToParent( doubleValue( s ) );
784 } // while ( t.hasMoreTokens() )
789 private static double doubleValue( final String str ) throws NHXFormatException {
791 return Double.valueOf( str ).doubleValue();
793 catch ( final NumberFormatException ex ) {
794 throw new NHXFormatException( "error in NH/NHX formatted data: failed to parse number from " + "\"" + str
799 private static boolean isBranchLengthsLikeBootstrapValues( final Phylogeny p ) {
800 final PhylogenyNodeIterator it = p.iteratorExternalForward();
801 final double d0 = it.next().getDistanceToParent();
802 if ( ( d0 < 10 ) || !it.hasNext() ) {
805 while ( it.hasNext() ) {
806 final double d = it.next().getDistanceToParent();
807 if ( ( d != d0 ) || ( d < 10 ) ) {
814 private static void moveBranchLengthsToConfidenceValues( final Phylogeny p ) {
815 final PhylogenyNodeIterator it = p.iteratorPostorder();
816 while ( it.hasNext() ) {
817 final PhylogenyNode n = it.next();
818 PhylogenyMethods.setBootstrapConfidence( n, n.getDistanceToParent() );
819 n.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
823 private static void processMrBayes3Data( final String s, final PhylogenyNode node_to_annotate )
824 throws NHXFormatException {
826 final Matcher mb_prob_sd_matcher = MB_PROB_SD_PATTERN.matcher( s );
827 if ( mb_prob_sd_matcher.find() ) {
829 sd = Double.parseDouble( mb_prob_sd_matcher.group( 1 ) );
831 catch ( final NumberFormatException e ) {
832 throw new NHXFormatException( "failed to parse probability standard deviation (Mr Bayes output) from \""
836 final Matcher mb_prob_matcher = MB_PROB_PATTERN.matcher( s );
837 if ( mb_prob_matcher.find() ) {
840 prob = Double.parseDouble( mb_prob_matcher.group( 1 ) );
842 catch ( final NumberFormatException e ) {
843 throw new NHXFormatException( "failed to parse probability (Mr Bayes output) from \"" + s + "\"" );
847 node_to_annotate.getBranchData()
848 .addConfidence( new Confidence( prob, "posterior probability", sd ) );
851 node_to_annotate.getBranchData().addConfidence( new Confidence( prob, "posterior probability" ) );
855 final Matcher mb_bl_matcher = MB_BL_PATTERN.matcher( s );
856 if ( mb_bl_matcher.find() ) {
859 bl = Double.parseDouble( mb_bl_matcher.group( 1 ) );
861 catch ( final NumberFormatException e ) {
862 throw new NHXFormatException( "failed to parse median branch length (Mr Bayes output) from \"" + s
866 node_to_annotate.setDistanceToParent( bl );
872 * Parses String s in the format r.g.b (e.g. "12.34.234" ) into red, green,
873 * and blue and returns the corresponding Color.
875 private static Color stringToColor( final String s ) {
876 final StringTokenizer st = new StringTokenizer( s, "." );
877 if ( st.countTokens() != 3 ) {
878 throw new IllegalArgumentException( "illegal format for color: " + s );
880 final int red = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
881 final int green = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
882 final int blu = ForesterUtil.limitRangeForColor( Integer.parseInt( st.nextToken() ) );
883 return new Color( red, green, blu );