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.CutAndPasteTransfer;
32 import jalview.gui.Desktop;
33 import jalview.gui.FeatureSettings;
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 progressWindow;
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 DBRefFetcher object and fetches from the currently selected
95 * set of databases, if this is null then it fetches based on feature settings
98 * fetch references for these SequenceI array
99 * @param progressIndicatorFrame
100 * the frame for progress bar monitoring
102 * array of DbSourceProxy to query references form
103 * @param featureSettings
104 * FeatureSettings to get alternative DbSourceProxy from
105 * @param isNucleotide
106 * indicates if the array of SequenceI are Nucleotides or not
108 public DBRefFetcher(SequenceI[] seqs,
109 IProgressIndicator progressIndicatorFrame,
110 DbSourceProxy[] sources, FeatureSettings featureSettings, boolean isNucleotide)
112 this.progressWindow = progressIndicatorFrame;
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)
120 ds[i] = seqs[i].getDatasetSequence();
128 // TODO Jalview 2.5 lots of this code should be in the gui package!
129 sfetcher = jalview.gui.SequenceFetcher
130 .getSequenceFetcherSingleton(progressIndicatorFrame);
131 // set default behaviour for transferring excess sequence data to the
133 trimDsSeqs = Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true);
136 // af.featureSettings_actionPerformed(null);
137 String[] defdb = null, otherdb = sfetcher
138 .getDbInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
139 List<DbSourceProxy> selsources = new ArrayList<DbSourceProxy>();
140 Vector dasselsrc = (featureSettings != null) ? featureSettings
141 .getSelectedSources() : new jalview.gui.DasSourceBrowser()
142 .getSelectedSources();
143 Enumeration<jalviewSourceI> en = dasselsrc.elements();
144 while (en.hasMoreElements())
146 jalviewSourceI src = en.nextElement();
147 List<DbSourceProxy> sp = src.getSequenceSourceProxies();
150 selsources.addAll(sp);
153 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
157 // select appropriate databases based on alignFrame context.
160 defdb = DBRefSource.DNACODINGDBS;
164 defdb = DBRefSource.PROTEINDBS;
166 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
167 for (String ddb : defdb)
169 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
170 if (srcesfordb != null)
172 srces.addAll(srcesfordb);
176 // append the selected sequence sources to the default dbs
177 srces.addAll(selsources);
178 dbSources = srces.toArray(new DbSourceProxy[0]);
182 // we assume the caller knows what they're doing and ensured that all the
183 // db source names are valid
189 * retrieve all the das sequence sources and add them to the list of db
190 * sources to retrieve from
192 public void appendAllDasSources()
194 if (dbSources == null)
196 dbSources = new DbSourceProxy[0];
198 // append additional sources
199 DbSourceProxy[] otherdb = sfetcher
200 .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
201 if (otherdb != null && otherdb.length > 0)
203 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
205 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
206 System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
212 * start the fetcher thread
214 * @param waitTillFinished
215 * true to block until the fetcher has finished
217 public void fetchDBRefs(boolean waitTillFinished)
219 Thread thread = new Thread(this);
223 if (waitTillFinished)
230 } catch (Exception ex)
238 * The sequence will be added to a vector of sequences belonging to key which
239 * could be either seq name or dbref id
246 void addSeqId(SequenceI seq, String key)
248 key = key.toUpperCase();
251 if (seqRefs.containsKey(key))
253 seqs = (Vector) seqRefs.get(key);
255 if (seqs != null && !seqs.contains(seq))
257 seqs.addElement(seq);
259 else if (seqs == null)
262 seqs.addElement(seq);
269 seqs.addElement(seq);
272 seqRefs.put(key, seqs);
281 if (dbSources == null)
285 .getString("error.implementation_error_must_init_dbsources"));
288 long startTime = System.currentTimeMillis();
289 if (progressWindow != null)
291 progressWindow.setProgressBar(
292 MessageManager.getString("status.fetching_db_refs"),
297 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
299 picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
300 .getAccessionMapperPort();
302 } catch (Exception e)
304 System.err.println("Couldn't locate PICR service instance.\n");
308 Vector sdataset = new Vector();
309 for (int s = 0; s < dataset.length; s++)
311 sdataset.addElement(dataset[s]);
313 while (sdataset.size() > 0 && db < dbSources.length)
315 int maxqlen = 1; // default number of queries made to at one time
316 System.err.println("Verifying against " + dbSources[db].getDbName());
319 // iterate through db for each remaining un-verified sequence
320 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
321 sdataset.copyInto(currSeqs);// seqs that are to be validated against
323 Vector queries = new Vector(); // generated queries curSeq
324 seqRefs = new Hashtable();
328 jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
330 // for moment, we dumbly iterate over all retrieval sources for a
331 // particular database
332 // TODO: introduce multithread multisource queries and logic to remove a
333 // query from other sources if any source for a database returns a
335 if (dbsource.getDbSourceProperties().containsKey(
336 DBRefSource.MULTIACC))
338 maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
339 DBRefSource.MULTIACC)).intValue();
345 while (queries.size() > 0 || seqIndex < currSeqs.length)
347 if (queries.size() > 0)
349 // Still queries to make for current seqIndex
350 StringBuffer queryString = new StringBuffer("");
351 int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
354 while (queries.size() > 0 && numq < nqSize)
356 String query = (String) queries.elementAt(0);
357 if (dbsource.isValidReference(query))
359 queryString.append((numq == 0) ? "" : dbsource
360 .getAccessionSeparator());
361 queryString.append(query);
364 // remove the extracted query string
365 queries.removeElementAt(0);
367 // make the queries and process the response
368 AlignmentI retrieved = null;
371 if (jalview.bin.Cache.log.isDebugEnabled())
373 jalview.bin.Cache.log.debug("Querying "
374 + dbsource.getDbName() + " with : '"
375 + queryString.toString() + "'");
377 retrieved = dbsource.getSequenceRecords(queryString
379 } catch (Exception ex)
381 ex.printStackTrace();
382 } catch (OutOfMemoryError err)
384 new OOMWarning("retrieving database references ("
385 + queryString.toString() + ")", err);
387 if (retrieved != null)
389 transferReferences(sdataset, dbsource.getDbSource(),
390 retrieved, trimDsSeqs);
395 // make some more strings for use as queries
396 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
398 SequenceI sequence = dataset[seqIndex];
399 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
400 sequence.getDBRefs(),
401 new String[] { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
403 // check for existing dbrefs to use
404 if (uprefs != null && uprefs.length > 0)
406 for (int j = 0; j < uprefs.length; j++)
408 addSeqId(sequence, uprefs[j].getAccessionId());
409 queries.addElement(uprefs[j].getAccessionId()
415 // generate queries from sequence ID string
416 StringTokenizer st = new StringTokenizer(
417 sequence.getName(), "|");
418 while (st.hasMoreTokens())
420 String token = st.nextToken();
421 UPEntry[] presp = null;
422 if (picrClient != null)
424 // resolve the string against PICR to recover valid IDs
427 presp = picrClient.getUPIForAccession(token, null,
428 picrClient.getMappedDatabaseNames(), null,
430 } catch (Exception e)
432 System.err.println("Exception with Picr for '"
437 if (presp != null && presp.length > 0)
439 for (int id = 0; id < presp.length; id++)
441 // construct sequences from response if sequences are
442 // present, and do a transferReferences
443 // otherwise transfer non sequence x-references directly.
446 .println("Validated ID against PICR... (for what its worth):"
448 addSeqId(sequence, token);
449 queries.addElement(token.toUpperCase());
454 // System.out.println("Not querying source with token="+token+"\n");
455 addSeqId(sequence, token);
456 queries.addElement(token.toUpperCase());
464 // advance to next database
466 } // all databases have been queries.
467 if (sbuffer.length() > 0)
469 output.setText(MessageManager
470 .getString("label.your_sequences_have_been_verified")
471 + sbuffer.toString());
472 Desktop.addInternalFrame(output,
473 MessageManager.getString("label.sequence_names_updated"),
475 // The above is the dataset, we must now find out the index
476 // of the viewed sequence
479 if (progressWindow != null)
481 progressWindow.setProgressBar(
482 MessageManager.getString("label.dbref_search_completed"),
484 // promptBeforeBlast();
493 * Verify local sequences in seqRefs against the retrieved sequence database
496 * @param trimDatasetSeqs
499 void transferReferences(Vector sdataset, String dbSource,
500 AlignmentI retrievedAl, boolean trimDatasetSeqs) // File
503 System.out.println("trimming ? " + trimDatasetSeqs);
504 if (retrievedAl == null || retrievedAl.getHeight() == 0)
508 SequenceI[] retrieved = recoverDbSequences(retrievedAl
509 .getSequencesArray());
510 SequenceI sequence = null;
511 boolean transferred = false;
512 StringBuffer messages = new StringBuffer();
514 // Vector entries = new Uniprot().getUniprotEntries(file);
516 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
517 // UniprotEntry entry;
518 for (i = 0; i < iSize; i++)
520 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
522 // Work out which sequences this sequence matches,
523 // taking into account all accessionIds and names in the file
524 Vector sequenceMatches = new Vector();
525 // look for corresponding accession ids
526 DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
527 entry.getDBRefs(), new String[] { dbSource });
528 if (entryRefs == null)
531 .println("Dud dbSource string ? no entryrefs selected for "
532 + dbSource + " on " + entry.getName());
535 for (int j = 0; j < entryRefs.length; j++)
537 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
538 // match up on accessionId
539 if (seqRefs.containsKey(accessionId.toUpperCase()))
541 Vector seqs = (Vector) seqRefs.get(accessionId);
542 for (int jj = 0; jj < seqs.size(); jj++)
544 sequence = (SequenceI) seqs.elementAt(jj);
545 if (!sequenceMatches.contains(sequence))
547 sequenceMatches.addElement(sequence);
552 if (sequenceMatches.size() == 0)
554 // failed to match directly on accessionId==query so just compare all
555 // sequences to entry
556 Enumeration e = seqRefs.keys();
557 while (e.hasMoreElements())
559 Vector sqs = (Vector) seqRefs.get(e.nextElement());
560 if (sqs != null && sqs.size() > 0)
562 Enumeration sqe = sqs.elements();
563 while (sqe.hasMoreElements())
565 sequenceMatches.addElement(sqe.nextElement());
570 // look for corresponding names
571 // this is uniprot specific ?
572 // could be useful to extend this so we try to find any 'significant'
573 // information in common between two sequence objects.
575 * DBRefEntry[] entryRefs =
576 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
577 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
578 * name = entry.getName().elementAt(j).toString(); if
579 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
580 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
581 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
582 * sequenceMatches.addElement(sequence); } } } }
584 // sequenceMatches now contains the set of all sequences associated with
585 // the returned db record
586 String entrySeq = entry.getSequenceAsString().toUpperCase();
587 for (int m = 0; m < sequenceMatches.size(); m++)
589 sequence = (SequenceI) sequenceMatches.elementAt(m);
590 // only update start and end positions and shift features if there are
591 // no existing references
592 // TODO: test for legacy where uniprot or EMBL refs exist but no
593 // mappings are made (but content matches retrieved set)
594 boolean updateRefFrame = sequence.getDBRefs() == null
595 || sequence.getDBRefs().length == 0;
597 // verify sequence against the entry sequence
599 String nonGapped = AlignSeq.extractGaps("-. ",
600 sequence.getSequenceAsString()).toUpperCase();
602 int absStart = entrySeq.indexOf(nonGapped);
605 final int sequenceStart = sequence.getStart();
608 // Is local sequence contained in dataset sequence?
609 absStart = nonGapped.indexOf(entrySeq);
611 { // verification failed.
612 messages.append(sequence.getName()
613 + " SEQUENCE NOT %100 MATCH \n");
617 sbuffer.append(sequence.getName() + " HAS " + absStart
618 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
620 // + " - ANY SEQUENCE FEATURES"
621 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
623 // create valid mapping between matching region of local sequence and
624 // the mapped sequence
625 mp = new Mapping(null, new int[] { sequenceStart + absStart,
626 sequenceStart + absStart + entrySeq.length() - 1 }, new int[]
627 { entry.getStart(), entry.getStart() + entrySeq.length() - 1 },
629 updateRefFrame = false; // mapping is based on current start/end so
630 // don't modify start and end
635 // update start and end of local sequence to place it in entry's
637 // apply identity map map from whole of local sequence to matching
638 // region of database
640 mp = null; // Mapping.getIdentityMap();
642 // new int[] { absStart+sequence.getStart(),
643 // absStart+sequence.getStart()+entrySeq.length()-1},
644 // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
645 // relocate local features for updated start
648 if (sequence.getSequenceFeatures() != null)
650 SequenceFeature[] sf = sequence.getSequenceFeatures();
651 int start = sequenceStart;
652 int end = sequence.getEnd();
653 int startShift = 1 - absStart - start; // how much the features
656 for (int sfi = 0; sfi < sf.length; sfi++)
658 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
660 // shift feature along by absstart
661 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
662 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
669 System.out.println("Adding dbrefs to " + sequence.getName()
670 + " from " + dbSource + " sequence : " + entry.getName());
671 sequence.transferAnnotation(entry, mp);
672 // unknownSequences.remove(sequence);
673 absStart += entry.getStart();
674 int absEnd = absStart + nonGapped.length() - 1;
675 if (!trimDatasetSeqs)
677 // insert full length sequence from record
678 sequence.setSequence(entry.getSequenceAsString());
679 sequence.setStart(entry.getStart());
683 // finally, update local sequence reference frame if we're allowed
686 // just fix start/end
687 sequence.setStart(absStart);
688 sequence.setEnd(absEnd);
690 // search for alignment sequences to update coordinate frame for
691 for (int alsq = 0; alsq < alseqs.length; alsq++)
693 if (alseqs[alsq].getDatasetSequence() == sequence)
695 String ngAlsq = AlignSeq.extractGaps("-. ",
696 alseqs[alsq].getSequenceAsString()).toUpperCase();
697 int oldstrt = alseqs[alsq].getStart();
698 alseqs[alsq].setStart(sequence.getSequenceAsString()
699 .toUpperCase().indexOf(ngAlsq)
700 + sequence.getStart());
701 if (oldstrt != alseqs[alsq].getStart())
703 alseqs[alsq].setEnd(ngAlsq.length()
704 + alseqs[alsq].getStart() - 1);
708 // TODO: search for all other references to this dataset sequence, and
710 // TODO: update all AlCodonMappings which involve this alignment
711 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
714 // and remove it from the rest
715 // TODO: decide if we should remove annotated sequence from set
716 sdataset.remove(sequence);
717 // TODO: should we make a note of sequences that have received new DB
718 // ids, so we can query all enabled DAS servers for them ?
723 // report the ID/sequence mismatches
724 sbuffer.append(messages);
729 * loop thru and collect additional sequences in Map.
731 * @param sequencesArray
734 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
736 Vector nseq = new Vector();
737 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
739 nseq.addElement(sequencesArray[i]);
740 DBRefEntry dbr[] = sequencesArray[i].getDBRefs();
741 jalview.datamodel.Mapping map = null;
742 for (int r = 0; (dbr != null) && r < dbr.length; r++)
744 if ((map = dbr[r].getMap()) != null)
746 if (map.getTo() != null && !nseq.contains(map.getTo()))
748 nseq.addElement(map.getTo());
755 sequencesArray = new SequenceI[nseq.size()];
756 nseq.toArray(sequencesArray);
758 return sequencesArray;