JAL-1705 add concrete ENSEMBL sequence fetchers
[jalview.git] / src / jalview / ws / SequenceFetcher.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;
22
23 import jalview.datamodel.Alignment;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.DBRefSource;
26 import jalview.datamodel.SequenceI;
27 import jalview.ws.dbsources.das.api.jalviewSourceI;
28 import jalview.ws.seqfetcher.ASequenceFetcher;
29 import jalview.ws.seqfetcher.DbSourceProxy;
30
31 import java.util.ArrayList;
32 import java.util.Enumeration;
33 import java.util.List;
34 import java.util.Vector;
35
36 /**
37  * This is the the concrete implementation of the sequence retrieval interface
38  * and abstract class in jalview.ws.seqfetcher. This implements the run-time
39  * discovery of sequence database clients, and provides a hardwired main for
40  * testing all registered handlers.
41  * 
42  */
43 public class SequenceFetcher extends ASequenceFetcher
44 {
45   /**
46    * Thread safe construction of database proxies TODO: extend to a configurable
47    * database plugin mechanism where classes are instantiated by reflection and
48    * queried for their DbRefSource and version association.
49    * 
50    */
51   public SequenceFetcher()
52   {
53     this(true);
54   }
55
56   public SequenceFetcher(boolean addDas)
57   {
58     addDBRefSourceImpl(jalview.ext.ensembl.EnsemblProtein.class);
59     addDBRefSourceImpl(jalview.ext.ensembl.EnsemblTranscript.class);
60     addDBRefSourceImpl(jalview.ext.ensembl.EnsemblCds.class);
61     addDBRefSourceImpl(jalview.ext.ensembl.EnsemblGenome.class);
62     addDBRefSourceImpl(jalview.ext.ensembl.EnsemblCdna.class);
63
64     addDBRefSourceImpl(jalview.ws.dbsources.EmblSource.class);
65     addDBRefSourceImpl(jalview.ws.dbsources.EmblCdsSouce.class);
66     addDBRefSourceImpl(jalview.ws.dbsources.Uniprot.class);
67     addDBRefSourceImpl(jalview.ws.dbsources.UnprotName.class);
68     addDBRefSourceImpl(jalview.ws.dbsources.Pdb.class);
69     addDBRefSourceImpl(jalview.ws.dbsources.PfamFull.class);
70     addDBRefSourceImpl(jalview.ws.dbsources.PfamSeed.class);
71     // ensures Seed alignment is 'default' for PFAM
72     addDBRefSourceImpl(jalview.ws.dbsources.RfamFull.class);
73     addDBRefSourceImpl(jalview.ws.dbsources.RfamSeed.class);
74     if (addDas)
75     {
76       registerDasSequenceSources();
77     }
78   }
79
80   /**
81    * return an ordered list of database sources where non-das database classes
82    * appear before das database classes
83    */
84   public String[] getOrderedSupportedSources()
85   {
86     String[] srcs = this.getSupportedDb();
87     ArrayList<String> dassrc = new ArrayList<String>(), nondas = new ArrayList<String>();
88     for (int i = 0; i < srcs.length; i++)
89     {
90       boolean das = false, skip = false;
91       String nm;
92       for (DbSourceProxy dbs : getSourceProxy(srcs[i]))
93       {
94         // Skip the alignment databases for the moment - they're not useful for
95         // verifying a single sequence against its reference source
96         if (dbs.isA(DBRefSource.ALIGNMENTDB))
97         {
98           skip = true;
99         }
100         else
101         {
102           nm = dbs.getDbName();
103           if (getSourceProxy(srcs[i]) instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
104           {
105             if (nm.startsWith("das:"))
106             {
107               nm = nm.substring(4);
108               das = true;
109             }
110             break;
111           }
112         }
113       }
114       if (skip)
115       {
116         continue;
117       }
118       if (das)
119       {
120         dassrc.add(srcs[i]);
121       }
122       else
123       {
124         nondas.add(srcs[i]);
125       }
126     }
127     String[] tosort = nondas.toArray(new String[0]), sorted = nondas
128             .toArray(new String[0]);
129     for (int j = 0, jSize = sorted.length; j < jSize; j++)
130     {
131       tosort[j] = tosort[j].toLowerCase();
132     }
133     jalview.util.QuickSort.sort(tosort, sorted);
134     // construct array with all sources listed
135
136     srcs = new String[sorted.length + dassrc.size()];
137     int i = 0;
138     for (int j = sorted.length - 1; j >= 0; j--, i++)
139     {
140       srcs[i] = sorted[j];
141       sorted[j] = null;
142     }
143
144     sorted = dassrc.toArray(new String[0]);
145     tosort = dassrc.toArray(new String[0]);
146     for (int j = 0, jSize = sorted.length; j < jSize; j++)
147     {
148       tosort[j] = tosort[j].toLowerCase();
149     }
150     jalview.util.QuickSort.sort(tosort, sorted);
151     for (int j = sorted.length - 1; j >= 0; j--, i++)
152     {
153       srcs[i] = sorted[j];
154     }
155     return srcs;
156   }
157
158   /**
159    * return plaintext databse list suitable for using in a GUI element
160    */
161   public String[] _getOrderedSupportedSources()
162   {
163     String[] srcs = this.getSupportedDb();
164     ArrayList dassrc = new ArrayList(), nondas = new ArrayList();
165     for (int i = 0; i < srcs.length; i++)
166     {
167       for (DbSourceProxy dbs : getSourceProxy(srcs[i]))
168       {
169         String nm = dbs.getDbName();
170         if (getSourceProxy(srcs[i]) instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
171         {
172           if (nm.startsWith("das:"))
173           {
174             nm = nm.substring(4);
175           }
176           dassrc.add(new String[]
177           { srcs[i], nm.toUpperCase() });
178         }
179         else
180         {
181           nondas.add(new String[]
182           { srcs[i], nm.toUpperCase() });
183         }
184       }
185     }
186     Object[] sorted = nondas.toArray();
187     String[] tosort = new String[sorted.length];
188     nondas.clear();
189     for (int j = 0; j < sorted.length; j++)
190     {
191       tosort[j] = ((String[]) sorted[j])[1];
192     }
193     jalview.util.QuickSort.sort(tosort, sorted);
194     int i = 0;
195     // construct array with all sources listed
196     srcs = new String[sorted.length + dassrc.size()];
197     for (int j = sorted.length - 1; j >= 0; j--, i++)
198     {
199       srcs[i] = ((String[]) sorted[j])[0];
200       sorted[j] = null;
201     }
202
203     sorted = dassrc.toArray();
204     tosort = new String[sorted.length];
205     dassrc.clear();
206     for (int j = 0; j < sorted.length; j++)
207     {
208       tosort[j] = ((String[]) sorted[j])[1];
209     }
210     jalview.util.QuickSort.sort(tosort, sorted);
211     for (int j = sorted.length - 1; j >= 0; j--, i++)
212     {
213       srcs[i] = ((String[]) sorted[j])[0];
214       sorted[j] = null;
215     }
216     return srcs;
217   }
218
219   /**
220    * simple run method to test dbsources.
221    * 
222    * @param argv
223    */
224   public static void main(String[] argv)
225   {
226     AlignmentI ds = null;
227     Vector noProds = new Vector();
228     String usage = "SequenceFetcher.main [-nodas] [<DBNAME> [<ACCNO>]]\n"
229             + "With no arguments, all DbSources will be queried with their test Accession number.\n"
230             + "With one argument, the argument will be resolved to one or more db sources and each will be queried with their test accession only.\n"
231             + "If given two arguments, SequenceFetcher will try to find the DbFetcher corresponding to <DBNAME> and retrieve <ACCNO> from it.\n"
232             + "The -nodas option will exclude DAS sources from the database fetchers Jalview will try to use.";
233     boolean withDas = true;
234     if (argv != null && argv.length > 0
235             && argv[0].toLowerCase().startsWith("-nodas"))
236     {
237       withDas = false;
238       String targs[] = new String[argv.length - 1];
239       System.arraycopy(argv, 1, targs, 0, targs.length);
240       argv = targs;
241     }
242     if (argv != null && argv.length > 0)
243     {
244       List<DbSourceProxy> sps = new SequenceFetcher(withDas)
245               .getSourceProxy(argv[0]);
246
247       if (sps != null)
248       {
249         for (DbSourceProxy sp : sps)
250         {
251           AlignmentI al = null;
252           try
253           {
254             al = sp.getSequenceRecords(argv.length > 1 ? argv[1] : sp
255                     .getTestQuery());
256           } catch (Exception e)
257           {
258             e.printStackTrace();
259             System.err.println("Error when retrieving "
260                     + (argv.length > 1 ? argv[1] : sp.getTestQuery())
261                     + " from " + argv[0] + "\nUsage: " + usage);
262           }
263           SequenceI[] prod = al.getSequencesArray();
264           if (al != null)
265           {
266             for (int p = 0; p < prod.length; p++)
267             {
268               System.out.println("Prod " + p + ": "
269                       + prod[p].getDisplayId(true) + " : "
270                       + prod[p].getDescription());
271             }
272           }
273         }
274         return;
275       }
276       else
277       {
278         System.err.println("Can't resolve " + argv[0]
279                 + " as a database name. Allowed values are :\n"
280                 + new SequenceFetcher().getSupportedDb());
281       }
282       System.out.println(usage);
283       return;
284     }
285     ASequenceFetcher sfetcher = new SequenceFetcher(withDas);
286     String[] dbSources = sfetcher.getSupportedDb();
287     for (int dbsource = 0; dbsource < dbSources.length; dbsource++)
288     {
289       String db = dbSources[dbsource];
290       // skip me
291       if (db.equals(DBRefSource.PDB))
292       {
293         continue;
294       }
295       for (DbSourceProxy sp : sfetcher.getSourceProxy(db))
296       {
297         System.out.println("Source: " + sp.getDbName() + " (" + db
298                 + "): retrieving test:" + sp.getTestQuery());
299         AlignmentI al = null;
300         try
301         {
302           al = sp.getSequenceRecords(sp.getTestQuery());
303           if (al != null && al.getHeight() > 0
304                   && sp.getDbSourceProperties() != null)
305           {
306             boolean dna = sp.getDbSourceProperties().containsKey(
307                     DBRefSource.DNACODINGSEQDB)
308                     || sp.getDbSourceProperties().containsKey(
309                             DBRefSource.DNASEQDB)
310                     || sp.getDbSourceProperties().containsKey(
311                             DBRefSource.CODINGSEQDB);
312             // try and find products
313             String types[] = jalview.analysis.CrossRef
314                     .findSequenceXrefTypes(dna, al.getSequencesArray());
315             if (types != null)
316             {
317               System.out.println("Xref Types for: "
318                       + (dna ? "dna" : "prot"));
319               for (int t = 0; t < types.length; t++)
320               {
321                 System.out.println("Type: " + types[t]);
322                 SequenceI[] prod = jalview.analysis.CrossRef
323                         .findXrefSequences(al.getSequencesArray(), dna,
324                                 types[t]).getSequencesArray();
325                 System.out.println("Found "
326                         + ((prod == null) ? "no" : "" + prod.length)
327                         + " products");
328                 if (prod != null)
329                 {
330                   for (int p = 0; p < prod.length; p++)
331                   {
332                     System.out.println("Prod " + p + ": "
333                             + prod[p].getDisplayId(true));
334                   }
335                 }
336               }
337             }
338             else
339             {
340               noProds.addElement((dna ? new Object[]
341               { al, al } : new Object[]
342               { al }));
343             }
344
345           }
346         } catch (Exception ex)
347         {
348           System.out.println("ERROR:Failed to retrieve test query.");
349           ex.printStackTrace(System.out);
350         }
351
352         if (al == null)
353         {
354           System.out.println("ERROR:No alignment retrieved.");
355           StringBuffer raw = sp.getRawRecords();
356           if (raw != null)
357           {
358             System.out.println(raw.toString());
359           }
360           else
361           {
362             System.out.println("ERROR:No Raw results.");
363           }
364         }
365         else
366         {
367           System.out.println("Retrieved " + al.getHeight() + " sequences.");
368           for (int s = 0; s < al.getHeight(); s++)
369           {
370             SequenceI sq = al.getSequenceAt(s);
371             while (sq.getDatasetSequence() != null)
372             {
373               sq = sq.getDatasetSequence();
374
375             }
376             if (ds == null)
377             {
378               ds = new Alignment(new SequenceI[]
379               { sq });
380
381             }
382             else
383             {
384               ds.addSequence(sq);
385             }
386           }
387         }
388         System.out.flush();
389         System.err.flush();
390
391       }
392       if (noProds.size() > 0)
393       {
394         Enumeration ts = noProds.elements();
395         while (ts.hasMoreElements())
396
397         {
398           Object[] typeSq = (Object[]) ts.nextElement();
399           boolean dna = (typeSq.length > 1);
400           AlignmentI al = (AlignmentI) typeSq[0];
401           System.out.println("Trying getProducts for "
402                   + al.getSequenceAt(0).getDisplayId(true));
403           System.out.println("Search DS Xref for: "
404                   + (dna ? "dna" : "prot"));
405           // have a bash at finding the products amongst all the retrieved
406           // sequences.
407           SequenceI[] seqs = al.getSequencesArray();
408           Alignment prodal = jalview.analysis.CrossRef.findXrefSequences(
409                   seqs, dna, null, ds);
410           System.out.println("Found "
411                   + ((prodal == null) ? "no" : "" + prodal.getHeight())
412                   + " products");
413           if (prodal != null)
414           {
415             SequenceI[] prod = prodal.getSequencesArray(); // note
416             // should
417             // test
418             // rather
419             // than
420             // throw
421             // away
422             // codon
423             // mapping
424             // (if
425             // present)
426             for (int p = 0; p < prod.length; p++)
427             {
428               System.out.println("Prod " + p + ": "
429                       + prod[p].getDisplayId(true));
430             }
431           }
432         }
433
434       }
435
436     }
437   }
438
439   /**
440    * query the currently defined DAS source registry for sequence sources and
441    * add a DasSequenceSource instance for each source to the SequenceFetcher
442    * source list.
443    */
444   public void registerDasSequenceSources()
445   {
446     // TODO: define a context as a registry provider (either desktop,
447     // jalview.bin.cache, or something else).
448     for (jalviewSourceI source : jalview.bin.Cache.getDasSourceRegistry()
449             .getSources())
450     {
451       if (source.isSequenceSource())
452       {
453         List<DbSourceProxy> dassources = source.getSequenceSourceProxies();
454         for (DbSourceProxy seqsrc : dassources)
455         {
456           addDbRefSourceImpl(seqsrc);
457         }
458       }
459     }
460   }
461
462 }