JAL-1705 various refactoring towards Uniprot-to-Ensembl fetching
[jalview.git] / src / jalview / ws / seqfetcher / ASequenceFetcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.ws.seqfetcher;
22
23 import jalview.bin.Cache;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.DBRefEntry;
26 import jalview.datamodel.SequenceI;
27 import jalview.util.DBRefUtils;
28 import jalview.util.MessageManager;
29
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.Comparator;
33 import java.util.Enumeration;
34 import java.util.HashSet;
35 import java.util.Hashtable;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Stack;
39 import java.util.Vector;
40
41 public class ASequenceFetcher
42 {
43
44   /*
45    * set of databases we can retrieve entries from
46    */
47   protected Hashtable<String, Map<String, DbSourceProxy>> fetchableDbs;
48
49   /*
50    * comparator to sort by tier (0/1/2) and name
51    */
52   private Comparator<DbSourceProxy> proxyComparator;
53
54   /**
55    * Constructor
56    */
57   public ASequenceFetcher()
58   {
59     super();
60
61     /*
62      * comparator to sort proxies by tier and name
63      */
64     proxyComparator = new Comparator<DbSourceProxy>()
65     {
66       @Override
67       public int compare(DbSourceProxy o1, DbSourceProxy o2)
68       {
69         /*
70          * Tier 0 precedes 1 precedes 2
71          */
72         int compared = Integer.compare(o1.getTier(), o2.getTier());
73         if (compared == 0)
74         {
75           // defend against NullPointer - should never happen
76           String o1Name = o1.getDbName();
77           String o2Name = o2.getDbName();
78           if (o1Name != null && o2Name != null)
79           {
80             compared = o1Name.compareToIgnoreCase(o2Name);
81           }
82         }
83         return compared;
84       }
85     };
86   }
87
88   /**
89    * get array of supported Databases
90    * 
91    * @return database source string for each database - only the latest version
92    *         of a source db is bound to each source.
93    */
94   public String[] getSupportedDb()
95   {
96     if (fetchableDbs == null)
97     {
98       return null;
99     }
100     String[] sf = fetchableDbs.keySet().toArray(
101             new String[fetchableDbs.size()]);
102     return sf;
103   }
104
105   public boolean isFetchable(String source)
106   {
107     for (String db : fetchableDbs.keySet())
108     {
109       if (source.equalsIgnoreCase(db))
110       {
111         return true;
112       }
113     }
114     Cache.log.warn("isFetchable doesn't know about '" + source
115             + "'");
116     return false;
117   }
118
119   /**
120    * Fetch sequences for the given cross-references
121    * 
122    * @param refs
123    * @param dna
124    *          if true, only fetch from nucleotide data sources, else peptide
125    * @return
126    */
127   public SequenceI[] getSequences(DBRefEntry[] refs, boolean dna)
128   {
129     Vector<SequenceI> rseqs = new Vector<SequenceI>();
130     Hashtable<String, List<String>> queries = new Hashtable<String, List<String>>();
131     for (int r = 0; r < refs.length; r++)
132     {
133       if (!queries.containsKey(refs[r].getSource()))
134       {
135         queries.put(refs[r].getSource(), new ArrayList<String>());
136       }
137       List<String> qset = queries.get(refs[r].getSource());
138       if (!qset.contains(refs[r].getAccessionId()))
139       {
140         qset.add(refs[r].getAccessionId());
141       }
142     }
143     Enumeration<String> e = queries.keys();
144     while (e.hasMoreElements())
145     {
146       List<String> query = null;
147       String db = null;
148       db = e.nextElement();
149       query = queries.get(db);
150       if (!isFetchable(db))
151       {
152         reportStdError(db, query, new Exception(
153                 "Don't know how to fetch from this database :" + db));
154         continue;
155       }
156
157       Stack<String> queriesLeft = new Stack<String>();
158       queriesLeft.addAll(query);
159
160       List<DbSourceProxy> proxies = getSourceProxy(db);
161       for (DbSourceProxy fetcher : proxies)
162       {
163         List<String> queriesMade = new ArrayList<String>();
164         HashSet<String> queriesFound = new HashSet<String>();
165         try
166         {
167           if (fetcher.isDnaCoding() != dna)
168           {
169             continue; // wrong sort of data
170           }
171           boolean doMultiple = fetcher.getMaximumQueryCount() > 1;
172           while (!queriesLeft.isEmpty())
173           {
174             StringBuffer qsb = new StringBuffer();
175             do
176             {
177               if (qsb.length() > 0)
178               {
179                 qsb.append(fetcher.getAccessionSeparator());
180               }
181               String q = queriesLeft.pop();
182               queriesMade.add(q);
183               qsb.append(q);
184             } while (doMultiple && !queriesLeft.isEmpty());
185
186             AlignmentI seqset = null;
187             try
188             {
189               // create a fetcher and go to it
190               seqset = fetcher.getSequenceRecords(qsb.toString());
191             } catch (Exception ex)
192             {
193               System.err.println("Failed to retrieve the following from "
194                       + db);
195               System.err.println(qsb);
196               ex.printStackTrace(System.err);
197             }
198             // TODO: Merge alignment together - perhaps
199             if (seqset != null)
200             {
201               SequenceI seqs[] = seqset.getSequencesArray();
202               if (seqs != null)
203               {
204                 for (int is = 0; is < seqs.length; is++)
205                 {
206                   rseqs.addElement(seqs[is]);
207                   DBRefEntry[] frefs = DBRefUtils.searchRefs(seqs[is]
208                           .getDBRefs(), new DBRefEntry(db, null, null));
209                   if (frefs != null)
210                   {
211                     for (DBRefEntry dbr : frefs)
212                     {
213                       queriesFound.add(dbr.getAccessionId());
214                       queriesMade.remove(dbr.getAccessionId());
215                     }
216                   }
217                   seqs[is] = null;
218                 }
219               }
220               else
221               {
222                 if (fetcher.getRawRecords() != null)
223                 {
224                   System.out.println("# Retrieved from " + db + ":"
225                           + qsb.toString());
226                   StringBuffer rrb = fetcher.getRawRecords();
227                   /*
228                    * for (int rr = 0; rr<rrb.length; rr++) {
229                    */
230                   String hdr;
231                   // if (rr<qs.length)
232                   // {
233                   hdr = "# " + db + ":" + qsb.toString();
234                   /*
235                    * } else { hdr = "# part "+rr; }
236                    */
237                   System.out.println(hdr);
238                   if (rrb != null)
239                   {
240                     System.out.println(rrb);
241                   }
242                   System.out.println("# end of " + hdr);
243                 }
244
245               }
246             }
247
248           }
249         } catch (Exception ex)
250         {
251           reportStdError(db, queriesMade, ex);
252         }
253         if (queriesMade.size() > 0)
254         {
255           System.out.println("# Adding " + queriesMade.size()
256                   + " ids back to queries list for searching again (" + db
257                   + ")");
258           queriesLeft.addAll(queriesMade);
259         }
260       }
261     }
262
263     SequenceI[] result = null;
264     if (rseqs.size() > 0)
265     {
266       result = new SequenceI[rseqs.size()];
267       int si = 0;
268       for (SequenceI s : rseqs)
269       {
270         result[si++] = s;
271         s.updatePDBIds();
272       }
273     }
274     return result;
275   }
276
277   public void reportStdError(String db, List<String> queriesMade,
278           Exception ex)
279   {
280
281     System.err.println("Failed to retrieve the following references from "
282             + db);
283     int n = 0;
284     for (String qv : queriesMade)
285     {
286       System.err.print(" " + qv + ";");
287       if (n++ > 10)
288       {
289         System.err.println();
290         n = 0;
291       }
292     }
293     System.err.println();
294     ex.printStackTrace();
295   }
296
297   /**
298    * Returns a list of proxies for the given source
299    * 
300    * @param db
301    *          database source string TODO: add version string/wildcard for
302    *          retrieval of specific DB source/version combinations.
303    * @return a list of DbSourceProxy for the db
304    */
305   public List<DbSourceProxy> getSourceProxy(String db)
306   {
307     db = DBRefUtils.getCanonicalName(db);
308     Map<String, DbSourceProxy> dblist = fetchableDbs.get(db);
309     if (dblist == null)
310     {
311       return new ArrayList<DbSourceProxy>();
312     }
313
314     /*
315      * sort so that primary sources precede secondary
316      */
317     List<DbSourceProxy> dbs = new ArrayList<DbSourceProxy>(dblist.values());
318     Collections.sort(dbs, proxyComparator);
319     return dbs;
320   }
321
322   /**
323    * constructs an instance of the proxy and registers it as a valid dbrefsource
324    * 
325    * @param dbSourceProxy
326    *          reference for class implementing
327    *          jalview.ws.seqfetcher.DbSourceProxy
328    */
329   protected void addDBRefSourceImpl(
330           Class<? extends DbSourceProxy> dbSourceProxy)
331           throws IllegalArgumentException
332   {
333     DbSourceProxy proxy = null;
334     try
335     {
336       DbSourceProxy proxyObj = dbSourceProxy.getConstructor().newInstance();
337       proxy = proxyObj;
338     } catch (IllegalArgumentException e)
339     {
340       throw e;
341     } catch (Exception e)
342     {
343       // Serious problems if this happens.
344       throw new Error(
345               MessageManager
346                       .getString("error.dbrefsource_implementation_exception"),
347               e);
348     }
349     addDbRefSourceImpl(proxy);
350   }
351
352   /**
353    * add the properly initialised DbSourceProxy object 'proxy' to the list of
354    * sequence fetchers
355    * 
356    * @param proxy
357    */
358   protected void addDbRefSourceImpl(DbSourceProxy proxy)
359   {
360     if (proxy != null)
361     {
362       if (fetchableDbs == null)
363       {
364         fetchableDbs = new Hashtable<String, Map<String, DbSourceProxy>>();
365       }
366       Map<String, DbSourceProxy> slist = fetchableDbs.get(proxy
367               .getDbSource());
368       if (slist == null)
369       {
370         fetchableDbs.put(proxy.getDbSource(),
371                 slist = new Hashtable<String, DbSourceProxy>());
372       }
373       slist.put(proxy.getDbName(), proxy);
374     }
375   }
376
377   /**
378    * select sources which are implemented by instances of the given class
379    * 
380    * @param class that implements DbSourceProxy
381    * @return null or vector of source names for fetchers
382    */
383   public String[] getDbInstances(Class class1)
384   {
385     if (!DbSourceProxy.class.isAssignableFrom(class1))
386     {
387       throw new Error(
388               MessageManager
389                       .formatMessage(
390                               "error.implementation_error_dbinstance_must_implement_interface",
391                               new String[] { class1.toString() }));
392     }
393     if (fetchableDbs == null)
394     {
395       return null;
396     }
397     String[] sources = null;
398     Vector<String> src = new Vector<String>();
399     Enumeration<String> dbs = fetchableDbs.keys();
400     while (dbs.hasMoreElements())
401     {
402       String dbn = dbs.nextElement();
403       for (DbSourceProxy dbp : fetchableDbs.get(dbn).values())
404       {
405         if (class1.isAssignableFrom(dbp.getClass()))
406         {
407           src.addElement(dbn);
408         }
409       }
410     }
411     if (src.size() > 0)
412     {
413       src.copyInto(sources = new String[src.size()]);
414     }
415     return sources;
416   }
417
418   public DbSourceProxy[] getDbSourceProxyInstances(Class class1)
419   {
420     List<DbSourceProxy> prlist = new ArrayList<DbSourceProxy>();
421     for (String fetchable : getSupportedDb())
422     {
423       for (DbSourceProxy pr : getSourceProxy(fetchable))
424       {
425         if (class1.isInstance(pr))
426         {
427           prlist.add(pr);
428         }
429       }
430     }
431     if (prlist.size() == 0)
432     {
433       return null;
434     }
435     return prlist.toArray(new DbSourceProxy[0]);
436   }
437
438 }