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