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.ws.dbsources.das.api.jalviewSourceI;
34 import jalview.ws.seqfetcher.DbSourceProxy;
36 import java.util.ArrayList;
37 import java.util.Enumeration;
38 import java.util.Hashtable;
39 import java.util.List;
40 import java.util.StringTokenizer;
41 import java.util.Vector;
43 import uk.ac.ebi.picr.model.UPEntry;
46 * Implements a runnable for validating a sequence against external databases
47 * and then propagating references and features onto the sequence(s)
52 public class DBRefFetcher implements Runnable
56 IProgressIndicator af;
58 CutAndPasteTransfer output = new CutAndPasteTransfer();
60 StringBuffer sbuffer = new StringBuffer();
62 boolean running = false;
65 * picr client instance
67 uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
69 // /This will be a collection of Vectors of sequenceI refs.
70 // The key will be the seq name or accession id of the seq
73 DbSourceProxy[] dbSources;
75 SequenceFetcher sfetcher;
77 private SequenceI[] alseqs;
84 * Creates a new SequenceFeatureFetcher object and fetches from the currently
85 * selected set of databases.
88 * fetch references for these sequences
90 * the parent alignframe for progress bar monitoring.
92 public DBRefFetcher(SequenceI[] seqs, AlignFrame af)
98 * Creates a new SequenceFeatureFetcher object and fetches from the currently
99 * selected set of databases.
102 * fetch references for these sequences
104 * the parent alignframe for progress bar monitoring.
106 * array of database source strings to query references from
108 public DBRefFetcher(SequenceI[] seqs, AlignFrame af,
109 DbSourceProxy[] sources)
112 alseqs = new SequenceI[seqs.length];
113 SequenceI[] ds = new SequenceI[seqs.length];
114 for (int i = 0; i < seqs.length; i++)
117 if (seqs[i].getDatasetSequence() != null)
118 ds[i] = seqs[i].getDatasetSequence();
123 // TODO Jalview 2.5 lots of this code should be in the gui package!
124 sfetcher = jalview.gui.SequenceFetcher.getSequenceFetcherSingleton(af);
127 // af.featureSettings_actionPerformed(null);
128 String[] defdb = null, otherdb = sfetcher
129 .getDbInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
130 List<DbSourceProxy> selsources = new ArrayList<DbSourceProxy>();
131 Vector dasselsrc = (af.featureSettings != null) ? af.featureSettings
132 .getSelectedSources() : new jalview.gui.DasSourceBrowser()
133 .getSelectedSources();
134 Enumeration<jalviewSourceI> en = dasselsrc.elements();
135 while (en.hasMoreElements())
137 jalviewSourceI src = en.nextElement();
138 List<DbSourceProxy> sp = src.getSequenceSourceProxies();
139 selsources.addAll(sp);
142 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
145 // select appropriate databases based on alignFrame context.
146 if (af.getViewport().getAlignment().isNucleotide())
148 defdb = DBRefSource.DNACODINGDBS;
152 defdb = DBRefSource.PROTEINDBS;
154 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
155 for (String ddb : defdb)
157 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
158 if (srcesfordb != null)
160 srces.addAll(srcesfordb);
164 // append the selected sequence sources to the default dbs
165 srces.addAll(selsources);
166 dbSources = srces.toArray(new DbSourceProxy[0]);
170 // we assume the caller knows what they're doing and ensured that all the
171 // db source names are valid
177 * retrieve all the das sequence sources and add them to the list of db
178 * sources to retrieve from
180 public void appendAllDasSources()
182 if (dbSources == null)
184 dbSources = new DbSourceProxy[0];
186 // append additional sources
187 DbSourceProxy[] otherdb = sfetcher
188 .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
189 if (otherdb != null && otherdb.length > 0)
191 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
193 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
194 System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
200 * start the fetcher thread
202 * @param waitTillFinished
203 * true to block until the fetcher has finished
205 public void fetchDBRefs(boolean waitTillFinished)
207 Thread thread = new Thread(this);
211 if (waitTillFinished)
218 } catch (Exception ex)
226 * The sequence will be added to a vector of sequences belonging to key which
227 * could be either seq name or dbref id
234 void addSeqId(SequenceI seq, String key)
236 key = key.toUpperCase();
239 if (seqRefs.containsKey(key))
241 seqs = (Vector) seqRefs.get(key);
243 if (seqs != null && !seqs.contains(seq))
245 seqs.addElement(seq);
247 else if (seqs == null)
250 seqs.addElement(seq);
257 seqs.addElement(seq);
260 seqRefs.put(key, seqs);
268 if (dbSources == null)
270 throw new Error("Implementation error. Must initialise dbSources");
273 long startTime = System.currentTimeMillis();
274 af.setProgressBar("Fetching db refs", startTime);
277 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
279 picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
280 .getAccessionMapperPort();
282 } catch (Exception e)
284 System.err.println("Couldn't locate PICR service instance.\n");
288 Vector sdataset = new Vector();
289 for (int s = 0; s < dataset.length; s++)
291 sdataset.addElement(dataset[s]);
293 while (sdataset.size() > 0 && db < dbSources.length)
295 int maxqlen = 1; // default number of queries made to at one time
296 System.err.println("Verifying against " + dbSources[db].getDbName());
299 // iterate through db for each remaining un-verified sequence
300 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
301 sdataset.copyInto(currSeqs);// seqs that are to be validated against
303 Vector queries = new Vector(); // generated queries curSeq
304 seqRefs = new Hashtable();
308 jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
310 // for moment, we dumbly iterate over all retrieval sources for a
311 // particular database
312 // TODO: introduce multithread multisource queries and logic to remove a
313 // query from other sources if any source for a database returns a
315 if (dbsource.getDbSourceProperties().containsKey(
316 DBRefSource.MULTIACC))
318 maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
319 DBRefSource.MULTIACC)).intValue();
325 while (queries.size() > 0 || seqIndex < currSeqs.length)
327 if (queries.size() > 0)
329 // Still queries to make for current seqIndex
330 StringBuffer queryString = new StringBuffer("");
331 int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
334 while (queries.size() > 0 && numq < nqSize)
336 String query = (String) queries.elementAt(0);
337 if (dbsource.isValidReference(query))
339 queryString.append((numq == 0) ? "" : dbsource
340 .getAccessionSeparator());
341 queryString.append(query);
344 // remove the extracted query string
345 queries.removeElementAt(0);
347 // make the queries and process the response
348 AlignmentI retrieved = null;
351 if (jalview.bin.Cache.log.isDebugEnabled())
353 jalview.bin.Cache.log.debug("Querying "
354 + dbsource.getDbName() + " with : '"
355 + queryString.toString() + "'");
357 retrieved = dbsource.getSequenceRecords(queryString
359 } catch (Exception ex)
361 ex.printStackTrace();
362 } catch (OutOfMemoryError err)
364 new OOMWarning("retrieving database references ("
365 + queryString.toString() + ")", err);
367 if (retrieved != null)
369 transferReferences(sdataset, dbsource.getDbSource(),
375 // make some more strings for use as queries
376 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
378 SequenceI sequence = dataset[seqIndex];
379 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
380 sequence.getDBRef(), new String[]
381 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
383 // check for existing dbrefs to use
384 if (uprefs != null && uprefs.length > 0)
386 for (int j = 0; j < uprefs.length; j++)
388 addSeqId(sequence, uprefs[j].getAccessionId());
389 queries.addElement(uprefs[j].getAccessionId()
395 // generate queries from sequence ID string
396 StringTokenizer st = new StringTokenizer(
397 sequence.getName(), "|");
398 while (st.hasMoreTokens())
400 String token = st.nextToken();
401 UPEntry[] presp = null;
402 if (picrClient != null)
404 // resolve the string against PICR to recover valid IDs
407 presp = picrClient.getUPIForAccession(token, null,
408 picrClient.getMappedDatabaseNames(), null,
410 } catch (Exception e)
412 System.err.println("Exception with Picr for '"
417 if (presp != null && presp.length > 0)
419 for (int id = 0; id < presp.length; id++)
421 // construct sequences from response if sequences are
422 // present, and do a transferReferences
423 // otherwise transfer non sequence x-references directly.
426 .println("Validated ID against PICR... (for what its worth):"
428 addSeqId(sequence, token);
429 queries.addElement(token.toUpperCase());
434 // System.out.println("Not querying source with token="+token+"\n");
435 addSeqId(sequence, token);
436 queries.addElement(token.toUpperCase());
444 // advance to next database
446 } // all databases have been queries.
447 if (sbuffer.length() > 0)
449 output.setText("Your sequences have been verified against known sequence databases. Some of the ids have been\n"
450 + "altered, most likely the start/end residue will have been updated.\n"
451 + "Save your alignment to maintain the updated id.\n\n"
452 + sbuffer.toString());
453 Desktop.addInternalFrame(output, "Sequence names updated ", 600, 300);
454 // The above is the dataset, we must now find out the index
455 // of the viewed sequence
459 af.setProgressBar("DBRef search completed", startTime);
460 // promptBeforeBlast();
467 * Verify local sequences in seqRefs against the retrieved sequence database
471 void transferReferences(Vector sdataset, String dbSource,
472 AlignmentI retrievedAl) // File
475 if (retrievedAl == null || retrievedAl.getHeight() == 0)
479 SequenceI[] retrieved = recoverDbSequences(retrievedAl
480 .getSequencesArray());
481 SequenceI sequence = null;
482 boolean transferred = false;
483 StringBuffer messages = new StringBuffer();
485 // Vector entries = new Uniprot().getUniprotEntries(file);
487 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
488 // UniprotEntry entry;
489 for (i = 0; i < iSize; i++)
491 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
493 // Work out which sequences this sequence matches,
494 // taking into account all accessionIds and names in the file
495 Vector sequenceMatches = new Vector();
496 // look for corresponding accession ids
497 DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
498 entry.getDBRef(), new String[]
500 if (entryRefs == null)
503 .println("Dud dbSource string ? no entryrefs selected for "
504 + dbSource + " on " + entry.getName());
507 for (int j = 0; j < entryRefs.length; j++)
509 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
510 // match up on accessionId
511 if (seqRefs.containsKey(accessionId.toUpperCase()))
513 Vector seqs = (Vector) seqRefs.get(accessionId);
514 for (int jj = 0; jj < seqs.size(); jj++)
516 sequence = (SequenceI) seqs.elementAt(jj);
517 if (!sequenceMatches.contains(sequence))
519 sequenceMatches.addElement(sequence);
524 if (sequenceMatches.size() == 0)
526 // failed to match directly on accessionId==query so just compare all
527 // sequences to entry
528 Enumeration e = seqRefs.keys();
529 while (e.hasMoreElements())
531 Vector sqs = (Vector) seqRefs.get(e.nextElement());
532 if (sqs != null && sqs.size() > 0)
534 Enumeration sqe = sqs.elements();
535 while (sqe.hasMoreElements())
537 sequenceMatches.addElement(sqe.nextElement());
542 // look for corresponding names
543 // this is uniprot specific ?
544 // could be useful to extend this so we try to find any 'significant'
545 // information in common between two sequence objects.
547 * DBRefEntry[] entryRefs =
548 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
549 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
550 * name = entry.getName().elementAt(j).toString(); if
551 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
552 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
553 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
554 * sequenceMatches.addElement(sequence); } } } }
556 // sequenceMatches now contains the set of all sequences associated with
557 // the returned db record
558 String entrySeq = entry.getSequenceAsString().toUpperCase();
559 for (int m = 0; m < sequenceMatches.size(); m++)
561 sequence = (SequenceI) sequenceMatches.elementAt(m);
562 // only update start and end positions and shift features if there are
563 // no existing references
564 // TODO: test for legacy where uniprot or EMBL refs exist but no
565 // mappings are made (but content matches retrieved set)
566 boolean updateRefFrame = sequence.getDBRef() == null
567 || sequence.getDBRef().length == 0;
568 // verify sequence against the entry sequence
570 String nonGapped = AlignSeq.extractGaps("-. ",
571 sequence.getSequenceAsString()).toUpperCase();
573 int absStart = entrySeq.indexOf(nonGapped);
574 int mapStart = entry.getStart();
575 jalview.datamodel.Mapping mp;
579 // Is local sequence contained in dataset sequence?
580 absStart = nonGapped.indexOf(entrySeq);
582 { // verification failed.
583 messages.append(sequence.getName()
584 + " SEQUENCE NOT %100 MATCH \n");
588 sbuffer.append(sequence.getName() + " HAS " + absStart
589 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
591 // + " - ANY SEQUENCE FEATURES"
592 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
594 // create valid mapping between matching region of local sequence and
595 // the mapped sequence
596 mp = new Mapping(null, new int[]
597 { sequence.getStart() + absStart,
598 sequence.getStart() + absStart + entrySeq.length() - 1 },
601 entry.getStart() + entrySeq.length() - 1 }, 1, 1);
602 updateRefFrame = false; // mapping is based on current start/end so
603 // don't modify start and end
608 // update start and end of local sequence to place it in entry's
610 // apply identity map map from whole of local sequence to matching
611 // region of database
613 mp = null; // Mapping.getIdentityMap();
615 // new int[] { absStart+sequence.getStart(),
616 // absStart+sequence.getStart()+entrySeq.length()-1},
617 // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
618 // relocate local features for updated start
621 if (sequence.getSequenceFeatures() != null)
623 SequenceFeature[] sf = sequence.getSequenceFeatures();
624 int start = sequence.getStart();
625 int end = sequence.getEnd();
626 int startShift = 1 - absStart - start; // how much the features
629 for (int sfi = 0; sfi < sf.length; sfi++)
631 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
633 // shift feature along by absstart
634 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
635 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
642 System.out.println("Adding dbrefs to " + sequence.getName()
643 + " from " + dbSource + " sequence : " + entry.getName());
644 sequence.transferAnnotation(entry, mp);
645 // unknownSequences.remove(sequence);
646 int absEnd = absStart + nonGapped.length();
650 // finally, update local sequence reference frame if we're allowed
651 sequence.setStart(absStart);
652 sequence.setEnd(absEnd);
653 // search for alignment sequences to update coordinate frame for
654 for (int alsq = 0; alsq < alseqs.length; alsq++)
656 if (alseqs[alsq].getDatasetSequence() == sequence)
658 String ngAlsq = AlignSeq.extractGaps("-. ",
659 alseqs[alsq].getSequenceAsString()).toUpperCase();
660 int oldstrt = alseqs[alsq].getStart();
661 alseqs[alsq].setStart(sequence.getSequenceAsString()
662 .toUpperCase().indexOf(ngAlsq)
663 + sequence.getStart());
664 if (oldstrt != alseqs[alsq].getStart())
666 alseqs[alsq].setEnd(ngAlsq.length()
667 + alseqs[alsq].getStart() - 1);
671 // TODO: search for all other references to this dataset sequence, and
673 // TODO: update all AlCodonMappings which involve this alignment
674 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
677 // and remove it from the rest
678 // TODO: decide if we should remove annotated sequence from set
679 sdataset.remove(sequence);
680 // TODO: should we make a note of sequences that have received new DB
681 // ids, so we can query all enabled DAS servers for them ?
686 // report the ID/sequence mismatches
687 sbuffer.append(messages);
692 * loop thru and collect additional sequences in Map.
694 * @param sequencesArray
697 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
699 Vector nseq = new Vector();
700 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
702 nseq.addElement(sequencesArray[i]);
703 DBRefEntry dbr[] = sequencesArray[i].getDBRef();
704 jalview.datamodel.Mapping map = null;
705 for (int r = 0; (dbr != null) && r < dbr.length; r++)
707 if ((map = dbr[r].getMap()) != null)
709 if (map.getTo() != null && !nseq.contains(map.getTo()))
711 nseq.addElement(map.getTo());
718 sequencesArray = new SequenceI[nseq.size()];
719 nseq.toArray(sequencesArray);
721 return sequencesArray;