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