in progress
[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         System.out.println( "SN=" + sn );
135         for( final String string : result ) {
136             System.out.println( "|" + string );
137         }
138         if ( result.size() > 0 ) {
139             return parseUniProtTaxonomy( result );
140         }
141         return null;
142     }
143
144     /**
145      * Does not return "sub-types".
146      * For example, for "Mus musculus" only returns "Mus musculus"
147      * and not "Mus musculus", "Mus musculus bactrianus", ...
148      * 
149      */
150     public static List<UniProtTaxonomy> getTaxonomiesFromScientificNameStrict( final String sn,
151                                                                                final int max_taxonomies_return )
152             throws IOException {
153         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromScientificName( sn, max_taxonomies_return );
154         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
155             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
156             for( final UniProtTaxonomy taxonomy : taxonomies ) {
157                 if ( taxonomy.getScientificName().equalsIgnoreCase( sn ) ) {
158                     filtered_taxonomies.add( taxonomy );
159                 }
160             }
161             return filtered_taxonomies;
162         }
163         return null;
164     }
165
166     public static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String code,
167                                                                        final int max_taxonomies_return )
168             throws IOException {
169         final String my_code = new String( code );
170         if ( ALLOW_TAXONOMY_CODE_HACKS ) {
171             final List<UniProtTaxonomy> l = resolveFakeTaxonomyCodes( max_taxonomies_return, my_code );
172             if ( l != null ) {
173                 return l;
174             }
175         }
176         final List<String> result = getTaxonomyStringFromTaxonomyCode( my_code, max_taxonomies_return );
177         if ( result.size() > 0 ) {
178             return parseUniProtTaxonomy( result );
179         }
180         return null;
181     }
182
183     private static List<UniProtTaxonomy> resolveFakeTaxonomyCodes( final int max_taxonomies_return, final String code )
184             throws IOException {
185         if ( code.equals( "CAP" ) ) {
186             return getTaxonomiesFromId( "283909", max_taxonomies_return );
187         }
188         else if ( code.equals( "FUGRU" ) ) {
189             return getTaxonomiesFromId( "31033", max_taxonomies_return );
190         }
191         else if ( code.equals( "GIALA" ) ) {
192             return getTaxonomiesFromId( "5741", max_taxonomies_return );
193         }
194         else if ( code.equals( "TRIVE" ) ) {
195             return getTaxonomiesFromId( "413071", max_taxonomies_return );
196         }
197         else if ( code.equals( "CAPOWC" ) ) {
198             return getTaxonomiesFromId( "192875", max_taxonomies_return );
199         }
200         else if ( code.equals( "SPHARC" ) ) {
201             return getTaxonomiesFromId( "667725", max_taxonomies_return );
202         }
203         else if ( code.equals( "THETRA" ) ) {
204             return getTaxonomiesFromId( "529818", max_taxonomies_return );
205         }
206         else if ( code.equals( "CHLVUL" ) ) {
207             return getTaxonomiesFromId( "574566", max_taxonomies_return );
208         }
209         else if ( code.equals( "CITCLE" ) ) {
210             return getTaxonomiesFromId( "85681", max_taxonomies_return );
211         }
212         else if ( code.equals( "MYCPOP" ) ) {
213             return getTaxonomiesFromId( "85929", max_taxonomies_return );
214         }
215         else if ( code.equals( "AGABB" ) ) {
216             return getTaxonomiesFromId( "597362", max_taxonomies_return );
217         }
218         else if ( code.equals( "BAUCOM" ) ) {
219             return getTaxonomiesFromId( "430998", max_taxonomies_return );
220         }
221         else if ( code.equals( "DICSQU" ) ) {
222             return getTaxonomiesFromId( "114155", max_taxonomies_return );
223         }
224         else if ( code.equals( "FOMPIN" ) ) {
225             return getTaxonomiesFromId( "40483", max_taxonomies_return );
226         }
227         else if ( code.equals( "HYDMA" ) ) {
228             return getTaxonomiesFromId( "6085", max_taxonomies_return );
229         }
230         else if ( code.equals( "MYCFI" ) ) {
231             return getTaxonomiesFromId( "83344", max_taxonomies_return );
232         }
233         else if ( code.equals( "OIDMAI" ) ) {
234             return getTaxonomiesFromId( "78148", max_taxonomies_return );
235         }
236         else if ( code.equals( "OSTRC" ) ) {
237             return getTaxonomiesFromId( "385169", max_taxonomies_return );
238         }
239         else if ( code.equals( "POSPL" ) ) {
240             return getTaxonomiesFromId( "104341", max_taxonomies_return );
241         }
242         else if ( code.equals( "SAICOM" ) ) {
243             return getTaxonomiesFromId( "5606", max_taxonomies_return );
244         }
245         else if ( code.equals( "SERLA" ) ) {
246             return getTaxonomiesFromId( "85982", max_taxonomies_return );
247         }
248         else if ( code.equals( "SPORO" ) ) {
249             return getTaxonomiesFromId( "40563", max_taxonomies_return );
250         }
251         else if ( code.equals( "ACRALC" ) ) {
252             return getTaxonomiesFromId( "398408", max_taxonomies_return );
253         }
254         else if ( code.equals( "THITER" ) ) {
255             return getTaxonomiesFromId( "35720", max_taxonomies_return );
256         }
257         else if ( code.equals( "MYCTHE" ) ) {
258             return getTaxonomiesFromId( "78579", max_taxonomies_return );
259         }
260         else if ( code.equals( "CONPUT" ) ) {
261             return getTaxonomiesFromId( "80637", max_taxonomies_return );
262         }
263         else if ( code.equals( "WOLCOC" ) ) {
264             return getTaxonomiesFromId( "81056", max_taxonomies_return );
265         }
266         else if ( code.equals( "CLAGRA" ) ) {
267             return getTaxonomiesFromId( "27339", max_taxonomies_return );
268         }
269         else if ( code.equals( "XANPAR" ) ) {
270             return getTaxonomiesFromId( "107463", max_taxonomies_return );
271         }
272         else if ( code.equals( "HYDPIN" ) ) {
273             return getTaxonomiesFromId( "388859", max_taxonomies_return );
274         }
275         else if ( code.equals( "SERLAC" ) ) {
276             return getTaxonomiesFromId( "85982", max_taxonomies_return );
277         }
278         else {
279             return null;
280         }
281     }
282
283     private static List<String> getTaxonomyStringFromCommonName( final String cn, final int max_lines_to_return )
284             throws IOException {
285         return queryUniprot( "taxonomy/?query=common%3a%22" + encode( cn ) + "%22&format=tab", max_lines_to_return );
286     }
287
288     private static List<String> getTaxonomyStringFromId( final String id, final int max_lines_to_return )
289             throws IOException {
290         return queryUniprot( "taxonomy/?query=id%3a%22" + encode( id ) + "%22&format=tab", max_lines_to_return );
291     }
292
293     private static List<String> getTaxonomyStringFromScientificName( final String sn, final int max_lines_to_return )
294             throws IOException {
295         return queryUniprot( "taxonomy/?query=scientific%3a%22" + encode( sn ) + "%22&format=tab", max_lines_to_return );
296     }
297
298     private static List<String> getTaxonomyStringFromTaxonomyCode( final String code, final int max_lines_to_return )
299             throws IOException {
300         return queryUniprot( "taxonomy/?query=mnemonic%3a%22" + encode( code ) + "%22&format=tab", max_lines_to_return );
301     }
302
303     private static List<UniProtTaxonomy> uniProtTaxonomyToList( final UniProtTaxonomy tax ) {
304         final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
305         l.add( tax );
306         return l;
307     }
308
309     private static List<UniProtTaxonomy> parseUniProtTaxonomy( final List<String> result ) throws IOException {
310         final List<UniProtTaxonomy> taxonomies = new ArrayList<UniProtTaxonomy>();
311         for( final String line : result ) {
312             if ( ForesterUtil.isEmpty( line ) ) {
313                 // Ignore empty lines.
314             }
315             else if ( line.startsWith( "Taxon" ) ) {
316                 final String[] items = line.split( "\t" );
317                 if ( !( items[ 1 ].equalsIgnoreCase( "Mnemonic" ) && items[ 2 ].equalsIgnoreCase( "Scientific name" )
318                         && items[ 3 ].equalsIgnoreCase( "Common name" ) && items[ 4 ].equalsIgnoreCase( "Synonym" )
319                         && items[ 5 ].equalsIgnoreCase( "Other Names" ) && items[ 6 ].equalsIgnoreCase( "Reviewed" )
320                         && items[ 7 ].equalsIgnoreCase( "Rank" ) && items[ 8 ].equalsIgnoreCase( "Lineage" ) ) ) {
321                     throw new IOException( "Unreconized UniProt Taxonomy format: " + line );
322                 }
323             }
324             else {
325                 if ( line.split( "\t" ).length > 4 ) {
326                     taxonomies.add( new UniProtTaxonomy( line ) );
327                 }
328             }
329         }
330         return taxonomies;
331     }
332
333     public static List<String> queryEmblDb( final Identifier id, final int max_lines_to_return ) throws IOException {
334         final StringBuilder url_sb = new StringBuilder();
335         url_sb.append( BASE_EMBL_DB_URL );
336         if ( ForesterUtil.isEmpty( id.getProvider() ) || id.getProvider().equalsIgnoreCase( Identifier.NCBI ) ) {
337             url_sb.append( SequenceDbWsTools.EMBL_DBS_EMBL );
338             url_sb.append( '/' );
339         }
340         else if ( id.getProvider().equalsIgnoreCase( Identifier.REFSEQ ) ) {
341             if ( id.getValue().toUpperCase().indexOf( 'P' ) == 1 ) {
342                 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_P );
343                 url_sb.append( '/' );
344             }
345             else {
346                 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_N );
347                 url_sb.append( '/' );
348             }
349         }
350         return queryDb( id.getValue(), max_lines_to_return, url_sb.toString() );
351     }
352
353     public static List<String> queryUniprot( final String query, final int max_lines_to_return ) throws IOException {
354         return queryDb( query, max_lines_to_return, BASE_UNIPROT_URL );
355     }
356
357     public static List<String> queryDb( final String query, int max_lines_to_return, final String base_url )
358             throws IOException {
359         if ( ForesterUtil.isEmpty( query ) ) {
360             throw new IllegalArgumentException( "illegal attempt to use empty query " );
361         }
362         if ( max_lines_to_return < 1 ) {
363             max_lines_to_return = 1;
364         }
365         final URL url = new URL( base_url + query );
366         if ( DEBUG ) {
367             System.out.println( "url: " + url.toString() );
368         }
369         final URLConnection urlc = url.openConnection();
370         final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
371         String line;
372         final List<String> result = new ArrayList<String>();
373         while ( ( line = in.readLine() ) != null ) {
374             if ( DEBUG ) {
375                 System.out.println( line );
376             }
377             result.add( line );
378             if ( result.size() > max_lines_to_return ) {
379                 break;
380             }
381         }
382         in.close();
383         try {
384             // To prevent accessing online dbs in too quick succession. 
385             Thread.sleep( 20 );
386         }
387         catch ( final InterruptedException e ) {
388             e.printStackTrace();
389         }
390         return result;
391     }
392
393     public static SequenceDatabaseEntry obtainUniProtEntry( final String query, final int max_lines_to_return )
394             throws IOException {
395         final List<String> lines = queryUniprot( "uniprot/" + query + ".txt", max_lines_to_return );
396         return UniProtEntry.createInstanceFromPlainText( lines );
397     }
398
399     public static SequenceDatabaseEntry obtainRefSeqEntryFromEmbl( final Identifier id, final int max_lines_to_return )
400             throws IOException {
401         final List<String> lines = queryEmblDb( id, max_lines_to_return );
402         return EbiDbEntry.createInstanceFromPlainTextForRefSeq( lines );
403     }
404
405     public static SequenceDatabaseEntry obtainEmblEntry( final Identifier id, final int max_lines_to_return )
406             throws IOException {
407         final List<String> lines = queryEmblDb( id, max_lines_to_return );
408         return EbiDbEntry.createInstanceFromPlainText( lines );
409     }
410 }