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