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