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