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 private static String SN_BN = "[A-Z][a-z]{2,30}[_ ][a-z]{3,30}";
59 final public static String TAX_CODE = "(?:[A-Z9][A-Z]{2}[A-Z0-9]{2})|RAT|PIG|PEA";
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 ) 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 reader = new BufferedReader( new FileReader( f ) );
208 else if ( source instanceof InputStream ) {
209 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
211 else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
212 reader = new BufferedReader( new StringReader( source.toString() ) );
215 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
216 + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
221 public final static String extractScientificNameFromNodeName( final String name ) {
222 final Matcher m_ss = TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN.matcher( name );
224 String s = m_ss.group( 1 ).replace( '_', ' ' );
225 if ( s.indexOf( " str " ) > 4 ) {
226 s = s.replaceFirst( " str ", " str. " );
228 if ( s.indexOf( " substr " ) > 4 ) {
229 s = s.replaceFirst( " substr ", " substr. " );
233 final Matcher m_str1 = TAXOMONY_SN_PATTERN_STRAIN_1.matcher( name );
234 if ( m_str1.find() ) {
235 String s = m_str1.group( 1 ).replace( '_', ' ' );
236 if ( s.indexOf( " str " ) > 4 ) {
237 s = s.replaceFirst( " str ", " str. " );
239 else if ( s.indexOf( " subsp " ) > 4 ) {
240 s = s.replaceFirst( " subsp ", " subsp. " );
242 else if ( s.indexOf( " ssp " ) > 4 ) {
243 s = s.replaceFirst( " ssp ", " subsp. " );
245 else if ( s.indexOf( " ssp. " ) > 4 ) {
246 s = s.replaceFirst( " ssp. ", " subsp. " );
248 else if ( s.indexOf( " var " ) > 4 ) {
249 s = s.replaceFirst( " var ", " var. " );
253 final Matcher m_str2 = TAXOMONY_SN_PATTERN_STRAIN_2.matcher( name );
254 if ( m_str2.find() ) {
255 String s = m_str2.group( 1 ).replace( '_', ' ' );
256 if ( s.indexOf( " (str " ) > 4 ) {
257 s = s.replaceFirst( " \\(str ", " (str. " );
259 else if ( s.indexOf( " (subsp " ) > 4 ) {
260 s = s.replaceFirst( " \\(subsp ", " (subsp. " );
262 else if ( s.indexOf( " (ssp " ) > 4 ) {
263 s = s.replaceFirst( " \\(ssp ", " (subsp. " );
265 else if ( s.indexOf( " (ssp. " ) > 4 ) {
266 s = s.replaceFirst( " \\(ssp. ", " (subsp. " );
268 else if ( s.indexOf( " (var " ) > 4 ) {
269 s = s.replaceFirst( " \\(var ", " (var. " );
273 final Matcher m_sns = TAXOMONY_SN_PATTERN_SNS.matcher( name );
274 if ( m_sns.find() ) {
275 return m_sns.group( 1 ).replace( '_', ' ' );
277 final Matcher m_sns2 = TAXOMONY_SN_PATTERN_SNS2.matcher( name );
278 if ( m_sns2.find() ) {
279 return m_sns2.group( 1 ).replace( '_', ' ' );
281 final Matcher m_sn = TAXOMONY_SN_PATTERN_SN.matcher( name );
283 return m_sn.group( 1 ).replace( '_', ' ' );
285 final Matcher m_sp = TAXOMONY_SN_PATTERN_SP.matcher( name );
287 String s = m_sp.group( 1 ).replace( '_', ' ' );
288 if ( s.endsWith( " sp" ) ) {
296 public final static String extractTaxonomyCodeFromNodeName( final String name,
297 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
298 Matcher m = TAXOMONY_CODE_PATTERN_PFS.matcher( name );
302 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
303 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
304 m = TAXOMONY_CODE_PATTERN_PFR.matcher( name );
308 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
309 m = TAXOMONY_CODE_PATTERN_A.matcher( name );
318 public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
319 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
320 throws PhyloXmlDataFormatException {
321 if ( taxonomy_extraction == TAXONOMY_EXTRACTION.NO ) {
322 throw new IllegalArgumentException();
324 final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
325 if ( !ForesterUtil.isEmpty( id ) ) {
326 if ( !node.getNodeData().isHasTaxonomy() ) {
327 node.getNodeData().setTaxonomy( new Taxonomy() );
329 node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
334 if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
335 code = extractTaxonomyCodeFromNodeNameLettersOnly( node.getName() );
336 if ( ForesterUtil.isEmpty( code ) ) {
337 final String sn = extractScientificNameFromNodeName( node.getName() );
338 if ( !ForesterUtil.isEmpty( sn ) ) {
339 if ( !node.getNodeData().isHasTaxonomy() ) {
340 node.getNodeData().setTaxonomy( new Taxonomy() );
342 node.getNodeData().getTaxonomy().setScientificName( sn );
347 if ( ForesterUtil.isEmpty( code ) ) {
348 code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
350 if ( !ForesterUtil.isEmpty( code ) ) {
351 if ( !node.getNodeData().isHasTaxonomy() ) {
352 node.getNodeData().setTaxonomy( new Taxonomy() );
354 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
361 public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
362 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
363 Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PFS.matcher( name );
367 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
368 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
369 m = TAXOMONY_UNIPROT_ID_PATTERN_PFR.matcher( name );
377 public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
378 return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
381 public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
382 return readPhylogenies( new File( file_name ) );
386 * Return null if it can not guess the parser to use based on name suffix.
391 final private static PhylogenyParser createParserDependingOnSuffix( final String filename,
392 final boolean phyloxml_validate_against_xsd ) {
393 PhylogenyParser parser = null;
394 final String filename_lc = filename.toLowerCase();
395 if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
396 parser = new TolParser();
398 else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( "phyloxml" ) || filename_lc.endsWith( ".zip" ) ) {
399 parser = PhyloXmlParser.createPhyloXmlParser();
400 if ( phyloxml_validate_against_xsd ) {
401 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
402 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
403 if ( xsd_url != null ) {
404 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
407 if ( ForesterConstants.RELEASE ) {
408 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
409 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
414 else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
415 parser = new NexusPhylogeniesParser();
417 else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
418 || filename_lc.endsWith( ".nwk" ) ) {
419 parser = new NHXParser();
424 private final static String extractTaxonomyCodeFromNodeNameLettersOnly( final String name ) {
425 final Matcher m = TAXOMONY_CODE_PATTERN_A_LO.matcher( name );