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