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