2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3 * Copyright (C) 2014 The Jalview Authors
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/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
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.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("Your sequences have been verified against known sequence databases. Some of the ids have been\n"
454 + "altered, most likely the start/end residue will have been updated.\n"
455 + "Save your alignment to maintain the updated id.\n\n"
456 + sbuffer.toString());
457 Desktop.addInternalFrame(output, "Sequence names updated ", 600, 300);
458 // The above is the dataset, we must now find out the index
459 // of the viewed sequence
463 af.setProgressBar("DBRef search completed", startTime);
464 // promptBeforeBlast();
471 * Verify local sequences in seqRefs against the retrieved sequence database
475 void transferReferences(Vector sdataset, String dbSource,
476 AlignmentI retrievedAl) // File
479 if (retrievedAl == null || retrievedAl.getHeight() == 0)
483 SequenceI[] retrieved = recoverDbSequences(retrievedAl
484 .getSequencesArray());
485 SequenceI sequence = null;
486 boolean transferred = false;
487 StringBuffer messages = new StringBuffer();
489 // Vector entries = new Uniprot().getUniprotEntries(file);
491 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
492 // UniprotEntry entry;
493 for (i = 0; i < iSize; i++)
495 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
497 // Work out which sequences this sequence matches,
498 // taking into account all accessionIds and names in the file
499 Vector sequenceMatches = new Vector();
500 // look for corresponding accession ids
501 DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
502 entry.getDBRef(), new String[]
504 if (entryRefs == null)
507 .println("Dud dbSource string ? no entryrefs selected for "
508 + dbSource + " on " + entry.getName());
511 for (int j = 0; j < entryRefs.length; j++)
513 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
514 // match up on accessionId
515 if (seqRefs.containsKey(accessionId.toUpperCase()))
517 Vector seqs = (Vector) seqRefs.get(accessionId);
518 for (int jj = 0; jj < seqs.size(); jj++)
520 sequence = (SequenceI) seqs.elementAt(jj);
521 if (!sequenceMatches.contains(sequence))
523 sequenceMatches.addElement(sequence);
528 if (sequenceMatches.size() == 0)
530 // failed to match directly on accessionId==query so just compare all
531 // sequences to entry
532 Enumeration e = seqRefs.keys();
533 while (e.hasMoreElements())
535 Vector sqs = (Vector) seqRefs.get(e.nextElement());
536 if (sqs != null && sqs.size() > 0)
538 Enumeration sqe = sqs.elements();
539 while (sqe.hasMoreElements())
541 sequenceMatches.addElement(sqe.nextElement());
546 // look for corresponding names
547 // this is uniprot specific ?
548 // could be useful to extend this so we try to find any 'significant'
549 // information in common between two sequence objects.
551 * DBRefEntry[] entryRefs =
552 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
553 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
554 * name = entry.getName().elementAt(j).toString(); if
555 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
556 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
557 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
558 * sequenceMatches.addElement(sequence); } } } }
560 // sequenceMatches now contains the set of all sequences associated with
561 // the returned db record
562 String entrySeq = entry.getSequenceAsString().toUpperCase();
563 for (int m = 0; m < sequenceMatches.size(); m++)
565 sequence = (SequenceI) sequenceMatches.elementAt(m);
566 // only update start and end positions and shift features if there are
567 // no existing references
568 // TODO: test for legacy where uniprot or EMBL refs exist but no
569 // mappings are made (but content matches retrieved set)
570 boolean updateRefFrame = sequence.getDBRef() == null
571 || sequence.getDBRef().length == 0;
572 // verify sequence against the entry sequence
574 String nonGapped = AlignSeq.extractGaps("-. ",
575 sequence.getSequenceAsString()).toUpperCase();
577 int absStart = entrySeq.indexOf(nonGapped);
578 int mapStart = entry.getStart();
579 jalview.datamodel.Mapping mp;
583 // Is local sequence contained in dataset sequence?
584 absStart = nonGapped.indexOf(entrySeq);
586 { // verification failed.
587 messages.append(sequence.getName()
588 + " SEQUENCE NOT %100 MATCH \n");
592 sbuffer.append(sequence.getName() + " HAS " + absStart
593 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
595 // + " - ANY SEQUENCE FEATURES"
596 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
598 // create valid mapping between matching region of local sequence and
599 // the mapped sequence
600 mp = new Mapping(null, new int[]
601 { sequence.getStart() + absStart,
602 sequence.getStart() + absStart + entrySeq.length() - 1 },
605 entry.getStart() + entrySeq.length() - 1 }, 1, 1);
606 updateRefFrame = false; // mapping is based on current start/end so
607 // don't modify start and end
612 // update start and end of local sequence to place it in entry's
614 // apply identity map map from whole of local sequence to matching
615 // region of database
617 mp = null; // Mapping.getIdentityMap();
619 // new int[] { absStart+sequence.getStart(),
620 // absStart+sequence.getStart()+entrySeq.length()-1},
621 // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
622 // relocate local features for updated start
625 if (sequence.getSequenceFeatures() != null)
627 SequenceFeature[] sf = sequence.getSequenceFeatures();
628 int start = sequence.getStart();
629 int end = sequence.getEnd();
630 int startShift = 1 - absStart - start; // how much the features
633 for (int sfi = 0; sfi < sf.length; sfi++)
635 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
637 // shift feature along by absstart
638 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
639 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
646 System.out.println("Adding dbrefs to " + sequence.getName()
647 + " from " + dbSource + " sequence : " + entry.getName());
648 sequence.transferAnnotation(entry, mp);
649 // unknownSequences.remove(sequence);
650 int absEnd = absStart + nonGapped.length();
654 // finally, update local sequence reference frame if we're allowed
655 sequence.setStart(absStart);
656 sequence.setEnd(absEnd);
657 // search for alignment sequences to update coordinate frame for
658 for (int alsq = 0; alsq < alseqs.length; alsq++)
660 if (alseqs[alsq].getDatasetSequence() == sequence)
662 String ngAlsq = AlignSeq.extractGaps("-. ",
663 alseqs[alsq].getSequenceAsString()).toUpperCase();
664 int oldstrt = alseqs[alsq].getStart();
665 alseqs[alsq].setStart(sequence.getSequenceAsString()
666 .toUpperCase().indexOf(ngAlsq)
667 + sequence.getStart());
668 if (oldstrt != alseqs[alsq].getStart())
670 alseqs[alsq].setEnd(ngAlsq.length()
671 + alseqs[alsq].getStart() - 1);
675 // TODO: search for all other references to this dataset sequence, and
677 // TODO: update all AlCodonMappings which involve this alignment
678 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
681 // and remove it from the rest
682 // TODO: decide if we should remove annotated sequence from set
683 sdataset.remove(sequence);
684 // TODO: should we make a note of sequences that have received new DB
685 // ids, so we can query all enabled DAS servers for them ?
690 // report the ID/sequence mismatches
691 sbuffer.append(messages);
696 * loop thru and collect additional sequences in Map.
698 * @param sequencesArray
701 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
703 Vector nseq = new Vector();
704 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
706 nseq.addElement(sequencesArray[i]);
707 DBRefEntry dbr[] = sequencesArray[i].getDBRef();
708 jalview.datamodel.Mapping map = null;
709 for (int r = 0; (dbr != null) && r < dbr.length; r++)
711 if ((map = dbr[r].getMap()) != null)
713 if (map.getTo() != null && !nseq.contains(map.getTo()))
715 nseq.addElement(map.getTo());
722 sequencesArray = new SequenceI[nseq.size()];
723 nseq.toArray(sequencesArray);
725 return sequencesArray;