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