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