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 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.length > 0)
404 for (int j = 0; j < uprefs.length; j++)
406 addSeqId(sequence, uprefs[j].getAccessionId());
408 uprefs[j].getAccessionId().toUpperCase());
413 // generate queries from sequence ID string
414 StringTokenizer st = new StringTokenizer(sequence.getName(),
416 while (st.hasMoreTokens())
418 String token = st.nextToken();
419 UPEntry[] presp = null;
420 if (picrClient != null)
422 // resolve the string against PICR to recover valid IDs
425 presp = picrClient.getUPIForAccession(token, null,
426 picrClient.getMappedDatabaseNames(), null,
428 } catch (Exception e)
431 "Exception with Picr for '" + token + "'\n");
435 if (presp != null && presp.length > 0)
437 for (int id = 0; id < presp.length; id++)
439 // construct sequences from response if sequences are
440 // present, and do a transferReferences
441 // otherwise transfer non sequence x-references directly.
444 "Validated ID against PICR... (for what its worth):"
446 addSeqId(sequence, token);
447 queries.addElement(token.toUpperCase());
452 // System.out.println("Not querying source with
453 // token="+token+"\n");
454 addSeqId(sequence, token);
455 queries.addElement(token.toUpperCase());
462 // advance to next database
464 } // all databases have been queried
465 if (!warningMessages.isEmpty())
467 StringBuilder sb = new StringBuilder(warningMessages.size() * 30);
468 sb.append(MessageManager
469 .getString("label.your_sequences_have_been_verified"));
470 for (String msg : warningMessages)
472 sb.append(msg).append(NEWLINE);
474 output.setText(sb.toString());
476 Desktop.addInternalFrame(output,
477 MessageManager.getString("label.sequences_updated"), 600,
479 // The above is the dataset, we must now find out the index
480 // of the viewed sequence
483 if (progressWindow != null)
485 progressWindow.setProgressBar(
486 MessageManager.getString("label.dbref_search_completed"),
490 for (FetchFinishedListenerI listener : listeners)
498 * Verify local sequences in seqRefs against the retrieved sequence database
499 * records. Returns true if any sequence was modified as a result (start/end
500 * changed and/or sequence enlarged), else false.
503 * dataset sequences we are retrieving for
505 * database source we are retrieving from
507 * retrieved sequences as alignment
508 * @param trimDatasetSeqs
509 * if true, sequences will not be enlarged to match longer retrieved
510 * sequences, only their start/end adjusted
511 * @param warningMessages
512 * a list of messages to add to
514 boolean transferReferences(Vector<SequenceI> sdataset, String dbSource,
515 AlignmentI retrievedAl, boolean trimDatasetSeqs,
516 List<String> warningMessages)
518 // System.out.println("trimming ? " + trimDatasetSeqs);
519 if (retrievedAl == null || retrievedAl.getHeight() == 0)
524 boolean modified = false;
525 SequenceI[] retrieved = recoverDbSequences(
526 retrievedAl.getSequencesArray());
527 SequenceI sequence = null;
529 for (SequenceI retrievedSeq : retrieved)
531 // Work out which sequences this sequence matches,
532 // taking into account all accessionIds and names in the file
533 Vector<SequenceI> sequenceMatches = new Vector<>();
534 // look for corresponding accession ids
535 DBRefEntry[] entryRefs = DBRefUtils
536 .selectRefs(retrievedSeq.getDBRefs(), new String[]
538 if (entryRefs == null)
541 .println("Dud dbSource string ? no entryrefs selected for "
542 + dbSource + " on " + retrievedSeq.getName());
545 for (int j = 0; j < entryRefs.length; j++)
547 String accessionId = entryRefs[j].getAccessionId();
548 // match up on accessionId
549 if (seqRefs.containsKey(accessionId.toUpperCase()))
551 Vector<SequenceI> seqs = seqRefs.get(accessionId);
552 for (int jj = 0; jj < seqs.size(); jj++)
554 sequence = seqs.elementAt(jj);
555 if (!sequenceMatches.contains(sequence))
557 sequenceMatches.addElement(sequence);
562 if (sequenceMatches.isEmpty())
564 // failed to match directly on accessionId==query so just compare all
565 // sequences to entry
566 Enumeration<String> e = seqRefs.keys();
567 while (e.hasMoreElements())
569 Vector<SequenceI> sqs = seqRefs.get(e.nextElement());
570 if (sqs != null && sqs.size() > 0)
572 Enumeration<SequenceI> sqe = sqs.elements();
573 while (sqe.hasMoreElements())
575 sequenceMatches.addElement(sqe.nextElement());
580 // look for corresponding names
581 // this is uniprot specific ?
582 // could be useful to extend this so we try to find any 'significant'
583 // information in common between two sequence objects.
585 * DBRefEntry[] entryRefs =
586 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
587 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
588 * name = entry.getName().elementAt(j).toString(); if
589 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
590 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
591 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
592 * sequenceMatches.addElement(sequence); } } } }
594 // sequenceMatches now contains the set of all sequences associated with
595 // the returned db record
596 final String retrievedSeqString = retrievedSeq.getSequenceAsString();
597 String entrySeq = retrievedSeqString.toUpperCase();
598 for (int m = 0; m < sequenceMatches.size(); m++)
600 sequence = sequenceMatches.elementAt(m);
601 // only update start and end positions and shift features if there are
602 // no existing references
603 // TODO: test for legacy where uniprot or EMBL refs exist but no
604 // mappings are made (but content matches retrieved set)
605 boolean updateRefFrame = sequence.getDBRefs() == null
606 || sequence.getDBRefs().length == 0;
608 // verify sequence against the entry sequence
611 final int sequenceStart = sequence.getStart();
613 boolean remoteEnclosesLocal = false;
614 String nonGapped = AlignSeq
615 .extractGaps("-. ", sequence.getSequenceAsString())
617 int absStart = entrySeq.indexOf(nonGapped);
620 // couldn't find local sequence in sequence from database, so check if
621 // the database sequence is a subsequence of local sequence
622 absStart = nonGapped.indexOf(entrySeq);
625 // verification failed. couldn't find any relationship between
626 // entrySeq and local sequence
627 // messages suppressed as many-to-many matches are confusing
628 // String msg = sequence.getName()
629 // + " Sequence not 100% match with "
630 // + retrievedSeq.getName();
631 // addWarningMessage(warningMessages, msg);
635 * retrieved sequence is a proper subsequence of local sequence
637 String msg = sequence.getName() + " has " + absStart
638 + " prefixed residues compared to "
639 + retrievedSeq.getName();
640 addWarningMessage(warningMessages, msg);
643 * So create a mapping to the external entry from the matching region of
644 * the local sequence, and leave local start/end untouched.
646 mp = new Mapping(null,
648 { sequenceStart + absStart,
649 sequenceStart + absStart + entrySeq.length() - 1 },
651 { retrievedSeq.getStart(),
652 retrievedSeq.getStart() + entrySeq.length() - 1 },
654 updateRefFrame = false;
659 * local sequence is a subsequence of (or matches) retrieved sequence
661 remoteEnclosesLocal = true;
667 * relocate existing sequence features by offset
669 int startShift = absStart - sequenceStart + 1;
672 modified |= sequence.getFeatures().shiftFeatures(1,
678 System.out.println("Adding dbrefs to " + sequence.getName()
679 + " from " + dbSource + " sequence : "
680 + retrievedSeq.getName());
681 sequence.transferAnnotation(retrievedSeq, mp);
683 absStart += retrievedSeq.getStart();
684 int absEnd = absStart + nonGapped.length() - 1;
685 if (!trimDatasetSeqs)
688 * update start position and/or expand to longer retrieved sequence
690 if (!retrievedSeqString.equals(sequence.getSequenceAsString())
691 && remoteEnclosesLocal)
693 sequence.setSequence(retrievedSeqString);
695 addWarningMessage(warningMessages,
696 "Sequence for " + sequence.getName() + " expanded from "
697 + retrievedSeq.getName());
699 if (sequence.getStart() != retrievedSeq.getStart())
701 sequence.setStart(retrievedSeq.getStart());
703 if (absStart != sequenceStart)
705 addWarningMessage(warningMessages,
706 "Start/end position for " + sequence.getName()
707 + " updated from " + retrievedSeq.getName());
713 // finally, update local sequence reference frame if we're allowed
716 // just fix start/end
717 if (sequence.getStart() != absStart
718 || sequence.getEnd() != absEnd)
720 sequence.setStart(absStart);
721 sequence.setEnd(absEnd);
723 addWarningMessage(warningMessages,
724 "Start/end for " + sequence.getName()
725 + " updated from " + retrievedSeq.getName());
728 // search for alignment sequences to update coordinate frame for
729 for (int alsq = 0; alsq < alseqs.length; alsq++)
731 if (alseqs[alsq].getDatasetSequence() == sequence)
733 String ngAlsq = AlignSeq
735 alseqs[alsq].getSequenceAsString())
737 int oldstrt = alseqs[alsq].getStart();
738 alseqs[alsq].setStart(sequence.getSequenceAsString()
739 .toUpperCase().indexOf(ngAlsq) + sequence.getStart());
740 if (oldstrt != alseqs[alsq].getStart())
743 ngAlsq.length() + alseqs[alsq].getStart() - 1);
748 // TODO: search for all other references to this dataset sequence, and
750 // TODO: update all AlCodonMappings which involve this alignment
751 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
754 // and remove it from the rest
755 // TODO: decide if we should remove annotated sequence from set
756 sdataset.remove(sequence);
757 // TODO: should we make a note of sequences that have received new DB
758 // ids, so we can query all enabled DAS servers for them ?
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)
786 Vector<SequenceI> nseq = new Vector<>();
787 for (int i = 0; sequencesArray != null
788 && i < sequencesArray.length; i++)
790 nseq.addElement(sequencesArray[i]);
791 DBRefEntry[] dbr = sequencesArray[i].getDBRefs();
793 for (int r = 0; (dbr != null) && r < dbr.length; r++)
795 if ((map = dbr[r].getMap()) != null)
797 if (map.getTo() != null && !nseq.contains(map.getTo()))
799 nseq.addElement(map.getTo());
806 sequencesArray = new SequenceI[nseq.size()];
807 nseq.toArray(sequencesArray);
809 return sequencesArray;