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