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