2ce06677735a089612031893fef4f1bcdedb5905
[jalview.git] / forester / java / src / org / forester / io / parsers / util / ParserUtils.java
1 // $Id:
2 //
3 // FORESTER -- software libraries and applications
4 // for evolutionary biology research and applications.
5 //
6 // Copyright (C) 2008-2009 Christian M. Zmasek
7 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
8 // All rights reserved
9 //
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.
14 //
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.
19 //
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
23 //
24 // Contact: phylosoft @ gmail . com
25 // WWW: www.phylosoft.org/
26
27 package org.forester.io.parsers.util;
28
29 import java.io.BufferedReader;
30 import java.io.File;
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;
37 import java.net.URL;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40
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;
55
56 public final class ParserUtils {
57
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_SN_PATTERN             = Pattern
60                                                                          .compile( "(?:\\b|_)[a-zA-Z0-9]{3,}_([A-Z][a-z]+_[a-z]{2,}(?:_[a-z][a-z0-9_]+)?)\\b" );
61     final private static Pattern TAXOMONY_CODE_PATTERN_PFS       = Pattern.compile( "(?:\\b|_)[A-Z0-9]{4,}_("
62                                                                          + TAX_CODE + ")/\\d+-\\d+\\b" );
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_CODE_PATTERN_A         = Pattern.compile( "(?:\\b|_)(" + TAX_CODE + ")\\b" );
66     final public static Pattern  TAXOMONY_CODE_PATTERN_BRACKETED = Pattern.compile( "\\[(" + TAX_CODE + ")\\]" );
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_PFS = Pattern
69                                                                          .compile( "(?:\\b|_)[A-Z0-9]{4,}_(\\d{1,7})/\\d+-\\d+\\b" );
70     final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFR = Pattern
71                                                                          .compile( "(?:\\b|_)[a-zA-Z0-9]{3,}_(\\d{1,7})\\b" );
72
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() );
85                 }
86                 else {
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 + "]" );
90                     }
91                 }
92             }
93         }
94         else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
95                 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
96             parser = new NexusPhylogeniesParser();
97         }
98         else {
99             parser = new NHXParser();
100         }
101         return parser;
102     }
103
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 );
111         }
112         if ( ( parser != null ) && file.toString().toLowerCase().endsWith( ".zip" ) ) {
113             if ( parser instanceof PhyloXmlParser ) {
114                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
115             }
116             else if ( parser instanceof TolParser ) {
117                 ( ( TolParser ) parser ).setZippedInputstream( true );
118             }
119         }
120         return parser;
121     }
122
123     /**
124      * Return null if it can not guess the parser to use based on name suffix.
125      * 
126      * @param filename
127      * @return
128      */
129     final private static PhylogenyParser createParserDependingOnSuffix( final String filename,
130                                                                         final boolean phyloxml_validate_against_xsd ) {
131         PhylogenyParser parser = null;
132         final String filename_lc = filename.toLowerCase();
133         if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
134             parser = new TolParser();
135         }
136         else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( "phyloxml" ) || filename_lc.endsWith( ".zip" ) ) {
137             parser = PhyloXmlParser.createPhyloXmlParser();
138             if ( phyloxml_validate_against_xsd ) {
139                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
140                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
141                 if ( xsd_url != null ) {
142                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
143                 }
144                 else {
145                     if ( ForesterConstants.RELEASE ) {
146                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
147                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
148                     }
149                 }
150             }
151         }
152         else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
153             parser = new NexusPhylogeniesParser();
154         }
155         else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
156                 || filename_lc.endsWith( ".nwk" ) ) {
157             parser = new NHXParser();
158         }
159         return parser;
160     }
161
162     final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
163                                                                             final boolean phyloxml_validate_against_xsd )
164             throws FileNotFoundException, IOException {
165         final String lc_filename = url.getFile().toString().toLowerCase();
166         PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
167         if ( parser == null ) {
168             final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
169             if ( first_line.startsWith( "<" ) ) {
170                 parser = PhyloXmlParser.createPhyloXmlParser();
171                 if ( phyloxml_validate_against_xsd ) {
172                     final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
173                     final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
174                     if ( xsd_url != null ) {
175                         ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
176                     }
177                     else {
178                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
179                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
180                     }
181                 }
182             }
183             else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
184                     || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
185                 parser = new NexusPhylogeniesParser();
186             }
187             else {
188                 parser = new NHXParser();
189             }
190         }
191         if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
192             if ( parser instanceof PhyloXmlParser ) {
193                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
194             }
195             else if ( parser instanceof TolParser ) {
196                 ( ( TolParser ) parser ).setZippedInputstream( true );
197             }
198         }
199         return parser;
200     }
201
202     public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
203         BufferedReader reader = null;
204         if ( ( source instanceof File ) || ( source instanceof String ) ) {
205             File f = null;
206             if ( source instanceof File ) {
207                 f = ( File ) source;
208             }
209             else {
210                 f = new File( ( String ) source );
211             }
212             if ( !f.exists() ) {
213                 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
214             }
215             else if ( !f.isFile() ) {
216                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
217             }
218             else if ( !f.canRead() ) {
219                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
220             }
221             reader = new BufferedReader( new FileReader( f ) );
222         }
223         else if ( source instanceof InputStream ) {
224             reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
225         }
226         else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
227             reader = new BufferedReader( new StringReader( source.toString() ) );
228         }
229         else {
230             throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
231                     + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
232         }
233         return reader;
234     }
235
236     public final static String extractScientificNameFromNodeName( final String name ) {
237         final Matcher m = TAXOMONY_SN_PATTERN.matcher( name );
238         if ( m.find() ) {
239             return m.group( 1 ).replace( '_', ' ' );
240         }
241         return null;
242     }
243
244     public final static String extractTaxonomyCodeFromNodeName( final String name,
245                                                                 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
246         Matcher m = TAXOMONY_CODE_PATTERN_PFS.matcher( name );
247         if ( m.find() ) {
248             return m.group( 1 );
249         }
250         else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
251                 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
252             m = TAXOMONY_CODE_PATTERN_PFR.matcher( name );
253             if ( m.find() ) {
254                 return m.group( 1 );
255             }
256             else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
257                 m = TAXOMONY_CODE_PATTERN_A.matcher( name );
258                 if ( m.find() ) {
259                     return m.group( 1 );
260                 }
261             }
262         }
263         return null;
264     }
265
266     public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
267                                                                 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
268             throws PhyloXmlDataFormatException {
269         if ( taxonomy_extraction == TAXONOMY_EXTRACTION.NO ) {
270             throw new IllegalArgumentException();
271         }
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() );
276             }
277             node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
278             return id;
279         }
280         else {
281             final String code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
282             if ( !ForesterUtil.isEmpty( code ) ) {
283                 if ( !node.getNodeData().isHasTaxonomy() ) {
284                     node.getNodeData().setTaxonomy( new Taxonomy() );
285                 }
286                 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
287                 return code;
288             }
289             else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
290                 final String sn = extractScientificNameFromNodeName( node.getName() );
291                 if ( !ForesterUtil.isEmpty( sn ) ) {
292                     if ( !node.getNodeData().isHasTaxonomy() ) {
293                         node.getNodeData().setTaxonomy( new Taxonomy() );
294                     }
295                     node.getNodeData().getTaxonomy().setScientificName( sn );
296                     return sn;
297                 }
298             }
299         }
300         return null;
301     }
302
303     public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
304                                                                      final TAXONOMY_EXTRACTION taxonomy_extraction ) {
305         Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PFS.matcher( name );
306         if ( m.find() ) {
307             return m.group( 1 );
308         }
309         else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
310                 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
311             m = TAXOMONY_UNIPROT_ID_PATTERN_PFR.matcher( name );
312             if ( m.find() ) {
313                 return m.group( 1 );
314             }
315             else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
316                 m = TAXOMONY_UNIPROT_ID_PATTERN_A.matcher( name );
317                 if ( m.find() ) {
318                     return m.group( 1 );
319                 }
320             }
321         }
322         return null;
323     }
324
325     public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
326         return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
327     }
328
329     public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
330         return readPhylogenies( new File( file_name ) );
331     }
332 }