b37dbebcb9ee2bea3b2c5dfdd49d30fb9b6849ea
[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_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]{2,30}_[a-z]{3,30}(?:_[a-z][a-z0-9_]+)?)\\b" );
65     final public static Pattern  TAXOMONY_SN_PATTERN_SN          = Pattern
66                                                                          .compile( "\\b([A-Z][a-z]{2,30}[_ ][a-z]{3,30}(?:[_ ][a-z]{3,30})?)(?:\\b|_)?" );
67     final public static Pattern  TAXOMONY_SN_PATTERN_STRAIN_1    = Pattern
68                                                                          .compile( "\\b([A-Z][a-z]{2,30}[_ ][a-z]{3,30}[_ ](?:str|subsp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60})(?:\\b|_)" );
69     final public static Pattern  TAXOMONY_SN_PATTERN_STRAIN_2    = Pattern
70                                                                          .compile( "\\b([A-Z][a-z]{2,30}[_ ][a-z]{3,30}[_ ]\\((?:str|subsp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60}\\))(?:\\b|_)?" );
71     final public static Pattern  TAXOMONY_SN_PATTERN_SP    = Pattern
72             .compile( "\\b([A-Z][a-z]{2,30}[_ ]sp\\.?)(?:\\b|_)?" );
73
74     final public static Pattern  TAXOMONY_SN_PATTERN_GENUS       = Pattern.compile( "([A-Z][a-z]{2,30})" );
75     final private static Pattern TAXOMONY_CODE_PATTERN_PFS       = Pattern.compile( "(?:\\b|_)[A-Z0-9]{4,}_("
76                                                                          + TAX_CODE + ")/\\d+-\\d+\\b" );
77     final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFR = Pattern
78                                                                          .compile( "(?:\\b|_)[A-Z0-9]{1,}_(\\d{1,7})\\b" );
79     final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFS = Pattern
80                                                                          .compile( "(?:\\b|_)[A-Z0-9]{4,}_(\\d{1,7})/\\d+-\\d+\\b" );
81
82     final public static PhylogenyParser createParserDependingFileContents( final File file,
83                                                                            final boolean phyloxml_validate_against_xsd )
84             throws FileNotFoundException, IOException {
85         PhylogenyParser parser = null;
86         final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
87         if ( first_line.startsWith( "<" ) ) {
88             parser = PhyloXmlParser.createPhyloXmlParser();
89             if ( phyloxml_validate_against_xsd ) {
90                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
91                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
92                 if ( xsd_url != null ) {
93                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
94                 }
95                 else {
96                     if ( ForesterConstants.RELEASE ) {
97                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
98                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
99                     }
100                 }
101             }
102         }
103         else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
104                 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
105             parser = new NexusPhylogeniesParser();
106         }
107         else {
108             parser = new NHXParser();
109         }
110         return parser;
111     }
112
113     final public static PhylogenyParser createParserDependingOnFileType( final File file,
114                                                                          final boolean phyloxml_validate_against_xsd )
115             throws FileNotFoundException, IOException {
116         PhylogenyParser parser = null;
117         parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
118         if ( parser == null ) {
119             parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
120         }
121         if ( ( parser != null ) && file.toString().toLowerCase().endsWith( ".zip" ) ) {
122             if ( parser instanceof PhyloXmlParser ) {
123                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
124             }
125             else if ( parser instanceof TolParser ) {
126                 ( ( TolParser ) parser ).setZippedInputstream( true );
127             }
128         }
129         return parser;
130     }
131
132     final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
133                                                                             final boolean phyloxml_validate_against_xsd )
134             throws FileNotFoundException, IOException {
135         final String lc_filename = url.getFile().toString().toLowerCase();
136         PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
137         if ( parser == null ) {
138             final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
139             if ( first_line.startsWith( "<" ) ) {
140                 parser = PhyloXmlParser.createPhyloXmlParser();
141                 if ( phyloxml_validate_against_xsd ) {
142                     final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
143                     final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
144                     if ( xsd_url != null ) {
145                         ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
146                     }
147                     else {
148                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
149                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
150                     }
151                 }
152             }
153             else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
154                     || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
155                 parser = new NexusPhylogeniesParser();
156             }
157             else {
158                 parser = new NHXParser();
159             }
160         }
161         if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
162             if ( parser instanceof PhyloXmlParser ) {
163                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
164             }
165             else if ( parser instanceof TolParser ) {
166                 ( ( TolParser ) parser ).setZippedInputstream( true );
167             }
168         }
169         return parser;
170     }
171
172     public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
173         BufferedReader reader = null;
174         if ( ( source instanceof File ) || ( source instanceof String ) ) {
175             File f = null;
176             if ( source instanceof File ) {
177                 f = ( File ) source;
178             }
179             else {
180                 f = new File( ( String ) source );
181             }
182             if ( !f.exists() ) {
183                 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
184             }
185             else if ( !f.isFile() ) {
186                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
187             }
188             else if ( !f.canRead() ) {
189                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
190             }
191             reader = new BufferedReader( new FileReader( f ) );
192         }
193         else if ( source instanceof InputStream ) {
194             reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
195         }
196         else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
197             reader = new BufferedReader( new StringReader( source.toString() ) );
198         }
199         else {
200             throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
201                     + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
202         }
203         return reader;
204     }
205
206     public final static String extractScientificNameFromNodeName( final String name ) {
207         final Matcher m = TAXOMONY_SN_PATTERN.matcher( name );
208         if ( m.find() ) {
209             return m.group( 1 ).replace( '_', ' ' );
210         }
211         final Matcher m_str1 = TAXOMONY_SN_PATTERN_STRAIN_1.matcher( name );
212         if ( m_str1.find() ) {
213             return m_str1.group( 1 ).replace( '_', ' ' );
214         }
215         final Matcher m_str2 = TAXOMONY_SN_PATTERN_STRAIN_2.matcher( name );
216         if ( m_str2.find() ) {
217             return m_str2.group( 1 ).replace( '_', ' ' );
218         }
219         final Matcher m_sn = TAXOMONY_SN_PATTERN_SN.matcher( name );
220        
221         if ( m_sn.find() ) {
222             return m_sn.group( 1 ).replace( '_', ' ' );
223         }
224         
225         final Matcher m_sp = TAXOMONY_SN_PATTERN_SP.matcher( name );
226         
227         if ( m_sp.find() ) {
228             return m_sp.group( 1 ).replace( '_', ' ' );
229         }
230         return null;
231     }
232
233     public final static String extractTaxonomyCodeFromNodeName( final String name,
234                                                                 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
235         Matcher m = TAXOMONY_CODE_PATTERN_PFS.matcher( name );
236         if ( m.find() ) {
237             return m.group( 1 );
238         }
239         else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
240                 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
241             m = TAXOMONY_CODE_PATTERN_PFR.matcher( name );
242             if ( m.find() ) {
243                 return m.group( 1 );
244             }
245             else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
246                 m = TAXOMONY_CODE_PATTERN_A.matcher( name );
247                 if ( m.find() ) {
248                     return m.group( 1 );
249                 }
250             }
251         }
252         return null;
253     }
254
255     public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
256                                                                 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
257             throws PhyloXmlDataFormatException {
258         if ( taxonomy_extraction == TAXONOMY_EXTRACTION.NO ) {
259             throw new IllegalArgumentException();
260         }
261         final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
262         if ( !ForesterUtil.isEmpty( id ) ) {
263             if ( !node.getNodeData().isHasTaxonomy() ) {
264                 node.getNodeData().setTaxonomy( new Taxonomy() );
265             }
266             node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
267             return id;
268         }
269         else {
270             final String code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
271             if ( !ForesterUtil.isEmpty( code ) ) {
272                 if ( !node.getNodeData().isHasTaxonomy() ) {
273                     node.getNodeData().setTaxonomy( new Taxonomy() );
274                 }
275                 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
276                 return code;
277             }
278             else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
279                 final String sn = extractScientificNameFromNodeName( node.getName() );
280                 if ( !ForesterUtil.isEmpty( sn ) ) {
281                     if ( !node.getNodeData().isHasTaxonomy() ) {
282                         node.getNodeData().setTaxonomy( new Taxonomy() );
283                     }
284                     node.getNodeData().getTaxonomy().setScientificName( sn );
285                     return sn;
286                 }
287             }
288         }
289         return null;
290     }
291
292     public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
293                                                                      final TAXONOMY_EXTRACTION taxonomy_extraction ) {
294         Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PFS.matcher( name );
295         if ( m.find() ) {
296             return m.group( 1 );
297         }
298         else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
299                 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
300             m = TAXOMONY_UNIPROT_ID_PATTERN_PFR.matcher( name );
301             if ( m.find() ) {
302                 return m.group( 1 );
303             }
304             //else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
305             //    m = TAXOMONY_UNIPROT_ID_PATTERN_A.matcher( name );
306             //    if ( m.find() ) {
307             //        return m.group( 1 );
308             //    }
309             //}
310         }
311         return null;
312     }
313
314     public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
315         return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
316     }
317
318     public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
319         return readPhylogenies( new File( file_name ) );
320     }
321
322     /**
323      * Return null if it can not guess the parser to use based on name suffix.
324      * 
325      * @param filename
326      * @return
327      */
328     final private static PhylogenyParser createParserDependingOnSuffix( final String filename,
329                                                                         final boolean phyloxml_validate_against_xsd ) {
330         PhylogenyParser parser = null;
331         final String filename_lc = filename.toLowerCase();
332         if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
333             parser = new TolParser();
334         }
335         else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( "phyloxml" ) || filename_lc.endsWith( ".zip" ) ) {
336             parser = PhyloXmlParser.createPhyloXmlParser();
337             if ( phyloxml_validate_against_xsd ) {
338                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
339                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
340                 if ( xsd_url != null ) {
341                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
342                 }
343                 else {
344                     if ( ForesterConstants.RELEASE ) {
345                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
346                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
347                     }
348                 }
349             }
350         }
351         else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
352             parser = new NexusPhylogeniesParser();
353         }
354         else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
355                 || filename_lc.endsWith( ".nwk" ) ) {
356             parser = new NHXParser();
357         }
358         return parser;
359     }
360 }