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