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.SequenceI;
30 import jalview.gui.CutAndPasteTransfer;
31 import jalview.gui.Desktop;
32 import jalview.gui.FeatureSettings;
33 import jalview.gui.IProgressIndicator;
34 import jalview.gui.OOMWarning;
35 import jalview.util.DBRefUtils;
36 import jalview.util.MessageManager;
37 import jalview.ws.seqfetcher.DbSourceProxy;
39 import java.util.ArrayList;
40 import java.util.Arrays;
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;
48 import uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator;
51 * Implements a runnable for validating a sequence against external databases
52 * and then propagating references and features onto the sequence(s)
57 public class DBRefFetcher implements Runnable
59 private static final String NEWLINE = System.lineSeparator();
61 public static final String TRIM_RETRIEVED_SEQUENCES = "TRIM_FETCHED_DATASET_SEQS";
63 public interface FetchFinishedListenerI
70 IProgressIndicator progressWindow;
72 CutAndPasteTransfer output = new CutAndPasteTransfer();
74 boolean running = false;
77 * picr client instance
79 uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
81 // This will be a collection of Vectors of sequenceI refs.
82 // The key will be the seq name or accession id of the seq
83 Hashtable<String, Vector<SequenceI>> seqRefs;
85 DbSourceProxy[] dbSources;
87 SequenceFetcher sfetcher;
89 private List<FetchFinishedListenerI> listeners;
91 private SequenceI[] alseqs;
94 * when true - retrieved sequences will be trimmed to cover longest derived
97 private boolean trimDsSeqs = true;
100 * Creates a new DBRefFetcher object and fetches from the currently selected
101 * set of databases, if this is null then it fetches based on feature settings
104 * fetch references for these SequenceI array
105 * @param progressIndicatorFrame
106 * the frame for progress bar monitoring
108 * array of DbSourceProxy to query references form
109 * @param featureSettings
110 * FeatureSettings to get alternative DbSourceProxy from
111 * @param isNucleotide
112 * indicates if the array of SequenceI are Nucleotides or not
114 public DBRefFetcher(SequenceI[] seqs,
115 IProgressIndicator progressIndicatorFrame,
116 DbSourceProxy[] sources, FeatureSettings featureSettings,
117 boolean isNucleotide)
119 listeners = new ArrayList<>();
120 this.progressWindow = progressIndicatorFrame;
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)
128 ds[i] = seqs[i].getDatasetSequence();
136 // TODO Jalview 2.5 lots of this code should be in the gui package!
137 sfetcher = jalview.gui.SequenceFetcher.getSequenceFetcherSingleton();
138 // set default behaviour for transferring excess sequence data to the
140 trimDsSeqs = Cache.getDefault(TRIM_RETRIEVED_SEQUENCES, true);
143 setDatabaseSources(featureSettings, isNucleotide);
147 // we assume the caller knows what they're doing and ensured that all the
148 // db source names are valid
154 * Helper method to configure the list of database sources to query
156 * @param featureSettings
157 * @param forNucleotide
159 void setDatabaseSources(FeatureSettings featureSettings,
160 boolean forNucleotide)
162 // af.featureSettings_actionPerformed(null);
163 String[] defdb = null;
164 List<DbSourceProxy> selsources = new ArrayList<>();
165 // select appropriate databases based on alignFrame context.
168 defdb = DBRefSource.DNACODINGDBS;
172 defdb = DBRefSource.PROTEINDBS;
174 List<DbSourceProxy> srces = new ArrayList<>();
175 for (String ddb : defdb)
177 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
178 if (srcesfordb != null)
180 for (DbSourceProxy src : srcesfordb)
182 if (!srces.contains(src))
184 srces.addAll(srcesfordb);
189 // append the PDB data source, since it is 'special', catering for both
190 // nucleotide and protein
191 // srces.addAll(sfetcher.getSourceProxy(DBRefSource.PDB));
193 srces.addAll(selsources);
194 dbSources = srces.toArray(new DbSourceProxy[srces.size()]);
198 * Constructor with only sequences provided
202 public DBRefFetcher(SequenceI[] sequences)
204 this(sequences, null, null, null, false);
208 * Add a listener to be notified when sequence fetching is complete
212 public void addListener(FetchFinishedListenerI l)
218 * start the fetcher thread
220 * @param waitTillFinished
221 * true to block until the fetcher has finished
223 public void fetchDBRefs(boolean waitTillFinished)
225 // TODO can we not simply write
226 // if (waitTillFinished) { run(); } else { new Thread(this).start(); }
228 Thread thread = new Thread(this);
232 if (waitTillFinished)
239 } catch (Exception ex)
247 * The sequence will be added to a vector of sequences belonging to key which
248 * could be either seq name or dbref id
255 void addSeqId(SequenceI seq, String key)
257 key = key.toUpperCase();
259 Vector<SequenceI> seqs;
260 if (seqRefs.containsKey(key))
262 seqs = seqRefs.get(key);
264 if (seqs != null && !seqs.contains(seq))
266 seqs.addElement(seq);
268 else if (seqs == null)
270 seqs = new Vector<>();
271 seqs.addElement(seq);
277 seqs = new Vector<>();
278 seqs.addElement(seq);
281 seqRefs.put(key, seqs);
290 if (dbSources == null)
292 throw new Error(MessageManager
293 .getString("error.implementation_error_must_init_dbsources"));
296 long startTime = System.currentTimeMillis();
297 if (progressWindow != null)
299 progressWindow.setProgressBar(
300 MessageManager.getString("status.fetching_db_refs"),
305 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
307 picrClient = new AccessionMapperServiceLocator()
308 .getAccessionMapperPort();
310 } catch (Exception e)
312 System.err.println("Couldn't locate PICR service instance.\n");
316 Vector<SequenceI> sdataset = new Vector<>(
317 Arrays.asList(dataset));
318 List<String> warningMessages = new ArrayList<>();
321 while (sdataset.size() > 0 && db < dbSources.length)
323 int maxqlen = 1; // default number of queries made at one time
324 System.out.println("Verifying against " + dbSources[db].getDbName());
326 // iterate through db for each remaining un-verified sequence
327 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
328 sdataset.copyInto(currSeqs);// seqs that are to be validated against
330 Vector<String> queries = new Vector<>(); // generated queries curSeq
331 seqRefs = new Hashtable<>();
335 DbSourceProxy dbsource = dbSources[db];
336 // for moment, we dumbly iterate over all retrieval sources for a
337 // particular database
338 // TODO: introduce multithread multisource queries and logic to remove a
339 // query from other sources if any source for a database returns a
341 maxqlen = dbsource.getMaximumQueryCount();
343 while (queries.size() > 0 || seqIndex < currSeqs.length)
345 if (queries.size() > 0)
347 // Still queries to make for current seqIndex
348 StringBuffer queryString = new StringBuffer("");
350 int nqSize = (maxqlen > queries.size()) ? queries.size()
353 while (queries.size() > 0 && numq < nqSize)
355 String query = queries.elementAt(0);
356 if (dbsource.isValidReference(query))
359 (numq == 0) ? "" : dbsource.getAccessionSeparator());
360 queryString.append(query);
363 // remove the extracted query string
364 queries.removeElementAt(0);
366 // make the queries and process the response
367 AlignmentI retrieved = null;
370 if (Cache.log.isDebugEnabled())
372 Cache.log.debug("Querying " + dbsource.getDbName()
373 + " with : '" + queryString.toString() + "'");
375 retrieved = dbsource.getSequenceRecords(queryString.toString());
376 } catch (Exception ex)
378 ex.printStackTrace();
379 } catch (OutOfMemoryError err)
381 new OOMWarning("retrieving database references ("
382 + queryString.toString() + ")", err);
384 if (retrieved != null)
386 transferReferences(sdataset, dbsource.getDbSource(), retrieved,
387 trimDsSeqs, warningMessages);
392 // make some more strings for use as queries
393 for (int i = 0; (seqIndex < dataset.length)
394 && (i < 50); seqIndex++, i++)
396 SequenceI sequence = dataset[seqIndex];
397 List<DBRefEntry> uprefs = DBRefUtils
398 .selectRefs(sequence.getDBRefs(), new String[]
399 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
401 // check for existing dbrefs to use
402 if (uprefs != null && uprefs.size() > 0)
404 for (int j = 0, n = uprefs.size(); j < n; j++)
406 DBRefEntry upref = uprefs.get(j);
407 addSeqId(sequence, upref.getAccessionId());
409 upref.getAccessionId().toUpperCase());
414 // generate queries from sequence ID string
415 StringTokenizer st = new StringTokenizer(sequence.getName(),
417 while (st.hasMoreTokens())
419 String token = st.nextToken();
420 UPEntry[] presp = null;
421 if (picrClient != null)
423 // resolve the string against PICR to recover valid IDs
426 presp = picrClient.getUPIForAccession(token, null,
427 picrClient.getMappedDatabaseNames(), null,
429 } catch (Exception e)
432 "Exception with Picr for '" + token + "'\n");
436 if (presp != null && presp.length > 0)
438 for (int id = 0; id < presp.length; id++)
440 // construct sequences from response if sequences are
441 // present, and do a transferReferences
442 // otherwise transfer non sequence x-references directly.
445 "Validated ID against PICR... (for what its worth):"
447 addSeqId(sequence, token);
448 queries.addElement(token.toUpperCase());
453 // System.out.println("Not querying source with
454 // token="+token+"\n");
455 addSeqId(sequence, token);
456 queries.addElement(token.toUpperCase());
463 // advance to next database
465 } // all databases have been queried
466 if (!warningMessages.isEmpty())
468 StringBuilder sb = new StringBuilder(warningMessages.size() * 30);
469 sb.append(MessageManager
470 .getString("label.your_sequences_have_been_verified"));
471 for (String msg : warningMessages)
473 sb.append(msg).append(NEWLINE);
475 output.setText(sb.toString());
477 Desktop.addInternalFrame(output,
478 MessageManager.getString("label.sequences_updated"), 600,
480 // The above is the dataset, we must now find out the index
481 // of the viewed sequence
484 if (progressWindow != null)
486 progressWindow.setProgressBar(
487 MessageManager.getString("label.dbref_search_completed"),
491 for (FetchFinishedListenerI listener : listeners)
499 * Verify local sequences in seqRefs against the retrieved sequence database
500 * records. Returns true if any sequence was modified as a result (start/end
501 * changed and/or sequence enlarged), else false.
504 * dataset sequences we are retrieving for
506 * database source we are retrieving from
508 * retrieved sequences as alignment
509 * @param trimDatasetSeqs
510 * if true, sequences will not be enlarged to match longer retrieved
511 * sequences, only their start/end adjusted
512 * @param warningMessages
513 * a list of messages to add to
515 boolean transferReferences(Vector<SequenceI> sdataset, String dbSource,
516 AlignmentI retrievedAl, boolean trimDatasetSeqs,
517 List<String> warningMessages)
519 // System.out.println("trimming ? " + trimDatasetSeqs);
520 if (retrievedAl == null || retrievedAl.getHeight() == 0)
525 boolean modified = false;
526 SequenceI[] retrieved = recoverDbSequences(
527 retrievedAl.getSequencesArray());
528 SequenceI sequence = null;
530 for (SequenceI retrievedSeq : retrieved)
532 // Work out which sequences this sequence matches,
533 // taking into account all accessionIds and names in the file
534 Vector<SequenceI> sequenceMatches = new Vector<>();
535 // look for corresponding accession ids
536 List<DBRefEntry> entryRefs = DBRefUtils
537 .selectRefs(retrievedSeq.getDBRefs(), new String[]
539 if (entryRefs == null)
542 .println("Dud dbSource string ? no entryrefs selected for "
543 + dbSource + " on " + retrievedSeq.getName());
546 for (int j = 0, n = entryRefs.size(); j < n; j++)
548 DBRefEntry ref = entryRefs.get(j);
549 String accessionId = ref.getAccessionId();
550 // match up on accessionId
551 if (seqRefs.containsKey(accessionId.toUpperCase()))
553 Vector<SequenceI> seqs = seqRefs.get(accessionId);
554 for (int jj = 0; jj < seqs.size(); jj++)
556 sequence = seqs.elementAt(jj);
557 if (!sequenceMatches.contains(sequence))
559 sequenceMatches.addElement(sequence);
564 if (sequenceMatches.isEmpty())
566 // failed to match directly on accessionId==query so just compare all
567 // sequences to entry
568 Enumeration<String> e = seqRefs.keys();
569 while (e.hasMoreElements())
571 Vector<SequenceI> sqs = seqRefs.get(e.nextElement());
572 if (sqs != null && sqs.size() > 0)
574 Enumeration<SequenceI> sqe = sqs.elements();
575 while (sqe.hasMoreElements())
577 sequenceMatches.addElement(sqe.nextElement());
582 // look for corresponding names
583 // this is uniprot specific ?
584 // could be useful to extend this so we try to find any 'significant'
585 // information in common between two sequence objects.
587 * List<DBRefEntry> entryRefs =
588 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
589 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
590 * name = entry.getName().elementAt(j).toString(); if
591 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
592 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
593 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
594 * sequenceMatches.addElement(sequence); } } } }
596 // sequenceMatches now contains the set of all sequences associated with
597 // the returned db record
598 final String retrievedSeqString = retrievedSeq.getSequenceAsString();
599 String entrySeq = retrievedSeqString.toUpperCase();
600 for (int m = 0; m < sequenceMatches.size(); m++)
602 sequence = sequenceMatches.elementAt(m);
603 // only update start and end positions and shift features if there are
604 // no existing references
605 // TODO: test for legacy where uniprot or EMBL refs exist but no
606 // mappings are made (but content matches retrieved set)
607 boolean updateRefFrame = sequence.getDBRefs() == null
608 || sequence.getDBRefs().size() == 0;
610 // verify sequence against the entry sequence
613 final int sequenceStart = sequence.getStart();
615 boolean remoteEnclosesLocal = false;
616 String nonGapped = AlignSeq
617 .extractGaps("-. ", sequence.getSequenceAsString())
619 int absStart = entrySeq.indexOf(nonGapped);
622 // couldn't find local sequence in sequence from database, so check if
623 // the database sequence is a subsequence of local sequence
624 absStart = nonGapped.indexOf(entrySeq);
627 // verification failed. couldn't find any relationship between
628 // entrySeq and local sequence
629 // messages suppressed as many-to-many matches are confusing
630 // String msg = sequence.getName()
631 // + " Sequence not 100% match with "
632 // + retrievedSeq.getName();
633 // addWarningMessage(warningMessages, msg);
637 * retrieved sequence is a proper subsequence of local sequence
639 String msg = sequence.getName() + " has " + absStart
640 + " prefixed residues compared to "
641 + retrievedSeq.getName();
642 addWarningMessage(warningMessages, msg);
645 * So create a mapping to the external entry from the matching region of
646 * the local sequence, and leave local start/end untouched.
648 mp = new Mapping(null,
650 { sequenceStart + absStart,
651 sequenceStart + absStart + entrySeq.length() - 1 },
653 { retrievedSeq.getStart(),
654 retrievedSeq.getStart() + entrySeq.length() - 1 },
656 updateRefFrame = false;
661 * local sequence is a subsequence of (or matches) retrieved sequence
663 remoteEnclosesLocal = true;
669 * relocate existing sequence features by offset
671 int startShift = absStart - sequenceStart + 1;
674 modified |= sequence.getFeatures().shiftFeatures(1,
680 System.out.println("Adding dbrefs to " + sequence.getName()
681 + " from " + dbSource + " sequence : "
682 + retrievedSeq.getName());
683 sequence.transferAnnotation(retrievedSeq, mp);
685 absStart += retrievedSeq.getStart();
686 int absEnd = absStart + nonGapped.length() - 1;
687 if (!trimDatasetSeqs)
690 * update start position and/or expand to longer retrieved sequence
692 if (!retrievedSeqString.equals(sequence.getSequenceAsString())
693 && remoteEnclosesLocal)
695 sequence.setSequence(retrievedSeqString);
697 addWarningMessage(warningMessages,
698 "Sequence for " + sequence.getName() + " expanded from "
699 + retrievedSeq.getName());
701 if (sequence.getStart() != retrievedSeq.getStart())
703 sequence.setStart(retrievedSeq.getStart());
705 if (absStart != sequenceStart)
707 addWarningMessage(warningMessages,
708 "Start/end position for " + sequence.getName()
709 + " updated from " + retrievedSeq.getName());
715 // finally, update local sequence reference frame if we're allowed
718 // just fix start/end
719 if (sequence.getStart() != absStart
720 || sequence.getEnd() != absEnd)
722 sequence.setStart(absStart);
723 sequence.setEnd(absEnd);
725 addWarningMessage(warningMessages,
726 "Start/end for " + sequence.getName()
727 + " updated from " + retrievedSeq.getName());
730 // search for alignment sequences to update coordinate frame for
731 for (int alsq = 0; alsq < alseqs.length; alsq++)
733 if (alseqs[alsq].getDatasetSequence() == sequence)
735 String ngAlsq = AlignSeq
737 alseqs[alsq].getSequenceAsString())
739 int oldstrt = alseqs[alsq].getStart();
740 alseqs[alsq].setStart(sequence.getSequenceAsString()
741 .toUpperCase().indexOf(ngAlsq) + sequence.getStart());
742 if (oldstrt != alseqs[alsq].getStart())
745 ngAlsq.length() + alseqs[alsq].getStart() - 1);
750 // TODO: search for all other references to this dataset sequence, and
752 // TODO: update all AlCodonMappings which involve this alignment
753 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
756 // and remove it from the rest
757 // TODO: decide if we should remove annotated sequence from set
758 sdataset.remove(sequence);
765 * Adds the message to the list unless it already contains it
770 void addWarningMessage(List<String> messageList, String msg)
772 if (!messageList.contains(msg))
774 messageList.add(msg);
779 * loop thru and collect additional sequences in Map.
781 * @param sequencesArray
784 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
787 if (sequencesArray == null || (n = sequencesArray.length) == 0)
788 return sequencesArray;
789 ArrayList<SequenceI> nseq = new ArrayList<>();
790 for (int i = 0;i < n; i++)
792 nseq.add(sequencesArray[i]);
793 List<DBRefEntry> dbr = sequencesArray[i].getDBRefs();
797 for (int r = 0, rn = dbr.size(); r < rn; r++)
799 if ((map = dbr.get(r).getMap()) != null)
801 if (map.getTo() != null && !nseq.contains(map.getTo()))
803 nseq.add(map.getTo());
809 // BH 2019.01.25 question here if this is the right logic. Return the original if nothing found?
812 return nseq.toArray(new SequenceI[nseq.size()]);
814 return sequencesArray;