sorting added ...
[jalview.git] / forester / java / src / org / forester / ws / uniprot / UniProtWsTools.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.uniprot;
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.util.ForesterUtil;
41
42 public final class UniProtWsTools {
43
44     public enum Db {
45         UNKNOWN, UNIPROT;
46     }
47     public final static String   BASE_URL           = "http://www.uniprot.org/";
48     public final static String   BASE_EMBL_DB_URL   = "http://www.ebi.ac.uk/Tools/dbfetch/dbfetch/embl/";
49     private final static String  URL_ENC            = "UTF-8";
50     // uniprot/expasy accession number format (6 chars):
51     // letter digit letter-or-digit letter-or-digit letter-or-digit digit
52     // ?: => no back-reference
53     // \A => begin of String
54     // \Z => end of String
55     private final static Pattern UNIPROT_AC_PATTERN = Pattern
56                                                             .compile( "(?:\\A|.*[^a-zA-Z0-9])([A-Z]\\d[A-Z0-9]{3}\\d)(?:[^a-zA-Z0-9]|\\Z)" );
57     private final static boolean DEBUG              = false;
58
59     private static String encode( final String str ) throws UnsupportedEncodingException {
60         return URLEncoder.encode( str.trim(), URL_ENC );
61     }
62
63     /**
64      * Returns null if no match.
65      * 
66      * @param query
67      * @param db 
68      * @return
69      */
70     static public String parseUniProtAccessor( final String query ) {
71         final Matcher m = UNIPROT_AC_PATTERN.matcher( query );
72         if ( m.lookingAt() ) {
73             return m.group( 1 );
74         }
75         else {
76             return null;
77         }
78     }
79
80     public static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String cn, final int max_taxonomies_return )
81             throws IOException {
82         final List<String> result = getTaxonomyStringFromCommonName( cn, max_taxonomies_return );
83         if ( result.size() > 0 ) {
84             return parseUniProtTaxonomy( result );
85         }
86         return null;
87     }
88
89     public static List<UniProtTaxonomy> getTaxonomiesFromCommonNameStrict( final String cn,
90                                                                            final int max_taxonomies_return )
91             throws IOException {
92         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromCommonName( cn, max_taxonomies_return );
93         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
94             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
95             for( final UniProtTaxonomy taxonomy : taxonomies ) {
96                 if ( taxonomy.getCommonName().equalsIgnoreCase( cn ) ) {
97                     filtered_taxonomies.add( taxonomy );
98                 }
99             }
100             return filtered_taxonomies;
101         }
102         return null;
103     }
104
105     public static List<UniProtTaxonomy> getTaxonomiesFromId( final String id, final int max_taxonomies_return )
106             throws IOException {
107         final List<String> result = getTaxonomyStringFromId( id, max_taxonomies_return );
108         if ( result.size() > 0 ) {
109             return parseUniProtTaxonomy( result );
110         }
111         return null;
112     }
113
114     public static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String sn,
115                                                                          final int max_taxonomies_return )
116             throws IOException {
117         // Hack!  Craniata? .. 
118         if ( sn.equals( "Drosophila" ) ) {
119             return hack( UniProtTaxonomy.DROSOPHILA_GENUS );
120         }
121         else if ( sn.equals( "Xenopus" ) ) {
122             return hack( UniProtTaxonomy.XENOPUS_GENUS );
123         }
124         // else if ( sn.equals( "Nucleariidae and Fonticula group" ) ) {
125         //     return hack( UniProtTaxonomy.NUCLEARIIDAE_AND_FONTICULA );
126         // }
127         final List<String> result = getTaxonomyStringFromScientificName( sn, max_taxonomies_return );
128         if ( result.size() > 0 ) {
129             return parseUniProtTaxonomy( result );
130         }
131         return null;
132     }
133
134     /**
135      * Does not return "sub-types".
136      * For example, for "Mus musculus" only returns "Mus musculus"
137      * and not "Mus musculus", "Mus musculus bactrianus", ...
138      * 
139      */
140     public static List<UniProtTaxonomy> getTaxonomiesFromScientificNameStrict( final String sn,
141                                                                                final int max_taxonomies_return )
142             throws IOException {
143         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromScientificName( sn, max_taxonomies_return );
144         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
145             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
146             for( final UniProtTaxonomy taxonomy : taxonomies ) {
147                 if ( taxonomy.getScientificName().equalsIgnoreCase( sn ) ) {
148                     filtered_taxonomies.add( taxonomy );
149                 }
150             }
151             return filtered_taxonomies;
152         }
153         return null;
154     }
155
156     public static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String code,
157                                                                        final int max_taxonomies_return )
158             throws IOException {
159         String my_code = new String( code );
160         // Hacks!
161         if ( my_code.equals( "FUGRU" ) ) {
162             my_code = "TAKRU";
163         }
164         else if ( my_code.equals( "CAP" ) ) {
165             return hack( UniProtTaxonomy.CAPITELLA_TELATA_SPECIES );
166         }
167         final List<String> result = getTaxonomyStringFromTaxonomyCode( my_code, max_taxonomies_return );
168         if ( result.size() > 0 ) {
169             return parseUniProtTaxonomy( result );
170         }
171         return null;
172     }
173
174     private static List<String> getTaxonomyStringFromCommonName( final String cn, final int max_lines_to_return )
175             throws IOException {
176         return queryUniprot( "taxonomy/?query=common%3a%22" + encode( cn ) + "%22&format=tab", max_lines_to_return );
177     }
178
179     private static List<String> getTaxonomyStringFromId( final String id, final int max_lines_to_return )
180             throws IOException {
181         return queryUniprot( "taxonomy/?query=id%3a%22" + encode( id ) + "%22&format=tab", max_lines_to_return );
182     }
183
184     private static List<String> getTaxonomyStringFromScientificName( final String sn, final int max_lines_to_return )
185             throws IOException {
186         return queryUniprot( "taxonomy/?query=scientific%3a%22" + encode( sn ) + "%22&format=tab", max_lines_to_return );
187     }
188
189     private static List<String> getTaxonomyStringFromTaxonomyCode( final String code, final int max_lines_to_return )
190             throws IOException {
191         return queryUniprot( "taxonomy/?query=mnemonic%3a%22" + encode( code ) + "%22&format=tab", max_lines_to_return );
192     }
193
194     private static List<UniProtTaxonomy> hack( final UniProtTaxonomy tax ) {
195         final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
196         l.add( tax );
197         return l;
198     }
199
200     private static List<UniProtTaxonomy> parseUniProtTaxonomy( final List<String> result ) throws IOException {
201         final List<UniProtTaxonomy> taxonomies = new ArrayList<UniProtTaxonomy>();
202         for( final String line : result ) {
203             if ( ForesterUtil.isEmpty( line ) ) {
204                 // Ignore empty lines.
205             }
206             else if ( line.startsWith( "Taxon" ) ) {
207                 final String[] items = line.split( "\t" );
208                 if ( !( items[ 1 ].equalsIgnoreCase( "Mnemonic" ) && items[ 2 ].equalsIgnoreCase( "Scientific name" )
209                         && items[ 3 ].equalsIgnoreCase( "Common name" ) && items[ 4 ].equalsIgnoreCase( "Synonym" )
210                         && items[ 5 ].equalsIgnoreCase( "Other Names" ) && items[ 6 ].equalsIgnoreCase( "Reviewed" )
211                         && items[ 7 ].equalsIgnoreCase( "Rank" ) && items[ 8 ].equalsIgnoreCase( "Lineage" ) ) ) {
212                     throw new IOException( "Unreconized UniProt Taxonomy format: " + line );
213                 }
214             }
215             else {
216                 if ( line.split( "\t" ).length > 4 ) {
217                     taxonomies.add( new UniProtTaxonomy( line ) );
218                 }
219             }
220         }
221         return taxonomies;
222     }
223
224     public static List<String> queryEmblDb( final String query, final int max_lines_to_return ) throws IOException {
225         return queryDb( query, max_lines_to_return, BASE_EMBL_DB_URL );
226     }
227
228     public static List<String> queryUniprot( final String query, final int max_lines_to_return ) throws IOException {
229         return queryDb( query, max_lines_to_return, BASE_URL );
230     }
231
232     public static List<String> queryDb( final String query, int max_lines_to_return, final String base_url )
233             throws IOException {
234         if ( ForesterUtil.isEmpty( query ) ) {
235             throw new IllegalArgumentException( "illegal attempt to use empty query " );
236         }
237         if ( max_lines_to_return < 1 ) {
238             max_lines_to_return = 1;
239         }
240         final URL url = new URL( base_url + query );
241         if ( DEBUG ) {
242             System.out.println( "url: " + url.toString() );
243         }
244         final URLConnection urlc = url.openConnection();
245         final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
246         String line;
247         final List<String> result = new ArrayList<String>();
248         while ( ( line = in.readLine() ) != null ) {
249             if ( DEBUG ) {
250                 System.out.println( line );
251             }
252             result.add( line );
253             if ( result.size() > max_lines_to_return ) {
254                 break;
255             }
256         }
257         in.close();
258         return result;
259     }
260
261     public static SequenceDatabaseEntry obtainUniProtEntry( final String query, final int max_lines_to_return )
262             throws IOException {
263         final List<String> lines = queryUniprot( "uniprot/" + query + ".txt", max_lines_to_return );
264         return UniProtEntry.createInstanceFromPlainText( lines );
265     }
266
267     public static SequenceDatabaseEntry obtainEmblEntry( final String query, final int max_lines_to_return )
268             throws IOException {
269         final List<String> lines = queryEmblDb( query, max_lines_to_return );
270         return EbiDbEntry.createInstanceFromPlainText( lines );
271     }
272 }