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