in progress
[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.FileInputStream;
32 import java.io.FileNotFoundException;
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( "_(" + 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, final String encoding ) 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             final InputStream is = new FileInputStream( f );
207             final InputStreamReader isr = new InputStreamReader( is, encoding );
208             reader = new BufferedReader( isr );
209         }
210         else if ( source instanceof InputStream ) {
211             reader = new BufferedReader( new InputStreamReader( ( InputStream ) source, encoding ) );
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 extractScientificNameFromNodeName( final String name ) {
224         final Matcher m_ss = TAXOMONY_SN_PATTERN_STRAIN_SUBSTRAIN.matcher( name );
225         if ( m_ss.find() ) {
226             String s = m_ss.group( 1 ).replace( '_', ' ' );
227             if ( s.indexOf( " str " ) > 4 ) {
228                 s = s.replaceFirst( " str ", " str. " );
229             }
230             if ( s.indexOf( " substr " ) > 4 ) {
231                 s = s.replaceFirst( " substr ", " substr. " );
232             }
233             return s;
234         }
235         final Matcher m_str1 = TAXOMONY_SN_PATTERN_STRAIN_1.matcher( name );
236         if ( m_str1.find() ) {
237             String s = m_str1.group( 1 ).replace( '_', ' ' );
238             if ( s.indexOf( " str " ) > 4 ) {
239                 s = s.replaceFirst( " str ", " str. " );
240             }
241             else if ( s.indexOf( " subsp " ) > 4 ) {
242                 s = s.replaceFirst( " subsp ", " subsp. " );
243             }
244             else if ( s.indexOf( " ssp " ) > 4 ) {
245                 s = s.replaceFirst( " ssp ", " subsp. " );
246             }
247             else if ( s.indexOf( " ssp. " ) > 4 ) {
248                 s = s.replaceFirst( " ssp. ", " subsp. " );
249             }
250             else if ( s.indexOf( " var " ) > 4 ) {
251                 s = s.replaceFirst( " var ", " var. " );
252             }
253             return s;
254         }
255         final Matcher m_str2 = TAXOMONY_SN_PATTERN_STRAIN_2.matcher( name );
256         if ( m_str2.find() ) {
257             String s = m_str2.group( 1 ).replace( '_', ' ' );
258             if ( s.indexOf( " (str " ) > 4 ) {
259                 s = s.replaceFirst( " \\(str ", " (str. " );
260             }
261             else if ( s.indexOf( " (subsp " ) > 4 ) {
262                 s = s.replaceFirst( " \\(subsp ", " (subsp. " );
263             }
264             else if ( s.indexOf( " (ssp " ) > 4 ) {
265                 s = s.replaceFirst( " \\(ssp ", " (subsp. " );
266             }
267             else if ( s.indexOf( " (ssp. " ) > 4 ) {
268                 s = s.replaceFirst( " \\(ssp. ", " (subsp. " );
269             }
270             else if ( s.indexOf( " (var " ) > 4 ) {
271                 s = s.replaceFirst( " \\(var ", " (var. " );
272             }
273             return s;
274         }
275         final Matcher m_sns = TAXOMONY_SN_PATTERN_SNS.matcher( name );
276         if ( m_sns.find() ) {
277             return m_sns.group( 1 ).replace( '_', ' ' );
278         }
279         final Matcher m_sns2 = TAXOMONY_SN_PATTERN_SNS2.matcher( name );
280         if ( m_sns2.find() ) {
281             return m_sns2.group( 1 ).replace( '_', ' ' );
282         }
283         final Matcher m_sn = TAXOMONY_SN_PATTERN_SN.matcher( name );
284         if ( m_sn.find() ) {
285             return m_sn.group( 1 ).replace( '_', ' ' );
286         }
287         final Matcher m_sp = TAXOMONY_SN_PATTERN_SP.matcher( name );
288         if ( m_sp.find() ) {
289             String s = m_sp.group( 1 ).replace( '_', ' ' );
290             if ( s.endsWith( " sp" ) ) {
291                 s = s + ".";
292             }
293             return s;
294         }
295         return null;
296     }
297
298     public final static String extractTaxonomyCodeFromNodeName( final String name,
299                                                                 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
300         Matcher m = TAXOMONY_CODE_PATTERN_PFS.matcher( name );
301         if ( m.find() ) {
302             return m.group( 1 );
303         }
304         else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
305                 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
306             m = TAXOMONY_CODE_PATTERN_PFR.matcher( name );
307             if ( m.find() ) {
308                 return m.group( 1 );
309             }
310             else if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
311                 m = TAXOMONY_CODE_PATTERN_A.matcher( name );
312                 if ( m.find() ) {
313                     return m.group( 1 );
314                 }
315             }
316         }
317         return null;
318     }
319
320     public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
321                                                                 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
322                                                                         throws PhyloXmlDataFormatException {
323         if ( taxonomy_extraction == TAXONOMY_EXTRACTION.NO ) {
324             throw new IllegalArgumentException();
325         }
326         final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
327         if ( !ForesterUtil.isEmpty( id ) ) {
328             if ( !node.getNodeData().isHasTaxonomy() ) {
329                 node.getNodeData().setTaxonomy( new Taxonomy() );
330             }
331             node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
332             return id;
333         }
334         else {
335             String code = null;
336             if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) {
337                 code = extractTaxonomyCodeFromNodeNameLettersOnly( node.getName() );
338                 if ( ForesterUtil.isEmpty( code ) ) {
339                     final String sn = extractScientificNameFromNodeName( node.getName() );
340                     if ( !ForesterUtil.isEmpty( sn ) ) {
341                         if ( !node.getNodeData().isHasTaxonomy() ) {
342                             node.getNodeData().setTaxonomy( new Taxonomy() );
343                         }
344                         node.getNodeData().getTaxonomy().setScientificName( sn );
345                         return sn;
346                     }
347                 }
348             }
349             if ( ForesterUtil.isEmpty( code ) ) {
350                 code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
351             }
352             if ( !ForesterUtil.isEmpty( code ) ) {
353                 if ( !node.getNodeData().isHasTaxonomy() ) {
354                     node.getNodeData().setTaxonomy( new Taxonomy() );
355                 }
356                 node.getNodeData().getTaxonomy().setTaxonomyCode( code );
357                 return code;
358             }
359         }
360         return null;
361     }
362
363     public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
364                                                                      final TAXONOMY_EXTRACTION taxonomy_extraction ) {
365         Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PFS.matcher( name );
366         if ( m.find() ) {
367             return m.group( 1 );
368         }
369         else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
370                 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGGRESSIVE ) ) {
371             m = TAXOMONY_UNIPROT_ID_PATTERN_PFR.matcher( name );
372             if ( m.find() ) {
373                 return m.group( 1 );
374             }
375         }
376         return null;
377     }
378
379     public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
380         return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
381     }
382
383     public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
384         return readPhylogenies( new File( file_name ) );
385     }
386
387     /**
388      * Return null if it can not guess the parser to use based on name suffix.
389      *
390      * @param filename
391      * @return
392      */
393     final private static PhylogenyParser createParserDependingOnSuffix( final String filename,
394                                                                         final boolean phyloxml_validate_against_xsd ) {
395         PhylogenyParser parser = null;
396         final String filename_lc = filename.toLowerCase();
397         if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
398             parser = new TolParser();
399         }
400         else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( "phyloxml" ) || filename_lc.endsWith( ".zip" ) ) {
401             parser = PhyloXmlParser.createPhyloXmlParser();
402             if ( phyloxml_validate_against_xsd ) {
403                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
404                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
405                 if ( xsd_url != null ) {
406                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
407                 }
408                 else {
409                     if ( ForesterConstants.RELEASE ) {
410                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
411                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
412                     }
413                 }
414             }
415         }
416         else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
417             parser = new NexusPhylogeniesParser();
418         }
419         else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
420                 || filename_lc.endsWith( ".nwk" ) ) {
421             parser = new NHXParser();
422         }
423         return parser;
424     }
425
426     private final static String extractTaxonomyCodeFromNodeNameLettersOnly( final String name ) {
427         final Matcher m = TAXOMONY_CODE_PATTERN_A_LO.matcher( name );
428         if ( m.find() ) {
429             return m.group( 1 );
430         }
431         return null;
432     }
433 }