4d74229ddb136e831acce4d641cfeeeec3e86205
[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 Pattern  TAXOMONY_SN_PATTERN            = Pattern
59                                                                         .compile( "[^_]{2,}_([A-Z][a-z]+_[a-z]{2,}(_[A-Za-z]\\w+|))\\b" );
60     final public static Pattern  TAXOMONY_CODE_PATTERN_1        = Pattern
61                                                                         .compile( "\\b[A-Z9][A-Z]{2}[A-Z0-9]{2}|RAT|PIG|PEA|CAP\\b" );
62     final private static Pattern TAXOMONY_CODE_PATTERN_2        = Pattern
63                                                                         .compile( "([A-Z9][A-Z]{2}[A-Z0-9]{2}|RAT|PIG|PEA|CAP)[^0-9A-Za-z].*" );
64     final private static Pattern TAXOMONY_CODE_PATTERN_3        = Pattern
65                                                                         .compile( "_([A-Z9][A-Z]{2}[A-Z0-9]{2}|RAT|PIG|PEA|CAP)_" );
66     final private static Pattern TAXOMONY_CODE_PATTERN_PF       = Pattern
67                                                                         .compile( "([A-Z9][A-Z]{2}[A-Z0-9]{2}|RAT|PIG|PEA|CAP)/\\d+-\\d+" );
68     final public static Pattern  TAXOMONY_CODE_PATTERN_4        = Pattern
69                                                                         .compile( "\\[(([A-Z9][A-Z]{2}[A-Z0-9]{2})|RAT|PIG|PEA|CAP)\\]" );
70     final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_1  = Pattern.compile( "\\b\\d{1,7}\\b" );
71     final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_2  = Pattern.compile( "(\\d{1,7})[^0-9A-Za-z].*" );
72     final private static Pattern TAXOMONY_UNIPROT_ID_PATTERN_PF = Pattern.compile( "(\\d{1,7})/\\d+-\\d+" );
73
74     final public static PhylogenyParser createParserDependingFileContents( final File file,
75                                                                            final boolean phyloxml_validate_against_xsd )
76             throws FileNotFoundException, IOException {
77         PhylogenyParser parser = null;
78         final String first_line = ForesterUtil.getFirstLine( file ).trim().toLowerCase();
79         if ( first_line.startsWith( "<" ) ) {
80             parser = new PhyloXmlParser();
81             if ( phyloxml_validate_against_xsd ) {
82                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
83                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
84                 if ( xsd_url != null ) {
85                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
86                 }
87                 else {
88                     if ( ForesterConstants.RELEASE ) {
89                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
90                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
91                     }
92                 }
93             }
94         }
95         else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
96                 || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
97             parser = new NexusPhylogeniesParser();
98         }
99         else {
100             parser = new NHXParser();
101         }
102         return parser;
103     }
104
105     final public static PhylogenyParser createParserDependingOnFileType( final File file,
106                                                                          final boolean phyloxml_validate_against_xsd )
107             throws FileNotFoundException, IOException {
108         PhylogenyParser parser = null;
109         parser = ParserUtils.createParserDependingOnSuffix( file.getName(), phyloxml_validate_against_xsd );
110         if ( parser == null ) {
111             parser = createParserDependingFileContents( file, phyloxml_validate_against_xsd );
112         }
113         return parser;
114     }
115
116     /**
117      * Return null if it can not guess the parser to use based on name suffix.
118      * 
119      * @param filename
120      * @return
121      */
122     final public static PhylogenyParser createParserDependingOnSuffix( final String filename,
123                                                                        final boolean phyloxml_validate_against_xsd ) {
124         PhylogenyParser parser = null;
125         final String filename_lc = filename.toLowerCase();
126         if ( filename_lc.endsWith( ".tol" ) || filename_lc.endsWith( ".tolxml" ) || filename_lc.endsWith( ".tol.zip" ) ) {
127             parser = new TolParser();
128         }
129         else if ( filename_lc.endsWith( ".xml" ) || filename_lc.endsWith( ".px" ) || filename_lc.endsWith( "phyloxml" )
130                 || filename_lc.endsWith( ".zip" ) ) {
131             parser = new PhyloXmlParser();
132             if ( phyloxml_validate_against_xsd ) {
133                 final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
134                 final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
135                 if ( xsd_url != null ) {
136                     ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
137                 }
138                 else {
139                     if ( ForesterConstants.RELEASE ) {
140                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
141                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
142                     }
143                 }
144             }
145         }
146         else if ( filename_lc.endsWith( ".nexus" ) || filename_lc.endsWith( ".nex" ) || filename_lc.endsWith( ".nx" ) ) {
147             parser = new NexusPhylogeniesParser();
148         }
149         else if ( filename_lc.endsWith( ".nhx" ) || filename_lc.endsWith( ".nh" ) || filename_lc.endsWith( ".newick" )
150                 || filename_lc.endsWith( ".nwk" ) ) {
151             parser = new NHXParser();
152         }
153         return parser;
154     }
155
156     final public static PhylogenyParser createParserDependingOnUrlContents( final URL url,
157                                                                             final boolean phyloxml_validate_against_xsd )
158             throws FileNotFoundException, IOException {
159         final String lc_filename = url.getFile().toString().toLowerCase();
160         PhylogenyParser parser = createParserDependingOnSuffix( lc_filename, phyloxml_validate_against_xsd );
161         if ( ( parser != null ) && lc_filename.endsWith( ".zip" ) ) {
162             if ( parser instanceof PhyloXmlParser ) {
163                 ( ( PhyloXmlParser ) parser ).setZippedInputstream( true );
164             }
165             else if ( parser instanceof TolParser ) {
166                 ( ( TolParser ) parser ).setZippedInputstream( true );
167             }
168         }
169         if ( parser == null ) {
170             final String first_line = ForesterUtil.getFirstLine( url ).trim().toLowerCase();
171             if ( first_line.startsWith( "<" ) ) {
172                 parser = new PhyloXmlParser();
173                 if ( phyloxml_validate_against_xsd ) {
174                     final ClassLoader cl = PhyloXmlParser.class.getClassLoader();
175                     final URL xsd_url = cl.getResource( ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE );
176                     if ( xsd_url != null ) {
177                         ( ( PhyloXmlParser ) parser ).setValidateAgainstSchema( xsd_url.toString() );
178                     }
179                     else {
180                         throw new RuntimeException( "failed to get URL for phyloXML XSD from jar file from ["
181                                 + ForesterConstants.LOCAL_PHYLOXML_XSD_RESOURCE + "]" );
182                     }
183                 }
184             }
185             else if ( ( first_line.startsWith( "nexus" ) ) || ( first_line.startsWith( "#nexus" ) )
186                     || ( first_line.startsWith( "# nexus" ) ) || ( first_line.startsWith( "begin" ) ) ) {
187                 parser = new NexusPhylogeniesParser();
188             }
189             else {
190                 parser = new NHXParser();
191             }
192         }
193         return parser;
194     }
195
196     public static BufferedReader createReader( final Object source ) throws IOException, FileNotFoundException {
197         BufferedReader reader = null;
198         if ( ( source instanceof File ) || ( source instanceof String ) ) {
199             File f = null;
200             if ( source instanceof File ) {
201                 f = ( File ) source;
202             }
203             else {
204                 f = new File( ( String ) source );
205             }
206             if ( !f.exists() ) {
207                 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
208             }
209             else if ( !f.isFile() ) {
210                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
211             }
212             else if ( !f.canRead() ) {
213                 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
214             }
215             reader = new BufferedReader( new FileReader( f ) );
216         }
217         else if ( source instanceof InputStream ) {
218             reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
219         }
220         else if ( ( source instanceof StringBuffer ) || ( source instanceof StringBuilder ) ) {
221             reader = new BufferedReader( new StringReader( source.toString() ) );
222         }
223         else {
224             throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
225                     + "] (can only parse objects of type File/String, InputStream, StringBuffer, or StringBuilder)" );
226         }
227         return reader;
228     }
229
230     public final static String extractTaxonomyCodeFromNodeName( final String name,
231                                                                 final TAXONOMY_EXTRACTION taxonomy_extraction ) {
232         if ( ( name.indexOf( "_" ) > 0 )
233                 && ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT ) || ( name.indexOf( "/" ) > 4 ) ) ) {
234             final String[] s = name.split( "[_\\s]" );
235             if ( s.length > 1 ) {
236                 final String str = s[ 1 ];
237                 if ( !ForesterUtil.isEmpty( str ) ) {
238                     if ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT ) {
239                         final Matcher m = TAXOMONY_CODE_PATTERN_PF.matcher( str );
240                         if ( m.matches() ) {
241                             return m.group( 1 );
242                         }
243                     }
244                     else {
245                         final Matcher m1 = TAXOMONY_CODE_PATTERN_1.matcher( str );
246                         if ( m1.matches() ) {
247                             return m1.group();
248                         }
249                         final Matcher m2 = TAXOMONY_CODE_PATTERN_2.matcher( str );
250                         if ( m2.matches() ) {
251                             return m2.group( 1 );
252                         }
253                     }
254                 }
255             }
256         }
257         if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
258                 || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGRESSIVE ) ) {
259             final Matcher m1 = TAXOMONY_CODE_PATTERN_1.matcher( name );
260             if ( m1.matches() ) {
261                 return name;
262             }
263             final Matcher m3 = TAXOMONY_CODE_PATTERN_3.matcher( name );
264             if ( m3.matches() ) {
265                 return m3.group( 1 );
266             }
267         }
268         return null;
269     }
270
271     public final static String extractScientificNameFromNodeName( final String name ) {
272         final Matcher m1 = TAXOMONY_SN_PATTERN.matcher( name );
273         if ( m1.matches() ) {
274             return m1.group( 1 ).replace( '_', ' ' );
275         }
276         return null;
277     }
278
279     public final static String extractTaxonomyDataFromNodeName( final PhylogenyNode node,
280                                                                 final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
281             throws PhyloXmlDataFormatException {
282         final String id = extractUniprotTaxonomyIdFromNodeName( node.getName(), taxonomy_extraction );
283         if ( !ForesterUtil.isEmpty( id ) ) {
284             if ( !node.getNodeData().isHasTaxonomy() ) {
285                 node.getNodeData().setTaxonomy( new Taxonomy() );
286             }
287             if ( ( node.getNodeData().getTaxonomy().getIdentifier() == null )
288                     || ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getIdentifier().getValue() ) ) {
289                 node.getNodeData().getTaxonomy().setIdentifier( new Identifier( id, "uniprot" ) );
290                 return id;
291             }
292         }
293         else {
294             final String code = extractTaxonomyCodeFromNodeName( node.getName(), taxonomy_extraction );
295             if ( !ForesterUtil.isEmpty( code ) ) {
296                 if ( !node.getNodeData().isHasTaxonomy() ) {
297                     node.getNodeData().setTaxonomy( new Taxonomy() );
298                 }
299                 if ( ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
300                     node.getNodeData().getTaxonomy().setTaxonomyCode( code );
301                     return code;
302                 }
303             }
304             else if ( ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED )
305                     || ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGRESSIVE ) ) {
306                 final String sn = extractScientificNameFromNodeName( node.getName() );
307                 if ( !ForesterUtil.isEmpty( sn ) ) {
308                     if ( !node.getNodeData().isHasTaxonomy() ) {
309                         node.getNodeData().setTaxonomy( new Taxonomy() );
310                     }
311                     if ( ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
312                         node.getNodeData().getTaxonomy().setScientificName( sn );
313                         return sn;
314                     }
315                 }
316             }
317         }
318         return null;
319     }
320
321     public final static String extractUniprotTaxonomyIdFromNodeName( final String name,
322                                                                      final TAXONOMY_EXTRACTION taxonomy_extraction ) {
323         if ( ( name.indexOf( "_" ) > 0 )
324                 && ( ( taxonomy_extraction != TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT ) || ( name.indexOf( "/" ) > 4 ) ) ) {
325             final String[] s = name.split( "[_\\s]" );
326             if ( s.length > 1 ) {
327                 final String str = s[ 1 ];
328                 if ( !ForesterUtil.isEmpty( str ) ) {
329                     if ( taxonomy_extraction == TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT ) {
330                         final Matcher m = TAXOMONY_UNIPROT_ID_PATTERN_PF.matcher( str );
331                         if ( m.matches() ) {
332                             return m.group( 1 );
333                         }
334                     }
335                     else {
336                         final Matcher m1 = TAXOMONY_UNIPROT_ID_PATTERN_1.matcher( str );
337                         if ( m1.matches() ) {
338                             return m1.group();
339                         }
340                         final Matcher m2 = TAXOMONY_UNIPROT_ID_PATTERN_2.matcher( str );
341                         if ( m2.matches() ) {
342                             return m2.group( 1 );
343                         }
344                     }
345                 }
346             }
347         }
348         if ( taxonomy_extraction == TAXONOMY_EXTRACTION.AGRESSIVE ) {
349             final Matcher m1 = TAXOMONY_UNIPROT_ID_PATTERN_1.matcher( name );
350             if ( m1.matches() ) {
351                 return name;
352             }
353         }
354         return null;
355     }
356
357     public final static Phylogeny[] readPhylogenies( final File file ) throws FileNotFoundException, IOException {
358         return PhylogenyMethods.readPhylogenies( ParserUtils.createParserDependingOnFileType( file, true ), file );
359     }
360
361     public final static Phylogeny[] readPhylogenies( final String file_name ) throws FileNotFoundException, IOException {
362         return readPhylogenies( new File( file_name ) );
363     }
364 }