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