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
5 * This file is part of Jalview.
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.
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.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
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;
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;
44 import uk.ac.ebi.picr.model.UPEntry;
47 * Implements a runnable for validating a sequence against external databases
48 * and then propagating references and features onto the sequence(s)
53 public class DBRefFetcher implements Runnable
57 IProgressIndicator af;
59 CutAndPasteTransfer output = new CutAndPasteTransfer();
61 StringBuffer sbuffer = new StringBuffer();
63 boolean running = false;
66 * picr client instance
68 uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
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
74 DbSourceProxy[] dbSources;
76 SequenceFetcher sfetcher;
78 private SequenceI[] alseqs;
85 * Creates a new SequenceFeatureFetcher object and fetches from the currently
86 * selected set of databases.
89 * fetch references for these sequences
91 * the parent alignframe for progress bar monitoring.
93 public DBRefFetcher(SequenceI[] seqs, AlignFrame af)
99 * Creates a new SequenceFeatureFetcher object and fetches from the currently
100 * selected set of databases.
103 * fetch references for these sequences
105 * the parent alignframe for progress bar monitoring.
107 * array of database source strings to query references from
109 public DBRefFetcher(SequenceI[] seqs, AlignFrame af,
110 DbSourceProxy[] sources)
113 alseqs = new SequenceI[seqs.length];
114 SequenceI[] ds = new SequenceI[seqs.length];
115 for (int i = 0; i < seqs.length; i++)
118 if (seqs[i].getDatasetSequence() != null)
119 ds[i] = seqs[i].getDatasetSequence();
124 // TODO Jalview 2.5 lots of this code should be in the gui package!
125 sfetcher = jalview.gui.SequenceFetcher.getSequenceFetcherSingleton(af);
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())
138 jalviewSourceI src = en.nextElement();
139 List<DbSourceProxy> sp = src.getSequenceSourceProxies();
142 selsources.addAll(sp);
145 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
149 // select appropriate databases based on alignFrame context.
150 if (af.getViewport().getAlignment().isNucleotide())
152 defdb = DBRefSource.DNACODINGDBS;
156 defdb = DBRefSource.PROTEINDBS;
158 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
159 for (String ddb : defdb)
161 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
162 if (srcesfordb != null)
164 srces.addAll(srcesfordb);
168 // append the selected sequence sources to the default dbs
169 srces.addAll(selsources);
170 dbSources = srces.toArray(new DbSourceProxy[0]);
174 // we assume the caller knows what they're doing and ensured that all the
175 // db source names are valid
181 * retrieve all the das sequence sources and add them to the list of db
182 * sources to retrieve from
184 public void appendAllDasSources()
186 if (dbSources == null)
188 dbSources = new DbSourceProxy[0];
190 // append additional sources
191 DbSourceProxy[] otherdb = sfetcher
192 .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
193 if (otherdb != null && otherdb.length > 0)
195 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
197 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
198 System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
204 * start the fetcher thread
206 * @param waitTillFinished
207 * true to block until the fetcher has finished
209 public void fetchDBRefs(boolean waitTillFinished)
211 Thread thread = new Thread(this);
215 if (waitTillFinished)
222 } catch (Exception ex)
230 * The sequence will be added to a vector of sequences belonging to key which
231 * could be either seq name or dbref id
238 void addSeqId(SequenceI seq, String key)
240 key = key.toUpperCase();
243 if (seqRefs.containsKey(key))
245 seqs = (Vector) seqRefs.get(key);
247 if (seqs != null && !seqs.contains(seq))
249 seqs.addElement(seq);
251 else if (seqs == null)
254 seqs.addElement(seq);
261 seqs.addElement(seq);
264 seqRefs.put(key, seqs);
272 if (dbSources == null)
274 throw new Error("Implementation error. Must initialise dbSources");
277 long startTime = System.currentTimeMillis();
278 af.setProgressBar("Fetching db refs", startTime);
281 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
283 picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
284 .getAccessionMapperPort();
286 } catch (Exception e)
288 System.err.println("Couldn't locate PICR service instance.\n");
292 Vector sdataset = new Vector();
293 for (int s = 0; s < dataset.length; s++)
295 sdataset.addElement(dataset[s]);
297 while (sdataset.size() > 0 && db < dbSources.length)
299 int maxqlen = 1; // default number of queries made to at one time
300 System.err.println("Verifying against " + dbSources[db].getDbName());
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
307 Vector queries = new Vector(); // generated queries curSeq
308 seqRefs = new Hashtable();
312 jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
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
319 if (dbsource.getDbSourceProperties().containsKey(
320 DBRefSource.MULTIACC))
322 maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
323 DBRefSource.MULTIACC)).intValue();
329 while (queries.size() > 0 || seqIndex < currSeqs.length)
331 if (queries.size() > 0)
333 // Still queries to make for current seqIndex
334 StringBuffer queryString = new StringBuffer("");
335 int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
338 while (queries.size() > 0 && numq < nqSize)
340 String query = (String) queries.elementAt(0);
341 if (dbsource.isValidReference(query))
343 queryString.append((numq == 0) ? "" : dbsource
344 .getAccessionSeparator());
345 queryString.append(query);
348 // remove the extracted query string
349 queries.removeElementAt(0);
351 // make the queries and process the response
352 AlignmentI retrieved = null;
355 if (jalview.bin.Cache.log.isDebugEnabled())
357 jalview.bin.Cache.log.debug("Querying "
358 + dbsource.getDbName() + " with : '"
359 + queryString.toString() + "'");
361 retrieved = dbsource.getSequenceRecords(queryString
363 } catch (Exception ex)
365 ex.printStackTrace();
366 } catch (OutOfMemoryError err)
368 new OOMWarning("retrieving database references ("
369 + queryString.toString() + ")", err);
371 if (retrieved != null)
373 transferReferences(sdataset, dbsource.getDbSource(),
379 // make some more strings for use as queries
380 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
382 SequenceI sequence = dataset[seqIndex];
383 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
384 sequence.getDBRef(), new String[]
385 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
387 // check for existing dbrefs to use
388 if (uprefs != null && uprefs.length > 0)
390 for (int j = 0; j < uprefs.length; j++)
392 addSeqId(sequence, uprefs[j].getAccessionId());
393 queries.addElement(uprefs[j].getAccessionId()
399 // generate queries from sequence ID string
400 StringTokenizer st = new StringTokenizer(
401 sequence.getName(), "|");
402 while (st.hasMoreTokens())
404 String token = st.nextToken();
405 UPEntry[] presp = null;
406 if (picrClient != null)
408 // resolve the string against PICR to recover valid IDs
411 presp = picrClient.getUPIForAccession(token, null,
412 picrClient.getMappedDatabaseNames(), null,
414 } catch (Exception e)
416 System.err.println("Exception with Picr for '"
421 if (presp != null && presp.length > 0)
423 for (int id = 0; id < presp.length; id++)
425 // construct sequences from response if sequences are
426 // present, and do a transferReferences
427 // otherwise transfer non sequence x-references directly.
430 .println("Validated ID against PICR... (for what its worth):"
432 addSeqId(sequence, token);
433 queries.addElement(token.toUpperCase());
438 // System.out.println("Not querying source with token="+token+"\n");
439 addSeqId(sequence, token);
440 queries.addElement(token.toUpperCase());
448 // advance to next database
450 } // all databases have been queries.
451 if (sbuffer.length() > 0)
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
461 af.setProgressBar(MessageManager.getString("label.dbref_search_completed"), startTime);
462 // promptBeforeBlast();
469 * Verify local sequences in seqRefs against the retrieved sequence database
473 void transferReferences(Vector sdataset, String dbSource,
474 AlignmentI retrievedAl) // File
477 if (retrievedAl == null || retrievedAl.getHeight() == 0)
481 SequenceI[] retrieved = recoverDbSequences(retrievedAl
482 .getSequencesArray());
483 SequenceI sequence = null;
484 boolean transferred = false;
485 StringBuffer messages = new StringBuffer();
487 // Vector entries = new Uniprot().getUniprotEntries(file);
489 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
490 // UniprotEntry entry;
491 for (i = 0; i < iSize; i++)
493 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
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[]
502 if (entryRefs == null)
505 .println("Dud dbSource string ? no entryrefs selected for "
506 + dbSource + " on " + entry.getName());
509 for (int j = 0; j < entryRefs.length; j++)
511 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
512 // match up on accessionId
513 if (seqRefs.containsKey(accessionId.toUpperCase()))
515 Vector seqs = (Vector) seqRefs.get(accessionId);
516 for (int jj = 0; jj < seqs.size(); jj++)
518 sequence = (SequenceI) seqs.elementAt(jj);
519 if (!sequenceMatches.contains(sequence))
521 sequenceMatches.addElement(sequence);
526 if (sequenceMatches.size() == 0)
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())
533 Vector sqs = (Vector) seqRefs.get(e.nextElement());
534 if (sqs != null && sqs.size() > 0)
536 Enumeration sqe = sqs.elements();
537 while (sqe.hasMoreElements())
539 sequenceMatches.addElement(sqe.nextElement());
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.
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); } } } }
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++)
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
572 String nonGapped = AlignSeq.extractGaps("-. ",
573 sequence.getSequenceAsString()).toUpperCase();
575 int absStart = entrySeq.indexOf(nonGapped);
576 int mapStart = entry.getStart();
577 jalview.datamodel.Mapping mp;
581 // Is local sequence contained in dataset sequence?
582 absStart = nonGapped.indexOf(entrySeq);
584 { // verification failed.
585 messages.append(sequence.getName()
586 + " SEQUENCE NOT %100 MATCH \n");
590 sbuffer.append(sequence.getName() + " HAS " + absStart
591 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
593 // + " - ANY SEQUENCE FEATURES"
594 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
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 },
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
610 // update start and end of local sequence to place it in entry's
612 // apply identity map map from whole of local sequence to matching
613 // region of database
615 mp = null; // Mapping.getIdentityMap();
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
623 if (sequence.getSequenceFeatures() != null)
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
631 for (int sfi = 0; sfi < sf.length; sfi++)
633 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
635 // shift feature along by absstart
636 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
637 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
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();
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++)
658 if (alseqs[alsq].getDatasetSequence() == sequence)
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())
668 alseqs[alsq].setEnd(ngAlsq.length()
669 + alseqs[alsq].getStart() - 1);
673 // TODO: search for all other references to this dataset sequence, and
675 // TODO: update all AlCodonMappings which involve this alignment
676 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
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 ?
688 // report the ID/sequence mismatches
689 sbuffer.append(messages);
694 * loop thru and collect additional sequences in Map.
696 * @param sequencesArray
699 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
701 Vector nseq = new Vector();
702 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
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++)
709 if ((map = dbr[r].getMap()) != null)
711 if (map.getTo() != null && !nseq.contains(map.getTo()))
713 nseq.addElement(map.getTo());
720 sequencesArray = new SequenceI[nseq.size()];
721 nseq.toArray(sequencesArray);
723 return sequencesArray;