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