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