fa58a2ca0dc69b091892c3aef1aa3868352a0abb
[jalview.git] / src / jalview / ws / SequenceFetcher.java
1 /*\r
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)\r
3  * Copyright (C) 2010 J Procter, AM Waterhouse, 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 java.util.ArrayList;\r
21 import java.util.Enumeration;\r
22 import java.util.Vector;\r
23 \r
24 import org.biojava.dasobert.das2.Das2Source;\r
25 import org.biojava.dasobert.dasregistry.Das1Source;\r
26 import org.biojava.dasobert.dasregistry.DasCoordinateSystem;\r
27 import org.biojava.dasobert.dasregistry.DasSource;\r
28 \r
29 import jalview.datamodel.Alignment;\r
30 import jalview.datamodel.AlignmentI;\r
31 import jalview.datamodel.DBRefSource;\r
32 import jalview.datamodel.SequenceI;\r
33 import jalview.ws.dbsources.DasSequenceSource;\r
34 import jalview.ws.seqfetcher.ASequenceFetcher;\r
35 import jalview.ws.seqfetcher.DbSourceProxy;\r
36 \r
37 /**\r
38  * This is the the concrete implementation of the sequence retrieval interface\r
39  * and abstract class in jalview.ws.seqfetcher. This implements the run-time\r
40  * discovery of sequence database clients, and provides a hardwired main for\r
41  * testing all registered handlers.\r
42  * \r
43  */\r
44 public class SequenceFetcher extends ASequenceFetcher\r
45 {\r
46   /**\r
47    * Thread safe construction of database proxies TODO: extend to a configurable\r
48    * database plugin mechanism where classes are instantiated by reflection and\r
49    * queried for their DbRefSource and version association.\r
50    * \r
51    */\r
52   public SequenceFetcher()\r
53   {\r
54     addDBRefSourceImpl(jalview.ws.dbsources.EmblSource.class);\r
55     addDBRefSourceImpl(jalview.ws.dbsources.EmblCdsSouce.class);\r
56     addDBRefSourceImpl(jalview.ws.dbsources.Uniprot.class);\r
57     addDBRefSourceImpl(jalview.ws.dbsources.UnprotName.class);\r
58     addDBRefSourceImpl(jalview.ws.dbsources.Pdb.class);\r
59     addDBRefSourceImpl(jalview.ws.dbsources.PfamFull.class);\r
60     addDBRefSourceImpl(jalview.ws.dbsources.PfamSeed.class); // ensures Seed\r
61     // alignment is\r
62     // 'default' for\r
63     // PFAM\r
64     registerDasSequenceSources();\r
65   }\r
66 \r
67   /**\r
68    * return an ordered list of database sources suitable for using in a GUI\r
69    * element\r
70    */\r
71   public String[] getOrderedSupportedSources()\r
72   {\r
73     String[] srcs = this.getSupportedDb();\r
74     ArrayList dassrc = new ArrayList(), nondas = new ArrayList();\r
75     for (int i = 0; i < srcs.length; i++)\r
76     {\r
77       String nm = getSourceProxy(srcs[i]).getDbName();\r
78       if (getSourceProxy(srcs[i]) instanceof jalview.ws.dbsources.DasSequenceSource)\r
79       {\r
80         if (nm.startsWith("das:"))\r
81         {\r
82           nm = nm.substring(4);\r
83         }\r
84         dassrc.add(new String[]\r
85         { srcs[i], nm.toUpperCase() });\r
86       }\r
87       else\r
88       {\r
89         nondas.add(new String[]\r
90         { srcs[i], nm.toUpperCase() });\r
91       }\r
92     }\r
93     Object[] sorted = nondas.toArray();\r
94     String[] tosort = new String[sorted.length];\r
95     nondas.clear();\r
96     for (int j = 0; j < sorted.length; j++)\r
97     {\r
98       tosort[j] = ((String[]) sorted[j])[1];\r
99     }\r
100     jalview.util.QuickSort.sort(tosort, sorted);\r
101     int i = 0;\r
102     for (int j = sorted.length - 1; j >= 0; j--, i++)\r
103     {\r
104       srcs[i] = ((String[]) sorted[j])[0];\r
105       sorted[j] = null;\r
106     }\r
107 \r
108     sorted = dassrc.toArray();\r
109     tosort = new String[sorted.length];\r
110     dassrc.clear();\r
111     for (int j = 0; j < sorted.length; j++)\r
112     {\r
113       tosort[j] = ((String[]) sorted[j])[1];\r
114     }\r
115     jalview.util.QuickSort.sort(tosort, sorted);\r
116     for (int j = sorted.length - 1; j >= 0; j--, i++)\r
117     {\r
118       srcs[i] = ((String[]) sorted[j])[0];\r
119       sorted[j] = null;\r
120     }\r
121     return srcs;\r
122   }\r
123 \r
124   /**\r
125    * simple run method to test dbsources.\r
126    * \r
127    * @param argv\r
128    */\r
129   public static void main(String[] argv)\r
130   {\r
131     AlignmentI ds = null;\r
132     Vector noProds = new Vector();\r
133     String usage = "SequenceFetcher.main [<DBNAME> <ACCNO>]\n"\r
134             + "With no arguments, all DbSources will be queried with their test Accession number.\n"\r
135             + "If given two arguments, SequenceFetcher will try to find the DbFetcher corresponding to <DBNAME> and retrieve <ACCNO> from it.";\r
136     if (argv != null && argv.length > 0)\r
137     {\r
138       DbSourceProxy sp = new SequenceFetcher().getSourceProxy(argv[0]);\r
139       if (sp != null)\r
140       {\r
141         AlignmentI al = null;\r
142         try\r
143         {\r
144           al = sp.getSequenceRecords(argv[1]);\r
145         } catch (Exception e)\r
146         {\r
147           e.printStackTrace();\r
148           System.err.println("Error when retrieving " + argv[1] + " from "\r
149                   + argv[0] + "\nUsage: " + usage);\r
150         }\r
151         SequenceI[] prod = al.getSequencesArray();\r
152         if (al != null)\r
153         {\r
154           for (int p = 0; p < prod.length; p++)\r
155           {\r
156             System.out.println("Prod " + p + ": "\r
157                     + prod[p].getDisplayId(true) + " : "\r
158                     + prod[p].getDescription());\r
159           }\r
160         }\r
161         return;\r
162       }\r
163       else\r
164       {\r
165         System.err.println("Can't resolve " + argv[0]\r
166                 + " as a database name. Allowed values are :\n"\r
167                 + new SequenceFetcher().getSupportedDb());\r
168       }\r
169       System.out.println(usage);\r
170     }\r
171     ASequenceFetcher sfetcher = new SequenceFetcher();\r
172     String[] dbSources = sfetcher.getSupportedDb();\r
173     for (int dbsource = 0; dbsource < dbSources.length; dbsource++)\r
174     {\r
175       String db = dbSources[dbsource];\r
176       // skip me\r
177       if (db.equals(DBRefSource.PDB))\r
178         continue;\r
179       DbSourceProxy sp = sfetcher.getSourceProxy(db);\r
180       System.out.println("Source: " + sp.getDbName() + " (" + db\r
181               + "): retrieving test:" + sp.getTestQuery());\r
182       AlignmentI al = null;\r
183       try\r
184       {\r
185         al = sp.getSequenceRecords(sp.getTestQuery());\r
186         if (al != null && al.getHeight() > 0\r
187                 && sp.getDbSourceProperties() != null)\r
188         {\r
189           boolean dna = sp.getDbSourceProperties().containsKey(\r
190                   DBRefSource.DNACODINGSEQDB)\r
191                   || sp.getDbSourceProperties().containsKey(\r
192                           DBRefSource.DNASEQDB)\r
193                   || sp.getDbSourceProperties().containsKey(\r
194                           DBRefSource.CODINGSEQDB);\r
195           // try and find products\r
196           String types[] = jalview.analysis.CrossRef.findSequenceXrefTypes(\r
197                   dna, al.getSequencesArray());\r
198           if (types != null)\r
199           {\r
200             System.out.println("Xref Types for: " + (dna ? "dna" : "prot"));\r
201             for (int t = 0; t < types.length; t++)\r
202             {\r
203               System.out.println("Type: " + types[t]);\r
204               SequenceI[] prod = jalview.analysis.CrossRef\r
205                       .findXrefSequences(al.getSequencesArray(), dna,\r
206                               types[t]).getSequencesArray();\r
207               System.out.println("Found "\r
208                       + ((prod == null) ? "no" : "" + prod.length)\r
209                       + " products");\r
210               if (prod != null)\r
211               {\r
212                 for (int p = 0; p < prod.length; p++)\r
213                 {\r
214                   System.out.println("Prod " + p + ": "\r
215                           + prod[p].getDisplayId(true));\r
216                 }\r
217               }\r
218             }\r
219           }\r
220           else\r
221           {\r
222             noProds.addElement((dna ? new Object[]\r
223             { al, al } : new Object[]\r
224             { al }));\r
225           }\r
226 \r
227         }\r
228       } catch (Exception ex)\r
229       {\r
230         System.out.println("ERROR:Failed to retrieve test query.");\r
231         ex.printStackTrace(System.out);\r
232       }\r
233       if (al == null)\r
234       {\r
235         System.out.println("ERROR:No alignment retrieved.");\r
236         StringBuffer raw = sp.getRawRecords();\r
237         if (raw != null)\r
238           System.out.println(raw.toString());\r
239         else\r
240           System.out.println("ERROR:No Raw results.");\r
241       }\r
242       else\r
243       {\r
244         System.out.println("Retrieved " + al.getHeight() + " sequences.");\r
245         for (int s = 0; s < al.getHeight(); s++)\r
246         {\r
247           SequenceI sq = al.getSequenceAt(s);\r
248           while (sq.getDatasetSequence() != null)\r
249           {\r
250             sq = sq.getDatasetSequence();\r
251 \r
252           }\r
253           if (ds == null)\r
254           {\r
255             ds = new Alignment(new SequenceI[]\r
256             { sq });\r
257 \r
258           }\r
259           else\r
260           {\r
261             ds.addSequence(sq);\r
262           }\r
263         }\r
264       }\r
265       System.out.flush();\r
266       System.err.flush();\r
267 \r
268     }\r
269     if (noProds.size() > 0)\r
270     {\r
271       Enumeration ts = noProds.elements();\r
272       while (ts.hasMoreElements())\r
273 \r
274       {\r
275         Object[] typeSq = (Object[]) ts.nextElement();\r
276         boolean dna = (typeSq.length > 1);\r
277         AlignmentI al = (AlignmentI) typeSq[0];\r
278         System.out.println("Trying getProducts for "\r
279                 + al.getSequenceAt(0).getDisplayId(true));\r
280         System.out.println("Search DS Xref for: " + (dna ? "dna" : "prot"));\r
281         // have a bash at finding the products amongst all the retrieved\r
282         // sequences.\r
283         SequenceI[] seqs = al.getSequencesArray();\r
284         Alignment prodal = jalview.analysis.CrossRef.findXrefSequences(\r
285                 seqs, dna, null, ds);\r
286         System.out.println("Found "\r
287                 + ((prodal == null) ? "no" : "" + prodal.getHeight())\r
288                 + " products");\r
289         if (prodal != null)\r
290         {\r
291           SequenceI[] prod = prodal.getSequencesArray(); // note\r
292           // should\r
293           // test\r
294           // rather\r
295           // than\r
296           // throw\r
297           // away\r
298           // codon\r
299           // mapping\r
300           // (if\r
301           // present)\r
302           for (int p = 0; p < prod.length; p++)\r
303           {\r
304             System.out.println("Prod " + p + ": "\r
305                     + prod[p].getDisplayId(true));\r
306           }\r
307         }\r
308       }\r
309 \r
310     }\r
311   }\r
312 \r
313   /**\r
314    * query the currently defined DAS source registry for sequence sources and\r
315    * add a DasSequenceSource instance for each source to the SequenceFetcher\r
316    * source list.\r
317    */\r
318   public void registerDasSequenceSources()\r
319   {\r
320     DasSource[] sources = jalview.ws.DasSequenceFeatureFetcher\r
321             .getDASSources();\r
322     if (sources != null)\r
323     {\r
324       for (int s = 0; sources != null && s < sources.length; s++)\r
325       {\r
326         addDasSequenceSource(sources[s]);\r
327       }\r
328     }\r
329 \r
330     Vector localsources = jalview.bin.Cache.getLocalDasSources();\r
331     if (localsources != null)\r
332     {\r
333       for (Enumeration ls = localsources.elements(); ls.hasMoreElements();)\r
334       {\r
335         addDasSequenceSource((DasSource) ls.nextElement());\r
336       }\r
337     }\r
338   }\r
339 \r
340   /**\r
341    * Try to create and add a DasSequenceSource to the list of sources.\r
342    * \r
343    * @param source\r
344    * @return null if no source was added, or the new DasSequenceSource created\r
345    */\r
346   DasSequenceSource addDasSequenceSource(DasSource source)\r
347   {\r
348     DasSequenceSource ds = null;\r
349     Das1Source d1s = null;\r
350     if (source.hasCapability("sequence"))\r
351     {\r
352       if (source instanceof Das2Source)\r
353       {\r
354         if (((Das2Source) source).hasDas1Capabilities())\r
355         {\r
356           try\r
357           {\r
358             d1s = org.biojava.dasobert.das2.DasSourceConverter\r
359                     .toDas1Source((Das2Source) source);\r
360           } catch (Exception e)\r
361           {\r
362             System.err.println("Ignoring DAS2 sequence source "\r
363                     + source.getNickname()\r
364                     + " - couldn't map to Das1Source.\n");\r
365             e.printStackTrace();\r
366           }\r
367         }\r
368       }\r
369       else\r
370       {\r
371         if (source instanceof Das1Source)\r
372         {\r
373           d1s = (Das1Source) source;\r
374         }\r
375       }\r
376     }\r
377     if (d1s != null)\r
378     {\r
379       DasCoordinateSystem[] css = d1s.getCoordinateSystem();\r
380       if (css == null || css.length == 0)\r
381       {\r
382         // TODO: query das source directly to identify coordinate system... or\r
383         // have to make up a coordinate system\r
384         css = new DasCoordinateSystem[]\r
385         { new DasCoordinateSystem() };\r
386         css[0].setName(d1s.getNickname());\r
387         css[0].setUniqueId(d1s.getNickname());\r
388       }\r
389       for (int c = 0; c < css.length; c++)\r
390       {\r
391         try\r
392         {\r
393           addDbRefSourceImpl(ds = new DasSequenceSource("das:"\r
394                   + d1s.getNickname() + " (" + css[c].getName() + ")",\r
395                   css[c].getName(), d1s, css[c]));\r
396         } catch (Exception e)\r
397         {\r
398           System.err.println("Ignoring sequence coord system " + c + " ("\r
399                   + css[c].getName() + ") for source " + d1s.getNickname()\r
400                   + "- threw exception when constructing fetcher.\n");\r
401           e.printStackTrace();\r
402         }\r
403       }\r
404     }\r
405     return ds;\r
406   }\r
407 }\r