2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.AlignSeq;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.DBRefSource;
28 import jalview.datamodel.Mapping;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.gui.AlignFrame;
32 import jalview.gui.CutAndPasteTransfer;
33 import jalview.gui.Desktop;
34 import jalview.gui.IProgressIndicator;
35 import jalview.gui.OOMWarning;
36 import jalview.util.MessageManager;
37 import jalview.ws.dbsources.das.api.jalviewSourceI;
38 import jalview.ws.seqfetcher.DbSourceProxy;
40 import java.util.ArrayList;
41 import java.util.Enumeration;
42 import java.util.Hashtable;
43 import java.util.List;
44 import java.util.StringTokenizer;
45 import java.util.Vector;
47 import uk.ac.ebi.picr.model.UPEntry;
50 * Implements a runnable for validating a sequence against external databases
51 * and then propagating references and features onto the sequence(s)
56 public class DBRefFetcher implements Runnable
60 IProgressIndicator af;
62 CutAndPasteTransfer output = new CutAndPasteTransfer();
64 StringBuffer sbuffer = new StringBuffer();
66 boolean running = false;
69 * picr client instance
71 uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
73 // /This will be a collection of Vectors of sequenceI refs.
74 // The key will be the seq name or accession id of the seq
77 DbSourceProxy[] dbSources;
79 SequenceFetcher sfetcher;
81 private SequenceI[] alseqs;
84 * when true - retrieved sequences will be trimmed to cover longest derived
87 private boolean trimDsSeqs = true;
94 * Creates a new SequenceFeatureFetcher object and fetches from the currently
95 * selected set of databases.
98 * fetch references for these sequences
100 * the parent alignframe for progress bar monitoring.
102 public DBRefFetcher(SequenceI[] seqs, AlignFrame af)
104 this(seqs, af, null);
108 * Creates a new SequenceFeatureFetcher object and fetches from the currently
109 * selected set of databases.
112 * fetch references for these sequences
114 * the parent alignframe for progress bar monitoring.
116 * array of database source strings to query references from
118 public DBRefFetcher(SequenceI[] seqs, AlignFrame af,
119 DbSourceProxy[] sources)
122 alseqs = new SequenceI[seqs.length];
123 SequenceI[] ds = new SequenceI[seqs.length];
124 for (int i = 0; i < seqs.length; i++)
127 if (seqs[i].getDatasetSequence() != null)
128 ds[i] = seqs[i].getDatasetSequence();
133 // TODO Jalview 2.5 lots of this code should be in the gui package!
134 sfetcher = jalview.gui.SequenceFetcher.getSequenceFetcherSingleton(af);
135 // set default behaviour for transferring excess sequence data to the
137 trimDsSeqs = Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true);
140 // af.featureSettings_actionPerformed(null);
141 String[] defdb = null, otherdb = sfetcher
142 .getDbInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
143 List<DbSourceProxy> selsources = new ArrayList<DbSourceProxy>();
144 Vector dasselsrc = (af.featureSettings != null) ? af.featureSettings
145 .getSelectedSources() : new jalview.gui.DasSourceBrowser()
146 .getSelectedSources();
147 Enumeration<jalviewSourceI> en = dasselsrc.elements();
148 while (en.hasMoreElements())
150 jalviewSourceI src = en.nextElement();
151 List<DbSourceProxy> sp = src.getSequenceSourceProxies();
154 selsources.addAll(sp);
157 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
161 // select appropriate databases based on alignFrame context.
162 if (af.getViewport().getAlignment().isNucleotide())
164 defdb = DBRefSource.DNACODINGDBS;
168 defdb = DBRefSource.PROTEINDBS;
170 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
171 for (String ddb : defdb)
173 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
174 if (srcesfordb != null)
176 srces.addAll(srcesfordb);
180 // append the selected sequence sources to the default dbs
181 srces.addAll(selsources);
182 dbSources = srces.toArray(new DbSourceProxy[0]);
186 // we assume the caller knows what they're doing and ensured that all the
187 // db source names are valid
193 * retrieve all the das sequence sources and add them to the list of db
194 * sources to retrieve from
196 public void appendAllDasSources()
198 if (dbSources == null)
200 dbSources = new DbSourceProxy[0];
202 // append additional sources
203 DbSourceProxy[] otherdb = sfetcher
204 .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
205 if (otherdb != null && otherdb.length > 0)
207 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
209 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
210 System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
216 * start the fetcher thread
218 * @param waitTillFinished
219 * true to block until the fetcher has finished
221 public void fetchDBRefs(boolean waitTillFinished)
223 Thread thread = new Thread(this);
227 if (waitTillFinished)
234 } catch (Exception ex)
242 * The sequence will be added to a vector of sequences belonging to key which
243 * could be either seq name or dbref id
250 void addSeqId(SequenceI seq, String key)
252 key = key.toUpperCase();
255 if (seqRefs.containsKey(key))
257 seqs = (Vector) seqRefs.get(key);
259 if (seqs != null && !seqs.contains(seq))
261 seqs.addElement(seq);
263 else if (seqs == null)
266 seqs.addElement(seq);
273 seqs.addElement(seq);
276 seqRefs.put(key, seqs);
284 if (dbSources == null)
286 throw new Error(MessageManager.getString("error.implementation_error_must_init_dbsources"));
289 long startTime = System.currentTimeMillis();
290 af.setProgressBar(MessageManager.getString("status.fetching_db_refs"), startTime);
293 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
295 picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
296 .getAccessionMapperPort();
298 } catch (Exception e)
300 System.err.println("Couldn't locate PICR service instance.\n");
304 Vector sdataset = new Vector();
305 for (int s = 0; s < dataset.length; s++)
307 sdataset.addElement(dataset[s]);
309 while (sdataset.size() > 0 && db < dbSources.length)
311 int maxqlen = 1; // default number of queries made to at one time
312 System.err.println("Verifying against " + dbSources[db].getDbName());
315 // iterate through db for each remaining un-verified sequence
316 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
317 sdataset.copyInto(currSeqs);// seqs that are to be validated against
319 Vector queries = new Vector(); // generated queries curSeq
320 seqRefs = new Hashtable();
324 jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
326 // for moment, we dumbly iterate over all retrieval sources for a
327 // particular database
328 // TODO: introduce multithread multisource queries and logic to remove a
329 // query from other sources if any source for a database returns a
331 if (dbsource.getDbSourceProperties().containsKey(
332 DBRefSource.MULTIACC))
334 maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
335 DBRefSource.MULTIACC)).intValue();
341 while (queries.size() > 0 || seqIndex < currSeqs.length)
343 if (queries.size() > 0)
345 // Still queries to make for current seqIndex
346 StringBuffer queryString = new StringBuffer("");
347 int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
350 while (queries.size() > 0 && numq < nqSize)
352 String query = (String) queries.elementAt(0);
353 if (dbsource.isValidReference(query))
355 queryString.append((numq == 0) ? "" : dbsource
356 .getAccessionSeparator());
357 queryString.append(query);
360 // remove the extracted query string
361 queries.removeElementAt(0);
363 // make the queries and process the response
364 AlignmentI retrieved = null;
367 if (jalview.bin.Cache.log.isDebugEnabled())
369 jalview.bin.Cache.log.debug("Querying "
370 + dbsource.getDbName() + " with : '"
371 + queryString.toString() + "'");
373 retrieved = dbsource.getSequenceRecords(queryString
375 } catch (Exception ex)
377 ex.printStackTrace();
378 } catch (OutOfMemoryError err)
380 new OOMWarning("retrieving database references ("
381 + queryString.toString() + ")", err);
383 if (retrieved != null)
385 transferReferences(sdataset, dbsource.getDbSource(),
386 retrieved, trimDsSeqs);
391 // make some more strings for use as queries
392 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
394 SequenceI sequence = dataset[seqIndex];
395 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
396 sequence.getDBRef(), new String[]
397 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
399 // check for existing dbrefs to use
400 if (uprefs != null && uprefs.length > 0)
402 for (int j = 0; j < uprefs.length; j++)
404 addSeqId(sequence, uprefs[j].getAccessionId());
405 queries.addElement(uprefs[j].getAccessionId()
411 // generate queries from sequence ID string
412 StringTokenizer st = new StringTokenizer(
413 sequence.getName(), "|");
414 while (st.hasMoreTokens())
416 String token = st.nextToken();
417 UPEntry[] presp = null;
418 if (picrClient != null)
420 // resolve the string against PICR to recover valid IDs
423 presp = picrClient.getUPIForAccession(token, null,
424 picrClient.getMappedDatabaseNames(), null,
426 } catch (Exception e)
428 System.err.println("Exception with Picr for '"
433 if (presp != null && presp.length > 0)
435 for (int id = 0; id < presp.length; id++)
437 // construct sequences from response if sequences are
438 // present, and do a transferReferences
439 // otherwise transfer non sequence x-references directly.
442 .println("Validated ID against PICR... (for what its worth):"
444 addSeqId(sequence, token);
445 queries.addElement(token.toUpperCase());
450 // System.out.println("Not querying source with token="+token+"\n");
451 addSeqId(sequence, token);
452 queries.addElement(token.toUpperCase());
460 // advance to next database
462 } // all databases have been queries.
463 if (sbuffer.length() > 0)
465 output.setText(MessageManager
466 .getString("label.your_sequences_have_been_verified")
467 + sbuffer.toString());
468 Desktop.addInternalFrame(output,
469 MessageManager.getString("label.sequence_names_updated"),
471 // The above is the dataset, we must now find out the index
472 // of the viewed sequence
477 MessageManager.getString("label.dbref_search_completed"),
479 // promptBeforeBlast();
486 * Verify local sequences in seqRefs against the retrieved sequence database
489 * @param trimDatasetSeqs
492 void transferReferences(Vector sdataset, String dbSource,
493 AlignmentI retrievedAl, boolean trimDatasetSeqs) // File
496 System.out.println("trimming ? " + trimDatasetSeqs);
497 if (retrievedAl == null || retrievedAl.getHeight() == 0)
501 SequenceI[] retrieved = recoverDbSequences(retrievedAl
502 .getSequencesArray());
503 SequenceI sequence = null;
504 boolean transferred = false;
505 StringBuffer messages = new StringBuffer();
507 // Vector entries = new Uniprot().getUniprotEntries(file);
509 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
510 // UniprotEntry entry;
511 for (i = 0; i < iSize; i++)
513 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
515 // Work out which sequences this sequence matches,
516 // taking into account all accessionIds and names in the file
517 Vector sequenceMatches = new Vector();
518 // look for corresponding accession ids
519 DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
520 entry.getDBRef(), new String[]
522 if (entryRefs == null)
525 .println("Dud dbSource string ? no entryrefs selected for "
526 + dbSource + " on " + entry.getName());
529 for (int j = 0; j < entryRefs.length; j++)
531 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
532 // match up on accessionId
533 if (seqRefs.containsKey(accessionId.toUpperCase()))
535 Vector seqs = (Vector) seqRefs.get(accessionId);
536 for (int jj = 0; jj < seqs.size(); jj++)
538 sequence = (SequenceI) seqs.elementAt(jj);
539 if (!sequenceMatches.contains(sequence))
541 sequenceMatches.addElement(sequence);
546 if (sequenceMatches.size() == 0)
548 // failed to match directly on accessionId==query so just compare all
549 // sequences to entry
550 Enumeration e = seqRefs.keys();
551 while (e.hasMoreElements())
553 Vector sqs = (Vector) seqRefs.get(e.nextElement());
554 if (sqs != null && sqs.size() > 0)
556 Enumeration sqe = sqs.elements();
557 while (sqe.hasMoreElements())
559 sequenceMatches.addElement(sqe.nextElement());
564 // look for corresponding names
565 // this is uniprot specific ?
566 // could be useful to extend this so we try to find any 'significant'
567 // information in common between two sequence objects.
569 * DBRefEntry[] entryRefs =
570 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
571 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
572 * name = entry.getName().elementAt(j).toString(); if
573 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
574 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
575 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
576 * sequenceMatches.addElement(sequence); } } } }
578 // sequenceMatches now contains the set of all sequences associated with
579 // the returned db record
580 String entrySeq = entry.getSequenceAsString().toUpperCase();
581 for (int m = 0; m < sequenceMatches.size(); m++)
583 sequence = (SequenceI) sequenceMatches.elementAt(m);
584 // only update start and end positions and shift features if there are
585 // no existing references
586 // TODO: test for legacy where uniprot or EMBL refs exist but no
587 // mappings are made (but content matches retrieved set)
588 boolean updateRefFrame = sequence.getDBRef() == null
589 || sequence.getDBRef().length == 0;
591 // verify sequence against the entry sequence
593 String nonGapped = AlignSeq.extractGaps("-. ",
594 sequence.getSequenceAsString()).toUpperCase();
596 int absStart = entrySeq.indexOf(nonGapped);
597 int mapStart = entry.getStart();
598 jalview.datamodel.Mapping mp;
602 // Is local sequence contained in dataset sequence?
603 absStart = nonGapped.indexOf(entrySeq);
605 { // verification failed.
606 messages.append(sequence.getName()
607 + " SEQUENCE NOT %100 MATCH \n");
611 sbuffer.append(sequence.getName() + " HAS " + absStart
612 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
614 // + " - ANY SEQUENCE FEATURES"
615 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
617 // create valid mapping between matching region of local sequence and
618 // the mapped sequence
619 mp = new Mapping(null, new int[]
620 { sequence.getStart() + absStart,
621 sequence.getStart() + absStart + entrySeq.length() - 1 },
624 entry.getStart() + entrySeq.length() - 1 }, 1, 1);
625 updateRefFrame = false; // mapping is based on current start/end so
626 // don't modify start and end
631 // update start and end of local sequence to place it in entry's
633 // apply identity map map from whole of local sequence to matching
634 // region of database
636 mp = null; // Mapping.getIdentityMap();
638 // new int[] { absStart+sequence.getStart(),
639 // absStart+sequence.getStart()+entrySeq.length()-1},
640 // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
641 // relocate local features for updated start
644 if (sequence.getSequenceFeatures() != null)
646 SequenceFeature[] sf = sequence.getSequenceFeatures();
647 int start = sequence.getStart();
648 int end = sequence.getEnd();
649 int startShift = 1 - absStart - start; // how much the features
652 for (int sfi = 0; sfi < sf.length; sfi++)
654 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
656 // shift feature along by absstart
657 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
658 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
665 System.out.println("Adding dbrefs to " + sequence.getName()
666 + " from " + dbSource + " sequence : " + entry.getName());
667 sequence.transferAnnotation(entry, mp);
668 // unknownSequences.remove(sequence);
669 int absEnd = absStart + nonGapped.length();
671 if (!trimDatasetSeqs)
673 // insert full length sequence from record
674 sequence.setSequence(entry.getSequenceAsString());
675 sequence.setStart(entry.getStart());
679 // finally, update local sequence reference frame if we're allowed
682 // just fix start/end
683 sequence.setStart(absStart);
684 sequence.setEnd(absEnd);
686 // search for alignment sequences to update coordinate frame for
687 for (int alsq = 0; alsq < alseqs.length; alsq++)
689 if (alseqs[alsq].getDatasetSequence() == sequence)
691 String ngAlsq = AlignSeq.extractGaps("-. ",
692 alseqs[alsq].getSequenceAsString()).toUpperCase();
693 int oldstrt = alseqs[alsq].getStart();
694 alseqs[alsq].setStart(sequence.getSequenceAsString()
695 .toUpperCase().indexOf(ngAlsq)
696 + sequence.getStart());
697 if (oldstrt != alseqs[alsq].getStart())
699 alseqs[alsq].setEnd(ngAlsq.length()
700 + alseqs[alsq].getStart() - 1);
704 // TODO: search for all other references to this dataset sequence, and
706 // TODO: update all AlCodonMappings which involve this alignment
707 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
710 // and remove it from the rest
711 // TODO: decide if we should remove annotated sequence from set
712 sdataset.remove(sequence);
713 // TODO: should we make a note of sequences that have received new DB
714 // ids, so we can query all enabled DAS servers for them ?
719 // report the ID/sequence mismatches
720 sbuffer.append(messages);
725 * loop thru and collect additional sequences in Map.
727 * @param sequencesArray
730 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
732 Vector nseq = new Vector();
733 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
735 nseq.addElement(sequencesArray[i]);
736 DBRefEntry dbr[] = sequencesArray[i].getDBRef();
737 jalview.datamodel.Mapping map = null;
738 for (int r = 0; (dbr != null) && r < dbr.length; r++)
740 if ((map = dbr[r].getMap()) != null)
742 if (map.getTo() != null && !nseq.contains(map.getTo()))
744 nseq.addElement(map.getTo());
751 sequencesArray = new SequenceI[nseq.size()];
752 nseq.toArray(sequencesArray);
754 return sequencesArray;