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