reordered
[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 private static String  SN_BN                                = "[A-Z][a-z]{2,30}[_ ][a-z]{3,30}";
59     final public static String   TAX_CODE                             = "(?:[A-Z9][A-Z]{2}[A-Z0-9]{2})|RAT|PIG|PEA";
60     final public static String   TAX_CODE_LO                          = "(?:[A-Z]{5})|RAT|PIG|PEA";
61     final public static Pattern  TAXOMONY_CODE_PATTERN_A              = Pattern.compile( "(?:\\b|_)(" + TAX_CODE
62                                                                               + ")(?:\\b|_)" );
63     final public static Pattern  TAXOMONY_CODE_PATTERN_A_LO           = Pattern.compile( "(?:\\b|_)(" + TAX_CODE_LO
64                                                                               + ")(?:\\b|_)" );
65     final public static Pattern  TAXOMONY_CODE_PATTERN_BRACKETED      = Pattern.compile( "\\[(" + TAX_CODE + ")\\]" );
66     final public static Pattern  TAXOMONY_CODE_PATTERN_PFR            = Pattern.compile( "(?:\\b|_)[a-zA-Z0-9]{3,}_("
67                                                                               + TAX_CODE + ")\\b" );
68     final public static Pattern  TAXOMONY_SN_PATTERN_GENUS            = Pattern.compile( "([A-Z][a-z]{2,30})" );
69     final public static Pattern  TAXOMONY_SN_PATTERN_SN               = Pattern.compile( "(?:\\b|_)(" + SN_BN
70                                                                               + ")(?:(\\s*$)|([_ ][a-z]*[A-Z0-9]))" );
71     final public static Pattern  TAXOMONY_SN_PATTERN_SNS              = Pattern.compile( "(?:\\b|_)(" + SN_BN
72                                                                               + "[_ ][a-z]{3,30}"
73                                                                               + ")[_ ][a-z]*[A-Z0-9]" );
74     final public static Pattern  TAXOMONY_SN_PATTERN_SNS2             = Pattern.compile( "[A-Z0-9][a-z]*[_ ](" + SN_BN
75                                                                               + "[_ ][a-z]{3,30}" + ")\\s*$" );
76     final public static Pattern  TAXOMONY_SN_PATTERN_SP               = Pattern
77                                                                               .compile( "(?:\\b|_)([A-Z][a-z]{2,30}[_ ]sp\\.?)(?:\\b|_)?" );
78     final public static Pattern  TAXOMONY_SN_PATTERN_STRAIN_1         = Pattern
79                                                                               .compile( "(?:\\b|_)("
80                                                                                       + SN_BN
81                                                                                       + "[_ ](?:str|subsp|ssp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60})(?:\\b|_)" );
82     final public static Pattern  TAXOMONY_SN_PATTERN_STRAIN_2         = Pattern
83                                                                               .compile( "(?:\\b|_)("
84                                                                                       + SN_BN
85                                                                                       + "[_ ]\\((?:str|subsp|ssp|var)[a-z]{0,5}\\.?[_ ]\\S{1,60}\\))" );
86     final public static Pattern  TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN = Pattern
87                                                                               .compile( "(?:\\b|_)("
88                                                                                       + SN_BN
89                                                                                       + "[_ ]str[a-z]{0,3}\\.?[_ ]\\S{1,60}[_ ]substr[a-z]{0,3}\\.?[_ ]\\S{1,60})(?:\\b|_)" );
90     final private static Pattern TAXOMONY_CODE_PATTERN_PFS            = Pattern.compile( "(?:\\b|_)[A-Z0-9]{4,}_("
91                                                                               + TAX_CODE + ")/\\d+-\\d+\\b" );
92     final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFR      = Pattern
93                                                                               .compile( "(?:\\b|_)[A-Z0-9]{1,}_(\\d{1,7})\\b" );
94     final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PFS      = Pattern
95                                                                               .compile( "(?:\\b|_)[A-Z0-9]{4,}_(\\d{1,7})/\\d+-\\d+\\b" );
96
97     final public static PhylogenyParser createParserDependingFileContents( final File file,
98                                                                            final boolean phyloxml_validate_against_xsd )
99             throws FileNotFoundException, IOException {
100         PhylogenyParser parser = null;
101         final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
102         if ( first_line.startsWith( "<" ) ) {
103             parser = PhyloXmlParser.createPhyloXmlParser();
104             if ( phyloxml_validate_against_xsd ) {
105                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
106                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
107                 if ( xsd_url != null ) {
108                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
109                 }
110                 else {
111                     if ( ForesterConstants.RELEASE ) {
112                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
113                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
114                     }
115                 }
116             }
117         }
118         else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
119                 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
120             parser = new NexusPhylogeniesParser();
121         }
122         else {
123             parser = new NHXParser();
124         }
125         return parser;
126     }
127
128     final public static PhylogenyParser createParserDependingOnFileType( final File file,
129                                                                          final boolean phyloxml_validate_against_xsd )
130             throws FileNotFoundException, IOException {
131         PhylogenyParser parser = null;
132         parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
133         if ( parser == null ) {
134             parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
135         }
136         if ( ( parser != null ) && file.toString().toLowerCase().endsWith( ".zip" ) ) {
137             if ( parser instanceof PhyloXmlParser ) {
138                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
139             }
140             else if ( parser instanceof TolParser ) {
141                 ( ( TolParser ) parser ).setZippedInputstream( true );
142             }
143         }
144         return parser;
145     }
146
147     final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
148                                                                             final boolean phyloxml_validate_against_xsd )
149             throws FileNotFoundException, IOException {
150         final String lc_filename = url.getFile().toString().toLowerCase();
151         PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
152         if ( parser == null ) {
153             final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
154             if ( first_line.startsWith( "<" ) ) {
155                 parser = PhyloXmlParser.createPhyloXmlParser();
156                 if ( phyloxml_validate_against_xsd ) {
157                     final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
158                     final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
159                     if ( xsd_url != null ) {
160                         ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
161                     }
162                     else {
163                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
164                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
165                     }
166                 }
167             }
168             else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
169                     || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
170                 parser = new NexusPhylogeniesParser();
171             }
172             else {
173                 parser = new NHXParser();
174             }
175         }
176         if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
177             if ( parser instanceof PhyloXmlParser ) {
178                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
179             }
180             else if ( parser instanceof TolParser ) {
181                 ( ( TolParser ) parser ).setZippedInputstream( true );
182             }
183         }
184         return parser;
185     }
186
187     public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
188         BufferedReader reader = null;
189         if ( ( source instanceof File ) || ( source instanceof String ) ) {
190             File f = null;
191             if ( source instanceof File ) {
192                 f = ( File ) source;
193             }
194             else {
195                 f = new File( ( String ) source );
196             }
197             if ( !f.exists() ) {
198                 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
199             }
200             else if ( !f.isFile() ) {
201                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
202             }
203             else if ( !f.canRead() ) {
204                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
205             }
206             reader = new BufferedReader( new FileReader( f ) );
207         }
208         else if ( source instanceof InputStream ) {
209             reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
210         }
211         else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
212             reader = new BufferedReader( new StringReader( source.toString() ) );
213         }
214         else {
215             throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
216                     + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
217         }
218         return reader;
219     }
220
221     public final static String extractScientificNameFromNodeName( final String name ) {
222         final Matcher m_ss = TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN.matcher( name );
223         if ( m_ss.find() ) {
224             String s = m_ss.group( 1 ).replace( '_', ' ' );
225             if ( s.indexOf( " str " ) > 4 ) {
226                 s = s.replaceFirst( " str ", " str. " );
227             }
228             if ( s.indexOf( " substr " ) > 4 ) {
229                 s = s.replaceFirst( " substr ", " substr. " );
230             }
231             return s;
232         }
233         final Matcher m_str1 = TAXOMONY_SN_PATTERN_STRAIN_1.matcher( name );
234         if ( m_str1.find() ) {
235             String s = m_str1.group( 1 ).replace( '_', ' ' );
236             if ( s.indexOf( " str " ) > 4 ) {
237                 s = s.replaceFirst( " str ", " str. " );
238             }
239             else if ( s.indexOf( " subsp " ) > 4 ) {
240                 s = s.replaceFirst( " subsp ", " subsp. " );
241             }
242             else if ( s.indexOf( " ssp " ) > 4 ) {
243                 s = s.replaceFirst( " ssp ", " subsp. " );
244             }
245             else if ( s.indexOf( " ssp. " ) > 4 ) {
246                 s = s.replaceFirst( " ssp. ", " subsp. " );
247             }
248             else if ( s.indexOf( " var " ) > 4 ) {
249                 s = s.replaceFirst( " var ", " var. " );
250             }
251             return s;
252         }
253         final Matcher m_str2 = TAXOMONY_SN_PATTERN_STRAIN_2.matcher( name );
254         if ( m_str2.find() ) {
255             String s = m_str2.group( 1 ).replace( '_', ' ' );
256             if ( s.indexOf( " (str " ) > 4 ) {
257                 s = s.replaceFirst( " \\(str ", " (str. " );
258             }
259             else if ( s.indexOf( " (subsp " ) > 4 ) {
260                 s = s.replaceFirst( " \\(subsp ", " (subsp. " );
261             }
262             else if ( s.indexOf( " (ssp " ) > 4 ) {
263                 s = s.replaceFirst( " \\(ssp ", " (subsp. " );
264             }
265             else if ( s.indexOf( " (ssp. " ) > 4 ) {
266                 s = s.replaceFirst( " \\(ssp. ", " (subsp. " );
267             }
268             else if ( s.indexOf( " (var " ) > 4 ) {
269                 s = s.replaceFirst( " \\(var ", " (var. " );
270             }
271             return s;
272         }
273         final Matcher m_sns = TAXOMONY_SN_PATTERN_SNS.matcher( name );
274         if ( m_sns.find() ) {
275             return m_sns.group( 1 ).replace( '_', ' ' );
276         }
277         final Matcher m_sns2 = TAXOMONY_SN_PATTERN_SNS2.matcher( name );
278         if ( m_sns2.find() ) {
279             return m_sns2.group( 1 ).replace( '_', ' ' );
280         }
281         final Matcher m_sn = TAXOMONY_SN_PATTERN_SN.matcher( name );
282         if ( m_sn.find() ) {
283             return m_sn.group( 1 ).replace( '_', ' ' );
284         }
285         final Matcher m_sp = TAXOMONY_SN_PATTERN_SP.matcher( name );
286         if ( m_sp.find() ) {
287             String s = m_sp.group( 1 ).replace( '_', ' ' );
288             if ( s.endsWith( " sp" ) ) {
289                 s = s + ".";
290             }
291             return s;
292         }
293         return null;
294     }
295
296     public final static String extractTaxonomyCodeFromNodeName( final String name,
297                                                                 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
298         Matcher m = TAXOMONY_CODE_PATTERN_PFS.matcher( name );
299         if ( m.find() ) {
300             return m.group( 1 );
301         }
302         else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
303                 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
304             m = TAXOMONY_CODE_PATTERN_PFR.matcher( name );
305             if ( m.find() ) {
306                 return m.group( 1 );
307             }
308             else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
309                 m = TAXOMONY_CODE_PATTERN_A.matcher( name );
310                 if ( m.find() ) {
311                     return m.group( 1 );
312                 }
313             }
314         }
315         return null;
316     }
317
318     public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
319                                                                 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
320             throws PhyloXmlDataFormatException {
321         if ( taxonomy_extraction == TAXONOMY_EXTRACTION.NO ) {
322             throw new IllegalArgumentException();
323         }
324         final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
325         if ( !ForesterUtil.isEmpty( id ) ) {
326             if ( !node.getNodeData().isHasTaxonomy() ) {
327                 node.getNodeData().setTaxonomy( new Taxonomy() );
328             }
329             node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
330             return id;
331         }
332         else {
333             String code = null;
334             if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
335                 code = extractTaxonomyCodeFromNodeNameLettersOnly( node.getName() );
336                 if ( ForesterUtil.isEmpty( code ) ) {
337                     final String sn = extractScientificNameFromNodeName( node.getName() );
338                     if ( !ForesterUtil.isEmpty( sn ) ) {
339                         if ( !node.getNodeData().isHasTaxonomy() ) {
340                             node.getNodeData().setTaxonomy( new Taxonomy() );
341                         }
342                         node.getNodeData().getTaxonomy().setScientificName( sn );
343                         return sn;
344                     }
345                 }
346             }
347             if ( ForesterUtil.isEmpty( code ) ) {
348                 code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
349             }
350             if ( !ForesterUtil.isEmpty( code ) ) {
351                 if ( !node.getNodeData().isHasTaxonomy() ) {
352                     node.getNodeData().setTaxonomy( new Taxonomy() );
353                 }
354                 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
355                 return code;
356             }
357         }
358         return null;
359     }
360
361     public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
362                                                                      final TAXONOMY_EXTRACTION taxonomy_extraction ) {
363         Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PFS.matcher( name );
364         if ( m.find() ) {
365             return m.group( 1 );
366         }
367         else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
368                 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
369             m = TAXOMONY_UNIPROT_ID_PATTERN_PFR.matcher( name );
370             if ( m.find() ) {
371                 return m.group( 1 );
372             }
373         }
374         return null;
375     }
376
377     public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
378         return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
379     }
380
381     public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
382         return readPhylogenies( new File( file_name ) );
383     }
384
385     /**
386      * Return null if it can not guess the parser to use based on name suffix.
387      * 
388      * @param filename
389      * @return
390      */
391     final private static PhylogenyParser createParserDependingOnSuffix( final String filename,
392                                                                         final boolean phyloxml_validate_against_xsd ) {
393         PhylogenyParser parser = null;
394         final String filename_lc = filename.toLowerCase();
395         if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
396             parser = new TolParser();
397         }
398         else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( "phyloxml" ) || filename_lc.endsWith( ".zip" ) ) {
399             parser = PhyloXmlParser.createPhyloXmlParser();
400             if ( phyloxml_validate_against_xsd ) {
401                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
402                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
403                 if ( xsd_url != null ) {
404                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
405                 }
406                 else {
407                     if ( ForesterConstants.RELEASE ) {
408                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
409                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
410                     }
411                 }
412             }
413         }
414         else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
415             parser = new NexusPhylogeniesParser();
416         }
417         else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
418                 || filename_lc.endsWith( ".nwk" ) ) {
419             parser = new NHXParser();
420         }
421         return parser;
422     }
423
424     private final static String extractTaxonomyCodeFromNodeNameLettersOnly( final String name ) {
425         final Matcher m = TAXOMONY_CODE_PATTERN_A_LO.matcher( name );
426         if ( m.find() ) {
427             return m.group( 1 );
428         }
429         return null;
430     }
431 }