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.nexus;
28 import java.io.BufferedReader;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
38 import org.forester.archaeopteryx.Constants;
39 import org.forester.io.parsers.IteratingPhylogenyParser;
40 import org.forester.io.parsers.PhylogenyParser;
41 import org.forester.io.parsers.nhx.NHXFormatException;
42 import org.forester.io.parsers.nhx.NHXParser;
43 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
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.PhylogenyNode;
48 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
49 import org.forester.util.ForesterUtil;
51 public final class NexusPhylogeniesParser implements IteratingPhylogenyParser, PhylogenyParser {
53 final private static String begin_trees = NexusConstants.BEGIN_TREES.toLowerCase();
54 final private static String taxlabels = NexusConstants.TAXLABELS.toLowerCase();
55 final private static String translate = NexusConstants.TRANSLATE.toLowerCase();
56 final private static String tree = NexusConstants.TREE.toLowerCase();
57 final private static String utree = NexusConstants.UTREE.toLowerCase();
58 final private static String end = NexusConstants.END.toLowerCase();
59 final private static String endblock = "endblock";
60 final private static Pattern TREE_NAME_PATTERN = Pattern.compile( "\\s*.?Tree\\s+(.+?)\\s*=.+",
61 Pattern.CASE_INSENSITIVE );
62 final private static Pattern ROOTEDNESS_PATTERN = Pattern.compile( ".+=\\s*\\[&([R|U])\\].*" );
63 private Object _nexus_source;
64 private List<String> _taxlabels;
65 private Map<String, String> _translate_map;
66 private boolean _replace_underscores = NHXParser.REPLACE_UNDERSCORES_DEFAULT;
67 private boolean _ignore_quotes_in_nh_data = Constants.NH_PARSING_IGNORE_QUOTES_DEFAULT;
68 private TAXONOMY_EXTRACTION _taxonomy_extraction = TAXONOMY_EXTRACTION.NO;
69 private Phylogeny _next;
70 private BufferedReader _br;
71 private boolean _in_trees_block;
72 private StringBuilder _nh;
74 private StringBuilder _translate_sb;
75 private boolean _in_taxalabels;
76 private boolean _in_translate;
77 private boolean _is_rooted;
78 private boolean _rooted_info_present;
79 private boolean _in_tree;
82 public final boolean hasNext() {
87 public final Phylogeny next() throws NHXFormatException, IOException {
88 final Phylogeny phy = _next;
94 public final Phylogeny[] parse() throws IOException {
95 final List<Phylogeny> l = new ArrayList<Phylogeny>();
99 final Phylogeny[] p = new Phylogeny[ l.size() ];
100 for( int i = 0; i < l.size(); ++i ) {
108 public final void reset() throws FileNotFoundException, IOException {
109 _taxlabels = new ArrayList<String>();
110 _translate_map = new HashMap<String, String>();
111 _nh = new StringBuilder();
113 _translate_sb = new StringBuilder();
115 _in_trees_block = false;
116 _in_taxalabels = false;
117 _in_translate = false;
119 _rooted_info_present = false;
121 _br = ParserUtils.createReader( _nexus_source );
125 public final void setIgnoreQuotes( final boolean ignore_quotes_in_nh_data ) {
126 _ignore_quotes_in_nh_data = ignore_quotes_in_nh_data;
129 public final void setReplaceUnderscores( final boolean replace_underscores ) {
130 _replace_underscores = replace_underscores;
134 public final void setSource( final Object nexus_source ) throws PhylogenyParserException, IOException {
135 if ( nexus_source == null ) {
136 throw new PhylogenyParserException( "attempt to parse null object" );
138 _nexus_source = nexus_source;
142 public final void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
143 _taxonomy_extraction = taxonomy_extraction;
146 private final void createPhylogeny( final String name,
147 final StringBuilder nhx,
148 final boolean rooted_info_present,
149 final boolean is_rooted ) throws IOException {
151 final NHXParser pars = new NHXParser();
152 pars.setTaxonomyExtraction( _taxonomy_extraction );
153 pars.setReplaceUnderscores( _replace_underscores );
154 pars.setIgnoreQuotes( _ignore_quotes_in_nh_data );
155 if ( rooted_info_present ) {
156 pars.setGuessRootedness( false );
158 pars.setSource( nhx );
159 final Phylogeny p = pars.next();
161 throw new PhylogenyParserException( "failed to create phylogeny" );
164 if ( rooted_info_present ) {
165 p.setRooted( is_rooted );
167 if ( ( _taxlabels.size() > 0 ) || ( _translate_map.size() > 0 ) ) {
168 final PhylogenyNodeIterator it = p.iteratorExternalForward();
169 while ( it.hasNext() ) {
170 final PhylogenyNode node = it.next();
171 if ( ( _translate_map.size() > 0 ) && _translate_map.containsKey( node.getName() ) ) {
172 node.setName( _translate_map.get( node.getName() ).replaceAll( "['\"]+", "" ) );
174 else if ( _taxlabels.size() > 0 ) {
177 i = Integer.parseInt( node.getName() );
179 catch ( final NumberFormatException e ) {
183 node.setName( _taxlabels.get( i - 1 ).replaceAll( "['\"]+", "" ) );
186 if ( !_replace_underscores && ( ( _taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
187 ParserUtils.extractTaxonomyDataFromNodeName( node, _taxonomy_extraction );
194 private final void getNext() throws IOException, NHXFormatException {
197 while ( ( line = _br.readLine() ) != null ) {
199 if ( ( line.length() > 0 ) && !line.startsWith( "#" ) && !line.startsWith( ">" ) ) {
200 line = ForesterUtil.collapseWhiteSpace( line );
201 line = removeWhiteSpaceBeforeSemicolon( line );
202 final String line_lc = line.toLowerCase();
203 if ( line_lc.startsWith( begin_trees ) ) {
204 _in_trees_block = true;
205 _in_taxalabels = false;
206 _in_translate = false;
208 else if ( line_lc.startsWith( taxlabels ) ) {
209 _in_trees_block = false;
210 _in_taxalabels = true;
211 _in_translate = false;
213 else if ( line_lc.startsWith( translate ) ) {
214 _in_taxalabels = false;
215 _in_translate = true;
217 else if ( _in_trees_block ) {
218 //FIXME TODO need to work on this "title" and "link"
219 if ( line_lc.startsWith( "title" ) || line_lc.startsWith( "link" ) ) {
222 else if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
223 _in_trees_block = false;
225 _in_translate = false;
226 if ( _nh.length() > 0 ) {
227 createPhylogeny( _name, _nh, _rooted_info_present, _is_rooted );
228 _nh = new StringBuilder();
230 _rooted_info_present = false;
232 if ( _next != null ) {
237 else if ( line_lc.startsWith( tree ) || ( line_lc.startsWith( utree ) ) ) {
238 boolean might = false;
239 if ( _nh.length() > 0 ) {
241 createPhylogeny( _name, _nh, _rooted_info_present, _is_rooted );
242 _nh = new StringBuilder();
244 _rooted_info_present = false;
248 _nh.append( line.substring( line.indexOf( '=' ) ) );
249 final Matcher name_matcher = TREE_NAME_PATTERN.matcher( line );
250 if ( name_matcher.matches() ) {
251 _name = name_matcher.group( 1 );
252 _name = _name.replaceAll( "['\"]+", "" );
254 final Matcher rootedness_matcher = ROOTEDNESS_PATTERN.matcher( line );
255 if ( rootedness_matcher.matches() ) {
256 final String s = rootedness_matcher.group( 1 );
257 line = line.replaceAll( "\\[\\&.\\]", "" );
258 _rooted_info_present = true;
259 if ( s.toUpperCase().equals( "R" ) ) {
263 if ( might && ( _next != null ) ) {
267 else if ( _in_tree && !_in_translate ) {
270 if ( !line_lc.startsWith( "title" ) && !line_lc.startsWith( "link" ) && !_in_translate
271 && !line_lc.startsWith( end ) && !line_lc.startsWith( endblock ) && line_lc.endsWith( ";" ) ) {
273 _in_translate = false;
274 createPhylogeny( _name, _nh, _rooted_info_present, _is_rooted );
275 _nh = new StringBuilder();
277 _rooted_info_present = false;
279 if ( _next != null ) {
284 if ( _in_taxalabels ) {
285 if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
286 _in_taxalabels = false;
289 final String[] labels = line.split( "\\s+" );
290 for( String label : labels ) {
291 if ( !label.toLowerCase().equals( taxlabels ) ) {
292 if ( label.endsWith( ";" ) ) {
293 _in_taxalabels = false;
294 label = label.substring( 0, label.length() - 1 );
296 if ( label.length() > 0 ) {
297 _taxlabels.add( label );
303 if ( _in_translate ) {
304 if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
305 _in_translate = false;
308 _translate_sb.append( " " );
309 _translate_sb.append( line.trim() );
310 if ( line.endsWith( ";" ) ) {
311 _in_translate = false;
312 setTranslateKeyValuePairs( _translate_sb );
318 if ( _nh.length() > 0 ) {
319 createPhylogeny( _name, _nh, _rooted_info_present, _is_rooted );
320 if ( _next != null ) {
326 private final void setTranslateKeyValuePairs( final StringBuilder translate_sb ) throws IOException {
327 String s = translate_sb.toString().trim();
328 if ( s.endsWith( ";" ) ) {
329 s = s.substring( 0, s.length() - 1 ).trim();
331 for( final String pair : s.split( "," ) ) {
332 final String[] kv = pair.trim().split( "\\s+" );
333 if ( ( kv.length < 2 ) || ( kv.length > 3 ) ) {
334 throw new IOException( "ill-formatted translate values: " + translate_sb );
336 if ( ( kv.length == 3 ) && !kv[ 0 ].toLowerCase().trim().equals( translate ) ) {
337 throw new IOException( "ill-formatted translate values: " + translate_sb );
341 if ( kv.length == 3 ) {
349 if ( value.endsWith( ";" ) ) {
350 value = value.substring( 0, value.length() - 1 );
352 _translate_map.put( key, value );
356 private final static String removeWhiteSpaceBeforeSemicolon( final String s ) {
357 return s.replaceAll( "\\s+;", ";" );
361 public String getName() {
362 return "Nexus Phylogenies Parser";