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