2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
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
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 alignment sequence
86 private boolean trimDsSeqs=true;
93 * Creates a new SequenceFeatureFetcher object and fetches from the currently
94 * selected set of databases.
97 * fetch references for these sequences
99 * the parent alignframe for progress bar monitoring.
101 public DBRefFetcher(SequenceI[] seqs, AlignFrame af)
103 this(seqs, af, null);
107 * Creates a new SequenceFeatureFetcher object and fetches from the currently
108 * selected set of databases.
111 * fetch references for these sequences
113 * the parent alignframe for progress bar monitoring.
115 * array of database source strings to query references from
117 public DBRefFetcher(SequenceI[] seqs, AlignFrame af,
118 DbSourceProxy[] sources)
121 alseqs = new SequenceI[seqs.length];
122 SequenceI[] ds = new SequenceI[seqs.length];
123 for (int i = 0; i < seqs.length; i++)
126 if (seqs[i].getDatasetSequence() != null)
127 ds[i] = seqs[i].getDatasetSequence();
132 // TODO Jalview 2.5 lots of this code should be in the gui package!
133 sfetcher = jalview.gui.SequenceFetcher.getSequenceFetcherSingleton(af);
134 // set default behaviour for transferring excess sequence data to the dataset
135 trimDsSeqs = Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true);
138 // af.featureSettings_actionPerformed(null);
139 String[] defdb = null, otherdb = sfetcher
140 .getDbInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
141 List<DbSourceProxy> selsources = new ArrayList<DbSourceProxy>();
142 Vector dasselsrc = (af.featureSettings != null) ? af.featureSettings
143 .getSelectedSources() : new jalview.gui.DasSourceBrowser()
144 .getSelectedSources();
145 Enumeration<jalviewSourceI> en = dasselsrc.elements();
146 while (en.hasMoreElements())
148 jalviewSourceI src = en.nextElement();
149 List<DbSourceProxy> sp = src.getSequenceSourceProxies();
152 selsources.addAll(sp);
155 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
159 // select appropriate databases based on alignFrame context.
160 if (af.getViewport().getAlignment().isNucleotide())
162 defdb = DBRefSource.DNACODINGDBS;
166 defdb = DBRefSource.PROTEINDBS;
168 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
169 for (String ddb : defdb)
171 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
172 if (srcesfordb != null)
174 srces.addAll(srcesfordb);
178 // append the selected sequence sources to the default dbs
179 srces.addAll(selsources);
180 dbSources = srces.toArray(new DbSourceProxy[0]);
184 // we assume the caller knows what they're doing and ensured that all the
185 // db source names are valid
191 * retrieve all the das sequence sources and add them to the list of db
192 * sources to retrieve from
194 public void appendAllDasSources()
196 if (dbSources == null)
198 dbSources = new DbSourceProxy[0];
200 // append additional sources
201 DbSourceProxy[] otherdb = sfetcher
202 .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
203 if (otherdb != null && otherdb.length > 0)
205 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
207 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
208 System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
214 * start the fetcher thread
216 * @param waitTillFinished
217 * true to block until the fetcher has finished
219 public void fetchDBRefs(boolean waitTillFinished)
221 Thread thread = new Thread(this);
225 if (waitTillFinished)
232 } catch (Exception ex)
240 * The sequence will be added to a vector of sequences belonging to key which
241 * could be either seq name or dbref id
248 void addSeqId(SequenceI seq, String key)
250 key = key.toUpperCase();
253 if (seqRefs.containsKey(key))
255 seqs = (Vector) seqRefs.get(key);
257 if (seqs != null && !seqs.contains(seq))
259 seqs.addElement(seq);
261 else if (seqs == null)
264 seqs.addElement(seq);
271 seqs.addElement(seq);
274 seqRefs.put(key, seqs);
282 if (dbSources == null)
284 throw new Error("Implementation error. Must initialise dbSources");
287 long startTime = System.currentTimeMillis();
288 af.setProgressBar("Fetching db refs", startTime);
291 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
293 picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
294 .getAccessionMapperPort();
296 } catch (Exception e)
298 System.err.println("Couldn't locate PICR service instance.\n");
302 Vector sdataset = new Vector();
303 for (int s = 0; s < dataset.length; s++)
305 sdataset.addElement(dataset[s]);
307 while (sdataset.size() > 0 && db < dbSources.length)
309 int maxqlen = 1; // default number of queries made to at one time
310 System.err.println("Verifying against " + dbSources[db].getDbName());
313 // iterate through db for each remaining un-verified sequence
314 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
315 sdataset.copyInto(currSeqs);// seqs that are to be validated against
317 Vector queries = new Vector(); // generated queries curSeq
318 seqRefs = new Hashtable();
322 jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
324 // for moment, we dumbly iterate over all retrieval sources for a
325 // particular database
326 // TODO: introduce multithread multisource queries and logic to remove a
327 // query from other sources if any source for a database returns a
329 if (dbsource.getDbSourceProperties().containsKey(
330 DBRefSource.MULTIACC))
332 maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
333 DBRefSource.MULTIACC)).intValue();
339 while (queries.size() > 0 || seqIndex < currSeqs.length)
341 if (queries.size() > 0)
343 // Still queries to make for current seqIndex
344 StringBuffer queryString = new StringBuffer("");
345 int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
348 while (queries.size() > 0 && numq < nqSize)
350 String query = (String) queries.elementAt(0);
351 if (dbsource.isValidReference(query))
353 queryString.append((numq == 0) ? "" : dbsource
354 .getAccessionSeparator());
355 queryString.append(query);
358 // remove the extracted query string
359 queries.removeElementAt(0);
361 // make the queries and process the response
362 AlignmentI retrieved = null;
365 if (jalview.bin.Cache.log.isDebugEnabled())
367 jalview.bin.Cache.log.debug("Querying "
368 + dbsource.getDbName() + " with : '"
369 + queryString.toString() + "'");
371 retrieved = dbsource.getSequenceRecords(queryString
373 } catch (Exception ex)
375 ex.printStackTrace();
376 } catch (OutOfMemoryError err)
378 new OOMWarning("retrieving database references ("
379 + queryString.toString() + ")", err);
381 if (retrieved != null)
383 transferReferences(sdataset, dbsource.getDbSource(),
384 retrieved,trimDsSeqs);
389 // make some more strings for use as queries
390 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
392 SequenceI sequence = dataset[seqIndex];
393 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
394 sequence.getDBRef(), new String[]
395 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
397 // check for existing dbrefs to use
398 if (uprefs != null && uprefs.length > 0)
400 for (int j = 0; j < uprefs.length; j++)
402 addSeqId(sequence, uprefs[j].getAccessionId());
403 queries.addElement(uprefs[j].getAccessionId()
409 // generate queries from sequence ID string
410 StringTokenizer st = new StringTokenizer(
411 sequence.getName(), "|");
412 while (st.hasMoreTokens())
414 String token = st.nextToken();
415 UPEntry[] presp = null;
416 if (picrClient != null)
418 // resolve the string against PICR to recover valid IDs
421 presp = picrClient.getUPIForAccession(token, null,
422 picrClient.getMappedDatabaseNames(), null,
424 } catch (Exception e)
426 System.err.println("Exception with Picr for '"
431 if (presp != null && presp.length > 0)
433 for (int id = 0; id < presp.length; id++)
435 // construct sequences from response if sequences are
436 // present, and do a transferReferences
437 // otherwise transfer non sequence x-references directly.
440 .println("Validated ID against PICR... (for what its worth):"
442 addSeqId(sequence, token);
443 queries.addElement(token.toUpperCase());
448 // System.out.println("Not querying source with token="+token+"\n");
449 addSeqId(sequence, token);
450 queries.addElement(token.toUpperCase());
458 // advance to next database
460 } // all databases have been queries.
461 if (sbuffer.length() > 0)
463 output.setText(MessageManager.getString("label.your_sequences_have_been_verified")
464 + sbuffer.toString());
465 Desktop.addInternalFrame(output, MessageManager.getString("label.sequence_names_updated"), 600, 300);
466 // The above is the dataset, we must now find out the index
467 // of the viewed sequence
471 af.setProgressBar(MessageManager.getString("label.dbref_search_completed"), startTime);
472 // promptBeforeBlast();
479 * Verify local sequences in seqRefs against the retrieved sequence database
481 * @param trimDatasetSeqs
484 void transferReferences(Vector sdataset, String dbSource,
485 AlignmentI retrievedAl, boolean trimDatasetSeqs) // File
488 System.out.println("trimming ? "+trimDatasetSeqs);
489 if (retrievedAl == null || retrievedAl.getHeight() == 0)
493 SequenceI[] retrieved = recoverDbSequences(retrievedAl
494 .getSequencesArray());
495 SequenceI sequence = null;
496 boolean transferred = false;
497 StringBuffer messages = new StringBuffer();
499 // Vector entries = new Uniprot().getUniprotEntries(file);
501 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
502 // UniprotEntry entry;
503 for (i = 0; i < iSize; i++)
505 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
507 // Work out which sequences this sequence matches,
508 // taking into account all accessionIds and names in the file
509 Vector sequenceMatches = new Vector();
510 // look for corresponding accession ids
511 DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
512 entry.getDBRef(), new String[]
514 if (entryRefs == null)
517 .println("Dud dbSource string ? no entryrefs selected for "
518 + dbSource + " on " + entry.getName());
521 for (int j = 0; j < entryRefs.length; j++)
523 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
524 // match up on accessionId
525 if (seqRefs.containsKey(accessionId.toUpperCase()))
527 Vector seqs = (Vector) seqRefs.get(accessionId);
528 for (int jj = 0; jj < seqs.size(); jj++)
530 sequence = (SequenceI) seqs.elementAt(jj);
531 if (!sequenceMatches.contains(sequence))
533 sequenceMatches.addElement(sequence);
538 if (sequenceMatches.size() == 0)
540 // failed to match directly on accessionId==query so just compare all
541 // sequences to entry
542 Enumeration e = seqRefs.keys();
543 while (e.hasMoreElements())
545 Vector sqs = (Vector) seqRefs.get(e.nextElement());
546 if (sqs != null && sqs.size() > 0)
548 Enumeration sqe = sqs.elements();
549 while (sqe.hasMoreElements())
551 sequenceMatches.addElement(sqe.nextElement());
556 // look for corresponding names
557 // this is uniprot specific ?
558 // could be useful to extend this so we try to find any 'significant'
559 // information in common between two sequence objects.
561 * DBRefEntry[] entryRefs =
562 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
563 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
564 * name = entry.getName().elementAt(j).toString(); if
565 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
566 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
567 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
568 * sequenceMatches.addElement(sequence); } } } }
570 // sequenceMatches now contains the set of all sequences associated with
571 // the returned db record
572 String entrySeq = entry.getSequenceAsString().toUpperCase();
573 for (int m = 0; m < sequenceMatches.size(); m++)
575 sequence = (SequenceI) sequenceMatches.elementAt(m);
576 // only update start and end positions and shift features if there are
577 // no existing references
578 // TODO: test for legacy where uniprot or EMBL refs exist but no
579 // mappings are made (but content matches retrieved set)
580 boolean updateRefFrame = sequence.getDBRef() == null
581 || sequence.getDBRef().length == 0;
583 // verify sequence against the entry sequence
585 String nonGapped = AlignSeq.extractGaps("-. ",
586 sequence.getSequenceAsString()).toUpperCase();
588 int absStart = entrySeq.indexOf(nonGapped);
589 int mapStart = entry.getStart();
590 jalview.datamodel.Mapping mp;
594 // Is local sequence contained in dataset sequence?
595 absStart = nonGapped.indexOf(entrySeq);
597 { // verification failed.
598 messages.append(sequence.getName()
599 + " SEQUENCE NOT %100 MATCH \n");
603 sbuffer.append(sequence.getName() + " HAS " + absStart
604 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
606 // + " - ANY SEQUENCE FEATURES"
607 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
609 // create valid mapping between matching region of local sequence and
610 // the mapped sequence
611 mp = new Mapping(null, new int[]
612 { sequence.getStart() + absStart,
613 sequence.getStart() + absStart + entrySeq.length() - 1 },
616 entry.getStart() + entrySeq.length() - 1 }, 1, 1);
617 updateRefFrame = false; // mapping is based on current start/end so
618 // don't modify start and end
623 // update start and end of local sequence to place it in entry's
625 // apply identity map map from whole of local sequence to matching
626 // region of database
628 mp = null; // Mapping.getIdentityMap();
630 // new int[] { absStart+sequence.getStart(),
631 // absStart+sequence.getStart()+entrySeq.length()-1},
632 // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
633 // relocate local features for updated start
636 if (sequence.getSequenceFeatures() != null)
638 SequenceFeature[] sf = sequence.getSequenceFeatures();
639 int start = sequence.getStart();
640 int end = sequence.getEnd();
641 int startShift = 1 - absStart - start; // how much the features
644 for (int sfi = 0; sfi < sf.length; sfi++)
646 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
648 // shift feature along by absstart
649 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
650 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
657 System.out.println("Adding dbrefs to " + sequence.getName()
658 + " from " + dbSource + " sequence : " + entry.getName());
659 sequence.transferAnnotation(entry, mp);
660 // unknownSequences.remove(sequence);
661 int absEnd = absStart + nonGapped.length();
663 if (!trimDatasetSeqs) {
664 // insert full length sequence from record
665 sequence.setSequence(entry.getSequenceAsString());
666 sequence.setStart(entry.getStart());
670 // finally, update local sequence reference frame if we're allowed
671 if (trimDatasetSeqs) {
672 // just fix start/end
673 sequence.setStart(absStart);
674 sequence.setEnd(absEnd);
676 // search for alignment sequences to update coordinate frame for
677 for (int alsq = 0; alsq < alseqs.length; alsq++)
679 if (alseqs[alsq].getDatasetSequence() == sequence)
681 String ngAlsq = AlignSeq.extractGaps("-. ",
682 alseqs[alsq].getSequenceAsString()).toUpperCase();
683 int oldstrt = alseqs[alsq].getStart();
684 alseqs[alsq].setStart(sequence.getSequenceAsString()
685 .toUpperCase().indexOf(ngAlsq)
686 + sequence.getStart());
687 if (oldstrt != alseqs[alsq].getStart())
689 alseqs[alsq].setEnd(ngAlsq.length()
690 + alseqs[alsq].getStart() - 1);
694 // TODO: search for all other references to this dataset sequence, and
696 // TODO: update all AlCodonMappings which involve this alignment
697 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
700 // and remove it from the rest
701 // TODO: decide if we should remove annotated sequence from set
702 sdataset.remove(sequence);
703 // TODO: should we make a note of sequences that have received new DB
704 // ids, so we can query all enabled DAS servers for them ?
709 // report the ID/sequence mismatches
710 sbuffer.append(messages);
715 * loop thru and collect additional sequences in Map.
717 * @param sequencesArray
720 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
722 Vector nseq = new Vector();
723 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
725 nseq.addElement(sequencesArray[i]);
726 DBRefEntry dbr[] = sequencesArray[i].getDBRef();
727 jalview.datamodel.Mapping map = null;
728 for (int r = 0; (dbr != null) && r < dbr.length; r++)
730 if ((map = dbr[r].getMap()) != null)
732 if (map.getTo() != null && !nseq.contains(map.getTo()))
734 nseq.addElement(map.getTo());
741 sequencesArray = new SequenceI[nseq.size()];
742 nseq.toArray(sequencesArray);
744 return sequencesArray;