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 public static Pattern TAXOMONY_CODE_PATTERN_A = Pattern.compile( "(?:\\b|_)(" + TAX_CODE + ")\\b" );
60 final public static Pattern TAXOMONY_CODE_PATTERN_BRACKETED = Pattern.compile( "\\[(" + TAX_CODE + ")\\]" );
61 final public static Pattern TAXOMONY_CODE_PATTERN_PFR = Pattern.compile( "(?:\\b|_)[a-zA-Z0-9]{3,}_("
62 + TAX_CODE + ")\\b" );
63 final public static Pattern TAXOMONY_SN_PATTERN = Pattern
64 .compile( "(?:\\b|_)[a-zA-Z0-9]{3,}_([A-Z][a-z]+_[a-z]{2,}(?:_[a-z][a-z0-9_]+)?)\\b" );
65 final private static Pattern TAXOMONY_CODE_PATTERN_PFS = Pattern.compile( "(?:\\b|_)[A-Z0-9]{4,}_("
66 + TAX_CODE + ")/\\d+-\\d+\\b" );
67 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_A = Pattern.compile( "(?:\\b|_)(\\d{1,7})\\b" );
68 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFR = Pattern
69 .compile( "(?:\\b|_)[a-zA-Z0-9]{3,}_(\\d{1,7})\\b" );
70 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFS = Pattern
71 .compile( "(?:\\b|_)[A-Z0-9]{4,}_(\\d{1,7})/\\d+-\\d+\\b" );
73 final public static PhylogenyParser createParserDependingFileContents( final File file,
74 final boolean phyloxml_validate_against_xsd )
75 throws FileNotFoundException, IOException {
76 PhylogenyParser parser = null;
77 final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
78 if ( first_line.startsWith( "<" ) ) {
79 parser = PhyloXmlParser.createPhyloXmlParser();
80 if ( phyloxml_validate_against_xsd ) {
81 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
82 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
83 if ( xsd_url != null ) {
84 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
87 if ( ForesterConstants.RELEASE ) {
88 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
89 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
94 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
95 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
96 parser = new NexusPhylogeniesParser();
99 parser = new NHXParser();
104 final public static PhylogenyParser createParserDependingOnFileType( final File file,
105 final boolean phyloxml_validate_against_xsd )
106 throws FileNotFoundException, IOException {
107 PhylogenyParser parser = null;
108 parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
109 if ( parser == null ) {
110 parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
112 if ( ( parser != null ) && file.toString().toLowerCase().endsWith( ".zip" ) ) {
113 if ( parser instanceof PhyloXmlParser ) {
114 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
116 else if ( parser instanceof TolParser ) {
117 ( ( TolParser ) parser ).setZippedInputstream( true );
123 final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
124 final boolean phyloxml_validate_against_xsd )
125 throws FileNotFoundException, IOException {
126 final String lc_filename = url.getFile().toString().toLowerCase();
127 PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
128 if ( parser == null ) {
129 final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
130 if ( first_line.startsWith( "<" ) ) {
131 parser = PhyloXmlParser.createPhyloXmlParser();
132 if ( phyloxml_validate_against_xsd ) {
133 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
134 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
135 if ( xsd_url != null ) {
136 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
139 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
140 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
144 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
145 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
146 parser = new NexusPhylogeniesParser();
149 parser = new NHXParser();
152 if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
153 if ( parser instanceof PhyloXmlParser ) {
154 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
156 else if ( parser instanceof TolParser ) {
157 ( ( TolParser ) parser ).setZippedInputstream( true );
163 public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
164 BufferedReader reader = null;
165 if ( ( source instanceof File ) || ( source instanceof String ) ) {
167 if ( source instanceof File ) {
171 f = new File( ( String ) source );
174 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
176 else if ( !f.isFile() ) {
177 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
179 else if ( !f.canRead() ) {
180 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
182 reader = new BufferedReader( new FileReader( f ) );
184 else if ( source instanceof InputStream ) {
185 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
187 else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
188 reader = new BufferedReader( new StringReader( source.toString() ) );
191 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
192 + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
197 public final static String extractScientificNameFromNodeName( final String name ) {
198 final Matcher m = TAXOMONY_SN_PATTERN.matcher( name );
200 return m.group( 1 ).replace( '_', ' ' );
205 public final static String extractTaxonomyCodeFromNodeName( final String name,
206 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
207 Matcher m = TAXOMONY_CODE_PATTERN_PFS.matcher( name );
211 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
212 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
213 m = TAXOMONY_CODE_PATTERN_PFR.matcher( name );
217 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
218 m = TAXOMONY_CODE_PATTERN_A.matcher( name );
227 public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
228 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
229 throws PhyloXmlDataFormatException {
230 if ( taxonomy_extraction == TAXONOMY_EXTRACTION.NO ) {
231 throw new IllegalArgumentException();
233 final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
234 if ( !ForesterUtil.isEmpty( id ) ) {
235 if ( !node.getNodeData().isHasTaxonomy() ) {
236 node.getNodeData().setTaxonomy( new Taxonomy() );
238 node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
242 final String code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
243 if ( !ForesterUtil.isEmpty( code ) ) {
244 if ( !node.getNodeData().isHasTaxonomy() ) {
245 node.getNodeData().setTaxonomy( new Taxonomy() );
247 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
250 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
251 final String sn = extractScientificNameFromNodeName( node.getName() );
252 if ( !ForesterUtil.isEmpty( sn ) ) {
253 if ( !node.getNodeData().isHasTaxonomy() ) {
254 node.getNodeData().setTaxonomy( new Taxonomy() );
256 node.getNodeData().getTaxonomy().setScientificName( sn );
264 public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
265 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
266 Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PFS.matcher( name );
270 else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
271 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
272 m = TAXOMONY_UNIPROT_ID_PATTERN_PFR.matcher( name );
276 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
277 m = TAXOMONY_UNIPROT_ID_PATTERN_A.matcher( name );
286 public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
287 return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
290 public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
291 return readPhylogenies( new File( file_name ) );
295 * Return null if it can not guess the parser to use based on name suffix.
300 final private static PhylogenyParser createParserDependingOnSuffix( final String filename,
301 final boolean phyloxml_validate_against_xsd ) {
302 PhylogenyParser parser = null;
303 final String filename_lc = filename.toLowerCase();
304 if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
305 parser = new TolParser();
307 else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( "phyloxml" ) || filename_lc.endsWith( ".zip" ) ) {
308 parser = PhyloXmlParser.createPhyloXmlParser();
309 if ( phyloxml_validate_against_xsd ) {
310 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
311 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
312 if ( xsd_url != null ) {
313 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
316 if ( ForesterConstants.RELEASE ) {
317 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
318 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
323 else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
324 parser = new NexusPhylogeniesParser();
326 else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
327 || filename_lc.endsWith( ".nwk" ) ) {
328 parser = new NHXParser();