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