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 end = NexusConstants.END.toLowerCase();
55 final private static String endblock = "endblock";
56 final private static Pattern ROOTEDNESS_PATTERN = Pattern.compile( ".+=\\s*\\[&([R|U])\\].*" );
57 final private static String taxlabels = NexusConstants.TAXLABELS.toLowerCase();
58 final private static Pattern TITLE_PATTERN = Pattern.compile( "TITLE.?\\s+([^;]+)",
59 Pattern.CASE_INSENSITIVE );
60 final private static String translate = NexusConstants.TRANSLATE.toLowerCase();
61 final private static String tree = NexusConstants.TREE.toLowerCase();
62 final private static Pattern TREE_NAME_PATTERN = Pattern.compile( "\\s*.?Tree\\s+(.+?)\\s*=.+",
63 Pattern.CASE_INSENSITIVE );
64 final private static Pattern TRANSLATE_PATTERN = Pattern.compile( "([0-9A-Za-z]+)\\s+(.+)" );
65 final private static String utree = NexusConstants.UTREE.toLowerCase();
66 private BufferedReader _br;
67 private boolean _ignore_quotes_in_nh_data = Constants.NH_PARSING_IGNORE_QUOTES_DEFAULT;
68 private boolean _in_taxalabels;
69 private boolean _in_translate;
70 private boolean _in_tree;
71 private boolean _in_trees_block;
72 private boolean _is_rooted;
74 private Phylogeny _next;
75 private Object _nexus_source;
76 private StringBuilder _nh;
77 private boolean _replace_underscores = NHXParser.REPLACE_UNDERSCORES_DEFAULT;
78 private boolean _rooted_info_present;
79 private List<String> _taxlabels;
80 private TAXONOMY_EXTRACTION _taxonomy_extraction = TAXONOMY_EXTRACTION.NO;
81 private String _title;
82 private Map<String, String> _translate_map;
83 private StringBuilder _translate_sb;
86 public String getName() {
87 return "Nexus Phylogenies Parser";
91 public final boolean hasNext() {
96 public final Phylogeny next() throws NHXFormatException, IOException {
97 final Phylogeny phy = _next;
103 public final Phylogeny[] parse() throws IOException {
104 final List<Phylogeny> l = new ArrayList<Phylogeny>();
105 while ( hasNext() ) {
108 final Phylogeny[] p = new Phylogeny[ l.size() ];
109 for( int i = 0; i < l.size(); ++i ) {
117 public final void reset() throws FileNotFoundException, IOException {
118 _taxlabels = new ArrayList<String>();
119 _translate_map = new HashMap<String, String>();
120 _nh = new StringBuilder();
123 _translate_sb = null;
125 _in_trees_block = false;
126 _in_taxalabels = false;
127 _in_translate = false;
129 _rooted_info_present = false;
131 _br = ParserUtils.createReader( _nexus_source );
135 public final void setIgnoreQuotes( final boolean ignore_quotes_in_nh_data ) {
136 _ignore_quotes_in_nh_data = ignore_quotes_in_nh_data;
139 public final void setReplaceUnderscores( final boolean replace_underscores ) {
140 _replace_underscores = replace_underscores;
144 public final void setSource( final Object nexus_source ) throws PhylogenyParserException, IOException {
145 if ( nexus_source == null ) {
146 throw new PhylogenyParserException( "attempt to parse null object" );
148 _nexus_source = nexus_source;
152 public final void setTaxonomyExtraction( final TAXONOMY_EXTRACTION taxonomy_extraction ) {
153 _taxonomy_extraction = taxonomy_extraction;
156 private final void createPhylogeny( final String title,
158 final StringBuilder nhx,
159 final boolean rooted_info_present,
160 final boolean is_rooted ) throws IOException {
162 final NHXParser pars = new NHXParser();
163 pars.setTaxonomyExtraction( _taxonomy_extraction );
164 pars.setReplaceUnderscores( _replace_underscores );
165 pars.setIgnoreQuotes( _ignore_quotes_in_nh_data );
166 if ( rooted_info_present ) {
167 pars.setGuessRootedness( false );
169 pars.setSource( nhx );
170 final Phylogeny p = pars.next();
172 throw new PhylogenyParserException( "failed to create phylogeny" );
174 String myname = null;
175 if ( !ForesterUtil.isEmpty( title ) && !ForesterUtil.isEmpty( name ) ) {
176 myname = title.replace( '_', ' ' ).trim() + " (" + name.trim() + ")";
178 else if ( !ForesterUtil.isEmpty( title ) ) {
179 myname = title.replace( '_', ' ' ).trim();
181 else if ( !ForesterUtil.isEmpty( name ) ) {
182 myname = name.trim();
184 if ( !ForesterUtil.isEmpty( myname ) ) {
187 if ( rooted_info_present ) {
188 p.setRooted( is_rooted );
190 if ( ( _taxlabels.size() > 0 ) || ( _translate_map.size() > 0 ) ) {
191 final PhylogenyNodeIterator it = p.iteratorExternalForward();
192 while ( it.hasNext() ) {
193 final PhylogenyNode node = it.next();
194 if ( ( _translate_map.size() > 0 ) && _translate_map.containsKey( node.getName() ) ) {
195 node.setName( _translate_map.get( node.getName() ).replaceAll( "['\"]+", "" ) );
197 else if ( _taxlabels.size() > 0 ) {
200 i = Integer.parseInt( node.getName() );
202 catch ( final NumberFormatException e ) {
206 node.setName( _taxlabels.get( i - 1 ).replaceAll( "['\"]+", "" ) );
209 if ( !_replace_underscores && ( ( _taxonomy_extraction != TAXONOMY_EXTRACTION.NO ) ) ) {
210 ParserUtils.extractTaxonomyDataFromNodeName( node, _taxonomy_extraction );
212 else if ( _replace_underscores ) {
213 if ( !ForesterUtil.isEmpty( node.getName() ) ) {
214 node.setName( node.getName().replace( '_', ' ' ).trim() );
222 private final void getNext() throws IOException, NHXFormatException {
225 while ( ( line = _br.readLine() ) != null ) {
227 if ( ( line.length() > 0 ) && !line.startsWith( "#" ) && !line.startsWith( ">" ) ) {
228 line = ForesterUtil.collapseWhiteSpace( line );
229 line = removeWhiteSpaceBeforeSemicolon( line );
230 final String line_lc = line.toLowerCase();
231 if ( line_lc.startsWith( begin_trees ) ) {
232 _in_trees_block = true;
233 _in_taxalabels = false;
234 _in_translate = false;
237 else if ( line_lc.startsWith( taxlabels ) ) {
238 _in_trees_block = false;
239 _in_taxalabels = true;
240 _in_translate = false;
242 else if ( line_lc.startsWith( translate ) ) {
243 _translate_sb = new StringBuilder();
244 _in_taxalabels = false;
245 _in_translate = true;
247 else if ( _in_trees_block ) {
248 if ( line_lc.startsWith( "title" ) ) {
249 final Matcher title_m = TITLE_PATTERN.matcher( line );
250 if ( title_m.lookingAt() ) {
251 _title = title_m.group( 1 );
254 else if ( line_lc.startsWith( "link" ) ) {
256 else if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
257 _in_trees_block = false;
259 _in_translate = false;
260 if ( _nh.length() > 0 ) {
261 createPhylogeny( _title, _name, _nh, _rooted_info_present, _is_rooted );
262 _nh = new StringBuilder();
264 _rooted_info_present = false;
266 if ( _next != null ) {
271 else if ( line_lc.startsWith( tree ) || ( line_lc.startsWith( utree ) ) ) {
272 boolean might = false;
273 if ( _nh.length() > 0 ) {
275 createPhylogeny( _title, _name, _nh, _rooted_info_present, _is_rooted );
276 _nh = new StringBuilder();
278 _rooted_info_present = false;
282 _nh.append( line.substring( line.indexOf( '=' ) ) );
283 final Matcher name_matcher = TREE_NAME_PATTERN.matcher( line );
284 if ( name_matcher.matches() ) {
285 _name = name_matcher.group( 1 );
286 _name = _name.replaceAll( "['\"]+", "" );
288 final Matcher rootedness_matcher = ROOTEDNESS_PATTERN.matcher( line );
289 if ( rootedness_matcher.matches() ) {
290 final String s = rootedness_matcher.group( 1 );
291 line = line.replaceAll( "\\[\\&.\\]", "" );
292 _rooted_info_present = true;
293 if ( s.toUpperCase().equals( "R" ) ) {
297 if ( might && ( _next != null ) ) {
301 else if ( _in_tree && !_in_translate ) {
304 if ( !line_lc.startsWith( "title" ) && !line_lc.startsWith( "link" ) && !_in_translate
305 && !line_lc.startsWith( end ) && !line_lc.startsWith( endblock ) && line_lc.endsWith( ";" ) ) {
307 _in_translate = false;
308 createPhylogeny( _title, _name, _nh, _rooted_info_present, _is_rooted );
309 _nh = new StringBuilder();
311 _rooted_info_present = false;
313 if ( _next != null ) {
318 if ( _in_taxalabels ) {
319 if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
320 _in_taxalabels = false;
323 final String[] labels = line.split( "\\s+" );
324 for( String label : labels ) {
325 if ( !label.toLowerCase().equals( taxlabels ) ) {
326 if ( label.endsWith( ";" ) ) {
327 _in_taxalabels = false;
328 label = label.substring( 0, label.length() - 1 );
330 if ( label.length() > 0 ) {
331 _taxlabels.add( label );
337 if ( _in_translate ) {
338 if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
339 _in_translate = false;
342 _translate_sb.append( " " );
343 _translate_sb.append( line.trim() );
344 if ( line.endsWith( ";" ) ) {
345 _in_translate = false;
346 setTranslateKeyValuePairs( _translate_sb );
352 if ( _nh.length() > 0 ) {
353 createPhylogeny( _title, _name, _nh, _rooted_info_present, _is_rooted );
354 if ( _next != null ) {
360 private final void setTranslateKeyValuePairs( final StringBuilder translate_sb ) throws IOException {
361 String s = translate_sb.toString().trim();
362 if ( s.endsWith( ";" ) ) {
363 s = s.substring( 0, s.length() - 1 ).trim();
365 for( String pair : s.split( "," ) ) {
368 final int ti = pair.toLowerCase().indexOf( "translate" );
370 pair = pair.substring( ti + 9 );
372 final Matcher m = TRANSLATE_PATTERN.matcher( pair );
375 value = m.group( 2 ).replaceAll( "\'", "" ).replaceAll( "\"", "" ).trim();
378 throw new IOException( "ill-formatted translate values: " + pair );
380 if ( value.endsWith( ";" ) ) {
381 value = value.substring( 0, value.length() - 1 );
383 _translate_map.put( key, value );
387 private final static String removeWhiteSpaceBeforeSemicolon( final String s ) {
388 return s.replaceAll( "\\s+;", ";" );