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