3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/
27 package org.forester.io.parsers.util;
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.io.StringReader;
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.nexus.NexusPhylogeniesParser;
43 import org.forester.io.parsers.nhx.NHXParser;
44 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
45 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
46 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
47 import org.forester.io.parsers.tol.TolParser;
48 import org.forester.phylogeny.Phylogeny;
49 import org.forester.phylogeny.PhylogenyMethods;
50 import org.forester.phylogeny.PhylogenyNode;
51 import org.forester.phylogeny.data.Identifier;
52 import org.forester.phylogeny.data.Taxonomy;
53 import org.forester.util.ForesterConstants;
54 import org.forester.util.ForesterUtil;
56 public final class ParserUtils {
58 final public static String TAX_CODE = "(?:[A-Z9][A-Z]{2}[A-Z0-9]{2})|RAT|PIG|PEA";
59 final private static String SN_BN = "[A-Z][a-z]{2,30}[_ ][a-z]{3,30}";
60 final public static Pattern TAXOMONY_CODE_PATTERN_A = Pattern.compile( "(?:\\b|_)(" + TAX_CODE
62 final public static Pattern TAXOMONY_CODE_PATTERN_BRACKETED = Pattern.compile( "\\[(" + TAX_CODE + ")\\]" );
63 final public static Pattern TAXOMONY_CODE_PATTERN_PFR = Pattern.compile( "(?:\\b|_)[a-zA-Z0-9]{3,}_("
64 + TAX_CODE + ")\\b" );
65 final public static Pattern TAXOMONY_SN_PATTERN_SN = Pattern.compile( "(?:\\b|_)(" + SN_BN
66 + ")(?:(\\s*$)|([_ ][a-z]*[A-Z0-9]))" );
67 final public static Pattern TAXOMONY_SN_PATTERN_SNS = Pattern.compile( "(?:\\b|_)(" + SN_BN
69 + ")[_ ][a-z]*[A-Z0-9]" );
70 final public static Pattern TAXOMONY_SN_PATTERN_SNS2 = Pattern.compile( "[A-Z0-9][a-z]*[_ ](" + SN_BN
71 + "[_ ][a-z]{3,30}" + ")\\s*$" );
72 final public static Pattern TAXOMONY_SN_PATTERN_STRAIN_1 = Pattern
73 .compile( "(?:\\b|_)("
75 + "[_ ](?:str|subsp|ssp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60})(?:\\b|_)" );
76 final public static Pattern TAXOMONY_SN_PATTERN_STRAIN_2 = Pattern
77 .compile( "(?:\\b|_)("
79 + "[_ ]\\((?:str|subsp|ssp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60}\\))" );
80 final public static Pattern TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN = Pattern
81 .compile( "(?:\\b|_)("
83 + "[_ ]str[a-z]{0,3}\\.?[_ ]\\S{1,60}[_ ]substr[a-z]{0,3}\\.?[_ ]\\S{1,60})(?:\\b|_)" );
84 final public static Pattern TAXOMONY_SN_PATTERN_SP = Pattern
85 .compile( "(?:\\b|_)([A-Z][a-z]{2,30}[_ ]sp\\.?)(?:\\b|_)?" );
86 final public static Pattern TAXOMONY_SN_PATTERN_GENUS = Pattern.compile( "([A-Z][a-z]{2,30})" );
87 final private static Pattern TAXOMONY_CODE_PATTERN_PFS = Pattern.compile( "(?:\\b|_)[A-Z0-9]{4,}_("
88 + TAX_CODE + ")/\\d+-\\d+\\b" );
89 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFR = Pattern
90 .compile( "(?:\\b|_)[A-Z0-9]{1,}_(\\d{1,7})\\b" );
91 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFS = Pattern
92 .compile( "(?:\\b|_)[A-Z0-9]{4,}_(\\d{1,7})/\\d+-\\d+\\b" );
94 final public static PhylogenyParser createParserDependingFileContents( final File file,
95 final boolean phyloxml_validate_against_xsd )
96 throws FileNotFoundException, IOException {
97 PhylogenyParser parser = null;
98 final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
99 if ( first_line.startsWith( "<" ) ) {
100 parser = PhyloXmlParser.createPhyloXmlParser();
101 if ( phyloxml_validate_against_xsd ) {
102 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
103 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
104 if ( xsd_url != null ) {
105 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
108 if ( ForesterConstants.RELEASE ) {
109 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
110 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
115 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
116 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
117 parser = new NexusPhylogeniesParser();
120 parser = new NHXParser();
125 final public static PhylogenyParser createParserDependingOnFileType( final File file,
126 final boolean phyloxml_validate_against_xsd )
127 throws FileNotFoundException, IOException {
128 PhylogenyParser parser = null;
129 parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
130 if ( parser == null ) {
131 parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
133 if ( ( parser != null ) && file.toString().toLowerCase().endsWith( ".zip" ) ) {
134 if ( parser instanceof PhyloXmlParser ) {
135 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
137 else if ( parser instanceof TolParser ) {
138 ( ( TolParser ) parser ).setZippedInputstream( true );
144 final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
145 final boolean phyloxml_validate_against_xsd )
146 throws FileNotFoundException, IOException {
147 final String lc_filename = url.getFile().toString().toLowerCase();
148 PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
149 if ( parser == null ) {
150 final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
151 if ( first_line.startsWith( "<" ) ) {
152 parser = PhyloXmlParser.createPhyloXmlParser();
153 if ( phyloxml_validate_against_xsd ) {
154 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
155 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
156 if ( xsd_url != null ) {
157 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
160 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
161 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
165 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
166 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
167 parser = new NexusPhylogeniesParser();
170 parser = new NHXParser();
173 if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
174 if ( parser instanceof PhyloXmlParser ) {
175 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
177 else if ( parser instanceof TolParser ) {
178 ( ( TolParser ) parser ).setZippedInputstream( true );
184 public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
185 BufferedReader reader = null;
186 if ( ( source instanceof File ) || ( source instanceof String ) ) {
188 if ( source instanceof File ) {
192 f = new File( ( String ) source );
195 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
197 else if ( !f.isFile() ) {
198 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
200 else if ( !f.canRead() ) {
201 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
203 reader = new BufferedReader( new FileReader( f ) );
205 else if ( source instanceof InputStream ) {
206 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
208 else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
209 reader = new BufferedReader( new StringReader( source.toString() ) );
212 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
213 + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
218 public final static String extractScientificNameFromNodeName( final String name ) {
219 final Matcher m_ss = TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN.matcher( name );
221 String s = m_ss.group( 1 ).replace( '_', ' ' );
222 if ( s.indexOf( " str " ) > 4 ) {
223 s = s.replaceFirst( " str ", " str. " );
225 if ( s.indexOf( " substr " ) > 4 ) {
226 s = s.replaceFirst( " substr ", " substr. " );
230 final Matcher m_str1 = TAXOMONY_SN_PATTERN_STRAIN_1.matcher( name );
231 if ( m_str1.find() ) {
232 String s = m_str1.group( 1 ).replace( '_', ' ' );
233 if ( s.indexOf( " str " ) > 4 ) {
234 s = s.replaceFirst( " str ", " str. " );
236 else if ( s.indexOf( " subsp " ) > 4 ) {
237 s = s.replaceFirst( " subsp ", " subsp. " );
239 else if ( s.indexOf( " ssp " ) > 4 ) {
240 s = s.replaceFirst( " ssp ", " subsp. " );
242 else if ( s.indexOf( " ssp. " ) > 4 ) {
243 s = s.replaceFirst( " ssp. ", " subsp. " );
245 else if ( s.indexOf( " var " ) > 4 ) {
246 s = s.replaceFirst( " var ", " var. " );
250 final Matcher m_str2 = TAXOMONY_SN_PATTERN_STRAIN_2.matcher( name );
251 if ( m_str2.find() ) {
252 String s = m_str2.group( 1 ).replace( '_', ' ' );
253 if ( s.indexOf( " (str " ) > 4 ) {
254 s = s.replaceFirst( " \\(str ", " (str. " );
256 else if ( s.indexOf( " (subsp " ) > 4 ) {
257 s = s.replaceFirst( " \\(subsp ", " (subsp. " );
259 else if ( s.indexOf( " (ssp " ) > 4 ) {
260 s = s.replaceFirst( " \\(ssp ", " (subsp. " );
262 else if ( s.indexOf( " (ssp. " ) > 4 ) {
263 s = s.replaceFirst( " \\(ssp. ", " (subsp. " );
265 else if ( s.indexOf( " (var " ) > 4 ) {
266 s = s.replaceFirst( " \\(var ", " (var. " );
270 final Matcher m_sns = TAXOMONY_SN_PATTERN_SNS.matcher( name );
271 if ( m_sns.find() ) {
272 return m_sns.group( 1 ).replace( '_', ' ' );
274 final Matcher m_sns2 = TAXOMONY_SN_PATTERN_SNS2.matcher( name );
275 if ( m_sns2.find() ) {
276 return m_sns2.group( 1 ).replace( '_', ' ' );
278 final Matcher m_sn = TAXOMONY_SN_PATTERN_SN.matcher( name );
280 return m_sn.group( 1 ).replace( '_', ' ' );
282 final Matcher m_sp = TAXOMONY_SN_PATTERN_SP.matcher( name );
284 String s = m_sp.group( 1 ).replace( '_', ' ' );
285 if ( s.endsWith( " sp" ) ) {
293 public final static String extractTaxonomyCodeFromNodeName( final String name,
294 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
295 Matcher m = TAXOMONY_CODE_PATTERN_PFS.matcher( name );
299 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
300 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
301 m = TAXOMONY_CODE_PATTERN_PFR.matcher( name );
305 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
306 m = TAXOMONY_CODE_PATTERN_A.matcher( name );
315 public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
316 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
317 throws PhyloXmlDataFormatException {
318 if ( taxonomy_extraction == TAXONOMY_EXTRACTION.NO ) {
319 throw new IllegalArgumentException();
321 final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
322 if ( !ForesterUtil.isEmpty( id ) ) {
323 if ( !node.getNodeData().isHasTaxonomy() ) {
324 node.getNodeData().setTaxonomy( new Taxonomy() );
326 node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
330 final String code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
331 if ( !ForesterUtil.isEmpty( code ) ) {
332 if ( !node.getNodeData().isHasTaxonomy() ) {
333 node.getNodeData().setTaxonomy( new Taxonomy() );
335 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
338 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
339 final String sn = extractScientificNameFromNodeName( node.getName() );
340 if ( !ForesterUtil.isEmpty( sn ) ) {
341 if ( !node.getNodeData().isHasTaxonomy() ) {
342 node.getNodeData().setTaxonomy( new Taxonomy() );
344 node.getNodeData().getTaxonomy().setScientificName( sn );
352 public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
353 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
354 Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PFS.matcher( name );
358 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
359 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
360 m = TAXOMONY_UNIPROT_ID_PATTERN_PFR.matcher( name );
364 //else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
365 // m = TAXOMONY_UNIPROT_ID_PATTERN_A.matcher( name );
367 // return m.group( 1 );
374 public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
375 return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
378 public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
379 return readPhylogenies( new File( file_name ) );
383 * Return null if it can not guess the parser to use based on name suffix.
388 final private static PhylogenyParser createParserDependingOnSuffix( final String filename,
389 final boolean phyloxml_validate_against_xsd ) {
390 PhylogenyParser parser = null;
391 final String filename_lc = filename.toLowerCase();
392 if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
393 parser = new TolParser();
395 else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( "phyloxml" ) || filename_lc.endsWith( ".zip" ) ) {
396 parser = PhyloXmlParser.createPhyloXmlParser();
397 if ( phyloxml_validate_against_xsd ) {
398 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
399 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
400 if ( xsd_url != null ) {
401 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
404 if ( ForesterConstants.RELEASE ) {
405 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
406 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
411 else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
412 parser = new NexusPhylogeniesParser();
414 else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
415 || filename_lc.endsWith( ".nwk" ) ) {
416 parser = new NHXParser();