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();
141 selsources.addAll(sp);
144 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
148 // select appropriate databases based on alignFrame context.
149 if (af.getViewport().getAlignment().isNucleotide())
151 defdb = DBRefSource.DNACODINGDBS;
155 defdb = DBRefSource.PROTEINDBS;
157 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
158 for (String ddb : defdb)
160 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
161 if (srcesfordb != null)
163 srces.addAll(srcesfordb);
167 // append the selected sequence sources to the default dbs
168 srces.addAll(selsources);
169 dbSources = srces.toArray(new DbSourceProxy[0]);
173 // we assume the caller knows what they're doing and ensured that all the
174 // db source names are valid
180 * retrieve all the das sequence sources and add them to the list of db
181 * sources to retrieve from
183 public void appendAllDasSources()
185 if (dbSources == null)
187 dbSources = new DbSourceProxy[0];
189 // append additional sources
190 DbSourceProxy[] otherdb = sfetcher
191 .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
192 if (otherdb != null && otherdb.length > 0)
194 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
196 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
197 System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
203 * start the fetcher thread
205 * @param waitTillFinished
206 * true to block until the fetcher has finished
208 public void fetchDBRefs(boolean waitTillFinished)
210 Thread thread = new Thread(this);
214 if (waitTillFinished)
221 } catch (Exception ex)
229 * The sequence will be added to a vector of sequences belonging to key which
230 * could be either seq name or dbref id
237 void addSeqId(SequenceI seq, String key)
239 key = key.toUpperCase();
242 if (seqRefs.containsKey(key))
244 seqs = (Vector) seqRefs.get(key);
246 if (seqs != null && !seqs.contains(seq))
248 seqs.addElement(seq);
250 else if (seqs == null)
253 seqs.addElement(seq);
260 seqs.addElement(seq);
263 seqRefs.put(key, seqs);
271 if (dbSources == null)
273 throw new Error("Implementation error. Must initialise dbSources");
276 long startTime = System.currentTimeMillis();
277 af.setProgressBar("Fetching db refs", startTime);
280 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
282 picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
283 .getAccessionMapperPort();
285 } catch (Exception e)
287 System.err.println("Couldn't locate PICR service instance.\n");
291 Vector sdataset = new Vector();
292 for (int s = 0; s < dataset.length; s++)
294 sdataset.addElement(dataset[s]);
296 while (sdataset.size() > 0 && db < dbSources.length)
298 int maxqlen = 1; // default number of queries made to at one time
299 System.err.println("Verifying against " + dbSources[db].getDbName());
302 // iterate through db for each remaining un-verified sequence
303 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
304 sdataset.copyInto(currSeqs);// seqs that are to be validated against
306 Vector queries = new Vector(); // generated queries curSeq
307 seqRefs = new Hashtable();
311 jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
313 // for moment, we dumbly iterate over all retrieval sources for a
314 // particular database
315 // TODO: introduce multithread multisource queries and logic to remove a
316 // query from other sources if any source for a database returns a
318 if (dbsource.getDbSourceProperties().containsKey(
319 DBRefSource.MULTIACC))
321 maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
322 DBRefSource.MULTIACC)).intValue();
328 while (queries.size() > 0 || seqIndex < currSeqs.length)
330 if (queries.size() > 0)
332 // Still queries to make for current seqIndex
333 StringBuffer queryString = new StringBuffer("");
334 int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
337 while (queries.size() > 0 && numq < nqSize)
339 String query = (String) queries.elementAt(0);
340 if (dbsource.isValidReference(query))
342 queryString.append((numq == 0) ? "" : dbsource
343 .getAccessionSeparator());
344 queryString.append(query);
347 // remove the extracted query string
348 queries.removeElementAt(0);
350 // make the queries and process the response
351 AlignmentI retrieved = null;
354 if (jalview.bin.Cache.log.isDebugEnabled())
356 jalview.bin.Cache.log.debug("Querying "
357 + dbsource.getDbName() + " with : '"
358 + queryString.toString() + "'");
360 retrieved = dbsource.getSequenceRecords(queryString
362 } catch (Exception ex)
364 ex.printStackTrace();
365 } catch (OutOfMemoryError err)
367 new OOMWarning("retrieving database references ("
368 + queryString.toString() + ")", err);
370 if (retrieved != null)
372 transferReferences(sdataset, dbsource.getDbSource(),
378 // make some more strings for use as queries
379 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
381 SequenceI sequence = dataset[seqIndex];
382 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
383 sequence.getDBRef(), new String[]
384 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
386 // check for existing dbrefs to use
387 if (uprefs != null && uprefs.length > 0)
389 for (int j = 0; j < uprefs.length; j++)
391 addSeqId(sequence, uprefs[j].getAccessionId());
392 queries.addElement(uprefs[j].getAccessionId()
398 // generate queries from sequence ID string
399 StringTokenizer st = new StringTokenizer(
400 sequence.getName(), "|");
401 while (st.hasMoreTokens())
403 String token = st.nextToken();
404 UPEntry[] presp = null;
405 if (picrClient != null)
407 // resolve the string against PICR to recover valid IDs
410 presp = picrClient.getUPIForAccession(token, null,
411 picrClient.getMappedDatabaseNames(), null,
413 } catch (Exception e)
415 System.err.println("Exception with Picr for '"
420 if (presp != null && presp.length > 0)
422 for (int id = 0; id < presp.length; id++)
424 // construct sequences from response if sequences are
425 // present, and do a transferReferences
426 // otherwise transfer non sequence x-references directly.
429 .println("Validated ID against PICR... (for what its worth):"
431 addSeqId(sequence, token);
432 queries.addElement(token.toUpperCase());
437 // System.out.println("Not querying source with token="+token+"\n");
438 addSeqId(sequence, token);
439 queries.addElement(token.toUpperCase());
447 // advance to next database
449 } // all databases have been queries.
450 if (sbuffer.length() > 0)
452 output.setText("Your sequences have been verified against known sequence databases. Some of the ids have been\n"
453 + "altered, most likely the start/end residue will have been updated.\n"
454 + "Save your alignment to maintain the updated id.\n\n"
455 + sbuffer.toString());
456 Desktop.addInternalFrame(output, "Sequence names updated ", 600, 300);
457 // The above is the dataset, we must now find out the index
458 // of the viewed sequence
462 af.setProgressBar("DBRef search completed", startTime);
463 // promptBeforeBlast();
470 * Verify local sequences in seqRefs against the retrieved sequence database
474 void transferReferences(Vector sdataset, String dbSource,
475 AlignmentI retrievedAl) // File
478 if (retrievedAl == null || retrievedAl.getHeight() == 0)
482 SequenceI[] retrieved = recoverDbSequences(retrievedAl
483 .getSequencesArray());
484 SequenceI sequence = null;
485 boolean transferred = false;
486 StringBuffer messages = new StringBuffer();
488 // Vector entries = new Uniprot().getUniprotEntries(file);
490 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
491 // UniprotEntry entry;
492 for (i = 0; i < iSize; i++)
494 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
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[]
503 if (entryRefs == null)
506 .println("Dud dbSource string ? no entryrefs selected for "
507 + dbSource + " on " + entry.getName());
510 for (int j = 0; j < entryRefs.length; j++)
512 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
513 // match up on accessionId
514 if (seqRefs.containsKey(accessionId.toUpperCase()))
516 Vector seqs = (Vector) seqRefs.get(accessionId);
517 for (int jj = 0; jj < seqs.size(); jj++)
519 sequence = (SequenceI) seqs.elementAt(jj);
520 if (!sequenceMatches.contains(sequence))
522 sequenceMatches.addElement(sequence);
527 if (sequenceMatches.size() == 0)
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())
534 Vector sqs = (Vector) seqRefs.get(e.nextElement());
535 if (sqs != null && sqs.size() > 0)
537 Enumeration sqe = sqs.elements();
538 while (sqe.hasMoreElements())
540 sequenceMatches.addElement(sqe.nextElement());
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.
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); } } } }
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++)
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
573 String nonGapped = AlignSeq.extractGaps("-. ",
574 sequence.getSequenceAsString()).toUpperCase();
576 int absStart = entrySeq.indexOf(nonGapped);
577 int mapStart = entry.getStart();
578 jalview.datamodel.Mapping mp;
582 // Is local sequence contained in dataset sequence?
583 absStart = nonGapped.indexOf(entrySeq);
585 { // verification failed.
586 messages.append(sequence.getName()
587 + " SEQUENCE NOT %100 MATCH \n");
591 sbuffer.append(sequence.getName() + " HAS " + absStart
592 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
594 // + " - ANY SEQUENCE FEATURES"
595 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
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 },
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
611 // update start and end of local sequence to place it in entry's
613 // apply identity map map from whole of local sequence to matching
614 // region of database
616 mp = null; // Mapping.getIdentityMap();
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
624 if (sequence.getSequenceFeatures() != null)
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
632 for (int sfi = 0; sfi < sf.length; sfi++)
634 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
636 // shift feature along by absstart
637 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
638 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
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();
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++)
659 if (alseqs[alsq].getDatasetSequence() == sequence)
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())
669 alseqs[alsq].setEnd(ngAlsq.length()
670 + alseqs[alsq].getStart() - 1);
674 // TODO: search for all other references to this dataset sequence, and
676 // TODO: update all AlCodonMappings which involve this alignment
677 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
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 ?
689 // report the ID/sequence mismatches
690 sbuffer.append(messages);
695 * loop thru and collect additional sequences in Map.
697 * @param sequencesArray
700 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
702 Vector nseq = new Vector();
703 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
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++)
710 if ((map = dbr[r].getMap()) != null)
712 if (map.getTo() != null && !nseq.contains(map.getTo()))
714 nseq.addElement(map.getTo());
721 sequencesArray = new SequenceI[nseq.size()];
722 nseq.toArray(sequencesArray);
724 return sequencesArray;