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