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.DasSourceBrowser;
33 import jalview.gui.Desktop;
34 import jalview.gui.FeatureSettings;
35 import jalview.gui.IProgressIndicator;
36 import jalview.gui.OOMWarning;
37 import jalview.util.DBRefUtils;
38 import jalview.util.MessageManager;
39 import jalview.ws.dbsources.das.api.jalviewSourceI;
40 import jalview.ws.dbsources.das.datamodel.DasSequenceSource;
41 import jalview.ws.seqfetcher.DbSourceProxy;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Enumeration;
46 import java.util.Hashtable;
47 import java.util.List;
48 import java.util.StringTokenizer;
49 import java.util.Vector;
51 import uk.ac.ebi.picr.model.UPEntry;
52 import uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator;
55 * Implements a runnable for validating a sequence against external databases
56 * and then propagating references and features onto the sequence(s)
61 public class DBRefFetcher implements Runnable
63 private static final String NEWLINE = System.lineSeparator();
65 public interface FetchFinishedListenerI
72 IProgressIndicator progressWindow;
74 CutAndPasteTransfer output = new CutAndPasteTransfer();
76 boolean running = false;
79 * picr client instance
81 uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
83 // This will be a collection of Vectors of sequenceI refs.
84 // The key will be the seq name or accession id of the seq
85 Hashtable<String, Vector<SequenceI>> seqRefs;
87 DbSourceProxy[] dbSources;
89 SequenceFetcher sfetcher;
91 private List<FetchFinishedListenerI> listeners;
93 private SequenceI[] alseqs;
96 * when true - retrieved sequences will be trimmed to cover longest derived
99 private boolean trimDsSeqs = true;
102 * Creates a new DBRefFetcher object and fetches from the currently selected
103 * set of databases, if this is null then it fetches based on feature settings
106 * fetch references for these SequenceI array
107 * @param progressIndicatorFrame
108 * the frame for progress bar monitoring
110 * array of DbSourceProxy to query references form
111 * @param featureSettings
112 * FeatureSettings to get alternative DbSourceProxy from
113 * @param isNucleotide
114 * indicates if the array of SequenceI are Nucleotides or not
116 public DBRefFetcher(SequenceI[] seqs,
117 IProgressIndicator progressIndicatorFrame,
118 DbSourceProxy[] sources, FeatureSettings featureSettings,
119 boolean isNucleotide)
121 listeners = new ArrayList<FetchFinishedListenerI>();
122 this.progressWindow = progressIndicatorFrame;
123 alseqs = new SequenceI[seqs.length];
124 SequenceI[] ds = new SequenceI[seqs.length];
125 for (int i = 0; i < seqs.length; i++)
128 if (seqs[i].getDatasetSequence() != null)
130 ds[i] = seqs[i].getDatasetSequence();
138 // TODO Jalview 2.5 lots of this code should be in the gui package!
139 sfetcher = jalview.gui.SequenceFetcher
140 .getSequenceFetcherSingleton(progressIndicatorFrame);
141 // set default behaviour for transferring excess sequence data to the
143 trimDsSeqs = Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true);
146 setDatabaseSources(featureSettings, isNucleotide);
150 // we assume the caller knows what they're doing and ensured that all the
151 // db source names are valid
157 * Helper method to configure the list of database sources to query
159 * @param featureSettings
160 * @param forNucleotide
162 void setDatabaseSources(FeatureSettings featureSettings,
163 boolean forNucleotide)
165 // af.featureSettings_actionPerformed(null);
166 String[] defdb = null;
167 List<DbSourceProxy> selsources = new ArrayList<DbSourceProxy>();
168 Vector<jalviewSourceI> dasselsrc = (featureSettings != null) ? featureSettings
169 .getSelectedSources() : new DasSourceBrowser()
170 .getSelectedSources();
172 for (jalviewSourceI src : dasselsrc)
174 List<DbSourceProxy> sp = src.getSequenceSourceProxies();
177 selsources.addAll(sp);
180 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
184 // select appropriate databases based on alignFrame context.
187 defdb = DBRefSource.DNACODINGDBS;
191 defdb = DBRefSource.PROTEINDBS;
193 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
194 for (String ddb : defdb)
196 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
197 if (srcesfordb != null)
199 for (DbSourceProxy src : srcesfordb)
201 if (!srces.contains(src))
203 srces.addAll(srcesfordb);
208 // append the PDB data source, since it is 'special', catering for both
209 // nucleotide and protein
210 // srces.addAll(sfetcher.getSourceProxy(DBRefSource.PDB));
212 srces.addAll(selsources);
213 dbSources = srces.toArray(new DbSourceProxy[srces.size()]);
217 * Constructor with only sequences provided
221 public DBRefFetcher(SequenceI[] sequences)
223 this(sequences, null, null, null, false);
227 * Add a listener to be notified when sequence fetching is complete
231 public void addListener(FetchFinishedListenerI l)
237 * retrieve all the das sequence sources and add them to the list of db
238 * sources to retrieve from
240 public void appendAllDasSources()
242 if (dbSources == null)
244 dbSources = new DbSourceProxy[0];
246 // append additional sources
247 DbSourceProxy[] otherdb = sfetcher
248 .getDbSourceProxyInstances(DasSequenceSource.class);
249 if (otherdb != null && otherdb.length > 0)
251 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
253 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
254 System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
260 * start the fetcher thread
262 * @param waitTillFinished
263 * true to block until the fetcher has finished
265 public void fetchDBRefs(boolean waitTillFinished)
267 // TODO can we not simply write
268 // if (waitTillFinished) { run(); } else { new Thread(this).start(); }
270 Thread thread = new Thread(this);
274 if (waitTillFinished)
281 } catch (Exception ex)
289 * The sequence will be added to a vector of sequences belonging to key which
290 * could be either seq name or dbref id
297 void addSeqId(SequenceI seq, String key)
299 key = key.toUpperCase();
301 Vector<SequenceI> seqs;
302 if (seqRefs.containsKey(key))
304 seqs = seqRefs.get(key);
306 if (seqs != null && !seqs.contains(seq))
308 seqs.addElement(seq);
310 else if (seqs == null)
312 seqs = new Vector<SequenceI>();
313 seqs.addElement(seq);
319 seqs = new Vector<SequenceI>();
320 seqs.addElement(seq);
323 seqRefs.put(key, seqs);
332 if (dbSources == null)
336 .getString("error.implementation_error_must_init_dbsources"));
339 long startTime = System.currentTimeMillis();
340 if (progressWindow != null)
342 progressWindow.setProgressBar(
343 MessageManager.getString("status.fetching_db_refs"),
348 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
350 picrClient = new AccessionMapperServiceLocator()
351 .getAccessionMapperPort();
353 } catch (Exception e)
355 System.err.println("Couldn't locate PICR service instance.\n");
359 Vector<SequenceI> sdataset = new Vector<SequenceI>(
360 Arrays.asList(dataset));
361 List<String> warningMessages = new ArrayList<String>();
364 while (sdataset.size() > 0 && db < dbSources.length)
366 int maxqlen = 1; // default number of queries made at one time
367 System.out.println("Verifying against " + dbSources[db].getDbName());
369 // iterate through db for each remaining un-verified sequence
370 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
371 sdataset.copyInto(currSeqs);// seqs that are to be validated against
373 Vector<String> queries = new Vector<String>(); // generated queries curSeq
374 seqRefs = new Hashtable<String, Vector<SequenceI>>();
378 DbSourceProxy dbsource = dbSources[db];
379 // for moment, we dumbly iterate over all retrieval sources for a
380 // particular database
381 // TODO: introduce multithread multisource queries and logic to remove a
382 // query from other sources if any source for a database returns a
384 maxqlen = dbsource.getMaximumQueryCount();
386 while (queries.size() > 0 || seqIndex < currSeqs.length)
388 if (queries.size() > 0)
390 // Still queries to make for current seqIndex
391 StringBuffer queryString = new StringBuffer("");
393 int nqSize = (maxqlen > queries.size()) ? queries.size()
396 while (queries.size() > 0 && numq < nqSize)
398 String query = queries.elementAt(0);
399 if (dbsource.isValidReference(query))
401 queryString.append((numq == 0) ? "" : dbsource
402 .getAccessionSeparator());
403 queryString.append(query);
406 // remove the extracted query string
407 queries.removeElementAt(0);
409 // make the queries and process the response
410 AlignmentI retrieved = null;
413 if (Cache.log.isDebugEnabled())
415 Cache.log.debug("Querying " + dbsource.getDbName()
416 + " with : '" + queryString.toString() + "'");
418 retrieved = dbsource.getSequenceRecords(queryString.toString());
419 } catch (Exception ex)
421 ex.printStackTrace();
422 } catch (OutOfMemoryError err)
424 new OOMWarning("retrieving database references ("
425 + queryString.toString() + ")", err);
427 if (retrieved != null)
429 transferReferences(sdataset, dbsource.getDbSource(), retrieved,
430 trimDsSeqs, warningMessages);
435 // make some more strings for use as queries
436 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
438 SequenceI sequence = dataset[seqIndex];
439 DBRefEntry[] uprefs = DBRefUtils.selectRefs(
440 sequence.getDBRefs(),
441 new String[] { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
443 // check for existing dbrefs to use
444 if (uprefs != null && uprefs.length > 0)
446 for (int j = 0; j < uprefs.length; j++)
448 addSeqId(sequence, uprefs[j].getAccessionId());
449 queries.addElement(uprefs[j].getAccessionId().toUpperCase());
454 // generate queries from sequence ID string
455 StringTokenizer st = new StringTokenizer(sequence.getName(),
457 while (st.hasMoreTokens())
459 String token = st.nextToken();
460 UPEntry[] presp = null;
461 if (picrClient != null)
463 // resolve the string against PICR to recover valid IDs
467 .getUPIForAccession(token, null,
468 picrClient.getMappedDatabaseNames(),
470 } catch (Exception e)
472 System.err.println("Exception with Picr for '" + token
477 if (presp != null && presp.length > 0)
479 for (int id = 0; id < presp.length; id++)
481 // construct sequences from response if sequences are
482 // present, and do a transferReferences
483 // otherwise transfer non sequence x-references directly.
486 .println("Validated ID against PICR... (for what its worth):"
488 addSeqId(sequence, token);
489 queries.addElement(token.toUpperCase());
494 // System.out.println("Not querying source with token="+token+"\n");
495 addSeqId(sequence, token);
496 queries.addElement(token.toUpperCase());
503 // advance to next database
505 } // all databases have been queried
506 if (!warningMessages.isEmpty())
508 StringBuilder sb = new StringBuilder(warningMessages.size() * 30);
509 sb.append(MessageManager
510 .getString("label.your_sequences_have_been_verified"));
511 for (String msg : warningMessages)
513 sb.append(msg).append(NEWLINE);
515 output.setText(sb.toString());
517 Desktop.addInternalFrame(output,
518 MessageManager.getString("label.sequences_updated"), 600, 300);
519 // The above is the dataset, we must now find out the index
520 // of the viewed sequence
523 if (progressWindow != null)
525 progressWindow.setProgressBar(
526 MessageManager.getString("label.dbref_search_completed"),
530 for (FetchFinishedListenerI listener : listeners)
538 * Verify local sequences in seqRefs against the retrieved sequence database
539 * records. Returns true if any sequence was modified as a result (start/end
540 * changed and/or sequence enlarged), else false.
543 * dataset sequences we are retrieving for
545 * database source we are retrieving from
547 * retrieved sequences as alignment
548 * @param trimDatasetSeqs
549 * if true, sequences will not be enlarged to match longer retrieved
550 * sequences, only their start/end adjusted
551 * @param warningMessages
552 * a list of messages to add to
554 boolean transferReferences(Vector<SequenceI> sdataset, String dbSource,
555 AlignmentI retrievedAl, boolean trimDatasetSeqs,
556 List<String> warningMessages)
558 // System.out.println("trimming ? " + trimDatasetSeqs);
559 if (retrievedAl == null || retrievedAl.getHeight() == 0)
564 boolean modified = false;
565 SequenceI[] retrieved = recoverDbSequences(retrievedAl
566 .getSequencesArray());
567 SequenceI sequence = null;
569 for (SequenceI retrievedSeq : retrieved)
571 // Work out which sequences this sequence matches,
572 // taking into account all accessionIds and names in the file
573 Vector<SequenceI> sequenceMatches = new Vector<SequenceI>();
574 // look for corresponding accession ids
575 DBRefEntry[] entryRefs = DBRefUtils.selectRefs(
576 retrievedSeq.getDBRefs(), new String[] { dbSource });
577 if (entryRefs == null)
580 .println("Dud dbSource string ? no entryrefs selected for "
581 + dbSource + " on " + retrievedSeq.getName());
584 for (int j = 0; j < entryRefs.length; j++)
586 String accessionId = entryRefs[j].getAccessionId();
587 // match up on accessionId
588 if (seqRefs.containsKey(accessionId.toUpperCase()))
590 Vector<SequenceI> seqs = seqRefs.get(accessionId);
591 for (int jj = 0; jj < seqs.size(); jj++)
593 sequence = seqs.elementAt(jj);
594 if (!sequenceMatches.contains(sequence))
596 sequenceMatches.addElement(sequence);
601 if (sequenceMatches.isEmpty())
603 // failed to match directly on accessionId==query so just compare all
604 // sequences to entry
605 Enumeration<String> e = seqRefs.keys();
606 while (e.hasMoreElements())
608 Vector<SequenceI> sqs = seqRefs.get(e.nextElement());
609 if (sqs != null && sqs.size() > 0)
611 Enumeration<SequenceI> sqe = sqs.elements();
612 while (sqe.hasMoreElements())
614 sequenceMatches.addElement(sqe.nextElement());
619 // look for corresponding names
620 // this is uniprot specific ?
621 // could be useful to extend this so we try to find any 'significant'
622 // information in common between two sequence objects.
624 * DBRefEntry[] entryRefs =
625 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
626 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
627 * name = entry.getName().elementAt(j).toString(); if
628 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
629 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
630 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
631 * sequenceMatches.addElement(sequence); } } } }
633 // sequenceMatches now contains the set of all sequences associated with
634 // the returned db record
635 final String retrievedSeqString = retrievedSeq.getSequenceAsString();
636 String entrySeq = retrievedSeqString.toUpperCase();
637 for (int m = 0; m < sequenceMatches.size(); m++)
639 sequence = sequenceMatches.elementAt(m);
640 // only update start and end positions and shift features if there are
641 // no existing references
642 // TODO: test for legacy where uniprot or EMBL refs exist but no
643 // mappings are made (but content matches retrieved set)
644 boolean updateRefFrame = sequence.getDBRefs() == null
645 || sequence.getDBRefs().length == 0;
647 // verify sequence against the entry sequence
650 final int sequenceStart = sequence.getStart();
652 boolean remoteEnclosesLocal = false;
653 String nonGapped = AlignSeq.extractGaps("-. ",
654 sequence.getSequenceAsString()).toUpperCase();
655 int absStart = entrySeq.indexOf(nonGapped);
658 // couldn't find local sequence in sequence from database, so check if
659 // the database sequence is a subsequence of local sequence
660 absStart = nonGapped.indexOf(entrySeq);
663 // verification failed. couldn't find any relationship between
664 // entrySeq and local sequence
665 // messages suppressed as many-to-many matches are confusing
666 // String msg = sequence.getName()
667 // + " Sequence not 100% match with "
668 // + retrievedSeq.getName();
669 // addWarningMessage(warningMessages, msg);
673 * retrieved sequence is a proper subsequence of local sequence
675 String msg = sequence.getName() + " has " + absStart
676 + " prefixed residues compared to "
677 + retrievedSeq.getName();
678 addWarningMessage(warningMessages, msg);
681 * So create a mapping to the external entry from the matching region of
682 * the local sequence, and leave local start/end untouched.
684 mp = new Mapping(null, new int[] { sequenceStart + absStart,
685 sequenceStart + absStart + entrySeq.length() - 1 }, new int[]
686 { retrievedSeq.getStart(),
687 retrievedSeq.getStart() + entrySeq.length() - 1 }, 1, 1);
688 updateRefFrame = false;
693 * local sequence is a subsequence of (or matches) retrieved sequence
695 remoteEnclosesLocal = true;
700 SequenceFeature[] sfs = sequence.getSequenceFeatures();
704 * relocate existing sequence features by offset
706 int start = sequenceStart;
707 int end = sequence.getEnd();
708 int startShift = 1 - absStart - start;
712 for (SequenceFeature sf : sfs)
714 if (sf.getBegin() >= start && sf.getEnd() <= end)
716 sf.setBegin(sf.getBegin() + startShift);
717 sf.setEnd(sf.getEnd() + startShift);
726 System.out.println("Adding dbrefs to " + sequence.getName()
727 + " from " + dbSource + " sequence : "
728 + retrievedSeq.getName());
729 sequence.transferAnnotation(retrievedSeq, mp);
731 absStart += retrievedSeq.getStart();
732 int absEnd = absStart + nonGapped.length() - 1;
733 if (!trimDatasetSeqs)
736 * update start position and/or expand to longer retrieved sequence
738 if (!retrievedSeqString.equals(sequence.getSequenceAsString())
739 && remoteEnclosesLocal)
741 sequence.setSequence(retrievedSeqString);
743 addWarningMessage(warningMessages,
744 "Sequence for " + sequence.getName()
745 + " expanded from " + retrievedSeq.getName());
747 if (sequence.getStart() != retrievedSeq.getStart())
749 sequence.setStart(retrievedSeq.getStart());
751 if (absStart != sequenceStart)
753 addWarningMessage(warningMessages, "Start/end position for "
754 + sequence.getName() + " updated from "
755 + retrievedSeq.getName());
761 // finally, update local sequence reference frame if we're allowed
764 // just fix start/end
765 if (sequence.getStart() != absStart
766 || sequence.getEnd() != absEnd)
768 sequence.setStart(absStart);
769 sequence.setEnd(absEnd);
771 addWarningMessage(warningMessages, "Start/end for "
772 + sequence.getName() + " updated from "
773 + retrievedSeq.getName());
776 // search for alignment sequences to update coordinate frame for
777 for (int alsq = 0; alsq < alseqs.length; alsq++)
779 if (alseqs[alsq].getDatasetSequence() == sequence)
781 String ngAlsq = AlignSeq.extractGaps("-. ",
782 alseqs[alsq].getSequenceAsString()).toUpperCase();
783 int oldstrt = alseqs[alsq].getStart();
784 alseqs[alsq].setStart(sequence.getSequenceAsString()
785 .toUpperCase().indexOf(ngAlsq)
786 + sequence.getStart());
787 if (oldstrt != alseqs[alsq].getStart())
789 alseqs[alsq].setEnd(ngAlsq.length()
790 + alseqs[alsq].getStart() - 1);
795 // TODO: search for all other references to this dataset sequence, and
797 // TODO: update all AlCodonMappings which involve this alignment
798 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
801 // and remove it from the rest
802 // TODO: decide if we should remove annotated sequence from set
803 sdataset.remove(sequence);
804 // TODO: should we make a note of sequences that have received new DB
805 // ids, so we can query all enabled DAS servers for them ?
812 * Adds the message to the list unless it already contains it
817 void addWarningMessage(List<String> messageList, String msg)
819 if (!messageList.contains(msg))
821 messageList.add(msg);
826 * loop thru and collect additional sequences in Map.
828 * @param sequencesArray
831 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
833 Vector<SequenceI> nseq = new Vector<SequenceI>();
834 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
836 nseq.addElement(sequencesArray[i]);
837 DBRefEntry[] dbr = sequencesArray[i].getDBRefs();
839 for (int r = 0; (dbr != null) && r < dbr.length; r++)
841 if ((map = dbr[r].getMap()) != null)
843 if (map.getTo() != null && !nseq.contains(map.getTo()))
845 nseq.addElement(map.getTo());
852 sequencesArray = new SequenceI[nseq.size()];
853 nseq.toArray(sequencesArray);
855 return sequencesArray;