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