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: www.phylosoft.org/forester
26 package org.forester.io.parsers.nexus;
28 import java.io.BufferedReader;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.List;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
37 import org.forester.archaeopteryx.Constants;
38 import org.forester.io.parsers.PhylogenyParser;
39 import org.forester.io.parsers.nhx.NHXFormatException;
40 import org.forester.io.parsers.nhx.NHXParser;
41 import org.forester.io.parsers.util.ParserUtils;
42 import org.forester.io.parsers.util.PhylogenyParserException;
43 import org.forester.phylogeny.Phylogeny;
44 import org.forester.phylogeny.PhylogenyNode;
45 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
46 import org.forester.phylogeny.factories.PhylogenyFactory;
47 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
48 import org.forester.util.ForesterUtil;
50 public class NexusPhylogeniesParser implements PhylogenyParser {
52 final private static String begin_trees = NexusConstants.BEGIN_TREES.toLowerCase();
53 final private static String taxlabels = NexusConstants.TAXLABELS.toLowerCase();
54 final private static String translate = NexusConstants.TRANSLATE.toLowerCase();
55 final private static String tree = NexusConstants.TREE.toLowerCase();
56 final private static String utree = NexusConstants.UTREE.toLowerCase();
57 final private static String end = NexusConstants.END.toLowerCase();
58 final private static String endblock = "endblock";
59 final private static Pattern TREE_NAME_PATTERN = Pattern.compile( "\\s*.?Tree\\s+(.+?)\\s*=.+",
60 Pattern.CASE_INSENSITIVE );
61 final private static Pattern ROOTEDNESS_PATTERN = Pattern.compile( ".+=\\s*\\[&([R|U])\\].*" );
62 private Object _nexus_source;
63 private List<Phylogeny> _phylogenies;
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;
69 private void createPhylogeny( final String name,
70 final StringBuffer nhx,
71 final boolean rooted_info_present,
72 final boolean is_rooted ) throws IOException {
73 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
74 final NHXParser pars = new NHXParser();
75 pars.setTaxonomyExtraction( ForesterUtil.TAXONOMY_EXTRACTION.NO );
76 pars.setReplaceUnderscores( isReplaceUnderscores() );
77 pars.setIgnoreQuotes( isIgnoreQuotes() );
78 if ( rooted_info_present ) {
79 pars.setGuessRootedness( false );
81 final Phylogeny p = factory.create( nhx, pars )[ 0 ];
83 if ( rooted_info_present ) {
84 p.setRooted( is_rooted );
86 if ( ( getTaxlabels().size() > 0 ) || ( getTranslateMap().size() > 0 ) ) {
87 final PhylogenyNodeIterator it = p.iteratorExternalForward();
88 while ( it.hasNext() ) {
89 final PhylogenyNode node = it.next();
90 if ( ( getTranslateMap().size() > 0 ) && getTranslateMap().containsKey( node.getName() ) ) {
91 node.setName( getTranslateMap().get( node.getName() ).replaceAll( "['\"]+", "" ) );
93 else if ( getTaxlabels().size() > 0 ) {
96 i = Integer.parseInt( node.getName() );
98 catch ( final NumberFormatException e ) {
102 node.setName( getTaxlabels().get( i - 1 ).replaceAll( "['\"]+", "" ) );
107 getPhylogenies().add( p );
110 private Object getNexusSource() {
111 return _nexus_source;
114 private List<Phylogeny> getPhylogenies() {
118 private Phylogeny[] getPhylogeniesAsArray() {
119 final Phylogeny[] p = new Phylogeny[ getPhylogenies().size() ];
120 for( int i = 0; i < getPhylogenies().size(); ++i ) {
121 p[ i ] = getPhylogenies().get( i );
126 private List<String> getTaxlabels() {
130 private Map<String, String> getTranslateMap() {
131 return _translate_map;
134 private boolean isIgnoreQuotes() {
135 return _ignore_quotes_in_nh_data;
138 private boolean isReplaceUnderscores() {
139 return _replace_underscores;
143 public Phylogeny[] parse() throws IOException, NHXFormatException {
145 final BufferedReader reader = ParserUtils.createReader( getNexusSource() );
148 StringBuffer nhx = new StringBuffer();
149 final StringBuffer translate_sb = new StringBuffer();
150 boolean in_trees_block = false;
151 boolean in_taxalabels = false;
152 boolean in_translate = false;
153 final boolean in_comment = false;
154 boolean in_tree = false;
155 boolean rooted_info_present = false;
156 boolean is_rooted = false;
157 while ( ( line = reader.readLine() ) != null ) {
159 if ( ( line.length() > 0 ) && !line.startsWith( "#" ) && !line.startsWith( ">" ) ) {
160 line = ForesterUtil.collapseWhiteSpace( line );
161 line = removeWhiteSpaceBeforeSemicolon( line );
162 final String line_lc = line.toLowerCase();
163 if ( line_lc.startsWith( begin_trees ) ) {
164 in_trees_block = true;
165 in_taxalabels = false;
166 in_translate = false;
168 else if ( line_lc.startsWith( taxlabels ) ) {
169 in_trees_block = false;
170 in_taxalabels = true;
171 in_translate = false;
173 else if ( line_lc.startsWith( translate ) ) {
174 in_taxalabels = false;
177 else if ( in_trees_block ) {
178 //FIXME TODO need to work on this "title" and "link"
179 if ( line_lc.startsWith( "title" ) || line_lc.startsWith( "link" ) ) {
182 else if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
183 in_trees_block = false;
185 in_translate = false;
186 if ( nhx.length() > 0 ) {
187 createPhylogeny( name, nhx, rooted_info_present, is_rooted );
188 nhx = new StringBuffer();
190 rooted_info_present = false;
194 else if ( line_lc.startsWith( tree ) || ( line_lc.startsWith( utree ) ) ) {
195 if ( nhx.length() > 0 ) {
196 createPhylogeny( name, nhx, rooted_info_present, is_rooted );
197 nhx = new StringBuffer();
199 rooted_info_present = false;
203 nhx.append( line.substring( line.indexOf( '=' ) ) );
204 final Matcher name_matcher = TREE_NAME_PATTERN.matcher( line );
205 if ( name_matcher.matches() ) {
206 name = name_matcher.group( 1 );
207 name = name.replaceAll( "['\"]+", "" );
209 final Matcher rootedness_matcher = ROOTEDNESS_PATTERN.matcher( line );
210 if ( rootedness_matcher.matches() ) {
211 final String s = rootedness_matcher.group( 1 );
212 line = line.replaceAll( "\\[\\&.\\]", "" );
213 rooted_info_present = true;
214 if ( s.toUpperCase().equals( "R" ) ) {
219 else if ( in_tree && !in_translate ) {
222 if ( !line_lc.startsWith( "title" ) && !line_lc.startsWith( "link" ) && !in_translate
223 && !line_lc.startsWith( end ) && !line_lc.startsWith( endblock ) && line_lc.endsWith( ";" ) ) {
225 in_translate = false;
226 createPhylogeny( name, nhx, rooted_info_present, is_rooted );
227 nhx = new StringBuffer();
229 rooted_info_present = false;
233 if ( in_taxalabels ) {
234 if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
235 in_taxalabels = false;
238 final String[] labels = line.split( "\\s+" );
239 for( String label : labels ) {
240 if ( !label.toLowerCase().equals( taxlabels ) ) {
241 if ( label.endsWith( ";" ) ) {
242 in_taxalabels = false;
243 label = label.substring( 0, label.length() - 1 );
245 if ( label.length() > 0 ) {
246 getTaxlabels().add( label );
252 if ( in_translate ) {
253 if ( line_lc.startsWith( end ) || line_lc.startsWith( endblock ) ) {
254 in_translate = false;
257 translate_sb.append( " " );
258 translate_sb.append( line.trim() );
259 if ( line.endsWith( ";" ) ) {
260 in_translate = false;
261 setTranslateKeyValuePairs( translate_sb );
267 if ( nhx.length() > 0 ) {
268 createPhylogeny( name, nhx, rooted_info_present, is_rooted );
270 return getPhylogeniesAsArray();
273 private void reset() {
274 setPhylogenies( new ArrayList<Phylogeny>() );
275 setTaxlabels( new ArrayList<String>() );
276 setTranslateMap( new HashMap<String, String>() );
279 public void setIgnoreQuotes( final boolean ignore_quotes_in_nh_data ) {
280 _ignore_quotes_in_nh_data = ignore_quotes_in_nh_data;
283 private void setPhylogenies( final ArrayList<Phylogeny> phylogenies ) {
284 _phylogenies = phylogenies;
287 public void setReplaceUnderscores( final boolean replace_underscores ) {
288 _replace_underscores = replace_underscores;
292 public void setSource( final Object nexus_source ) throws PhylogenyParserException, IOException {
293 if ( nexus_source == null ) {
294 throw new PhylogenyParserException( getClass() + ": attempt to parse null object." );
296 _nexus_source = nexus_source;
299 private void setTaxlabels( final List<String> taxlabels ) {
300 _taxlabels = taxlabels;
303 private void setTranslateKeyValuePairs( final StringBuffer translate_sb ) throws IOException {
304 String s = translate_sb.toString().trim();
305 if ( s.endsWith( ";" ) ) {
306 s = s.substring( 0, s.length() - 1 ).trim();
308 for( final String pair : s.split( "," ) ) {
309 final String[] kv = pair.trim().split( "\\s+" );
310 if ( ( kv.length < 2 ) || ( kv.length > 3 ) ) {
311 throw new IOException( "ill formatted translate values: " + translate_sb );
313 if ( ( kv.length == 3 ) && !kv[ 0 ].toLowerCase().trim().equals( translate ) ) {
314 throw new IOException( "ill formatted translate values: " + translate_sb );
318 if ( kv.length == 3 ) {
326 if ( value.endsWith( ";" ) ) {
327 value = value.substring( 0, value.length() - 1 );
329 getTranslateMap().put( key, value );
333 private void setTranslateMap( final Map<String, String> translate_map ) {
334 _translate_map = translate_map;
337 private static String removeWhiteSpaceBeforeSemicolon( final String s ) {
338 return s.replaceAll( "\\s+;", ";" );