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 Pattern TAXOMONY_SN_PATTERN = Pattern
59 .compile( "[^_]{2,}_([A-Z][a-z]+_[a-z]{2,}(_[A-Za-z]\\w+|))\\b" );
60 final public static Pattern TAXOMONY_CODE_PATTERN_1 = Pattern.compile( "\\b[A-Z0-9]{5}|RAT|PIG|PEA|CAP\\b" );
61 final private static Pattern TAXOMONY_CODE_PATTERN_2 = Pattern
62 .compile( "([A-Z0-9]{5}|RAT|PIG|PEA|CAP)[^0-9A-Za-z].*" );
63 final private static Pattern TAXOMONY_CODE_PATTERN_PF = Pattern
64 .compile( "([A-Z0-9]{5}|RAT|PIG|PEA|CAP)/\\d+-\\d+" );
65 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_1 = Pattern.compile( "\\b\\d{1,7}\\b" );
66 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_2 = Pattern.compile( "(\\d{1,7})[^0-9A-Za-z].*" );
67 final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PF = Pattern.compile( "(\\d{1,7})/\\d+-\\d+" );
69 final public static PhylogenyParser createParserDependingFileContents( final File file,
70 final boolean phyloxml_validate_against_xsd )
71 throws FileNotFoundException, IOException {
72 PhylogenyParser parser = null;
73 final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
74 if ( first_line.startsWith( "<" ) ) {
75 parser = new PhyloXmlParser();
76 if ( phyloxml_validate_against_xsd ) {
77 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
78 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
79 if ( xsd_url != null ) {
80 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
83 if ( ForesterConstants.RELEASE ) {
84 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
85 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
90 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
91 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
92 parser = new NexusPhylogeniesParser();
95 parser = new NHXParser();
100 final public static PhylogenyParser createParserDependingOnFileType( final File file,
101 final boolean phyloxml_validate_against_xsd )
102 throws FileNotFoundException, IOException {
103 PhylogenyParser parser = null;
104 parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
105 if ( parser == null ) {
106 parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
112 * Return null if it can not guess the parser to use based on name suffix.
117 final public static PhylogenyParser createParserDependingOnSuffix( final String filename,
118 final boolean phyloxml_validate_against_xsd ) {
119 PhylogenyParser parser = null;
120 final String filename_lc = filename.toLowerCase();
121 if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
122 parser = new TolParser();
124 else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( ".px" ) || filename_lc.endsWith( "phyloxml" )
125 || filename_lc.endsWith( ".zip" ) ) {
126 parser = new PhyloXmlParser();
127 if ( phyloxml_validate_against_xsd ) {
128 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
129 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
130 if ( xsd_url != null ) {
131 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
134 if ( ForesterConstants.RELEASE ) {
135 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
136 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
141 else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
142 parser = new NexusPhylogeniesParser();
144 else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
145 || filename_lc.endsWith( ".nwk" ) ) {
146 parser = new NHXParser();
151 final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
152 final boolean phyloxml_validate_against_xsd )
153 throws FileNotFoundException, IOException {
154 final String lc_filename = url.getFile().toString().toLowerCase();
155 PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
156 if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
157 if ( parser instanceof PhyloXmlParser ) {
158 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
160 else if ( parser instanceof TolParser ) {
161 ( ( TolParser ) parser ).setZippedInputstream( true );
164 if ( parser == null ) {
165 final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
166 if ( first_line.startsWith( "<" ) ) {
167 parser = new PhyloXmlParser();
168 if ( phyloxml_validate_against_xsd ) {
169 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
170 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
171 if ( xsd_url != null ) {
172 ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
175 throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
176 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
180 else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
181 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
182 parser = new NexusPhylogeniesParser();
185 parser = new NHXParser();
191 public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
192 BufferedReader reader = null;
193 if ( ( source instanceof File ) || ( source instanceof String ) ) {
195 if ( source instanceof File ) {
199 f = new File( ( String ) source );
202 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
204 else if ( !f.isFile() ) {
205 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
207 else if ( !f.canRead() ) {
208 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
210 reader = new BufferedReader( new FileReader( f ) );
212 else if ( source instanceof InputStream ) {
213 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
215 else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
216 reader = new BufferedReader( new StringReader( source.toString() ) );
219 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
220 + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
225 public final static String extractTaxonomyCodeFromNodeName( final String name,
226 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
227 if ( ( name.indexOf( "_" ) > 0 )
228 && ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY ) || ( name.indexOf( "/" ) > 4 ) ) ) {
229 final String[] s = name.split( "[_\\s]" );
230 if ( s.length > 1 ) {
231 final String str = s[ 1 ];
232 if ( !ForesterUtil.isEmpty( str ) ) {
233 if ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY ) {
234 final Matcher m = TAXOMONY_CODE_PATTERN_PF.matcher( str );
240 final Matcher m1 = TAXOMONY_CODE_PATTERN_1.matcher( str );
241 if ( m1.matches() ) {
244 final Matcher m2 = TAXOMONY_CODE_PATTERN_2.matcher( str );
245 if ( m2.matches() ) {
246 return m2.group( 1 );
252 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.YES ) {
253 final Matcher m1 = TAXOMONY_CODE_PATTERN_1.matcher( name );
254 if ( m1.matches() ) {
261 public final static String extractScientificNameFromNodeName( final String name ) {
262 final Matcher m1 = TAXOMONY_SN_PATTERN.matcher( name );
263 if ( m1.matches() ) {
264 return m1.group( 1 ).replace( '_', ' ' );
269 public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
270 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
271 throws PhyloXmlDataFormatException {
272 final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
273 if ( !ForesterUtil.isEmpty( id ) ) {
274 if ( !node.getNodeData().isHasTaxonomy() ) {
275 node.getNodeData().setTaxonomy( new Taxonomy() );
277 if ( ( node.getNodeData().getTaxonomy().getIdentifier() == null )
278 || ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getIdentifier().getValue() ) ) {
279 node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
284 final String code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
285 if ( !ForesterUtil.isEmpty( code ) ) {
286 if ( !node.getNodeData().isHasTaxonomy() ) {
287 node.getNodeData().setTaxonomy( new Taxonomy() );
289 if ( ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
290 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
294 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.YES ) {
295 final String sn = extractScientificNameFromNodeName( node.getName() );
296 if ( !ForesterUtil.isEmpty( sn ) ) {
297 if ( !node.getNodeData().isHasTaxonomy() ) {
298 node.getNodeData().setTaxonomy( new Taxonomy() );
300 if ( ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
301 node.getNodeData().getTaxonomy().setScientificName( sn );
310 public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
311 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
312 if ( ( name.indexOf( "_" ) > 0 )
313 && ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY ) || ( name.indexOf( "/" ) > 4 ) ) ) {
314 final String[] s = name.split( "[_\\s]" );
315 if ( s.length > 1 ) {
316 final String str = s[ 1 ];
317 if ( !ForesterUtil.isEmpty( str ) ) {
318 if ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_ONLY ) {
319 final Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PF.matcher( str );
325 final Matcher m1 = TAXOMONY_UNIPROT_ID_PATTERN_1.matcher( str );
326 if ( m1.matches() ) {
329 final Matcher m2 = TAXOMONY_UNIPROT_ID_PATTERN_2.matcher( str );
330 if ( m2.matches() ) {
331 return m2.group( 1 );
337 else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.YES ) {
338 final Matcher m1 = TAXOMONY_UNIPROT_ID_PATTERN_1.matcher( name );
339 if ( m1.matches() ) {
346 public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
347 return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
350 public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
351 return readPhylogenies( new File( file_name ) );