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.FileInputStream;
32 import java.io.FileNotFoundException;
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 private static String SN_BN = "[A-Z][a-z]{2,30}[_ ][a-z]{3,30}";
59 final public static String TAX_CODE = "(?:[A-Z0-9]{3,5})";
60 final public static String TAX_CODE_LO = "(?:[A-Z]{5})|RAT|PIG|PEA";
61 final public static Pattern TAXOMONY_CODE_PATTERN_A = Pattern.compile( "(?:\\b|_)(" + TAX_CODE
63 final public static Pattern TAXOMONY_CODE_PATTERN_A_LO = Pattern.compile( "_(" + TAX_CODE_LO
65 final public static Pattern TAXOMONY_CODE_PATTERN_BRACKETED = Pattern.compile( "\\[(" + TAX_CODE + ")\\]" );
66 final public static Pattern TAXOMONY_CODE_PATTERN_PFR = Pattern.compile( "(?:\\b|_)[a-zA-Z0-9]{3,}_("
67 + TAX_CODE + ")\\b" );
68 final public static Pattern TAXOMONY_SN_PATTERN_GENUS = Pattern.compile( "([A-Z][a-z]{2,30})" );
69 final public static Pattern TAXOMONY_SN_PATTERN_SN = Pattern.compile( "(?:\\b|_)(" + SN_BN
70 + ")(?:(\\s*$)|([_ ][a-z]*[A-Z0-9]))" );
71 final public static Pattern TAXOMONY_SN_PATTERN_SNS = Pattern.compile( "(?:\\b|_)(" + SN_BN
73 + ")[_ ][a-z]*[A-Z0-9]" );
74 final public static Pattern TAXOMONY_SN_PATTERN_SNS2 = Pattern.compile( "[A-Z0-9][a-z]*[_ ](" + SN_BN
75 + "[_ ][a-z]{3,30}" + ")\\s*$" );
76 final public static Pattern TAXOMONY_SN_PATTERN_SP = Pattern
77 .compile( "(?:\\b|_)([A-Z][a-z]{2,30}[_ ]sp\\.?)(?:\\b|_)?" );
78 final public static Pattern TAXOMONY_SN_PATTERN_STRAIN_1 = Pattern
79 .compile( "(?:\\b|_)("
81 + "[_ ](?:str|subsp|ssp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60})(?:\\b|_)" );
82 final public static Pattern TAXOMONY_SN_PATTERN_STRAIN_2 = Pattern
83 .compile( "(?:\\b|_)("
85 + "[_ ]\\((?:str|subsp|ssp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60}\\))" );
86 final public static Pattern TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN = Pattern
87 .compile( "(?:\\b|_)("
89 + "[_ ]str[a-z]{0,3}\\.?[_ ]\\S{1,60}[_ ]substr[a-z]{0,3}\\.?[_ ]\\S{1,60})(?:\\b|_)" );
90 final private static Pattern TAXOMONY_CODE_PATTERN_PFS = Pattern.compile( "(?:\\b|_)[A-Z0-9]{4,}_("
91 + TAX_CODE + ")/\\d+-\\d+\\b" );
92 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFR = Pattern
93 .compile( "(?:\\b|_)[A-Z0-9]{1,}_(\\d{1,7})\\b" );
94 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFS = Pattern
95 .compile( "(?:\\b|_)[A-Z0-9]{4,}_(\\d{1,7})/\\d+-\\d+\\b" );
97 final public static PhylogenyParser createParserDependingFileContents( final File file,
98 final boolean phyloxml_validate_against_xsd )
99 throws FileNotFoundException, IOException {
100 PhylogenyParser parser = null;
101 final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
102 if ( first_line.startsWith( "<" ) ) {
103 parser = PhyloXmlParser.createPhyloXmlParser();
104 if ( phyloxml_validate_against_xsd ) {
105 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
106 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
107 if ( xsd_url != null ) {
108 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
111 if ( ForesterConstants.RELEASE ) {
112 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
113 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
118 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
119 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
120 parser = new NexusPhylogeniesParser();
123 parser = new NHXParser();
128 final public static PhylogenyParser createParserDependingOnFileType( final File file,
129 final boolean phyloxml_validate_against_xsd )
130 throws FileNotFoundException, IOException {
131 PhylogenyParser parser = null;
132 parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
133 if ( parser == null ) {
134 parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
136 if ( ( parser != null ) && file.toString().toLowerCase().endsWith( ".zip" ) ) {
137 if ( parser instanceof PhyloXmlParser ) {
138 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
140 else if ( parser instanceof TolParser ) {
141 ( ( TolParser ) parser ).setZippedInputstream( true );
147 final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
148 final boolean phyloxml_validate_against_xsd )
149 throws FileNotFoundException, IOException {
150 final String lc_filename = url.getFile().toString().toLowerCase();
151 PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
152 if ( parser == null ) {
153 final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
154 if ( first_line.startsWith( "<" ) ) {
155 parser = PhyloXmlParser.createPhyloXmlParser();
156 if ( phyloxml_validate_against_xsd ) {
157 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
158 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
159 if ( xsd_url != null ) {
160 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
163 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
164 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
168 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
169 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
170 parser = new NexusPhylogeniesParser();
173 parser = new NHXParser();
176 if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
177 if ( parser instanceof PhyloXmlParser ) {
178 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
180 else if ( parser instanceof TolParser ) {
181 ( ( TolParser ) parser ).setZippedInputstream( true );
187 public static BufferedReader createReader( final Object source, final String encoding ) throws IOException, FileNotFoundException {
188 BufferedReader reader = null;
189 if ( ( source instanceof File ) || ( source instanceof String ) ) {
191 if ( source instanceof File ) {
195 f = new File( ( String ) source );
198 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
200 else if ( !f.isFile() ) {
201 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
203 else if ( !f.canRead() ) {
204 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
206 final InputStream is = new FileInputStream( f );
207 final InputStreamReader isr = new InputStreamReader( is, encoding );
208 reader = new BufferedReader( isr );
210 else if ( source instanceof InputStream ) {
211 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source, encoding ) );
213 else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
214 reader = new BufferedReader( new StringReader( source.toString() ) );
217 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
218 + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
223 public final static String extractScientificNameFromNodeName( final String name ) {
224 final Matcher m_ss = TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN.matcher( name );
226 String s = m_ss.group( 1 ).replace( '_', ' ' );
227 if ( s.indexOf( " str " ) > 4 ) {
228 s = s.replaceFirst( " str ", " str. " );
230 if ( s.indexOf( " substr " ) > 4 ) {
231 s = s.replaceFirst( " substr ", " substr. " );
235 final Matcher m_str1 = TAXOMONY_SN_PATTERN_STRAIN_1.matcher( name );
236 if ( m_str1.find() ) {
237 String s = m_str1.group( 1 ).replace( '_', ' ' );
238 if ( s.indexOf( " str " ) > 4 ) {
239 s = s.replaceFirst( " str ", " str. " );
241 else if ( s.indexOf( " subsp " ) > 4 ) {
242 s = s.replaceFirst( " subsp ", " subsp. " );
244 else if ( s.indexOf( " ssp " ) > 4 ) {
245 s = s.replaceFirst( " ssp ", " subsp. " );
247 else if ( s.indexOf( " ssp. " ) > 4 ) {
248 s = s.replaceFirst( " ssp. ", " subsp. " );
250 else if ( s.indexOf( " var " ) > 4 ) {
251 s = s.replaceFirst( " var ", " var. " );
255 final Matcher m_str2 = TAXOMONY_SN_PATTERN_STRAIN_2.matcher( name );
256 if ( m_str2.find() ) {
257 String s = m_str2.group( 1 ).replace( '_', ' ' );
258 if ( s.indexOf( " (str " ) > 4 ) {
259 s = s.replaceFirst( " \\(str ", " (str. " );
261 else if ( s.indexOf( " (subsp " ) > 4 ) {
262 s = s.replaceFirst( " \\(subsp ", " (subsp. " );
264 else if ( s.indexOf( " (ssp " ) > 4 ) {
265 s = s.replaceFirst( " \\(ssp ", " (subsp. " );
267 else if ( s.indexOf( " (ssp. " ) > 4 ) {
268 s = s.replaceFirst( " \\(ssp. ", " (subsp. " );
270 else if ( s.indexOf( " (var " ) > 4 ) {
271 s = s.replaceFirst( " \\(var ", " (var. " );
275 final Matcher m_sns = TAXOMONY_SN_PATTERN_SNS.matcher( name );
276 if ( m_sns.find() ) {
277 return m_sns.group( 1 ).replace( '_', ' ' );
279 final Matcher m_sns2 = TAXOMONY_SN_PATTERN_SNS2.matcher( name );
280 if ( m_sns2.find() ) {
281 return m_sns2.group( 1 ).replace( '_', ' ' );
283 final Matcher m_sn = TAXOMONY_SN_PATTERN_SN.matcher( name );
285 return m_sn.group( 1 ).replace( '_', ' ' );
287 final Matcher m_sp = TAXOMONY_SN_PATTERN_SP.matcher( name );
289 String s = m_sp.group( 1 ).replace( '_', ' ' );
290 if ( s.endsWith( " sp" ) ) {
298 public final static String extractTaxonomyCodeFromNodeName( final String name,
299 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
300 Matcher m = TAXOMONY_CODE_PATTERN_PFS.matcher( name );
304 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
305 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
306 m = TAXOMONY_CODE_PATTERN_PFR.matcher( name );
310 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
311 m = TAXOMONY_CODE_PATTERN_A.matcher( name );
320 public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
321 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
322 throws PhyloXmlDataFormatException {
323 if ( taxonomy_extraction == TAXONOMY_EXTRACTION.NO ) {
324 throw new IllegalArgumentException();
326 final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
327 if ( !ForesterUtil.isEmpty( id ) ) {
328 if ( !node.getNodeData().isHasTaxonomy() ) {
329 node.getNodeData().setTaxonomy( new Taxonomy() );
331 node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
336 if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
337 code = extractTaxonomyCodeFromNodeNameLettersOnly( node.getName() );
338 if ( ForesterUtil.isEmpty( code ) ) {
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 );
349 if ( ForesterUtil.isEmpty( code ) ) {
350 code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
352 if ( !ForesterUtil.isEmpty( code ) ) {
353 if ( !node.getNodeData().isHasTaxonomy() ) {
354 node.getNodeData().setTaxonomy( new Taxonomy() );
356 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
363 public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
364 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
365 Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PFS.matcher( name );
369 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
370 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
371 m = TAXOMONY_UNIPROT_ID_PATTERN_PFR.matcher( name );
379 public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
380 return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
383 public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
384 return readPhylogenies( new File( file_name ) );
388 * Return null if it can not guess the parser to use based on name suffix.
393 final private static PhylogenyParser createParserDependingOnSuffix( final String filename,
394 final boolean phyloxml_validate_against_xsd ) {
395 PhylogenyParser parser = null;
396 final String filename_lc = filename.toLowerCase();
397 if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
398 parser = new TolParser();
400 else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( "phyloxml" ) || filename_lc.endsWith( ".zip" ) ) {
401 parser = PhyloXmlParser.createPhyloXmlParser();
402 if ( phyloxml_validate_against_xsd ) {
403 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
404 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
405 if ( xsd_url != null ) {
406 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
409 if ( ForesterConstants.RELEASE ) {
410 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
411 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
416 else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
417 parser = new NexusPhylogeniesParser();
419 else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
420 || filename_lc.endsWith( ".nwk" ) ) {
421 parser = new NHXParser();
426 private final static String extractTaxonomyCodeFromNodeNameLettersOnly( final String name ) {
427 final Matcher m = TAXOMONY_CODE_PATTERN_A_LO.matcher( name );