Jalview 2.8 Source Header
[jalview.git] / src / jalview / ws / DBRefFetcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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  */
18 package jalview.ws;
19
20 import jalview.analysis.AlignSeq;
21 import jalview.bin.Cache;
22 import jalview.datamodel.AlignmentI;
23 import jalview.datamodel.DBRefEntry;
24 import jalview.datamodel.DBRefSource;
25 import jalview.datamodel.Mapping;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.SequenceI;
28 import jalview.gui.AlignFrame;
29 import jalview.gui.CutAndPasteTransfer;
30 import jalview.gui.Desktop;
31 import jalview.gui.IProgressIndicator;
32 import jalview.gui.OOMWarning;
33 import jalview.ws.dbsources.das.api.jalviewSourceI;
34 import jalview.ws.seqfetcher.DbSourceProxy;
35
36 import java.lang.reflect.Array;
37 import java.util.ArrayList;
38 import java.util.Enumeration;
39 import java.util.Hashtable;
40 import java.util.List;
41 import java.util.StringTokenizer;
42 import java.util.Vector;
43
44 import uk.ac.ebi.picr.model.UPEntry;
45
46 /**
47  * Implements a runnable for validating a sequence against external databases
48  * and then propagating references and features onto the sequence(s)
49  * 
50  * @author $author$
51  * @version $Revision$
52  */
53 public class DBRefFetcher implements Runnable
54 {
55   SequenceI[] dataset;
56
57   IProgressIndicator af;
58
59   CutAndPasteTransfer output = new CutAndPasteTransfer();
60
61   StringBuffer sbuffer = new StringBuffer();
62
63   boolean running = false;
64
65   /**
66    * picr client instance
67    */
68   uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
69
70   // /This will be a collection of Vectors of sequenceI refs.
71   // The key will be the seq name or accession id of the seq
72   Hashtable seqRefs;
73
74   DbSourceProxy[] dbSources;
75
76   SequenceFetcher sfetcher;
77
78   private SequenceI[] alseqs;
79
80   public DBRefFetcher()
81   {
82   }
83
84   /**
85    * Creates a new SequenceFeatureFetcher object and fetches from the currently
86    * selected set of databases.
87    * 
88    * @param seqs
89    *          fetch references for these sequences
90    * @param af
91    *          the parent alignframe for progress bar monitoring.
92    */
93   public DBRefFetcher(SequenceI[] seqs, AlignFrame af)
94   {
95     this(seqs, af, null);
96   }
97
98   /**
99    * Creates a new SequenceFeatureFetcher object and fetches from the currently
100    * selected set of databases.
101    * 
102    * @param seqs
103    *          fetch references for these sequences
104    * @param af
105    *          the parent alignframe for progress bar monitoring.
106    * @param sources
107    *          array of database source strings to query references from
108    */
109   public DBRefFetcher(SequenceI[] seqs, AlignFrame af,
110           DbSourceProxy[] sources)
111   {
112     this.af = af;
113     alseqs = new SequenceI[seqs.length];
114     SequenceI[] ds = new SequenceI[seqs.length];
115     for (int i = 0; i < seqs.length; i++)
116     {
117       alseqs[i] = seqs[i];
118       if (seqs[i].getDatasetSequence() != null)
119         ds[i] = seqs[i].getDatasetSequence();
120       else
121         ds[i] = seqs[i];
122     }
123     this.dataset = ds;
124     // TODO Jalview 2.5 lots of this code should be in the gui package!
125     sfetcher = jalview.gui.SequenceFetcher.getSequenceFetcherSingleton(af);
126     if (sources == null)
127     {
128       // af.featureSettings_actionPerformed(null);
129       String[] defdb = null, otherdb = sfetcher
130               .getDbInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
131       List<DbSourceProxy> selsources = new ArrayList<DbSourceProxy>();
132       Vector dasselsrc = (af.featureSettings != null) ? af.featureSettings
133               .getSelectedSources() : new jalview.gui.DasSourceBrowser()
134               .getSelectedSources();
135       Enumeration<jalviewSourceI> en = dasselsrc.elements();
136       while (en.hasMoreElements())
137       {
138         jalviewSourceI src = en.nextElement();
139         List<DbSourceProxy> sp = src.getSequenceSourceProxies();
140         selsources.addAll(sp);
141         if (sp.size() > 1)
142         {
143           Cache.log.debug("Added many Db Sources for :" + src.getTitle());
144         }
145       }
146       // select appropriate databases based on alignFrame context.
147       if (af.getViewport().getAlignment().isNucleotide())
148       {
149         defdb = DBRefSource.DNACODINGDBS;
150       }
151       else
152       {
153         defdb = DBRefSource.PROTEINDBS;
154       }
155       List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
156       for (String ddb : defdb)
157       {
158         List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
159         if (srcesfordb != null)
160         {
161           srces.addAll(srcesfordb);
162         }
163       }
164
165       // append the selected sequence sources to the default dbs
166       srces.addAll(selsources);
167       dbSources = srces.toArray(new DbSourceProxy[0]);
168     }
169     else
170     {
171       // we assume the caller knows what they're doing and ensured that all the
172       // db source names are valid
173       dbSources = sources;
174     }
175   }
176
177   /**
178    * retrieve all the das sequence sources and add them to the list of db
179    * sources to retrieve from
180    */
181   public void appendAllDasSources()
182   {
183     if (dbSources == null)
184     {
185       dbSources = new DbSourceProxy[0];
186     }
187     // append additional sources
188     DbSourceProxy[] otherdb = sfetcher
189             .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
190     if (otherdb != null && otherdb.length > 0)
191     {
192       DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
193               + otherdb.length];
194       System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
195       System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
196       dbSources = newsrc;
197     }
198   }
199
200   /**
201    * start the fetcher thread
202    * 
203    * @param waitTillFinished
204    *          true to block until the fetcher has finished
205    */
206   public void fetchDBRefs(boolean waitTillFinished)
207   {
208     Thread thread = new Thread(this);
209     thread.start();
210     running = true;
211
212     if (waitTillFinished)
213     {
214       while (running)
215       {
216         try
217         {
218           Thread.sleep(500);
219         } catch (Exception ex)
220         {
221         }
222       }
223     }
224   }
225
226   /**
227    * The sequence will be added to a vector of sequences belonging to key which
228    * could be either seq name or dbref id
229    * 
230    * @param seq
231    *          SequenceI
232    * @param key
233    *          String
234    */
235   void addSeqId(SequenceI seq, String key)
236   {
237     key = key.toUpperCase();
238
239     Vector seqs;
240     if (seqRefs.containsKey(key))
241     {
242       seqs = (Vector) seqRefs.get(key);
243
244       if (seqs != null && !seqs.contains(seq))
245       {
246         seqs.addElement(seq);
247       }
248       else if (seqs == null)
249       {
250         seqs = new Vector();
251         seqs.addElement(seq);
252       }
253
254     }
255     else
256     {
257       seqs = new Vector();
258       seqs.addElement(seq);
259     }
260
261     seqRefs.put(key, seqs);
262   }
263
264   /**
265    * DOCUMENT ME!
266    */
267   public void run()
268   {
269     if (dbSources == null)
270     {
271       throw new Error("Implementation error. Must initialise dbSources");
272     }
273     running = true;
274     long startTime = System.currentTimeMillis();
275     af.setProgressBar("Fetching db refs", startTime);
276     try
277     {
278       if (Cache.getDefault("DBREFFETCH_USEPICR", false))
279       {
280         picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
281                 .getAccessionMapperPort();
282       }
283     } catch (Exception e)
284     {
285       System.err.println("Couldn't locate PICR service instance.\n");
286       e.printStackTrace();
287     }
288     int db = 0;
289     Vector sdataset = new Vector();
290     for (int s = 0; s < dataset.length; s++)
291     {
292       sdataset.addElement(dataset[s]);
293     }
294     while (sdataset.size() > 0 && db < dbSources.length)
295     {
296       int maxqlen = 1; // default number of queries made to at one time
297       System.err.println("Verifying against " + dbSources[db].getDbName());
298       boolean dn = false;
299
300       // iterate through db for each remaining un-verified sequence
301       SequenceI[] currSeqs = new SequenceI[sdataset.size()];
302       sdataset.copyInto(currSeqs);// seqs that are to be validated against
303       // dbSources[db]
304       Vector queries = new Vector(); // generated queries curSeq
305       seqRefs = new Hashtable();
306
307       int seqIndex = 0;
308
309       jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
310       {
311         // for moment, we dumbly iterate over all retrieval sources for a
312         // particular database
313         // TODO: introduce multithread multisource queries and logic to remove a
314         // query from other sources if any source for a database returns a
315         // record
316         if (dbsource.getDbSourceProperties().containsKey(
317                 DBRefSource.MULTIACC))
318         {
319           maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
320                   DBRefSource.MULTIACC)).intValue();
321         }
322         else
323         {
324           maxqlen = 1;
325         }
326         while (queries.size() > 0 || seqIndex < currSeqs.length)
327         {
328           if (queries.size() > 0)
329           {
330             // Still queries to make for current seqIndex
331             StringBuffer queryString = new StringBuffer("");
332             int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
333                     .size() : maxqlen;
334
335             while (queries.size() > 0 && numq < nqSize)
336             {
337               String query = (String) queries.elementAt(0);
338               if (dbsource.isValidReference(query))
339               {
340                 queryString.append((numq == 0) ? "" : dbsource
341                         .getAccessionSeparator());
342                 queryString.append(query);
343                 numq++;
344               }
345               // remove the extracted query string
346               queries.removeElementAt(0);
347             }
348             // make the queries and process the response
349             AlignmentI retrieved = null;
350             try
351             {
352               if (jalview.bin.Cache.log.isDebugEnabled())
353               {
354                 jalview.bin.Cache.log.debug("Querying "
355                         + dbsource.getDbName() + " with : '"
356                         + queryString.toString() + "'");
357               }
358               retrieved = dbsource.getSequenceRecords(queryString
359                       .toString());
360             } catch (Exception ex)
361             {
362               ex.printStackTrace();
363             } catch (OutOfMemoryError err)
364             {
365               new OOMWarning("retrieving database references ("
366                       + queryString.toString() + ")", err);
367             }
368             if (retrieved != null)
369             {
370               transferReferences(sdataset, dbsource.getDbSource(),
371                       retrieved);
372             }
373           }
374           else
375           {
376             // make some more strings for use as queries
377             for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
378             {
379               SequenceI sequence = dataset[seqIndex];
380               DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
381                       sequence.getDBRef(), new String[]
382                       { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
383               // });
384               // check for existing dbrefs to use
385               if (uprefs != null && uprefs.length > 0)
386               {
387                 for (int j = 0; j < uprefs.length; j++)
388                 {
389                   addSeqId(sequence, uprefs[j].getAccessionId());
390                   queries.addElement(uprefs[j].getAccessionId()
391                           .toUpperCase());
392                 }
393               }
394               else
395               {
396                 // generate queries from sequence ID string
397                 StringTokenizer st = new StringTokenizer(
398                         sequence.getName(), "|");
399                 while (st.hasMoreTokens())
400                 {
401                   String token = st.nextToken();
402                   UPEntry[] presp = null;
403                   if (picrClient != null)
404                   {
405                     // resolve the string against PICR to recover valid IDs
406                     try
407                     {
408                       presp = picrClient.getUPIForAccession(token, null,
409                               picrClient.getMappedDatabaseNames(), null,
410                               true);
411                     } catch (Exception e)
412                     {
413                       System.err.println("Exception with Picr for '"
414                               + token + "'\n");
415                       e.printStackTrace();
416                     }
417                   }
418                   if (presp != null && presp.length > 0)
419                   {
420                     for (int id = 0; id < presp.length; id++)
421                     {
422                       // construct sequences from response if sequences are
423                       // present, and do a transferReferences
424                       // otherwise transfer non sequence x-references directly.
425                     }
426                     System.out
427                             .println("Validated ID against PICR... (for what its worth):"
428                                     + token);
429                     addSeqId(sequence, token);
430                     queries.addElement(token.toUpperCase());
431                   }
432                   else
433                   {
434                     // if ()
435                     // System.out.println("Not querying source with token="+token+"\n");
436                     addSeqId(sequence, token);
437                     queries.addElement(token.toUpperCase());
438                   }
439                 }
440               }
441             }
442           }
443         }
444       }
445       // advance to next database
446       db++;
447     } // all databases have been queries.
448     if (sbuffer.length() > 0)
449     {
450       output.setText("Your sequences have been verified against known sequence databases. Some of the ids have been\n"
451               + "altered, most likely the start/end residue will have been updated.\n"
452               + "Save your alignment to maintain the updated id.\n\n"
453               + sbuffer.toString());
454       Desktop.addInternalFrame(output, "Sequence names updated ", 600, 300);
455       // The above is the dataset, we must now find out the index
456       // of the viewed sequence
457
458     }
459
460     af.setProgressBar("DBRef search completed", startTime);
461     // promptBeforeBlast();
462
463     running = false;
464
465   }
466
467   /**
468    * Verify local sequences in seqRefs against the retrieved sequence database
469    * records.
470    * 
471    */
472   void transferReferences(Vector sdataset, String dbSource,
473           AlignmentI retrievedAl) // File
474   // file)
475   {
476     if (retrievedAl == null || retrievedAl.getHeight() == 0)
477     {
478       return;
479     }
480     SequenceI[] retrieved = recoverDbSequences(retrievedAl
481             .getSequencesArray());
482     SequenceI sequence = null;
483     boolean transferred = false;
484     StringBuffer messages = new StringBuffer();
485
486     // Vector entries = new Uniprot().getUniprotEntries(file);
487
488     int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
489     // UniprotEntry entry;
490     for (i = 0; i < iSize; i++)
491     {
492       SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
493
494       // Work out which sequences this sequence matches,
495       // taking into account all accessionIds and names in the file
496       Vector sequenceMatches = new Vector();
497       // look for corresponding accession ids
498       DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
499               entry.getDBRef(), new String[]
500               { dbSource });
501       if (entryRefs == null)
502       {
503         System.err
504                 .println("Dud dbSource string ? no entryrefs selected for "
505                         + dbSource + " on " + entry.getName());
506         continue;
507       }
508       for (int j = 0; j < entryRefs.length; j++)
509       {
510         String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
511         // match up on accessionId
512         if (seqRefs.containsKey(accessionId.toUpperCase()))
513         {
514           Vector seqs = (Vector) seqRefs.get(accessionId);
515           for (int jj = 0; jj < seqs.size(); jj++)
516           {
517             sequence = (SequenceI) seqs.elementAt(jj);
518             if (!sequenceMatches.contains(sequence))
519             {
520               sequenceMatches.addElement(sequence);
521             }
522           }
523         }
524       }
525       if (sequenceMatches.size() == 0)
526       {
527         // failed to match directly on accessionId==query so just compare all
528         // sequences to entry
529         Enumeration e = seqRefs.keys();
530         while (e.hasMoreElements())
531         {
532           Vector sqs = (Vector) seqRefs.get(e.nextElement());
533           if (sqs != null && sqs.size() > 0)
534           {
535             Enumeration sqe = sqs.elements();
536             while (sqe.hasMoreElements())
537             {
538               sequenceMatches.addElement(sqe.nextElement());
539             }
540           }
541         }
542       }
543       // look for corresponding names
544       // this is uniprot specific ?
545       // could be useful to extend this so we try to find any 'significant'
546       // information in common between two sequence objects.
547       /*
548        * DBRefEntry[] entryRefs =
549        * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
550        * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
551        * name = entry.getName().elementAt(j).toString(); if
552        * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
553        * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
554        * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
555        * sequenceMatches.addElement(sequence); } } } }
556        */
557       // sequenceMatches now contains the set of all sequences associated with
558       // the returned db record
559       String entrySeq = entry.getSequenceAsString().toUpperCase();
560       for (int m = 0; m < sequenceMatches.size(); m++)
561       {
562         sequence = (SequenceI) sequenceMatches.elementAt(m);
563         // only update start and end positions and shift features if there are
564         // no existing references
565         // TODO: test for legacy where uniprot or EMBL refs exist but no
566         // mappings are made (but content matches retrieved set)
567         boolean updateRefFrame = sequence.getDBRef() == null
568                 || sequence.getDBRef().length == 0;
569         // verify sequence against the entry sequence
570
571         String nonGapped = AlignSeq.extractGaps("-. ",
572                 sequence.getSequenceAsString()).toUpperCase();
573
574         int absStart = entrySeq.indexOf(nonGapped);
575         int mapStart = entry.getStart();
576         jalview.datamodel.Mapping mp;
577
578         if (absStart == -1)
579         {
580           // Is local sequence contained in dataset sequence?
581           absStart = nonGapped.indexOf(entrySeq);
582           if (absStart == -1)
583           { // verification failed.
584             messages.append(sequence.getName()
585                     + " SEQUENCE NOT %100 MATCH \n");
586             continue;
587           }
588           transferred = true;
589           sbuffer.append(sequence.getName() + " HAS " + absStart
590                   + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
591           //
592           // + " - ANY SEQUENCE FEATURES"
593           // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
594           // absStart = 0;
595           // create valid mapping between matching region of local sequence and
596           // the mapped sequence
597           mp = new Mapping(null, new int[]
598           { sequence.getStart() + absStart,
599               sequence.getStart() + absStart + entrySeq.length() - 1 },
600                   new int[]
601                   { entry.getStart(),
602                       entry.getStart() + entrySeq.length() - 1 }, 1, 1);
603           updateRefFrame = false; // mapping is based on current start/end so
604           // don't modify start and end
605         }
606         else
607         {
608           transferred = true;
609           // update start and end of local sequence to place it in entry's
610           // reference frame.
611           // apply identity map map from whole of local sequence to matching
612           // region of database
613           // sequence
614           mp = null; // Mapping.getIdentityMap();
615           // new Mapping(null,
616           // new int[] { absStart+sequence.getStart(),
617           // absStart+sequence.getStart()+entrySeq.length()-1},
618           // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
619           // relocate local features for updated start
620           if (updateRefFrame)
621           {
622             if (sequence.getSequenceFeatures() != null)
623             {
624               SequenceFeature[] sf = sequence.getSequenceFeatures();
625               int start = sequence.getStart();
626               int end = sequence.getEnd();
627               int startShift = 1 - absStart - start; // how much the features
628                                                      // are
629               // to be shifted by
630               for (int sfi = 0; sfi < sf.length; sfi++)
631               {
632                 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
633                 {
634                   // shift feature along by absstart
635                   sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
636                   sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
637                 }
638               }
639             }
640           }
641         }
642
643         System.out.println("Adding dbrefs to " + sequence.getName()
644                 + " from " + dbSource + " sequence : " + entry.getName());
645         sequence.transferAnnotation(entry, mp);
646         // unknownSequences.remove(sequence);
647         int absEnd = absStart + nonGapped.length();
648         absStart += 1;
649         if (updateRefFrame)
650         {
651           // finally, update local sequence reference frame if we're allowed
652           sequence.setStart(absStart);
653           sequence.setEnd(absEnd);
654           // search for alignment sequences to update coordinate frame for
655           for (int alsq = 0; alsq < alseqs.length; alsq++)
656           {
657             if (alseqs[alsq].getDatasetSequence() == sequence)
658             {
659               String ngAlsq = AlignSeq.extractGaps("-. ",
660                       alseqs[alsq].getSequenceAsString()).toUpperCase();
661               int oldstrt = alseqs[alsq].getStart();
662               alseqs[alsq].setStart(sequence.getSequenceAsString()
663                       .toUpperCase().indexOf(ngAlsq)
664                       + sequence.getStart());
665               if (oldstrt != alseqs[alsq].getStart())
666               {
667                 alseqs[alsq].setEnd(ngAlsq.length()
668                         + alseqs[alsq].getStart() - 1);
669               }
670             }
671           }
672           // TODO: search for all other references to this dataset sequence, and
673           // update start/end
674           // TODO: update all AlCodonMappings which involve this alignment
675           // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
676           // demo)
677         }
678         // and remove it from the rest
679         // TODO: decide if we should remove annotated sequence from set
680         sdataset.remove(sequence);
681         // TODO: should we make a note of sequences that have received new DB
682         // ids, so we can query all enabled DAS servers for them ?
683       }
684     }
685     if (!transferred)
686     {
687       // report the ID/sequence mismatches
688       sbuffer.append(messages);
689     }
690   }
691
692   /**
693    * loop thru and collect additional sequences in Map.
694    * 
695    * @param sequencesArray
696    * @return
697    */
698   private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
699   {
700     Vector nseq = new Vector();
701     for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
702     {
703       nseq.addElement(sequencesArray[i]);
704       DBRefEntry dbr[] = sequencesArray[i].getDBRef();
705       jalview.datamodel.Mapping map = null;
706       for (int r = 0; (dbr != null) && r < dbr.length; r++)
707       {
708         if ((map = dbr[r].getMap()) != null)
709         {
710           if (map.getTo() != null && !nseq.contains(map.getTo()))
711           {
712             nseq.addElement(map.getTo());
713           }
714         }
715       }
716     }
717     if (nseq.size() > 0)
718     {
719       sequencesArray = new SequenceI[nseq.size()];
720       nseq.toArray(sequencesArray);
721     }
722     return sequencesArray;
723   }
724 }