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