cleanup
[jalview.git] / forester / java / src / org / forester / ws / seqdb / SequenceDbWsTools.java
1 // $Id:
2 // forester -- software libraries and applications
3 // for genomics and evolutionary biology research.
4 //
5 // Copyright (C) 2010 Christian M Zmasek
6 // Copyright (C) 2010 Sanford-Burnham Medical Research Institute
7 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
25
26 package org.forester.ws.seqdb;
27
28 import java.io.BufferedReader;
29 import java.io.IOException;
30 import java.io.InputStreamReader;
31 import java.io.UnsupportedEncodingException;
32 import java.net.URL;
33 import java.net.URLConnection;
34 import java.net.URLEncoder;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
39
40 import org.forester.phylogeny.data.Identifier;
41 import org.forester.util.ForesterUtil;
42
43 public final class SequenceDbWsTools {
44
45     private static final boolean ALLOW_TAXONOMY_CODE_HACKS = true; //TODO turn off for final realease!
46
47     public enum Db {
48         UNKNOWN, UNIPROT;
49     }
50     public final static String   BASE_UNIPROT_URL   = "http://www.uniprot.org/";
51     public final static String   BASE_EMBL_DB_URL   = "http://www.ebi.ac.uk/Tools/dbfetch/dbfetch/";
52     public final static String   EMBL_DBS_EMBL      = "embl";
53     public final static String   EMBL_DBS_REFSEQ_P  = "refseqp";
54     public final static String   EMBL_DBS_REFSEQ_N  = "refseqn";
55     private final static String  URL_ENC            = "UTF-8";
56     // uniprot/expasy accession number format (6 chars):
57     // letter digit letter-or-digit letter-or-digit letter-or-digit digit
58     // ?: => no back-reference
59     // \A => begin of String
60     // \Z => end of String
61     private final static Pattern UNIPROT_AC_PATTERN = Pattern
62                                                             .compile( "(?:\\A|.*[^a-zA-Z0-9])([A-Z]\\d[A-Z0-9]{3}\\d)(?:[^a-zA-Z0-9]|\\Z)" );
63     private final static boolean DEBUG              = false;
64
65     private static String encode( final String str ) throws UnsupportedEncodingException {
66         return URLEncoder.encode( str.trim(), URL_ENC );
67     }
68
69     /**
70      * Returns null if no match.
71      * 
72      * @param query
73      * @param db 
74      * @return
75      */
76     static public String parseUniProtAccessor( final String query ) {
77         final Matcher m = UNIPROT_AC_PATTERN.matcher( query );
78         if ( m.lookingAt() ) {
79             return m.group( 1 );
80         }
81         else {
82             return null;
83         }
84     }
85
86     public static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String cn, final int max_taxonomies_return )
87             throws IOException {
88         final List<String> result = getTaxonomyStringFromCommonName( cn, max_taxonomies_return );
89         if ( result.size() > 0 ) {
90             return parseUniProtTaxonomy( result );
91         }
92         return null;
93     }
94
95     public static List<UniProtTaxonomy> getTaxonomiesFromCommonNameStrict( final String cn,
96                                                                            final int max_taxonomies_return )
97             throws IOException {
98         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromCommonName( cn, max_taxonomies_return );
99         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
100             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
101             for( final UniProtTaxonomy taxonomy : taxonomies ) {
102                 if ( taxonomy.getCommonName().equalsIgnoreCase( cn ) ) {
103                     filtered_taxonomies.add( taxonomy );
104                 }
105             }
106             return filtered_taxonomies;
107         }
108         return null;
109     }
110
111     public static List<UniProtTaxonomy> getTaxonomiesFromId( final String id, final int max_taxonomies_return )
112             throws IOException {
113         final List<String> result = getTaxonomyStringFromId( id, max_taxonomies_return );
114         if ( result.size() > 0 ) {
115             return parseUniProtTaxonomy( result );
116         }
117         return null;
118     }
119
120     public static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String sn,
121                                                                          final int max_taxonomies_return )
122             throws IOException {
123         // Hack!  Craniata? .. 
124         if ( sn.equals( "Drosophila" ) ) {
125             return uniProtTaxonomyToList( UniProtTaxonomy.DROSOPHILA_GENUS );
126         }
127         else if ( sn.equals( "Xenopus" ) ) {
128             return uniProtTaxonomyToList( UniProtTaxonomy.XENOPUS_GENUS );
129         }
130         // else if ( sn.equals( "Nucleariidae and Fonticula group" ) ) {
131         //     return hack( UniProtTaxonomy.NUCLEARIIDAE_AND_FONTICULA );
132         // }
133         final List<String> result = getTaxonomyStringFromScientificName( sn, max_taxonomies_return );
134         if ( result.size() > 0 ) {
135             return parseUniProtTaxonomy( result );
136         }
137         return null;
138     }
139
140     /**
141      * Does not return "sub-types".
142      * For example, for "Mus musculus" only returns "Mus musculus"
143      * and not "Mus musculus", "Mus musculus bactrianus", ...
144      * 
145      */
146     public static List<UniProtTaxonomy> getTaxonomiesFromScientificNameStrict( final String sn,
147                                                                                final int max_taxonomies_return )
148             throws IOException {
149         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromScientificName( sn, max_taxonomies_return );
150         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
151             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
152             for( final UniProtTaxonomy taxonomy : taxonomies ) {
153                 if ( taxonomy.getScientificName().equalsIgnoreCase( sn ) ) {
154                     filtered_taxonomies.add( taxonomy );
155                 }
156             }
157             return filtered_taxonomies;
158         }
159         return null;
160     }
161
162     public static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String code,
163                                                                        final int max_taxonomies_return )
164             throws IOException {
165         final String my_code = new String( code );
166         if ( ALLOW_TAXONOMY_CODE_HACKS ) {
167             final List<UniProtTaxonomy> l = resolveFakeTaxonomyCodes( max_taxonomies_return, my_code );
168             if ( l != null ) {
169                 return l;
170             }
171         }
172         final List<String> result = getTaxonomyStringFromTaxonomyCode( my_code, max_taxonomies_return );
173         if ( result.size() > 0 ) {
174             return parseUniProtTaxonomy( result );
175         }
176         return null;
177     }
178
179     private static List<UniProtTaxonomy> resolveFakeTaxonomyCodes( final int max_taxonomies_return, final String code )
180             throws IOException {
181         if ( code.equals( "CAP" ) ) {
182             return getTaxonomiesFromId( "283909", max_taxonomies_return );
183         }
184         else if ( code.equals( "FUGRU" ) ) {
185             return getTaxonomiesFromId( "31033", max_taxonomies_return );
186         }
187         else if ( code.equals( "GIALA" ) ) {
188             return getTaxonomiesFromId( "5741", max_taxonomies_return );
189         }
190         else if ( code.equals( "TRIVE" ) ) {
191             return getTaxonomiesFromId( "413071", max_taxonomies_return );
192         }
193         else if ( code.equals( "CAPOWC" ) ) {
194             return getTaxonomiesFromId( "192875", max_taxonomies_return );
195         }
196         else if ( code.equals( "SPHARC" ) ) {
197             return getTaxonomiesFromId( "667725", max_taxonomies_return );
198         }
199         else if ( code.equals( "THETRA" ) ) {
200             return getTaxonomiesFromId( "529818", max_taxonomies_return );
201         }
202         else if ( code.equals( "CHLVUL" ) ) {
203             return getTaxonomiesFromId( "574566", max_taxonomies_return );
204         }
205         else if ( code.equals( "CITCLE" ) ) {
206             return getTaxonomiesFromId( "85681", max_taxonomies_return );
207         }
208         else if ( code.equals( "MYCPOP" ) ) {
209             return getTaxonomiesFromId( "85929", max_taxonomies_return );
210         }
211         else if ( code.equals( "AGABB" ) ) {
212             return getTaxonomiesFromId( "597362", max_taxonomies_return );
213         }
214         else if ( code.equals( "BAUCOM" ) ) {
215             return getTaxonomiesFromId( "430998", max_taxonomies_return );
216         }
217         else if ( code.equals( "DICSQU" ) ) {
218             return getTaxonomiesFromId( "114155", max_taxonomies_return );
219         }
220         else if ( code.equals( "FOMPIN" ) ) {
221             return getTaxonomiesFromId( "40483", max_taxonomies_return );
222         }
223         else if ( code.equals( "HYDMA" ) ) {
224             return getTaxonomiesFromId( "6085", max_taxonomies_return );
225         }
226         else if ( code.equals( "MYCFI" ) ) {
227             return getTaxonomiesFromId( "83344", max_taxonomies_return );
228         }
229         else if ( code.equals( "OIDMAI" ) ) {
230             return getTaxonomiesFromId( "78148", max_taxonomies_return );
231         }
232         else if ( code.equals( "OSTRC" ) ) {
233             return getTaxonomiesFromId( "385169", max_taxonomies_return );
234         }
235         else if ( code.equals( "POSPL" ) ) {
236             return getTaxonomiesFromId( "104341", max_taxonomies_return );
237         }
238         else if ( code.equals( "SAICOM" ) ) {
239             return getTaxonomiesFromId( "5606", max_taxonomies_return );
240         }
241         else if ( code.equals( "SERLA" ) ) {
242             return getTaxonomiesFromId( "85982", max_taxonomies_return );
243         }
244         else if ( code.equals( "SPORO" ) ) {
245             return getTaxonomiesFromId( "40563", max_taxonomies_return );
246         }
247         else if ( code.equals( "ACRALC" ) ) {
248             return getTaxonomiesFromId( "398408", max_taxonomies_return );
249         }
250         else if ( code.equals( "THITER" ) ) {
251             return getTaxonomiesFromId( "35720", max_taxonomies_return );
252         }
253         else if ( code.equals( "MYCTHE" ) ) {
254             return getTaxonomiesFromId( "78579", max_taxonomies_return );
255         }
256         else if ( code.equals( "CONPUT" ) ) {
257             return getTaxonomiesFromId( "80637", max_taxonomies_return );
258         }
259         else if ( code.equals( "WOLCOC" ) ) {
260             return getTaxonomiesFromId( "81056", max_taxonomies_return );
261         }
262         else if ( code.equals( "CLAGRA" ) ) {
263             return getTaxonomiesFromId( "27339", max_taxonomies_return );
264         }
265         else if ( code.equals( "XANPAR" ) ) {
266             return getTaxonomiesFromId( "107463", max_taxonomies_return );
267         }
268         else if ( code.equals( "HYDPIN" ) ) {
269             return getTaxonomiesFromId( "388859", max_taxonomies_return );
270         }
271         else if ( code.equals( "SERLAC" ) ) {
272             return getTaxonomiesFromId( "85982", max_taxonomies_return );
273         }
274         else {
275             return null;
276         }
277     }
278
279     private static List<String> getTaxonomyStringFromCommonName( final String cn, final int max_lines_to_return )
280             throws IOException {
281         return queryUniprot( "taxonomy/?query=common%3a%22" + encode( cn ) + "%22&format=tab", max_lines_to_return );
282     }
283
284     private static List<String> getTaxonomyStringFromId( final String id, final int max_lines_to_return )
285             throws IOException {
286         return queryUniprot( "taxonomy/?query=id%3a%22" + encode( id ) + "%22&format=tab", max_lines_to_return );
287     }
288
289     private static List<String> getTaxonomyStringFromScientificName( final String sn, final int max_lines_to_return )
290             throws IOException {
291         return queryUniprot( "taxonomy/?query=scientific%3a%22" + encode( sn ) + "%22&format=tab", max_lines_to_return );
292     }
293
294     private static List<String> getTaxonomyStringFromTaxonomyCode( final String code, final int max_lines_to_return )
295             throws IOException {
296         return queryUniprot( "taxonomy/?query=mnemonic%3a%22" + encode( code ) + "%22&format=tab", max_lines_to_return );
297     }
298
299     private static List<UniProtTaxonomy> uniProtTaxonomyToList( final UniProtTaxonomy tax ) {
300         final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
301         l.add( tax );
302         return l;
303     }
304
305     private static List<UniProtTaxonomy> parseUniProtTaxonomy( final List<String> result ) throws IOException {
306         final List<UniProtTaxonomy> taxonomies = new ArrayList<UniProtTaxonomy>();
307         for( final String line : result ) {
308             if ( ForesterUtil.isEmpty( line ) ) {
309                 // Ignore empty lines.
310             }
311             else if ( line.startsWith( "Taxon" ) ) {
312                 final String[] items = line.split( "\t" );
313                 if ( !( items[ 1 ].equalsIgnoreCase( "Mnemonic" ) && items[ 2 ].equalsIgnoreCase( "Scientific name" )
314                         && items[ 3 ].equalsIgnoreCase( "Common name" ) && items[ 4 ].equalsIgnoreCase( "Synonym" )
315                         && items[ 5 ].equalsIgnoreCase( "Other Names" ) && items[ 6 ].equalsIgnoreCase( "Reviewed" )
316                         && items[ 7 ].equalsIgnoreCase( "Rank" ) && items[ 8 ].equalsIgnoreCase( "Lineage" ) ) ) {
317                     throw new IOException( "Unreconized UniProt Taxonomy format: " + line );
318                 }
319             }
320             else {
321                 if ( line.split( "\t" ).length > 4 ) {
322                     taxonomies.add( new UniProtTaxonomy( line ) );
323                 }
324             }
325         }
326         return taxonomies;
327     }
328
329     public static List<String> queryEmblDb( final Identifier id, final int max_lines_to_return ) throws IOException {
330         final StringBuilder url_sb = new StringBuilder();
331         url_sb.append( BASE_EMBL_DB_URL );
332         if ( ForesterUtil.isEmpty( id.getProvider() ) || id.getProvider().equalsIgnoreCase( Identifier.NCBI ) ) {
333             url_sb.append( SequenceDbWsTools.EMBL_DBS_EMBL );
334             url_sb.append( '/' );
335         }
336         else if ( id.getProvider().equalsIgnoreCase( Identifier.REFSEQ ) ) {
337             if ( id.getValue().toUpperCase().indexOf( 'P' ) == 1 ) {
338                 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_P );
339                 url_sb.append( '/' );
340             }
341             else {
342                 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_N );
343                 url_sb.append( '/' );
344             }
345         }
346         return queryDb( id.getValue(), max_lines_to_return, url_sb.toString() );
347     }
348
349     public static List<String> queryUniprot( final String query, final int max_lines_to_return ) throws IOException {
350         return queryDb( query, max_lines_to_return, BASE_UNIPROT_URL );
351     }
352
353     public static List<String> queryDb( final String query, int max_lines_to_return, final String base_url )
354             throws IOException {
355         if ( ForesterUtil.isEmpty( query ) ) {
356             throw new IllegalArgumentException( "illegal attempt to use empty query " );
357         }
358         if ( max_lines_to_return < 1 ) {
359             max_lines_to_return = 1;
360         }
361         final URL url = new URL( base_url + query );
362         if ( DEBUG ) {
363             System.out.println( "url: " + url.toString() );
364         }
365         final URLConnection urlc = url.openConnection();
366         final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
367         String line;
368         final List<String> result = new ArrayList<String>();
369         while ( ( line = in.readLine() ) != null ) {
370             if ( DEBUG ) {
371                 System.out.println( line );
372             }
373             result.add( line );
374             if ( result.size() > max_lines_to_return ) {
375                 break;
376             }
377         }
378         in.close();
379         try {
380             // To prevent accessing online dbs in too quick succession. 
381             Thread.sleep( 20 );
382         }
383         catch ( final InterruptedException e ) {
384             e.printStackTrace();
385         }
386         return result;
387     }
388
389     public static SequenceDatabaseEntry obtainUniProtEntry( final String query, final int max_lines_to_return )
390             throws IOException {
391         final List<String> lines = queryUniprot( "uniprot/" + query + ".txt", max_lines_to_return );
392         return UniProtEntry.createInstanceFromPlainText( lines );
393     }
394
395     public static SequenceDatabaseEntry obtainRefSeqEntryFromEmbl( final Identifier id, final int max_lines_to_return )
396             throws IOException {
397         final List<String> lines = queryEmblDb( id, max_lines_to_return );
398         return EbiDbEntry.createInstanceFromPlainTextForRefSeq( lines );
399     }
400
401     public static SequenceDatabaseEntry obtainEmblEntry( final Identifier id, final int max_lines_to_return )
402             throws IOException {
403         final List<String> lines = queryEmblDb( id, max_lines_to_return );
404         return EbiDbEntry.createInstanceFromPlainText( lines );
405     }
406 }