JAL-1355 (basic i18n support)
[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.util.MessageManager;
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(MessageManager.getString("label.your_sequences_have_been_verified")
454               + sbuffer.toString());
455       Desktop.addInternalFrame(output, MessageManager.getString("label.sequence_names_updated"), 600, 300);
456       // The above is the dataset, we must now find out the index
457       // of the viewed sequence
458
459     }
460
461     af.setProgressBar(MessageManager.getString("label.dbref_search_completed"), startTime);
462     // promptBeforeBlast();
463
464     running = false;
465
466   }
467
468   /**
469    * Verify local sequences in seqRefs against the retrieved sequence database
470    * records.
471    * 
472    */
473   void transferReferences(Vector sdataset, String dbSource,
474           AlignmentI retrievedAl) // File
475   // file)
476   {
477     if (retrievedAl == null || retrievedAl.getHeight() == 0)
478     {
479       return;
480     }
481     SequenceI[] retrieved = recoverDbSequences(retrievedAl
482             .getSequencesArray());
483     SequenceI sequence = null;
484     boolean transferred = false;
485     StringBuffer messages = new StringBuffer();
486
487     // Vector entries = new Uniprot().getUniprotEntries(file);
488
489     int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
490     // UniprotEntry entry;
491     for (i = 0; i < iSize; i++)
492     {
493       SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
494
495       // Work out which sequences this sequence matches,
496       // taking into account all accessionIds and names in the file
497       Vector sequenceMatches = new Vector();
498       // look for corresponding accession ids
499       DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
500               entry.getDBRef(), new String[]
501               { dbSource });
502       if (entryRefs == null)
503       {
504         System.err
505                 .println("Dud dbSource string ? no entryrefs selected for "
506                         + dbSource + " on " + entry.getName());
507         continue;
508       }
509       for (int j = 0; j < entryRefs.length; j++)
510       {
511         String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
512         // match up on accessionId
513         if (seqRefs.containsKey(accessionId.toUpperCase()))
514         {
515           Vector seqs = (Vector) seqRefs.get(accessionId);
516           for (int jj = 0; jj < seqs.size(); jj++)
517           {
518             sequence = (SequenceI) seqs.elementAt(jj);
519             if (!sequenceMatches.contains(sequence))
520             {
521               sequenceMatches.addElement(sequence);
522             }
523           }
524         }
525       }
526       if (sequenceMatches.size() == 0)
527       {
528         // failed to match directly on accessionId==query so just compare all
529         // sequences to entry
530         Enumeration e = seqRefs.keys();
531         while (e.hasMoreElements())
532         {
533           Vector sqs = (Vector) seqRefs.get(e.nextElement());
534           if (sqs != null && sqs.size() > 0)
535           {
536             Enumeration sqe = sqs.elements();
537             while (sqe.hasMoreElements())
538             {
539               sequenceMatches.addElement(sqe.nextElement());
540             }
541           }
542         }
543       }
544       // look for corresponding names
545       // this is uniprot specific ?
546       // could be useful to extend this so we try to find any 'significant'
547       // information in common between two sequence objects.
548       /*
549        * DBRefEntry[] entryRefs =
550        * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
551        * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
552        * name = entry.getName().elementAt(j).toString(); if
553        * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
554        * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
555        * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
556        * sequenceMatches.addElement(sequence); } } } }
557        */
558       // sequenceMatches now contains the set of all sequences associated with
559       // the returned db record
560       String entrySeq = entry.getSequenceAsString().toUpperCase();
561       for (int m = 0; m < sequenceMatches.size(); m++)
562       {
563         sequence = (SequenceI) sequenceMatches.elementAt(m);
564         // only update start and end positions and shift features if there are
565         // no existing references
566         // TODO: test for legacy where uniprot or EMBL refs exist but no
567         // mappings are made (but content matches retrieved set)
568         boolean updateRefFrame = sequence.getDBRef() == null
569                 || sequence.getDBRef().length == 0;
570         // verify sequence against the entry sequence
571
572         String nonGapped = AlignSeq.extractGaps("-. ",
573                 sequence.getSequenceAsString()).toUpperCase();
574
575         int absStart = entrySeq.indexOf(nonGapped);
576         int mapStart = entry.getStart();
577         jalview.datamodel.Mapping mp;
578
579         if (absStart == -1)
580         {
581           // Is local sequence contained in dataset sequence?
582           absStart = nonGapped.indexOf(entrySeq);
583           if (absStart == -1)
584           { // verification failed.
585             messages.append(sequence.getName()
586                     + " SEQUENCE NOT %100 MATCH \n");
587             continue;
588           }
589           transferred = true;
590           sbuffer.append(sequence.getName() + " HAS " + absStart
591                   + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
592           //
593           // + " - ANY SEQUENCE FEATURES"
594           // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
595           // absStart = 0;
596           // create valid mapping between matching region of local sequence and
597           // the mapped sequence
598           mp = new Mapping(null, new int[]
599           { sequence.getStart() + absStart,
600               sequence.getStart() + absStart + entrySeq.length() - 1 },
601                   new int[]
602                   { entry.getStart(),
603                       entry.getStart() + entrySeq.length() - 1 }, 1, 1);
604           updateRefFrame = false; // mapping is based on current start/end so
605           // don't modify start and end
606         }
607         else
608         {
609           transferred = true;
610           // update start and end of local sequence to place it in entry's
611           // reference frame.
612           // apply identity map map from whole of local sequence to matching
613           // region of database
614           // sequence
615           mp = null; // Mapping.getIdentityMap();
616           // new Mapping(null,
617           // new int[] { absStart+sequence.getStart(),
618           // absStart+sequence.getStart()+entrySeq.length()-1},
619           // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
620           // relocate local features for updated start
621           if (updateRefFrame)
622           {
623             if (sequence.getSequenceFeatures() != null)
624             {
625               SequenceFeature[] sf = sequence.getSequenceFeatures();
626               int start = sequence.getStart();
627               int end = sequence.getEnd();
628               int startShift = 1 - absStart - start; // how much the features
629                                                      // are
630               // to be shifted by
631               for (int sfi = 0; sfi < sf.length; sfi++)
632               {
633                 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
634                 {
635                   // shift feature along by absstart
636                   sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
637                   sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
638                 }
639               }
640             }
641           }
642         }
643
644         System.out.println("Adding dbrefs to " + sequence.getName()
645                 + " from " + dbSource + " sequence : " + entry.getName());
646         sequence.transferAnnotation(entry, mp);
647         // unknownSequences.remove(sequence);
648         int absEnd = absStart + nonGapped.length();
649         absStart += 1;
650         if (updateRefFrame)
651         {
652           // finally, update local sequence reference frame if we're allowed
653           sequence.setStart(absStart);
654           sequence.setEnd(absEnd);
655           // search for alignment sequences to update coordinate frame for
656           for (int alsq = 0; alsq < alseqs.length; alsq++)
657           {
658             if (alseqs[alsq].getDatasetSequence() == sequence)
659             {
660               String ngAlsq = AlignSeq.extractGaps("-. ",
661                       alseqs[alsq].getSequenceAsString()).toUpperCase();
662               int oldstrt = alseqs[alsq].getStart();
663               alseqs[alsq].setStart(sequence.getSequenceAsString()
664                       .toUpperCase().indexOf(ngAlsq)
665                       + sequence.getStart());
666               if (oldstrt != alseqs[alsq].getStart())
667               {
668                 alseqs[alsq].setEnd(ngAlsq.length()
669                         + alseqs[alsq].getStart() - 1);
670               }
671             }
672           }
673           // TODO: search for all other references to this dataset sequence, and
674           // update start/end
675           // TODO: update all AlCodonMappings which involve this alignment
676           // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
677           // demo)
678         }
679         // and remove it from the rest
680         // TODO: decide if we should remove annotated sequence from set
681         sdataset.remove(sequence);
682         // TODO: should we make a note of sequences that have received new DB
683         // ids, so we can query all enabled DAS servers for them ?
684       }
685     }
686     if (!transferred)
687     {
688       // report the ID/sequence mismatches
689       sbuffer.append(messages);
690     }
691   }
692
693   /**
694    * loop thru and collect additional sequences in Map.
695    * 
696    * @param sequencesArray
697    * @return
698    */
699   private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
700   {
701     Vector nseq = new Vector();
702     for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
703     {
704       nseq.addElement(sequencesArray[i]);
705       DBRefEntry dbr[] = sequencesArray[i].getDBRef();
706       jalview.datamodel.Mapping map = null;
707       for (int r = 0; (dbr != null) && r < dbr.length; r++)
708       {
709         if ((map = dbr[r].getMap()) != null)
710         {
711           if (map.getTo() != null && !nseq.contains(map.getTo()))
712           {
713             nseq.addElement(map.getTo());
714           }
715         }
716       }
717     }
718     if (nseq.size() > 0)
719     {
720       sequencesArray = new SequenceI[nseq.size()];
721       nseq.toArray(sequencesArray);
722     }
723     return sequencesArray;
724   }
725 }