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   BASE_UNIPROT_URL        = "http://www.uniprot.org/";
58     public final static int      DEFAULT_LINES_TO_RETURN = 4000;
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     public final static String   EMBL_GENBANK            = "http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=GENBANK&style=raw&id=";
63     public final static String   EMBL_REFSEQ             = "http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=REFSEQ&style=raw&id=";
64     public final static String   EMBL_EMBL               = "http://www.ebi.ac.uk/Tools/dbfetch/dbfetch?db=EMBL&style=raw&id=";
65     private final static boolean DEBUG                   = true;
66     private final static String  URL_ENC                 = "UTF-8";
67
68     public static List<UniProtTaxonomy> getTaxonomiesFromCommonNameStrict( final String cn,
69                                                                            final int max_taxonomies_return )
70             throws IOException {
71         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromCommonName( cn, max_taxonomies_return );
72         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
73             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
74             for( final UniProtTaxonomy taxonomy : taxonomies ) {
75                 if ( taxonomy.getCommonName().equalsIgnoreCase( cn ) ) {
76                     filtered_taxonomies.add( taxonomy );
77                 }
78             }
79             return filtered_taxonomies;
80         }
81         return null;
82     }
83
84     public static List<UniProtTaxonomy> getTaxonomiesFromId( final String id, final int max_taxonomies_return )
85             throws IOException {
86         final List<String> result = getTaxonomyStringFromId( id, max_taxonomies_return );
87         if ( result.size() > 0 ) {
88             return parseUniProtTaxonomy( result );
89         }
90         return null;
91     }
92
93     /**
94      * Does not return "sub-types".
95      * For example, for "Mus musculus" only returns "Mus musculus"
96      * and not "Mus musculus", "Mus musculus bactrianus", ...
97      * 
98      */
99     public static List<UniProtTaxonomy> getTaxonomiesFromScientificNameStrict( final String sn,
100                                                                                final int max_taxonomies_return )
101             throws IOException {
102         final List<UniProtTaxonomy> taxonomies = getTaxonomiesFromScientificName( sn, max_taxonomies_return );
103         if ( ( taxonomies != null ) && ( taxonomies.size() > 0 ) ) {
104             final List<UniProtTaxonomy> filtered_taxonomies = new ArrayList<UniProtTaxonomy>();
105             for( final UniProtTaxonomy taxonomy : taxonomies ) {
106                 if ( taxonomy.getScientificName().equalsIgnoreCase( sn ) ) {
107                     filtered_taxonomies.add( taxonomy );
108                 }
109             }
110             return filtered_taxonomies;
111         }
112         return null;
113     }
114
115     public static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String code,
116                                                                        final int max_taxonomies_return )
117             throws IOException {
118         final String my_code = new String( code );
119         final List<String> result = getTaxonomyStringFromTaxonomyCode( my_code, max_taxonomies_return );
120         if ( result.size() > 0 ) {
121             return parseUniProtTaxonomy( result );
122         }
123         return null;
124     }
125
126     public static SequenceDatabaseEntry obtainEmblEntry( final Accession acc ) throws IOException {
127         return obtainEmblEntry( acc, DEFAULT_LINES_TO_RETURN );
128     }
129
130     public static SequenceDatabaseEntry obtainEmblEntry( final Accession acc, final int max_lines_to_return )
131             throws IOException {
132         final List<String> lines = queryEmblDb( acc, max_lines_to_return );
133         return EbiDbEntry.createInstanceFromPlainTextForRefSeq( lines );
134     }
135
136     public static SequenceDatabaseEntry obtainEntry( final String acc_str ) throws IOException {
137         if ( ForesterUtil.isEmpty( acc_str ) ) {
138             throw new IllegalArgumentException( "cannot not extract sequence db accessor from null or empty string" );
139         }
140         final Accession acc = SequenceAccessionTools.parseAccessorFromString( acc_str );
141         if ( acc == null ) {
142             throw new IllegalArgumentException( "could not extract acceptable sequence db accessor from \"" + acc_str
143                     + "\"" );
144         }
145         if ( acc.getSource().equals( Source.REFSEQ.toString() ) || acc.getSource().equals( Source.EMBL.toString() )
146                 || acc.getSource().equals( Source.NCBI.toString() ) ) {
147             return obtainEmblEntry( acc, DEFAULT_LINES_TO_RETURN );
148         }
149         else if ( acc.getSource().equals( Source.UNIPROT.toString() ) ) {
150             return obtainUniProtEntry( acc.getValue(), DEFAULT_LINES_TO_RETURN );
151         }
152         else {
153             throw new IllegalArgumentException( "don't know how to handle request for source \"" + acc.getSource()
154                     + "\"" );
155         }
156     }
157
158     public static SequenceDatabaseEntry obtainRefSeqEntryFromEmbl( final Accession acc ) throws IOException {
159         return obtainRefSeqEntryFromEmbl( acc, DEFAULT_LINES_TO_RETURN );
160     }
161
162     public static SequenceDatabaseEntry obtainRefSeqEntryFromEmbl( final Accession acc, final int max_lines_to_return )
163             throws IOException {
164         final List<String> lines = queryEmblDbForRefSeqEntry( acc, max_lines_to_return );
165         return EbiDbEntry.createInstanceFromPlainTextForRefSeq( lines );
166     }
167
168     public final static Accession obtainSeqAccession( final PhylogenyNode node ) {
169         Accession acc = SequenceAccessionTools.obtainFromSeqAccession( node );
170         if ( !isAccessionAcceptable( acc ) ) {
171             acc = SequenceAccessionTools.obtainAccessorFromDataFields( node );
172         }
173         return acc;
174     }
175
176     public final static void obtainSeqInformation( final boolean allow_to_set_taxonomic_data,
177                                                    final int lines_to_return,
178                                                    final SortedSet<String> not_found,
179                                                    final PhylogenyNode node ) throws IOException {
180         final Accession acc = obtainSeqAccession( node );
181         if ( !isAccessionAcceptable( acc ) ) {
182             if ( node.isExternal() || !node.isEmpty() ) {
183                 not_found.add( node.toString() );
184             }
185         }
186         else {
187             addDataFromDbToNode( allow_to_set_taxonomic_data, lines_to_return, not_found, node, acc );
188         }
189     }
190
191     public final static void obtainSeqInformation( final boolean allow_to_set_taxonomic_data,
192                                                    final SortedSet<String> not_found,
193                                                    final PhylogenyNode node ) throws IOException {
194         obtainSeqInformation( allow_to_set_taxonomic_data, DEFAULT_LINES_TO_RETURN, not_found, node );
195     }
196
197     public final static SortedSet<String> obtainSeqInformation( final Phylogeny phy,
198                                                                 final boolean ext_nodes_only,
199                                                                 final boolean allow_to_set_taxonomic_data,
200                                                                 final int lines_to_return ) throws IOException {
201         final SortedSet<String> not_found = new TreeSet<String>();
202         for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
203             final PhylogenyNode node = iter.next();
204             if ( node.isExternal() || !ext_nodes_only ) {
205                 obtainSeqInformation( allow_to_set_taxonomic_data, lines_to_return, not_found, node );
206             }
207         }
208         return not_found;
209     }
210
211     public final static void obtainSeqInformation( final PhylogenyNode node ) throws IOException {
212         obtainSeqInformation( true, DEFAULT_LINES_TO_RETURN, new TreeSet<String>(), node );
213     }
214
215     public static SequenceDatabaseEntry obtainUniProtEntry( final String query ) throws IOException {
216         return obtainUniProtEntry( query, DEFAULT_LINES_TO_RETURN );
217     }
218
219     public static SequenceDatabaseEntry obtainUniProtEntry( final String query, final int max_lines_to_return )
220             throws IOException {
221         final List<String> lines = queryUniprot( "uniprot/" + query + ".txt", max_lines_to_return );
222         return UniProtEntry.createInstanceFromPlainText( lines );
223     }
224
225     public static List<String> queryDb( final String query, int max_lines_to_return, final String base_url )
226             throws IOException {
227         if ( ForesterUtil.isEmpty( query ) ) {
228             throw new IllegalArgumentException( "illegal attempt to use empty query " );
229         }
230         if ( max_lines_to_return < 1 ) {
231             max_lines_to_return = 1;
232         }
233         final URL url = new URL( base_url + query );
234         if ( DEBUG ) {
235             System.out.println( "url: " + url.toString() );
236         }
237         final URLConnection urlc = url.openConnection();
238         final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
239         String line;
240         final List<String> result = new ArrayList<String>();
241         while ( ( line = in.readLine() ) != null ) {
242             if ( DEBUG ) {
243                 System.out.println( line );
244             }
245             result.add( line );
246             if ( result.size() > max_lines_to_return ) {
247                 break;
248             }
249         }
250         in.close();
251         try {
252             // To prevent accessing online dbs in too quick succession. 
253             Thread.sleep( 20 );
254         }
255         catch ( final InterruptedException e ) {
256             e.printStackTrace();
257         }
258         return result;
259     }
260
261     public static List<String> queryEmblDb( final Accession acc, final int max_lines_to_return ) throws IOException {
262         final StringBuilder url_sb = new StringBuilder();
263         //  url_sb.append( BASE_EMBL_DB_URL );
264         System.out.println( "source: " + acc.getSource() );
265         if ( acc.getSource().equals( Source.NCBI.toString() ) ) {
266             url_sb.append( EMBL_GENBANK );
267             //url_sb.append( '/' );
268         }
269         else if ( acc.getSource().equals( Source.REFSEQ.toString() ) ) {
270             url_sb.append( EMBL_REFSEQ );
271         }
272         else if ( acc.getSource().equals( Source.EMBL.toString() ) ) {
273             url_sb.append( EMBL_EMBL );
274         }
275         else {
276             throw new IllegalArgumentException( "unable to handle source: " + acc.getSource() );
277         }
278         return queryDb( acc.getValue(), max_lines_to_return, url_sb.toString() );
279     }
280
281     public static List<String> queryEmblDbForRefSeqEntry( final Accession id, final int max_lines_to_return )
282             throws IOException {
283         final StringBuilder url_sb = new StringBuilder();
284         url_sb.append( EMBL_REFSEQ );
285         return queryDb( id.getValue(), max_lines_to_return, url_sb.toString() );
286     }
287
288     public static List<String> queryUniprot( final String query, final int max_lines_to_return ) throws IOException {
289         return queryDb( query, max_lines_to_return, BASE_UNIPROT_URL );
290     }
291
292     final static String extractFrom( final String target, final String a ) {
293         final int i_a = target.indexOf( a );
294         return target.substring( i_a + a.length() ).trim();
295     }
296
297     final static String extractFromTo( final String target, final String a, final String b ) {
298         final int i_a = target.indexOf( a );
299         final int i_b = target.indexOf( b );
300         if ( ( i_a < 0 ) || ( i_b < i_a ) ) {
301             throw new IllegalArgumentException( "attempt to extract from \"" + target + "\" between \"" + a
302                     + "\" and \"" + b + "\"" );
303         }
304         return target.substring( i_a + a.length(), i_b ).trim();
305     }
306
307     final static String extractTo( final String target, final String b ) {
308         final int i_b = target.indexOf( b );
309         return target.substring( 0, i_b ).trim();
310     }
311
312     private static void addDataFromDbToNode( final boolean allow_to_set_taxonomic_data,
313                                              final int lines_to_return,
314                                              final SortedSet<String> not_found,
315                                              final PhylogenyNode node,
316                                              final Accession acc ) throws IOException {
317         SequenceDatabaseEntry db_entry = null;
318         final String query = acc.getValue();
319         if ( acc.getSource().equals( Source.UNIPROT.toString() ) ) {
320             if ( DEBUG ) {
321                 System.out.println( "uniprot: " + query );
322             }
323             try {
324                 db_entry = obtainUniProtEntry( query, lines_to_return );
325             }
326             catch ( final FileNotFoundException e ) {
327                 // Eat this, and move to next.
328             }
329         }
330         else if ( acc.getSource().equals( Source.REFSEQ.toString() ) ) {
331             if ( DEBUG ) {
332                 System.out.println( "refseq: " + query );
333             }
334             try {
335                 db_entry = obtainRefSeqEntryFromEmbl( new Accession( query ), lines_to_return );
336             }
337             catch ( final FileNotFoundException e ) {
338                 // Eat this, and move to next.
339             }
340         }
341         else if ( acc.getSource().equals( Source.EMBL.toString() ) || acc.getSource().equals( Source.NCBI.toString() )
342                 || acc.getSource().equals( Source.EMBL.toString() ) ) {
343             if ( DEBUG ) {
344                 System.out.println( acc.toString() );
345             }
346             try {
347                 db_entry = obtainEmblEntry( acc, lines_to_return );
348             }
349             catch ( final FileNotFoundException e ) {
350                 // Eat this, and move to next.
351             }
352         }
353         else if ( acc.getSource().equals( Source.GI.toString() ) ) {
354             if ( DEBUG ) {
355                 System.out.println( "gi: " + query );
356             }
357             try {
358                 db_entry = obtainRefSeqEntryFromEmbl( new Accession( query ), lines_to_return );
359             }
360             catch ( final FileNotFoundException e ) {
361                 // Eat this, and move to next.
362             }
363         }
364         if ( ( db_entry != null ) && !db_entry.isEmpty() ) {
365             final Sequence seq = node.getNodeData().isHasSequence() ? node.getNodeData().getSequence() : new Sequence();
366             if ( !ForesterUtil.isEmpty( db_entry.getAccession() ) ) {
367                 seq.setAccession( new Accession( db_entry.getAccession(), acc.getSource() ) );
368             }
369             if ( !ForesterUtil.isEmpty( db_entry.getSequenceName() ) ) {
370                 seq.setName( db_entry.getSequenceName() );
371             }
372             if ( !ForesterUtil.isEmpty( db_entry.getGeneName() ) ) {
373                 seq.setGeneName( db_entry.getGeneName() );
374             }
375             if ( !ForesterUtil.isEmpty( db_entry.getSequenceSymbol() ) ) {
376                 try {
377                     seq.setSymbol( db_entry.getSequenceSymbol() );
378                 }
379                 catch ( final PhyloXmlDataFormatException e ) {
380                     // Eat this exception.
381                 }
382             }
383             if ( ( db_entry.getGoTerms() != null ) && !db_entry.getGoTerms().isEmpty() ) {
384                 for( final GoTerm go : db_entry.getGoTerms() ) {
385                     final Annotation ann = new Annotation( go.getGoId().getId() );
386                     ann.setDesc( go.getName() );
387                     seq.addAnnotation( ann );
388                 }
389             }
390             if ( ( db_entry.getCrossReferences() != null ) && !db_entry.getCrossReferences().isEmpty() ) {
391                 for( final Accession x : db_entry.getCrossReferences() ) {
392                     seq.addCrossReference( x );
393                 }
394             }
395             if ( !ForesterUtil.isEmpty( db_entry.getChromosome() ) && !ForesterUtil.isEmpty( db_entry.getMap() ) ) {
396                 seq.setLocation( "chr " + db_entry.getChromosome() + ", " + db_entry.getMap() );
397             }
398             else if ( !ForesterUtil.isEmpty( db_entry.getChromosome() ) ) {
399                 seq.setLocation( "chr " + db_entry.getChromosome() );
400             }
401             else if ( !ForesterUtil.isEmpty( db_entry.getMap() ) ) {
402                 seq.setLocation( db_entry.getMap() );
403             }
404             final Taxonomy tax = node.getNodeData().isHasTaxonomy() ? node.getNodeData().getTaxonomy() : new Taxonomy();
405             if ( !ForesterUtil.isEmpty( db_entry.getTaxonomyScientificName() ) ) {
406                 tax.setScientificName( db_entry.getTaxonomyScientificName() );
407             }
408             if ( allow_to_set_taxonomic_data && !ForesterUtil.isEmpty( db_entry.getTaxonomyIdentifier() ) ) {
409                 tax.setIdentifier( new Identifier( db_entry.getTaxonomyIdentifier(), "uniprot" ) );
410             }
411             node.getNodeData().setTaxonomy( tax );
412             node.getNodeData().setSequence( seq );
413         }
414         else {
415             if ( node.isExternal() || !node.isEmpty() ) {
416                 not_found.add( node.toString() );
417             }
418         }
419         try {
420             Thread.sleep( 10 );// Sleep for 10 ms
421         }
422         catch ( final InterruptedException ie ) {
423         }
424     }
425
426     private static String encode( final String str ) throws UnsupportedEncodingException {
427         return URLEncoder.encode( str.trim(), URL_ENC );
428     }
429
430     private static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String cn, final int max_taxonomies_return )
431             throws IOException {
432         final List<String> result = getTaxonomyStringFromCommonName( cn, max_taxonomies_return );
433         if ( result.size() > 0 ) {
434             return parseUniProtTaxonomy( result );
435         }
436         return null;
437     }
438
439     private static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String sn,
440                                                                           final int max_taxonomies_return )
441             throws IOException {
442         final List<String> result = getTaxonomyStringFromScientificName( sn, max_taxonomies_return );
443         if ( result.size() > 0 ) {
444             return parseUniProtTaxonomy( result );
445         }
446         return null;
447     }
448
449     private static List<String> getTaxonomyStringFromCommonName( final String cn, final int max_lines_to_return )
450             throws IOException {
451         return queryUniprot( "taxonomy/?query=common%3a%22" + encode( cn ) + "%22&format=tab", max_lines_to_return );
452     }
453
454     private static List<String> getTaxonomyStringFromId( final String id, final int max_lines_to_return )
455             throws IOException {
456         return queryUniprot( "taxonomy/?query=id%3a%22" + encode( id ) + "%22&format=tab", max_lines_to_return );
457     }
458
459     private static List<String> getTaxonomyStringFromScientificName( final String sn, final int max_lines_to_return )
460             throws IOException {
461         return queryUniprot( "taxonomy/?query=scientific%3a%22" + encode( sn ) + "%22&format=tab", max_lines_to_return );
462     }
463
464     private static List<String> getTaxonomyStringFromTaxonomyCode( final String code, final int max_lines_to_return )
465             throws IOException {
466         return queryUniprot( "taxonomy/?query=mnemonic%3a%22" + encode( code ) + "%22&format=tab", max_lines_to_return );
467     }
468
469     private final static boolean isAccessionAcceptable( final Accession acc ) {
470         return ( !( ( acc == null ) || ForesterUtil.isEmpty( acc.getSource() ) || ForesterUtil.isEmpty( acc.getValue() ) || ( ( acc
471                 .getSource().equals( Source.UNIPROT.toString() ) )
472                 && ( acc.getSource().toString().equals( Source.EMBL.toString() ) ) && ( acc.getSource().toString()
473                 .equals( Source.REFSEQ.toString() ) ) ) ) );
474     }
475
476     private static List<UniProtTaxonomy> parseUniProtTaxonomy( final List<String> result ) throws IOException {
477         final List<UniProtTaxonomy> taxonomies = new ArrayList<UniProtTaxonomy>();
478         for( final String line : result ) {
479             if ( ForesterUtil.isEmpty( line ) ) {
480                 // Ignore empty lines.
481             }
482             else if ( line.startsWith( "Taxon" ) ) {
483                 final String[] items = line.split( "\t" );
484                 if ( !( items[ 1 ].equalsIgnoreCase( "Mnemonic" ) && items[ 2 ].equalsIgnoreCase( "Scientific name" )
485                         && items[ 3 ].equalsIgnoreCase( "Common name" ) && items[ 4 ].equalsIgnoreCase( "Synonym" )
486                         && items[ 5 ].equalsIgnoreCase( "Other Names" ) && items[ 6 ].equalsIgnoreCase( "Reviewed" )
487                         && items[ 7 ].equalsIgnoreCase( "Rank" ) && items[ 8 ].equalsIgnoreCase( "Lineage" ) ) ) {
488                     throw new IOException( "Unreconized UniProt Taxonomy format: " + line );
489                 }
490             }
491             else {
492                 if ( line.split( "\t" ).length > 4 ) {
493                     taxonomies.add( new UniProtTaxonomy( line ) );
494                 }
495             }
496         }
497         return taxonomies;
498     }
499 }