inprogress
[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: https://sites.google.com/site/cmzmasek/home/software/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.SortedSet;
38 import java.util.TreeSet;
39
40 import org.forester.phylogeny.Phylogeny;
41 import org.forester.phylogeny.PhylogenyNode;
42 import org.forester.phylogeny.data.Accession;
43 import org.forester.phylogeny.data.Identifier;
44 import org.forester.phylogeny.data.Sequence;
45 import org.forester.phylogeny.data.Taxonomy;
46 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
47 import org.forester.util.ForesterUtil;
48 import org.forester.util.SequenceIdParser;
49
50 public final class SequenceDbWsTools {
51
52     public final static String   BASE_UNIPROT_URL  = "http://www.uniprot.org/";
53     public final static String   BASE_EMBL_DB_URL  = "http://www.ebi.ac.uk/Tools/dbfetch/dbfetch/";
54     public final static String   EMBL_DBS_EMBL     = "embl";
55     public final static String   EMBL_DBS_REFSEQ_P = "refseqp";
56     public final static String   EMBL_DBS_REFSEQ_N = "refseqn";
57     private final static String  URL_ENC           = "UTF-8";
58     private final static boolean DEBUG             = false;
59
60     private static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String cn, final int max_taxonomies_return )
61             throws IOException {
62         final List<String> result = getTaxonomyStringFromCommonName( cn, max_taxonomies_return );
63         if ( result.size() > 0 ) {
64             return parseUniProtTaxonomy( result );
65         }
66         return null;
67     }
68
69     public static List<UniProtTaxonomy> getTaxonomiesFromCommonNameStrict( final String cn,
70                                                                            final int max_taxonomies_return )
71             throws IOException {
72         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromCommonName( cn, max_taxonomies_return );
73         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
74             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
75             for( final UniProtTaxonomy taxonomy : taxonomies ) {
76                 if ( taxonomy.getCommonName().equalsIgnoreCase( cn ) ) {
77                     filtered_taxonomies.add( taxonomy );
78                 }
79             }
80             return filtered_taxonomies;
81         }
82         return null;
83     }
84
85     public static List<UniProtTaxonomy> getTaxonomiesFromId( final String id, final int max_taxonomies_return )
86             throws IOException {
87         final List<String> result = getTaxonomyStringFromId( id, max_taxonomies_return );
88         if ( result.size() > 0 ) {
89             return parseUniProtTaxonomy( result );
90         }
91         return null;
92     }
93
94     private static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String sn,
95                                                                           final int max_taxonomies_return )
96             throws IOException {
97         final List<String> result = getTaxonomyStringFromScientificName( sn, max_taxonomies_return );
98         if ( result.size() > 0 ) {
99             return parseUniProtTaxonomy( result );
100         }
101         return null;
102     }
103
104     /**
105      * Does not return "sub-types".
106      * For example, for "Mus musculus" only returns "Mus musculus"
107      * and not "Mus musculus", "Mus musculus bactrianus", ...
108      * 
109      */
110     public static List<UniProtTaxonomy> getTaxonomiesFromScientificNameStrict( final String sn,
111                                                                                final int max_taxonomies_return )
112             throws IOException {
113         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromScientificName( sn, max_taxonomies_return );
114         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
115             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
116             for( final UniProtTaxonomy taxonomy : taxonomies ) {
117                 if ( taxonomy.getScientificName().equalsIgnoreCase( sn ) ) {
118                     filtered_taxonomies.add( taxonomy );
119                 }
120             }
121             return filtered_taxonomies;
122         }
123         return null;
124     }
125
126     public static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String code,
127                                                                        final int max_taxonomies_return )
128             throws IOException {
129         final String my_code = new String( code );
130         final List<String> result = getTaxonomyStringFromTaxonomyCode( my_code, max_taxonomies_return );
131         if ( result.size() > 0 ) {
132             return parseUniProtTaxonomy( result );
133         }
134         return null;
135     }
136
137     public static SequenceDatabaseEntry obtainEmblEntry( final Identifier id, final int max_lines_to_return )
138             throws IOException {
139         final List<String> lines = queryEmblDb( id, max_lines_to_return );
140         return EbiDbEntry.createInstanceFromPlainText( lines );
141     }
142
143     public static SequenceDatabaseEntry obtainRefSeqEntryFromEmbl( final Identifier id, final int max_lines_to_return )
144             throws IOException {
145         final List<String> lines = queryEmblDb( id, max_lines_to_return );
146         return EbiDbEntry.createInstanceFromPlainTextForRefSeq( lines );
147     }
148
149     public static SortedSet<String> obtainSeqInformation( final Phylogeny phy,
150                                                           final boolean ext_nodes_only,
151                                                           final boolean allow_to_set_taxonomic_data,
152                                                           final int lines_to_return ) throws IOException {
153         final SortedSet<String> not_found = new TreeSet<String>();
154         for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
155             final PhylogenyNode node = iter.next();
156             if ( ext_nodes_only && node.isInternal() ) {
157                 continue;
158             }
159             String query = null;
160             Identifier id = null;
161             Db db = Db.NONE;
162             if ( node.getNodeData().isHasSequence() && ( node.getNodeData().getSequence().getAccession() != null )
163                     && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getSource() )
164                     && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getValue() )
165                     && node.getNodeData().getSequence().getAccession().getValue().toLowerCase().startsWith( "uniprot" ) ) {
166                 query = node.getNodeData().getSequence().getAccession().getValue();
167                 db = Db.UNIPROT;
168             }
169             else if ( node.getNodeData().isHasSequence()
170                     && ( node.getNodeData().getSequence().getAccession() != null )
171                     && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getSource() )
172                     && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().getValue() )
173                     && ( node.getNodeData().getSequence().getAccession().getValue().toLowerCase().startsWith( "embl" ) || node
174                             .getNodeData().getSequence().getAccession().getValue().toLowerCase().startsWith( "ebi" ) ) ) {
175                 query = node.getNodeData().getSequence().getAccession().getValue();
176                 db = Db.EMBL;
177             }
178             else if ( !ForesterUtil.isEmpty( node.getName() ) ) {
179                 if ( ( query = ForesterUtil.extractUniProtKbProteinSeqIdentifier( node ) ) != null ) {
180                     db = Db.UNIPROT;
181                 }
182                 else if ( ( id = SequenceIdParser.parse( node.getName() ) ) != null ) {
183                     if ( id.getProvider().equalsIgnoreCase( Identifier.NCBI ) ) {
184                         db = Db.NCBI;
185                     }
186                     else if ( id.getProvider().equalsIgnoreCase( Identifier.REFSEQ ) ) {
187                         db = Db.REFSEQ;
188                     }
189                 }
190             }
191             if ( db == Db.NONE ) {
192                 not_found.add( node.getName() );
193             }
194             SequenceDatabaseEntry db_entry = null;
195             if ( !ForesterUtil.isEmpty( query ) ) {
196                 if ( db == Db.UNIPROT ) {
197                     if ( DEBUG ) {
198                         System.out.println( "uniprot: " + query );
199                     }
200                     db_entry = obtainUniProtEntry( query, lines_to_return );
201                 }
202                 if ( ( db == Db.EMBL ) || ( ( db == Db.UNIPROT ) && ( db_entry == null ) ) ) {
203                     if ( DEBUG ) {
204                         System.out.println( "embl: " + query );
205                     }
206                     db_entry = obtainEmblEntry( new Identifier( query ), lines_to_return );
207                     if ( ( db == Db.UNIPROT ) && ( db_entry != null ) ) {
208                         db = Db.EMBL;
209                     }
210                 }
211             }
212             else if ( ( db == Db.REFSEQ ) && ( id != null ) ) {
213                 db_entry = obtainRefSeqEntryFromEmbl( id, lines_to_return );
214             }
215             else if ( ( db == Db.NCBI ) && ( id != null ) ) {
216                 db_entry = obtainEmblEntry( id, lines_to_return ); //TODO ?
217             }
218             if ( ( db_entry != null ) && !db_entry.isEmpty() ) {
219                 final Sequence seq = node.getNodeData().isHasSequence() ? node.getNodeData().getSequence()
220                         : new Sequence();
221                 if ( !ForesterUtil.isEmpty( db_entry.getAccession() ) ) {
222                     String type = null;
223                     if ( db == Db.EMBL ) {
224                         type = "embl";
225                     }
226                     else if ( db == Db.UNIPROT ) {
227                         type = "uniprot";
228                     }
229                     else if ( db == Db.NCBI ) {
230                         type = "ncbi";
231                     }
232                     else if ( db == Db.REFSEQ ) {
233                         type = "refseq";
234                     }
235                     seq.setAccession( new Accession( db_entry.getAccession(), type ) );
236                 }
237                 if ( !ForesterUtil.isEmpty( db_entry.getSequenceName() ) ) {
238                     seq.setName( db_entry.getSequenceName() );
239                 }
240                 if ( !ForesterUtil.isEmpty( db_entry.getSequenceSymbol() ) ) {
241                     seq.setSymbol( db_entry.getSequenceSymbol() );
242                 }
243                 final Taxonomy tax = node.getNodeData().isHasTaxonomy() ? node.getNodeData().getTaxonomy()
244                         : new Taxonomy();
245                 if ( !ForesterUtil.isEmpty( db_entry.getTaxonomyScientificName() ) ) {
246                     tax.setScientificName( db_entry.getTaxonomyScientificName() );
247                 }
248                 if ( allow_to_set_taxonomic_data && !ForesterUtil.isEmpty( db_entry.getTaxonomyIdentifier() ) ) {
249                     tax.setIdentifier( new Identifier( db_entry.getTaxonomyIdentifier(), "uniprot" ) );
250                 }
251                 node.getNodeData().setTaxonomy( tax );
252                 node.getNodeData().setSequence( seq );
253             }
254             else if ( db != Db.NONE ) {
255                 not_found.add( node.getName() );
256             }
257             try {
258                 Thread.sleep( 10 );// Sleep for 10 ms
259             }
260             catch ( final InterruptedException ie ) {
261             }
262         }
263         return not_found;
264     }
265
266     public static SequenceDatabaseEntry obtainUniProtEntry( final String query, final int max_lines_to_return )
267             throws IOException {
268         final List<String> lines = queryUniprot( "uniprot/" + query + ".txt", max_lines_to_return );
269         return UniProtEntry.createInstanceFromPlainText( lines );
270     }
271
272     public static List<String> queryDb( final String query, int max_lines_to_return, final String base_url )
273             throws IOException {
274         if ( ForesterUtil.isEmpty( query ) ) {
275             throw new IllegalArgumentException( "illegal attempt to use empty query " );
276         }
277         if ( max_lines_to_return < 1 ) {
278             max_lines_to_return = 1;
279         }
280         final URL url = new URL( base_url + query );
281         if ( DEBUG ) {
282             System.out.println( "url: " + url.toString() );
283         }
284         final URLConnection urlc = url.openConnection();
285         final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
286         String line;
287         final List<String> result = new ArrayList<String>();
288         while ( ( line = in.readLine() ) != null ) {
289             if ( DEBUG ) {
290                 System.out.println( line );
291             }
292             result.add( line );
293             if ( result.size() > max_lines_to_return ) {
294                 break;
295             }
296         }
297         in.close();
298         try {
299             // To prevent accessing online dbs in too quick succession. 
300             Thread.sleep( 20 );
301         }
302         catch ( final InterruptedException e ) {
303             e.printStackTrace();
304         }
305         return result;
306     }
307
308     public static List<String> queryEmblDb( final Identifier id, final int max_lines_to_return ) throws IOException {
309         final StringBuilder url_sb = new StringBuilder();
310         url_sb.append( BASE_EMBL_DB_URL );
311         if ( ForesterUtil.isEmpty( id.getProvider() ) || id.getProvider().equalsIgnoreCase( Identifier.NCBI ) ) {
312             url_sb.append( SequenceDbWsTools.EMBL_DBS_EMBL );
313             url_sb.append( '/' );
314         }
315         else if ( id.getProvider().equalsIgnoreCase( Identifier.REFSEQ ) ) {
316             if ( id.getValue().toUpperCase().indexOf( 'P' ) == 1 ) {
317                 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_P );
318                 url_sb.append( '/' );
319             }
320             else {
321                 url_sb.append( SequenceDbWsTools.EMBL_DBS_REFSEQ_N );
322                 url_sb.append( '/' );
323             }
324         }
325         return queryDb( id.getValue(), max_lines_to_return, url_sb.toString() );
326     }
327
328     public static List<String> queryUniprot( final String query, final int max_lines_to_return ) throws IOException {
329         return queryDb( query, max_lines_to_return, BASE_UNIPROT_URL );
330     }
331
332     private static String encode( final String str ) throws UnsupportedEncodingException {
333         return URLEncoder.encode( str.trim(), URL_ENC );
334     }
335
336     private static List<String> getTaxonomyStringFromCommonName( final String cn, final int max_lines_to_return )
337             throws IOException {
338         return queryUniprot( "taxonomy/?query=common%3a%22" + encode( cn ) + "%22&format=tab", max_lines_to_return );
339     }
340
341     private static List<String> getTaxonomyStringFromId( final String id, final int max_lines_to_return )
342             throws IOException {
343         return queryUniprot( "taxonomy/?query=id%3a%22" + encode( id ) + "%22&format=tab", max_lines_to_return );
344     }
345
346     private static List<String> getTaxonomyStringFromScientificName( final String sn, final int max_lines_to_return )
347             throws IOException {
348         return queryUniprot( "taxonomy/?query=scientific%3a%22" + encode( sn ) + "%22&format=tab", max_lines_to_return );
349     }
350
351     private static List<String> getTaxonomyStringFromTaxonomyCode( final String code, final int max_lines_to_return )
352             throws IOException {
353         return queryUniprot( "taxonomy/?query=mnemonic%3a%22" + encode( code ) + "%22&format=tab", max_lines_to_return );
354     }
355
356     private static List<UniProtTaxonomy> parseUniProtTaxonomy( final List<String> result ) throws IOException {
357         final List<UniProtTaxonomy> taxonomies = new ArrayList<UniProtTaxonomy>();
358         for( final String line : result ) {
359             if ( ForesterUtil.isEmpty( line ) ) {
360                 // Ignore empty lines.
361             }
362             else if ( line.startsWith( "Taxon" ) ) {
363                 final String[] items = line.split( "\t" );
364                 if ( !( items[ 1 ].equalsIgnoreCase( "Mnemonic" ) && items[ 2 ].equalsIgnoreCase( "Scientific name" )
365                         && items[ 3 ].equalsIgnoreCase( "Common name" ) && items[ 4 ].equalsIgnoreCase( "Synonym" )
366                         && items[ 5 ].equalsIgnoreCase( "Other Names" ) && items[ 6 ].equalsIgnoreCase( "Reviewed" )
367                         && items[ 7 ].equalsIgnoreCase( "Rank" ) && items[ 8 ].equalsIgnoreCase( "Lineage" ) ) ) {
368                     throw new IOException( "Unreconized UniProt Taxonomy format: " + line );
369                 }
370             }
371             else {
372                 if ( line.split( "\t" ).length > 4 ) {
373                     taxonomies.add( new UniProtTaxonomy( line ) );
374                 }
375             }
376         }
377         return taxonomies;
378     }
379
380     public enum Db {
381         UNIPROT, EMBL, NCBI, NONE, REFSEQ;
382     }
383 }