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.lang.reflect.Array;
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();
140 selsources.addAll(sp);
143 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
146 // select appropriate databases based on alignFrame context.
147 if (af.getViewport().getAlignment().isNucleotide())
149 defdb = DBRefSource.DNACODINGDBS;
153 defdb = DBRefSource.PROTEINDBS;
155 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
156 for (String ddb : defdb)
158 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
159 if (srcesfordb != null)
161 srces.addAll(srcesfordb);
165 // append the selected sequence sources to the default dbs
166 srces.addAll(selsources);
167 dbSources = srces.toArray(new DbSourceProxy[0]);
171 // we assume the caller knows what they're doing and ensured that all the
172 // db source names are valid
178 * retrieve all the das sequence sources and add them to the list of db
179 * sources to retrieve from
181 public void appendAllDasSources()
183 if (dbSources == null)
185 dbSources = new DbSourceProxy[0];
187 // append additional sources
188 DbSourceProxy[] otherdb = sfetcher
189 .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
190 if (otherdb != null && otherdb.length > 0)
192 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
194 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
195 System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
201 * start the fetcher thread
203 * @param waitTillFinished
204 * true to block until the fetcher has finished
206 public void fetchDBRefs(boolean waitTillFinished)
208 Thread thread = new Thread(this);
212 if (waitTillFinished)
219 } catch (Exception ex)
227 * The sequence will be added to a vector of sequences belonging to key which
228 * could be either seq name or dbref id
235 void addSeqId(SequenceI seq, String key)
237 key = key.toUpperCase();
240 if (seqRefs.containsKey(key))
242 seqs = (Vector) seqRefs.get(key);
244 if (seqs != null && !seqs.contains(seq))
246 seqs.addElement(seq);
248 else if (seqs == null)
251 seqs.addElement(seq);
258 seqs.addElement(seq);
261 seqRefs.put(key, seqs);
269 if (dbSources == null)
271 throw new Error("Implementation error. Must initialise dbSources");
274 long startTime = System.currentTimeMillis();
275 af.setProgressBar("Fetching db refs", startTime);
278 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
280 picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
281 .getAccessionMapperPort();
283 } catch (Exception e)
285 System.err.println("Couldn't locate PICR service instance.\n");
289 Vector sdataset = new Vector();
290 for (int s = 0; s < dataset.length; s++)
292 sdataset.addElement(dataset[s]);
294 while (sdataset.size() > 0 && db < dbSources.length)
296 int maxqlen = 1; // default number of queries made to at one time
297 System.err.println("Verifying against " + dbSources[db].getDbName());
300 // iterate through db for each remaining un-verified sequence
301 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
302 sdataset.copyInto(currSeqs);// seqs that are to be validated against
304 Vector queries = new Vector(); // generated queries curSeq
305 seqRefs = new Hashtable();
309 jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
311 // for moment, we dumbly iterate over all retrieval sources for a
312 // particular database
313 // TODO: introduce multithread multisource queries and logic to remove a
314 // query from other sources if any source for a database returns a
316 if (dbsource.getDbSourceProperties().containsKey(
317 DBRefSource.MULTIACC))
319 maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
320 DBRefSource.MULTIACC)).intValue();
326 while (queries.size() > 0 || seqIndex < currSeqs.length)
328 if (queries.size() > 0)
330 // Still queries to make for current seqIndex
331 StringBuffer queryString = new StringBuffer("");
332 int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
335 while (queries.size() > 0 && numq < nqSize)
337 String query = (String) queries.elementAt(0);
338 if (dbsource.isValidReference(query))
340 queryString.append((numq == 0) ? "" : dbsource
341 .getAccessionSeparator());
342 queryString.append(query);
345 // remove the extracted query string
346 queries.removeElementAt(0);
348 // make the queries and process the response
349 AlignmentI retrieved = null;
352 if (jalview.bin.Cache.log.isDebugEnabled())
354 jalview.bin.Cache.log.debug("Querying "
355 + dbsource.getDbName() + " with : '"
356 + queryString.toString() + "'");
358 retrieved = dbsource.getSequenceRecords(queryString
360 } catch (Exception ex)
362 ex.printStackTrace();
363 } catch (OutOfMemoryError err)
365 new OOMWarning("retrieving database references ("
366 + queryString.toString() + ")", err);
368 if (retrieved != null)
370 transferReferences(sdataset, dbsource.getDbSource(),
376 // make some more strings for use as queries
377 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
379 SequenceI sequence = dataset[seqIndex];
380 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
381 sequence.getDBRef(), new String[]
382 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
384 // check for existing dbrefs to use
385 if (uprefs != null && uprefs.length > 0)
387 for (int j = 0; j < uprefs.length; j++)
389 addSeqId(sequence, uprefs[j].getAccessionId());
390 queries.addElement(uprefs[j].getAccessionId()
396 // generate queries from sequence ID string
397 StringTokenizer st = new StringTokenizer(
398 sequence.getName(), "|");
399 while (st.hasMoreTokens())
401 String token = st.nextToken();
402 UPEntry[] presp = null;
403 if (picrClient != null)
405 // resolve the string against PICR to recover valid IDs
408 presp = picrClient.getUPIForAccession(token, null,
409 picrClient.getMappedDatabaseNames(), null,
411 } catch (Exception e)
413 System.err.println("Exception with Picr for '"
418 if (presp != null && presp.length > 0)
420 for (int id = 0; id < presp.length; id++)
422 // construct sequences from response if sequences are
423 // present, and do a transferReferences
424 // otherwise transfer non sequence x-references directly.
427 .println("Validated ID against PICR... (for what its worth):"
429 addSeqId(sequence, token);
430 queries.addElement(token.toUpperCase());
435 // System.out.println("Not querying source with token="+token+"\n");
436 addSeqId(sequence, token);
437 queries.addElement(token.toUpperCase());
445 // advance to next database
447 } // all databases have been queries.
448 if (sbuffer.length() > 0)
450 output.setText("Your sequences have been verified against known sequence databases. Some of the ids have been\n"
451 + "altered, most likely the start/end residue will have been updated.\n"
452 + "Save your alignment to maintain the updated id.\n\n"
453 + sbuffer.toString());
454 Desktop.addInternalFrame(output, "Sequence names updated ", 600, 300);
455 // The above is the dataset, we must now find out the index
456 // of the viewed sequence
460 af.setProgressBar("DBRef search completed", startTime);
461 // promptBeforeBlast();
468 * Verify local sequences in seqRefs against the retrieved sequence database
472 void transferReferences(Vector sdataset, String dbSource,
473 AlignmentI retrievedAl) // File
476 if (retrievedAl == null || retrievedAl.getHeight() == 0)
480 SequenceI[] retrieved = recoverDbSequences(retrievedAl
481 .getSequencesArray());
482 SequenceI sequence = null;
483 boolean transferred = false;
484 StringBuffer messages = new StringBuffer();
486 // Vector entries = new Uniprot().getUniprotEntries(file);
488 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
489 // UniprotEntry entry;
490 for (i = 0; i < iSize; i++)
492 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
494 // Work out which sequences this sequence matches,
495 // taking into account all accessionIds and names in the file
496 Vector sequenceMatches = new Vector();
497 // look for corresponding accession ids
498 DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
499 entry.getDBRef(), new String[]
501 if (entryRefs == null)
504 .println("Dud dbSource string ? no entryrefs selected for "
505 + dbSource + " on " + entry.getName());
508 for (int j = 0; j < entryRefs.length; j++)
510 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
511 // match up on accessionId
512 if (seqRefs.containsKey(accessionId.toUpperCase()))
514 Vector seqs = (Vector) seqRefs.get(accessionId);
515 for (int jj = 0; jj < seqs.size(); jj++)
517 sequence = (SequenceI) seqs.elementAt(jj);
518 if (!sequenceMatches.contains(sequence))
520 sequenceMatches.addElement(sequence);
525 if (sequenceMatches.size() == 0)
527 // failed to match directly on accessionId==query so just compare all
528 // sequences to entry
529 Enumeration e = seqRefs.keys();
530 while (e.hasMoreElements())
532 Vector sqs = (Vector) seqRefs.get(e.nextElement());
533 if (sqs != null && sqs.size() > 0)
535 Enumeration sqe = sqs.elements();
536 while (sqe.hasMoreElements())
538 sequenceMatches.addElement(sqe.nextElement());
543 // look for corresponding names
544 // this is uniprot specific ?
545 // could be useful to extend this so we try to find any 'significant'
546 // information in common between two sequence objects.
548 * DBRefEntry[] entryRefs =
549 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
550 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
551 * name = entry.getName().elementAt(j).toString(); if
552 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
553 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
554 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
555 * sequenceMatches.addElement(sequence); } } } }
557 // sequenceMatches now contains the set of all sequences associated with
558 // the returned db record
559 String entrySeq = entry.getSequenceAsString().toUpperCase();
560 for (int m = 0; m < sequenceMatches.size(); m++)
562 sequence = (SequenceI) sequenceMatches.elementAt(m);
563 // only update start and end positions and shift features if there are
564 // no existing references
565 // TODO: test for legacy where uniprot or EMBL refs exist but no
566 // mappings are made (but content matches retrieved set)
567 boolean updateRefFrame = sequence.getDBRef() == null
568 || sequence.getDBRef().length == 0;
569 // verify sequence against the entry sequence
571 String nonGapped = AlignSeq.extractGaps("-. ",
572 sequence.getSequenceAsString()).toUpperCase();
574 int absStart = entrySeq.indexOf(nonGapped);
575 int mapStart = entry.getStart();
576 jalview.datamodel.Mapping mp;
580 // Is local sequence contained in dataset sequence?
581 absStart = nonGapped.indexOf(entrySeq);
583 { // verification failed.
584 messages.append(sequence.getName()
585 + " SEQUENCE NOT %100 MATCH \n");
589 sbuffer.append(sequence.getName() + " HAS " + absStart
590 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
592 // + " - ANY SEQUENCE FEATURES"
593 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
595 // create valid mapping between matching region of local sequence and
596 // the mapped sequence
597 mp = new Mapping(null, new int[]
598 { sequence.getStart() + absStart,
599 sequence.getStart() + absStart + entrySeq.length() - 1 },
602 entry.getStart() + entrySeq.length() - 1 }, 1, 1);
603 updateRefFrame = false; // mapping is based on current start/end so
604 // don't modify start and end
609 // update start and end of local sequence to place it in entry's
611 // apply identity map map from whole of local sequence to matching
612 // region of database
614 mp = null; // Mapping.getIdentityMap();
616 // new int[] { absStart+sequence.getStart(),
617 // absStart+sequence.getStart()+entrySeq.length()-1},
618 // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
619 // relocate local features for updated start
622 if (sequence.getSequenceFeatures() != null)
624 SequenceFeature[] sf = sequence.getSequenceFeatures();
625 int start = sequence.getStart();
626 int end = sequence.getEnd();
627 int startShift = 1 - absStart - start; // how much the features
630 for (int sfi = 0; sfi < sf.length; sfi++)
632 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
634 // shift feature along by absstart
635 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
636 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
643 System.out.println("Adding dbrefs to " + sequence.getName()
644 + " from " + dbSource + " sequence : " + entry.getName());
645 sequence.transferAnnotation(entry, mp);
646 // unknownSequences.remove(sequence);
647 int absEnd = absStart + nonGapped.length();
651 // finally, update local sequence reference frame if we're allowed
652 sequence.setStart(absStart);
653 sequence.setEnd(absEnd);
654 // search for alignment sequences to update coordinate frame for
655 for (int alsq = 0; alsq < alseqs.length; alsq++)
657 if (alseqs[alsq].getDatasetSequence() == sequence)
659 String ngAlsq = AlignSeq.extractGaps("-. ",
660 alseqs[alsq].getSequenceAsString()).toUpperCase();
661 int oldstrt = alseqs[alsq].getStart();
662 alseqs[alsq].setStart(sequence.getSequenceAsString()
663 .toUpperCase().indexOf(ngAlsq)
664 + sequence.getStart());
665 if (oldstrt != alseqs[alsq].getStart())
667 alseqs[alsq].setEnd(ngAlsq.length()
668 + alseqs[alsq].getStart() - 1);
672 // TODO: search for all other references to this dataset sequence, and
674 // TODO: update all AlCodonMappings which involve this alignment
675 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
678 // and remove it from the rest
679 // TODO: decide if we should remove annotated sequence from set
680 sdataset.remove(sequence);
681 // TODO: should we make a note of sequences that have received new DB
682 // ids, so we can query all enabled DAS servers for them ?
687 // report the ID/sequence mismatches
688 sbuffer.append(messages);
693 * loop thru and collect additional sequences in Map.
695 * @param sequencesArray
698 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
700 Vector nseq = new Vector();
701 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
703 nseq.addElement(sequencesArray[i]);
704 DBRefEntry dbr[] = sequencesArray[i].getDBRef();
705 jalview.datamodel.Mapping map = null;
706 for (int r = 0; (dbr != null) && r < dbr.length; r++)
708 if ((map = dbr[r].getMap()) != null)
710 if (map.getTo() != null && !nseq.contains(map.getTo()))
712 nseq.addElement(map.getTo());
719 sequencesArray = new SequenceI[nseq.size()];
720 nseq.toArray(sequencesArray);
722 return sequencesArray;