JAL-1645 Version-Rel Version 2.9 Year-Rel 2015 Licensing glob
[jalview.git] / src / jalview / ws / SequenceFetcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9)
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     addDBRefSourceImpl(jalview.ws.dbsources.RfamFull.class);
67     addDBRefSourceImpl(jalview.ws.dbsources.RfamSeed.class);
68     if (addDas)
69     {
70       registerDasSequenceSources();
71     }
72   }
73
74   /**
75    * return an ordered list of database sources where non-das database classes
76    * appear before das database classes
77    */
78   public String[] getOrderedSupportedSources()
79   {
80     String[] srcs = this.getSupportedDb();
81     ArrayList<String> dassrc = new ArrayList<String>(), nondas = new ArrayList<String>();
82     for (int i = 0; i < srcs.length; i++)
83     {
84       boolean das = false, skip = false;
85       String nm;
86       for (DbSourceProxy dbs : getSourceProxy(srcs[i]))
87       {
88         // Skip the alignment databases for the moment - they're not useful for
89         // verifying a single sequence against its reference source
90         if (dbs.isA(DBRefSource.ALIGNMENTDB))
91         {
92           skip = true;
93         }
94         else
95         {
96           nm = dbs.getDbName();
97           if (getSourceProxy(srcs[i]) instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
98           {
99             if (nm.startsWith("das:"))
100             {
101               nm = nm.substring(4);
102               das = true;
103             }
104             break;
105           }
106         }
107       }
108       if (skip)
109       {
110         continue;
111       }
112       if (das)
113       {
114         dassrc.add(srcs[i]);
115       }
116       else
117       {
118         nondas.add(srcs[i]);
119       }
120     }
121     String[] tosort = nondas.toArray(new String[0]), sorted = nondas
122             .toArray(new String[0]);
123     for (int j = 0, jSize = sorted.length; j < jSize; j++)
124     {
125       tosort[j] = tosort[j].toLowerCase();
126     }
127     jalview.util.QuickSort.sort(tosort, sorted);
128     // construct array with all sources listed
129
130     srcs = new String[sorted.length + dassrc.size()];
131     int i = 0;
132     for (int j = sorted.length - 1; j >= 0; j--, i++)
133     {
134       srcs[i] = sorted[j];
135       sorted[j] = null;
136     }
137
138     sorted = dassrc.toArray(new String[0]);
139     tosort = dassrc.toArray(new String[0]);
140     for (int j = 0, jSize = sorted.length; j < jSize; j++)
141     {
142       tosort[j] = tosort[j].toLowerCase();
143     }
144     jalview.util.QuickSort.sort(tosort, sorted);
145     for (int j = sorted.length - 1; j >= 0; j--, i++)
146     {
147       srcs[i] = sorted[j];
148     }
149     return srcs;
150   }
151
152   /**
153    * return plaintext databse list suitable for using in a GUI element
154    */
155   public String[] _getOrderedSupportedSources()
156   {
157     String[] srcs = this.getSupportedDb();
158     ArrayList dassrc = new ArrayList(), nondas = new ArrayList();
159     for (int i = 0; i < srcs.length; i++)
160     {
161       for (DbSourceProxy dbs : getSourceProxy(srcs[i]))
162       {
163         String nm = dbs.getDbName();
164         if (getSourceProxy(srcs[i]) instanceof jalview.ws.dbsources.das.datamodel.DasSequenceSource)
165         {
166           if (nm.startsWith("das:"))
167           {
168             nm = nm.substring(4);
169           }
170           dassrc.add(new String[] { srcs[i], nm.toUpperCase() });
171         }
172         else
173         {
174           nondas.add(new String[] { srcs[i], nm.toUpperCase() });
175         }
176       }
177     }
178     Object[] sorted = nondas.toArray();
179     String[] tosort = new String[sorted.length];
180     nondas.clear();
181     for (int j = 0; j < sorted.length; j++)
182     {
183       tosort[j] = ((String[]) sorted[j])[1];
184     }
185     jalview.util.QuickSort.sort(tosort, sorted);
186     int i = 0;
187     // construct array with all sources listed
188     srcs = new String[sorted.length + dassrc.size()];
189     for (int j = sorted.length - 1; j >= 0; j--, i++)
190     {
191       srcs[i] = ((String[]) sorted[j])[0];
192       sorted[j] = null;
193     }
194
195     sorted = dassrc.toArray();
196     tosort = new String[sorted.length];
197     dassrc.clear();
198     for (int j = 0; j < sorted.length; j++)
199     {
200       tosort[j] = ((String[]) sorted[j])[1];
201     }
202     jalview.util.QuickSort.sort(tosort, sorted);
203     for (int j = sorted.length - 1; j >= 0; j--, i++)
204     {
205       srcs[i] = ((String[]) sorted[j])[0];
206       sorted[j] = null;
207     }
208     return srcs;
209   }
210
211   /**
212    * simple run method to test dbsources.
213    * 
214    * @param argv
215    */
216   public static void main(String[] argv)
217   {
218     AlignmentI ds = null;
219     Vector noProds = new Vector();
220     String usage = "SequenceFetcher.main [-nodas] [<DBNAME> [<ACCNO>]]\n"
221             + "With no arguments, all DbSources will be queried with their test Accession number.\n"
222             + "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"
223             + "If given two arguments, SequenceFetcher will try to find the DbFetcher corresponding to <DBNAME> and retrieve <ACCNO> from it.\n"
224             + "The -nodas option will exclude DAS sources from the database fetchers Jalview will try to use.";
225     boolean withDas = true;
226     if (argv != null && argv.length > 0
227             && argv[0].toLowerCase().startsWith("-nodas"))
228     {
229       withDas = false;
230       String targs[] = new String[argv.length - 1];
231       System.arraycopy(argv, 1, targs, 0, targs.length);
232       argv = targs;
233     }
234     if (argv != null && argv.length > 0)
235     {
236       List<DbSourceProxy> sps = new SequenceFetcher(withDas)
237               .getSourceProxy(argv[0]);
238
239       if (sps != null)
240       {
241         for (DbSourceProxy sp : sps)
242         {
243           AlignmentI al = null;
244           try
245           {
246             al = sp.getSequenceRecords(argv.length > 1 ? argv[1] : sp
247                     .getTestQuery());
248           } catch (Exception e)
249           {
250             e.printStackTrace();
251             System.err.println("Error when retrieving "
252                     + (argv.length > 1 ? argv[1] : sp.getTestQuery())
253                     + " from " + argv[0] + "\nUsage: " + usage);
254           }
255           SequenceI[] prod = al.getSequencesArray();
256           if (al != null)
257           {
258             for (int p = 0; p < prod.length; p++)
259             {
260               System.out.println("Prod " + p + ": "
261                       + prod[p].getDisplayId(true) + " : "
262                       + prod[p].getDescription());
263             }
264           }
265         }
266         return;
267       }
268       else
269       {
270         System.err.println("Can't resolve " + argv[0]
271                 + " as a database name. Allowed values are :\n"
272                 + new SequenceFetcher().getSupportedDb());
273       }
274       System.out.println(usage);
275       return;
276     }
277     ASequenceFetcher sfetcher = new SequenceFetcher(withDas);
278     String[] dbSources = sfetcher.getSupportedDb();
279     for (int dbsource = 0; dbsource < dbSources.length; dbsource++)
280     {
281       String db = dbSources[dbsource];
282       // skip me
283       if (db.equals(DBRefSource.PDB))
284       {
285         continue;
286       }
287       for (DbSourceProxy sp : sfetcher.getSourceProxy(db))
288       {
289         System.out.println("Source: " + sp.getDbName() + " (" + db
290                 + "): retrieving test:" + sp.getTestQuery());
291         AlignmentI al = null;
292         try
293         {
294           al = sp.getSequenceRecords(sp.getTestQuery());
295           if (al != null && al.getHeight() > 0
296                   && sp.getDbSourceProperties() != null)
297           {
298             boolean dna = sp.getDbSourceProperties().containsKey(
299                     DBRefSource.DNACODINGSEQDB)
300                     || sp.getDbSourceProperties().containsKey(
301                             DBRefSource.DNASEQDB)
302                     || sp.getDbSourceProperties().containsKey(
303                             DBRefSource.CODINGSEQDB);
304             // try and find products
305             String types[] = jalview.analysis.CrossRef
306                     .findSequenceXrefTypes(dna, al.getSequencesArray());
307             if (types != null)
308             {
309               System.out.println("Xref Types for: "
310                       + (dna ? "dna" : "prot"));
311               for (int t = 0; t < types.length; t++)
312               {
313                 System.out.println("Type: " + types[t]);
314                 SequenceI[] prod = jalview.analysis.CrossRef
315                         .findXrefSequences(al.getSequencesArray(), dna,
316                                 types[t]).getSequencesArray();
317                 System.out.println("Found "
318                         + ((prod == null) ? "no" : "" + prod.length)
319                         + " products");
320                 if (prod != null)
321                 {
322                   for (int p = 0; p < prod.length; p++)
323                   {
324                     System.out.println("Prod " + p + ": "
325                             + prod[p].getDisplayId(true));
326                   }
327                 }
328               }
329             }
330             else
331             {
332               noProds.addElement((dna ? new Object[] { al, al }
333                       : new Object[] { al }));
334             }
335
336           }
337         } catch (Exception ex)
338         {
339           System.out.println("ERROR:Failed to retrieve test query.");
340           ex.printStackTrace(System.out);
341         }
342
343         if (al == null)
344         {
345           System.out.println("ERROR:No alignment retrieved.");
346           StringBuffer raw = sp.getRawRecords();
347           if (raw != null)
348           {
349             System.out.println(raw.toString());
350           }
351           else
352           {
353             System.out.println("ERROR:No Raw results.");
354           }
355         }
356         else
357         {
358           System.out.println("Retrieved " + al.getHeight() + " sequences.");
359           for (int s = 0; s < al.getHeight(); s++)
360           {
361             SequenceI sq = al.getSequenceAt(s);
362             while (sq.getDatasetSequence() != null)
363             {
364               sq = sq.getDatasetSequence();
365
366             }
367             if (ds == null)
368             {
369               ds = new Alignment(new SequenceI[] { 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 }