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