phylotastic hackathon at NESCENT 120606
[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     
56     private final static String  URL_ENC            = "UTF-8";
57     // uniprot/expasy accession number format (6 chars):
58     // letter digit letter-or-digit letter-or-digit letter-or-digit digit
59     // ?: => no back-reference
60     // \A => begin of String
61     // \Z => end of String
62     private final static Pattern UNIPROT_AC_PATTERN = Pattern
63                                                             .compile( "(?:\\A|.*[^a-zA-Z0-9])([A-Z]\\d[A-Z0-9]{3}\\d)(?:[^a-zA-Z0-9]|\\Z)" );
64     private final static boolean DEBUG              = false;
65
66     private static String encode( final String str ) throws UnsupportedEncodingException {
67         return URLEncoder.encode( str.trim(), URL_ENC );
68     }
69
70     /**
71      * Returns null if no match.
72      * 
73      * @param query
74      * @param db 
75      * @return
76      */
77     static public String parseUniProtAccessor( final String query ) {
78         final Matcher m = UNIPROT_AC_PATTERN.matcher( query );
79         if ( m.lookingAt() ) {
80             return m.group( 1 );
81         }
82         else {
83             return null;
84         }
85     }
86
87     public static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String cn, final int max_taxonomies_return )
88             throws IOException {
89         final List<String> result = getTaxonomyStringFromCommonName( cn, max_taxonomies_return );
90         if ( result.size() > 0 ) {
91             return parseUniProtTaxonomy( result );
92         }
93         return null;
94     }
95
96     public static List<UniProtTaxonomy> getTaxonomiesFromCommonNameStrict( final String cn,
97                                                                            final int max_taxonomies_return )
98             throws IOException {
99         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromCommonName( cn, max_taxonomies_return );
100         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
101             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
102             for( final UniProtTaxonomy taxonomy : taxonomies ) {
103                 if ( taxonomy.getCommonName().equalsIgnoreCase( cn ) ) {
104                     filtered_taxonomies.add( taxonomy );
105                 }
106             }
107             return filtered_taxonomies;
108         }
109         return null;
110     }
111
112     public static List<UniProtTaxonomy> getTaxonomiesFromId( final String id, final int max_taxonomies_return )
113             throws IOException {
114         final List<String> result = getTaxonomyStringFromId( id, max_taxonomies_return );
115         if ( result.size() > 0 ) {
116             return parseUniProtTaxonomy( result );
117         }
118         return null;
119     }
120
121     public static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String sn,
122                                                                          final int max_taxonomies_return )
123             throws IOException {
124         // Hack!  Craniata? .. 
125         if ( sn.equals( "Drosophila" ) ) {
126             return uniProtTaxonomyToList( UniProtTaxonomy.DROSOPHILA_GENUS );
127         }
128         else if ( sn.equals( "Xenopus" ) ) {
129             return uniProtTaxonomyToList( UniProtTaxonomy.XENOPUS_GENUS );
130         }
131         // else if ( sn.equals( "Nucleariidae and Fonticula group" ) ) {
132         //     return hack( UniProtTaxonomy.NUCLEARIIDAE_AND_FONTICULA );
133         // }
134         final List<String> result = getTaxonomyStringFromScientificName( sn, max_taxonomies_return );
135         if ( result.size() > 0 ) {
136             return parseUniProtTaxonomy( result );
137         }
138         return null;
139     }
140
141     /**
142      * Does not return "sub-types".
143      * For example, for "Mus musculus" only returns "Mus musculus"
144      * and not "Mus musculus", "Mus musculus bactrianus", ...
145      * 
146      */
147     public static List<UniProtTaxonomy> getTaxonomiesFromScientificNameStrict( final String sn,
148                                                                                final int max_taxonomies_return )
149             throws IOException {
150         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromScientificName( sn, max_taxonomies_return );
151         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
152             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
153             for( final UniProtTaxonomy taxonomy : taxonomies ) {
154                 if ( taxonomy.getScientificName().equalsIgnoreCase( sn ) ) {
155                     filtered_taxonomies.add( taxonomy );
156                 }
157             }
158             return filtered_taxonomies;
159         }
160         return null;
161     }
162
163     public static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String code,
164                                                                        final int max_taxonomies_return )
165             throws IOException {
166         final String my_code = new String( code );
167         if ( ALLOW_TAXONOMY_CODE_HACKS ) {
168             final List<UniProtTaxonomy> l = resolveFakeTaxonomyCodes( max_taxonomies_return, my_code );
169             if ( l != null ) {
170                 return l;
171             }
172         }
173         final List<String> result = getTaxonomyStringFromTaxonomyCode( my_code, max_taxonomies_return );
174         if ( result.size() > 0 ) {
175             return parseUniProtTaxonomy( result );
176         }
177         return null;
178     }
179
180     private static List<UniProtTaxonomy> resolveFakeTaxonomyCodes( final int max_taxonomies_return, final String code )
181             throws IOException {
182         if ( code.equals( "CAP" ) ) {
183             return getTaxonomiesFromId( "283909", max_taxonomies_return );
184         }
185         else if ( code.equals( "FUGRU" ) ) {
186             return getTaxonomiesFromId( "31033", max_taxonomies_return );
187         }
188         else if ( code.equals( "GIALA" ) ) {
189             return getTaxonomiesFromId( "5741", max_taxonomies_return );
190         }
191         else if ( code.equals( "TRIVE" ) ) {
192             return getTaxonomiesFromId( "413071", max_taxonomies_return );
193         }
194         else if ( code.equals( "CAPOWC" ) ) {
195             return getTaxonomiesFromId( "192875", max_taxonomies_return );
196         }
197         else if ( code.equals( "SPHARC" ) ) {
198             return getTaxonomiesFromId( "667725", max_taxonomies_return );
199         }
200         else if ( code.equals( "THETRA" ) ) {
201             return getTaxonomiesFromId( "529818", max_taxonomies_return );
202         }
203         else if ( code.equals( "CHLVUL" ) ) {
204             return getTaxonomiesFromId( "574566", max_taxonomies_return );
205         }
206         else if ( code.equals( "CITCLE" ) ) {
207             return getTaxonomiesFromId( "85681", max_taxonomies_return );
208         }
209         else if ( code.equals( "MYCPOP" ) ) {
210             return getTaxonomiesFromId( "85929", max_taxonomies_return );
211         }
212         else if ( code.equals( "AGABB" ) ) {
213             return getTaxonomiesFromId( "597362", max_taxonomies_return );
214         }
215         else if ( code.equals( "BAUCOM" ) ) {
216             return getTaxonomiesFromId( "430998", max_taxonomies_return );
217         }
218         else if ( code.equals( "DICSQU" ) ) {
219             return getTaxonomiesFromId( "114155", max_taxonomies_return );
220         }
221         else if ( code.equals( "FOMPIN" ) ) {
222             return getTaxonomiesFromId( "40483", max_taxonomies_return );
223         }
224         else if ( code.equals( "HYDMA" ) ) {
225             return getTaxonomiesFromId( "6085", max_taxonomies_return );
226         }
227         else if ( code.equals( "MYCFI" ) ) {
228             return getTaxonomiesFromId( "83344", max_taxonomies_return );
229         }
230         else if ( code.equals( "OIDMAI" ) ) {
231             return getTaxonomiesFromId( "78148", max_taxonomies_return );
232         }
233         else if ( code.equals( "OSTRC" ) ) {
234             return getTaxonomiesFromId( "385169", max_taxonomies_return );
235         }
236         else if ( code.equals( "POSPL" ) ) {
237             return getTaxonomiesFromId( "104341", max_taxonomies_return );
238         }
239         else if ( code.equals( "SAICOM" ) ) {
240             return getTaxonomiesFromId( "5606", max_taxonomies_return );
241         }
242         else if ( code.equals( "SERLA" ) ) {
243             return getTaxonomiesFromId( "85982", max_taxonomies_return );
244         }
245         else if ( code.equals( "SPORO" ) ) {
246             return getTaxonomiesFromId( "40563", max_taxonomies_return );
247         }
248         else if ( code.equals( "ACRALC" ) ) {
249             return getTaxonomiesFromId( "398408", max_taxonomies_return );
250         }
251         else if ( code.equals( "THITER" ) ) {
252             return getTaxonomiesFromId( "35720", max_taxonomies_return );
253         }
254         else if ( code.equals( "MYCTHE" ) ) {
255             return getTaxonomiesFromId( "78579", max_taxonomies_return );
256         }
257         else if ( code.equals( "CONPUT" ) ) {
258             return getTaxonomiesFromId( "80637", max_taxonomies_return );
259         }
260         else if ( code.equals( "WOLCOC" ) ) {
261             return getTaxonomiesFromId( "81056", max_taxonomies_return );
262         }
263         else if ( code.equals( "CLAGRA" ) ) {
264             return getTaxonomiesFromId( "27339", max_taxonomies_return );
265         }
266         else if ( code.equals( "XANPAR" ) ) {
267             return getTaxonomiesFromId( "107463", max_taxonomies_return );
268         }
269         else if ( code.equals( "HYDPIN" ) ) {
270             return getTaxonomiesFromId( "388859", max_taxonomies_return );
271         }
272         else if ( code.equals( "SERLAC" ) ) {
273             return getTaxonomiesFromId( "85982", max_taxonomies_return );
274         }
275         else {
276             return null;
277         }
278     }
279
280     private static List<String> getTaxonomyStringFromCommonName( final String cn, final int max_lines_to_return )
281             throws IOException {
282         return queryUniprot( "taxonomy/?query=common%3a%22" + encode( cn ) + "%22&format=tab", max_lines_to_return );
283     }
284
285     private static List<String> getTaxonomyStringFromId( final String id, final int max_lines_to_return )
286             throws IOException {
287         return queryUniprot( "taxonomy/?query=id%3a%22" + encode( id ) + "%22&format=tab", max_lines_to_return );
288     }
289
290     private static List<String> getTaxonomyStringFromScientificName( final String sn, final int max_lines_to_return )
291             throws IOException {
292         return queryUniprot( "taxonomy/?query=scientific%3a%22" + encode( sn ) + "%22&format=tab", max_lines_to_return );
293     }
294
295     private static List<String> getTaxonomyStringFromTaxonomyCode( final String code, final int max_lines_to_return )
296             throws IOException {
297         return queryUniprot( "taxonomy/?query=mnemonic%3a%22" + encode( code ) + "%22&format=tab", max_lines_to_return );
298     }
299
300     private static List<UniProtTaxonomy> uniProtTaxonomyToList( final UniProtTaxonomy tax ) {
301         final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
302         l.add( tax );
303         return l;
304     }
305
306     private static List<UniProtTaxonomy> parseUniProtTaxonomy( final List<String> result ) throws IOException {
307         final List<UniProtTaxonomy> taxonomies = new ArrayList<UniProtTaxonomy>();
308         for( final String line : result ) {
309             if ( ForesterUtil.isEmpty( line ) ) {
310                 // Ignore empty lines.
311             }
312             else if ( line.startsWith( "Taxon" ) ) {
313                 final String[] items = line.split( "\t" );
314                 if ( !( items[ 1 ].equalsIgnoreCase( "Mnemonic" ) && items[ 2 ].equalsIgnoreCase( "Scientific name" )
315                         && items[ 3 ].equalsIgnoreCase( "Common name" ) && items[ 4 ].equalsIgnoreCase( "Synonym" )
316                         && items[ 5 ].equalsIgnoreCase( "Other Names" ) && items[ 6 ].equalsIgnoreCase( "Reviewed" )
317                         && items[ 7 ].equalsIgnoreCase( "Rank" ) && items[ 8 ].equalsIgnoreCase( "Lineage" ) ) ) {
318                     throw new IOException( "Unreconized UniProt Taxonomy format: " + line );
319                 }
320             }
321             else {
322                 if ( line.split( "\t" ).length > 4 ) {
323                     taxonomies.add( new UniProtTaxonomy( line ) );
324                 }
325             }
326         }
327         return taxonomies;
328     }
329
330     public static List<String> queryEmblDb( final Identifier id, final int max_lines_to_return ) throws IOException {
331         
332         StringBuilder url_sb = new StringBuilder();
333         url_sb.append( BASE_EMBL_DB_URL );
334         
335         if ( ForesterUtil.isEmpty(  id.getProvider() ) ||  id.getProvider().equalsIgnoreCase( Identifier.NCBI ) ) {
336            
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               
343                 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_P );
344                 url_sb.append( '/');
345             }
346             else {
347                
348                 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_N );
349                 url_sb.append( '/');
350             }
351         }
352         return queryDb( id.getValue(), max_lines_to_return, url_sb.toString() );
353     }
354
355     public static List<String> queryUniprot( final String query, final int max_lines_to_return ) throws IOException {
356         return queryDb( query, max_lines_to_return, BASE_UNIPROT_URL );
357     }
358
359     public static List<String> queryDb( final String query, int max_lines_to_return, final String base_url )
360             throws IOException {
361         if ( ForesterUtil.isEmpty( query ) ) {
362             throw new IllegalArgumentException( "illegal attempt to use empty query " );
363         }
364         if ( max_lines_to_return < 1 ) {
365             max_lines_to_return = 1;
366         }
367         final URL url = new URL( base_url + query );
368         if ( DEBUG ) {
369             System.out.println( "url: " + url.toString() );
370         }
371         final URLConnection urlc = url.openConnection();
372         final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
373         String line;
374         final List<String> result = new ArrayList<String>();
375         while ( ( line = in.readLine() ) != null ) {
376             if ( DEBUG ) {
377                 System.out.println( line );
378             }
379             result.add( line );
380             if ( result.size() > max_lines_to_return ) {
381                 break;
382             }
383         }
384         in.close();
385         return result;
386     }
387
388     public static SequenceDatabaseEntry obtainUniProtEntry( final String query, final int max_lines_to_return )
389             throws IOException {
390         final List<String> lines = queryUniprot( "uniprot/" + query + ".txt", max_lines_to_return );
391         return UniProtEntry.createInstanceFromPlainText( lines );
392     }
393
394     public static SequenceDatabaseEntry obtainRefSeqEntryFromEmbl( final Identifier id, final int max_lines_to_return )
395             throws IOException {
396         final List<String> lines = queryEmblDb( id, max_lines_to_return );
397         return EbiDbEntry.createInstanceFromPlainTextForRefSeq( lines );
398     }
399
400     public static SequenceDatabaseEntry obtainEmblEntry( final Identifier id, final int max_lines_to_return )
401             throws IOException {
402         final List<String> lines = queryEmblDb( id , max_lines_to_return );
403         return EbiDbEntry.createInstanceFromPlainText( lines );
404     }
405 }