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 = Pattern
66 // .compile( "(?:\\b|_)[a-zA-Z0-9]{3,}_([A-Z][a-z]{2,30}_[a-z]{3,30}(?:_[a-z][a-z0-9_]+)?)\\b" );
67 final public static Pattern TAXOMONY_SN_PATTERN_SN = Pattern.compile( "(?:\\b|_)(" + SN_BN
68 + ")(?:(\\s*$)|([_ ][a-z]*[A-Z0-9]))" );
69 final public static Pattern TAXOMONY_SN_PATTERN_SNS = Pattern.compile( "(?:\\b|_)(" + SN_BN
71 + ")[_ ][a-z]*[A-Z0-9]" );
72 final public static Pattern TAXOMONY_SN_PATTERN_SNS2 = Pattern.compile( "[A-Z0-9][a-z]*[_ ](" + SN_BN
73 + "[_ ][a-z]{3,30}" + ")\\s*$" );
74 final public static Pattern TAXOMONY_SN_PATTERN_STRAIN_1 = Pattern
75 .compile( "(?:\\b|_)("
77 + "[_ ](?:str|subsp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60})(?:\\b|_)" );
78 final public static Pattern TAXOMONY_SN_PATTERN_STRAIN_2 = Pattern
79 .compile( "(?:\\b|_)("
81 + "[_ ]\\((?:str|subsp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60}\\))" );
82 final public static Pattern TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN = Pattern
83 .compile( "(?:\\b|_)("
85 + "[_ ]str[a-z]{0,3}\\.?[_ ]\\S{1,60}[_ ]substr[a-z]{0,3}\\.?[_ ]\\S{1,60})(?:\\b|_)" );
86 final public static Pattern TAXOMONY_SN_PATTERN_SP = Pattern
87 .compile( "(?:\\b|_)([A-Z][a-z]{2,30}[_ ]sp\\.?)(?:\\b|_)?" );
88 final public static Pattern TAXOMONY_SN_PATTERN_GENUS = Pattern.compile( "([A-Z][a-z]{2,30})" );
89 final private static Pattern TAXOMONY_CODE_PATTERN_PFS = Pattern.compile( "(?:\\b|_)[A-Z0-9]{4,}_("
90 + TAX_CODE + ")/\\d+-\\d+\\b" );
91 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFR = Pattern
92 .compile( "(?:\\b|_)[A-Z0-9]{1,}_(\\d{1,7})\\b" );
93 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFS = Pattern
94 .compile( "(?:\\b|_)[A-Z0-9]{4,}_(\\d{1,7})/\\d+-\\d+\\b" );
96 final public static PhylogenyParser createParserDependingFileContents( final File file,
97 final boolean phyloxml_validate_against_xsd )
98 throws FileNotFoundException, IOException {
99 PhylogenyParser parser = null;
100 final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
101 if ( first_line.startsWith( "<" ) ) {
102 parser = PhyloXmlParser.createPhyloXmlParser();
103 if ( phyloxml_validate_against_xsd ) {
104 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
105 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
106 if ( xsd_url != null ) {
107 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
110 if ( ForesterConstants.RELEASE ) {
111 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
112 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
117 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
118 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
119 parser = new NexusPhylogeniesParser();
122 parser = new NHXParser();
127 final public static PhylogenyParser createParserDependingOnFileType( final File file,
128 final boolean phyloxml_validate_against_xsd )
129 throws FileNotFoundException, IOException {
130 PhylogenyParser parser = null;
131 parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
132 if ( parser == null ) {
133 parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
135 if ( ( parser != null ) && file.toString().toLowerCase().endsWith( ".zip" ) ) {
136 if ( parser instanceof PhyloXmlParser ) {
137 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
139 else if ( parser instanceof TolParser ) {
140 ( ( TolParser ) parser ).setZippedInputstream( true );
146 final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
147 final boolean phyloxml_validate_against_xsd )
148 throws FileNotFoundException, IOException {
149 final String lc_filename = url.getFile().toString().toLowerCase();
150 PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
151 if ( parser == null ) {
152 final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
153 if ( first_line.startsWith( "<" ) ) {
154 parser = PhyloXmlParser.createPhyloXmlParser();
155 if ( phyloxml_validate_against_xsd ) {
156 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
157 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
158 if ( xsd_url != null ) {
159 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
162 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
163 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
167 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
168 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
169 parser = new NexusPhylogeniesParser();
172 parser = new NHXParser();
175 if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
176 if ( parser instanceof PhyloXmlParser ) {
177 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
179 else if ( parser instanceof TolParser ) {
180 ( ( TolParser ) parser ).setZippedInputstream( true );
186 public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
187 BufferedReader reader = null;
188 if ( ( source instanceof File ) || ( source instanceof String ) ) {
190 if ( source instanceof File ) {
194 f = new File( ( String ) source );
197 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
199 else if ( !f.isFile() ) {
200 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
202 else if ( !f.canRead() ) {
203 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
205 reader = new BufferedReader( new FileReader( f ) );
207 else if ( source instanceof InputStream ) {
208 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
210 else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
211 reader = new BufferedReader( new StringReader( source.toString() ) );
214 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
215 + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
220 public final static String extractScientificNameFromNodeName( final String name ) {
221 // final Matcher m = TAXOMONY_SN_PATTERN.matcher( name );
223 // return m.group( 1 ).replace( '_', ' ' );
225 final Matcher m_ss = TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN.matcher( name );
227 String s = m_ss.group( 1 ).replace( '_', ' ' );
228 if ( s.indexOf( " str " ) > 4 ) {
229 s = s.replaceFirst( " str ", " str. " );
231 if ( s.indexOf( " substr " ) > 4 ) {
232 s = s.replaceFirst( " substr ", " substr. " );
236 final Matcher m_str1 = TAXOMONY_SN_PATTERN_STRAIN_1.matcher( name );
237 if ( m_str1.find() ) {
238 String s = m_str1.group( 1 ).replace( '_', ' ' );
239 if ( s.indexOf( " str " ) > 4 ) {
240 s = s.replaceFirst( " str ", " str. " );
242 else if ( s.indexOf( " subsp " ) > 4 ) {
243 s = s.replaceFirst( " subsp ", " 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( " (var " ) > 4 ) {
260 s = s.replaceFirst( " \\(var ", " (var. " );
264 final Matcher m_sns = TAXOMONY_SN_PATTERN_SNS.matcher( name );
265 if ( m_sns.find() ) {
266 return m_sns.group( 1 ).replace( '_', ' ' );
268 final Matcher m_sns2 = TAXOMONY_SN_PATTERN_SNS2.matcher( name );
269 if ( m_sns2.find() ) {
270 return m_sns2.group( 1 ).replace( '_', ' ' );
272 final Matcher m_sn = TAXOMONY_SN_PATTERN_SN.matcher( name );
274 return m_sn.group( 1 ).replace( '_', ' ' );
276 final Matcher m_sp = TAXOMONY_SN_PATTERN_SP.matcher( name );
278 return m_sp.group( 1 ).replace( '_', ' ' );
283 public final static String extractTaxonomyCodeFromNodeName( final String name,
284 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
285 Matcher m = TAXOMONY_CODE_PATTERN_PFS.matcher( name );
289 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
290 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
291 m = TAXOMONY_CODE_PATTERN_PFR.matcher( name );
295 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
296 m = TAXOMONY_CODE_PATTERN_A.matcher( name );
305 public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
306 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
307 throws PhyloXmlDataFormatException {
308 if ( taxonomy_extraction == TAXONOMY_EXTRACTION.NO ) {
309 throw new IllegalArgumentException();
311 final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
312 if ( !ForesterUtil.isEmpty( id ) ) {
313 if ( !node.getNodeData().isHasTaxonomy() ) {
314 node.getNodeData().setTaxonomy( new Taxonomy() );
316 node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
320 final String code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
321 if ( !ForesterUtil.isEmpty( code ) ) {
322 if ( !node.getNodeData().isHasTaxonomy() ) {
323 node.getNodeData().setTaxonomy( new Taxonomy() );
325 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
328 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
329 final String sn = extractScientificNameFromNodeName( node.getName() );
330 if ( !ForesterUtil.isEmpty( sn ) ) {
331 if ( !node.getNodeData().isHasTaxonomy() ) {
332 node.getNodeData().setTaxonomy( new Taxonomy() );
334 node.getNodeData().getTaxonomy().setScientificName( sn );
342 public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
343 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
344 Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PFS.matcher( name );
348 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
349 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
350 m = TAXOMONY_UNIPROT_ID_PATTERN_PFR.matcher( name );
354 //else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
355 // m = TAXOMONY_UNIPROT_ID_PATTERN_A.matcher( name );
357 // return m.group( 1 );
364 public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
365 return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
368 public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
369 return readPhylogenies( new File( file_name ) );
373 * Return null if it can not guess the parser to use based on name suffix.
378 final private static PhylogenyParser createParserDependingOnSuffix( final String filename,
379 final boolean phyloxml_validate_against_xsd ) {
380 PhylogenyParser parser = null;
381 final String filename_lc = filename.toLowerCase();
382 if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
383 parser = new TolParser();
385 else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( "phyloxml" ) || filename_lc.endsWith( ".zip" ) ) {
386 parser = PhyloXmlParser.createPhyloXmlParser();
387 if ( phyloxml_validate_against_xsd ) {
388 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
389 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
390 if ( xsd_url != null ) {
391 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
394 if ( ForesterConstants.RELEASE ) {
395 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
396 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
401 else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
402 parser = new NexusPhylogeniesParser();
404 else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
405 || filename_lc.endsWith( ".nwk" ) ) {
406 parser = new NHXParser();