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
138 .getSequenceFetcherSingleton(progressIndicatorFrame);
139 // set default behaviour for transferring excess sequence data to the
141 trimDsSeqs = Cache.getDefault(TRIM_RETRIEVED_SEQUENCES, true);
144 setDatabaseSources(featureSettings, isNucleotide);
148 // we assume the caller knows what they're doing and ensured that all the
149 // db source names are valid
155 * Helper method to configure the list of database sources to query
157 * @param featureSettings
158 * @param forNucleotide
160 void setDatabaseSources(FeatureSettings featureSettings,
161 boolean forNucleotide)
163 // af.featureSettings_actionPerformed(null);
164 String[] defdb = null;
165 List<DbSourceProxy> selsources = new ArrayList<>();
166 // select appropriate databases based on alignFrame context.
169 defdb = DBRefSource.DNACODINGDBS;
173 defdb = DBRefSource.PROTEINDBS;
175 List<DbSourceProxy> srces = new ArrayList<>();
176 for (String ddb : defdb)
178 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
179 if (srcesfordb != null)
181 for (DbSourceProxy src : srcesfordb)
183 if (!srces.contains(src))
185 srces.addAll(srcesfordb);
190 // append the PDB data source, since it is 'special', catering for both
191 // nucleotide and protein
192 // srces.addAll(sfetcher.getSourceProxy(DBRefSource.PDB));
194 srces.addAll(selsources);
195 dbSources = srces.toArray(new DbSourceProxy[srces.size()]);
199 * Constructor with only sequences provided
203 public DBRefFetcher(SequenceI[] sequences)
205 this(sequences, null, null, null, false);
209 * Add a listener to be notified when sequence fetching is complete
213 public void addListener(FetchFinishedListenerI l)
219 * start the fetcher thread
221 * @param waitTillFinished
222 * true to block until the fetcher has finished
224 public void fetchDBRefs(boolean waitTillFinished)
226 // TODO can we not simply write
227 // if (waitTillFinished) { run(); } else { new Thread(this).start(); }
229 Thread thread = new Thread(this);
233 if (waitTillFinished)
240 } catch (Exception ex)
248 * The sequence will be added to a vector of sequences belonging to key which
249 * could be either seq name or dbref id
256 void addSeqId(SequenceI seq, String key)
258 key = key.toUpperCase();
260 Vector<SequenceI> seqs;
261 if (seqRefs.containsKey(key))
263 seqs = seqRefs.get(key);
265 if (seqs != null && !seqs.contains(seq))
267 seqs.addElement(seq);
269 else if (seqs == null)
271 seqs = new Vector<>();
272 seqs.addElement(seq);
278 seqs = new Vector<>();
279 seqs.addElement(seq);
282 seqRefs.put(key, seqs);
291 if (dbSources == null)
293 throw new Error(MessageManager
294 .getString("error.implementation_error_must_init_dbsources"));
297 long startTime = System.currentTimeMillis();
298 if (progressWindow != null)
300 progressWindow.setProgressBar(
301 MessageManager.getString("status.fetching_db_refs"),
306 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
308 picrClient = new AccessionMapperServiceLocator()
309 .getAccessionMapperPort();
311 } catch (Exception e)
313 System.err.println("Couldn't locate PICR service instance.\n");
317 Vector<SequenceI> sdataset = new Vector<>(
318 Arrays.asList(dataset));
319 List<String> warningMessages = new ArrayList<>();
322 while (sdataset.size() > 0 && db < dbSources.length)
324 int maxqlen = 1; // default number of queries made at one time
325 System.out.println("Verifying against " + dbSources[db].getDbName());
327 // iterate through db for each remaining un-verified sequence
328 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
329 sdataset.copyInto(currSeqs);// seqs that are to be validated against
331 Vector<String> queries = new Vector<>(); // generated queries curSeq
332 seqRefs = new Hashtable<>();
336 DbSourceProxy dbsource = dbSources[db];
337 // for moment, we dumbly iterate over all retrieval sources for a
338 // particular database
339 // TODO: introduce multithread multisource queries and logic to remove a
340 // query from other sources if any source for a database returns a
342 maxqlen = dbsource.getMaximumQueryCount();
344 while (queries.size() > 0 || seqIndex < currSeqs.length)
346 if (queries.size() > 0)
348 // Still queries to make for current seqIndex
349 StringBuffer queryString = new StringBuffer("");
351 int nqSize = (maxqlen > queries.size()) ? queries.size()
354 while (queries.size() > 0 && numq < nqSize)
356 String query = queries.elementAt(0);
357 if (dbsource.isValidReference(query))
360 (numq == 0) ? "" : dbsource.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 (Cache.log.isDebugEnabled())
373 Cache.log.debug("Querying " + dbsource.getDbName()
374 + " with : '" + queryString.toString() + "'");
376 retrieved = dbsource.getSequenceRecords(queryString.toString());
377 } catch (Exception ex)
379 ex.printStackTrace();
380 } catch (OutOfMemoryError err)
382 new OOMWarning("retrieving database references ("
383 + queryString.toString() + ")", err);
385 if (retrieved != null)
387 transferReferences(sdataset, dbsource.getDbSource(), retrieved,
388 trimDsSeqs, warningMessages);
393 // make some more strings for use as queries
394 for (int i = 0; (seqIndex < dataset.length)
395 && (i < 50); seqIndex++, i++)
397 SequenceI sequence = dataset[seqIndex];
398 DBRefEntry[] uprefs = DBRefUtils
399 .selectRefs(sequence.getDBRefs(), new String[]
400 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
402 // check for existing dbrefs to use
403 if (uprefs != null && uprefs.length > 0)
405 for (int j = 0; j < uprefs.length; j++)
407 addSeqId(sequence, uprefs[j].getAccessionId());
409 uprefs[j].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 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; j < entryRefs.length; j++)
548 String accessionId = entryRefs[j].getAccessionId();
549 // match up on accessionId
550 if (seqRefs.containsKey(accessionId.toUpperCase()))
552 Vector<SequenceI> seqs = seqRefs.get(accessionId);
553 for (int jj = 0; jj < seqs.size(); jj++)
555 sequence = seqs.elementAt(jj);
556 if (!sequenceMatches.contains(sequence))
558 sequenceMatches.addElement(sequence);
563 if (sequenceMatches.isEmpty())
565 // failed to match directly on accessionId==query so just compare all
566 // sequences to entry
567 Enumeration<String> e = seqRefs.keys();
568 while (e.hasMoreElements())
570 Vector<SequenceI> sqs = seqRefs.get(e.nextElement());
571 if (sqs != null && sqs.size() > 0)
573 Enumeration<SequenceI> sqe = sqs.elements();
574 while (sqe.hasMoreElements())
576 sequenceMatches.addElement(sqe.nextElement());
581 // look for corresponding names
582 // this is uniprot specific ?
583 // could be useful to extend this so we try to find any 'significant'
584 // information in common between two sequence objects.
586 * DBRefEntry[] entryRefs =
587 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
588 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
589 * name = entry.getName().elementAt(j).toString(); if
590 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
591 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
592 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
593 * sequenceMatches.addElement(sequence); } } } }
595 // sequenceMatches now contains the set of all sequences associated with
596 // the returned db record
597 final String retrievedSeqString = retrievedSeq.getSequenceAsString();
598 String entrySeq = retrievedSeqString.toUpperCase();
599 for (int m = 0; m < sequenceMatches.size(); m++)
601 sequence = sequenceMatches.elementAt(m);
602 // only update start and end positions and shift features if there are
603 // no existing references
604 // TODO: test for legacy where uniprot or EMBL refs exist but no
605 // mappings are made (but content matches retrieved set)
606 boolean updateRefFrame = sequence.getDBRefs() == null
607 || sequence.getDBRefs().length == 0;
609 // verify sequence against the entry sequence
612 final int sequenceStart = sequence.getStart();
614 boolean remoteEnclosesLocal = false;
615 String nonGapped = AlignSeq
616 .extractGaps("-. ", sequence.getSequenceAsString())
618 int absStart = entrySeq.indexOf(nonGapped);
621 // couldn't find local sequence in sequence from database, so check if
622 // the database sequence is a subsequence of local sequence
623 absStart = nonGapped.indexOf(entrySeq);
626 // verification failed. couldn't find any relationship between
627 // entrySeq and local sequence
628 // messages suppressed as many-to-many matches are confusing
629 // String msg = sequence.getName()
630 // + " Sequence not 100% match with "
631 // + retrievedSeq.getName();
632 // addWarningMessage(warningMessages, msg);
636 * retrieved sequence is a proper subsequence of local sequence
638 String msg = sequence.getName() + " has " + absStart
639 + " prefixed residues compared to "
640 + retrievedSeq.getName();
641 addWarningMessage(warningMessages, msg);
644 * So create a mapping to the external entry from the matching region of
645 * the local sequence, and leave local start/end untouched.
647 mp = new Mapping(null,
649 { sequenceStart + absStart,
650 sequenceStart + absStart + entrySeq.length() - 1 },
652 { retrievedSeq.getStart(),
653 retrievedSeq.getStart() + entrySeq.length() - 1 },
655 updateRefFrame = false;
660 * local sequence is a subsequence of (or matches) retrieved sequence
662 remoteEnclosesLocal = true;
668 * relocate existing sequence features by offset
670 int startShift = absStart - sequenceStart + 1;
673 modified |= sequence.getFeatures().shiftFeatures(1,
679 System.out.println("Adding dbrefs to " + sequence.getName()
680 + " from " + dbSource + " sequence : "
681 + retrievedSeq.getName());
682 sequence.transferAnnotation(retrievedSeq, mp);
684 absStart += retrievedSeq.getStart();
685 int absEnd = absStart + nonGapped.length() - 1;
686 if (!trimDatasetSeqs)
689 * update start position and/or expand to longer retrieved sequence
691 if (!retrievedSeqString.equals(sequence.getSequenceAsString())
692 && remoteEnclosesLocal)
694 sequence.setSequence(retrievedSeqString);
696 addWarningMessage(warningMessages,
697 "Sequence for " + sequence.getName() + " expanded from "
698 + retrievedSeq.getName());
700 if (sequence.getStart() != retrievedSeq.getStart())
702 sequence.setStart(retrievedSeq.getStart());
704 if (absStart != sequenceStart)
706 addWarningMessage(warningMessages,
707 "Start/end position for " + sequence.getName()
708 + " updated from " + retrievedSeq.getName());
714 // finally, update local sequence reference frame if we're allowed
717 // just fix start/end
718 if (sequence.getStart() != absStart
719 || sequence.getEnd() != absEnd)
721 sequence.setStart(absStart);
722 sequence.setEnd(absEnd);
724 addWarningMessage(warningMessages,
725 "Start/end for " + sequence.getName()
726 + " updated from " + retrievedSeq.getName());
729 // search for alignment sequences to update coordinate frame for
730 for (int alsq = 0; alsq < alseqs.length; alsq++)
732 if (alseqs[alsq].getDatasetSequence() == sequence)
734 String ngAlsq = AlignSeq
736 alseqs[alsq].getSequenceAsString())
738 int oldstrt = alseqs[alsq].getStart();
739 alseqs[alsq].setStart(sequence.getSequenceAsString()
740 .toUpperCase().indexOf(ngAlsq) + sequence.getStart());
741 if (oldstrt != alseqs[alsq].getStart())
744 ngAlsq.length() + alseqs[alsq].getStart() - 1);
749 // TODO: search for all other references to this dataset sequence, and
751 // TODO: update all AlCodonMappings which involve this alignment
752 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
755 // and remove it from the rest
756 // TODO: decide if we should remove annotated sequence from set
757 sdataset.remove(sequence);
764 * Adds the message to the list unless it already contains it
769 void addWarningMessage(List<String> messageList, String msg)
771 if (!messageList.contains(msg))
773 messageList.add(msg);
778 * loop thru and collect additional sequences in Map.
780 * @param sequencesArray
783 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
785 Vector<SequenceI> nseq = new Vector<>();
786 for (int i = 0; sequencesArray != null
787 && i < sequencesArray.length; i++)
789 nseq.addElement(sequencesArray[i]);
790 DBRefEntry[] dbr = sequencesArray[i].getDBRefs();
792 for (int r = 0; (dbr != null) && r < dbr.length; r++)
794 if ((map = dbr[r].getMap()) != null)
796 if (map.getTo() != null && !nseq.contains(map.getTo()))
798 nseq.addElement(map.getTo());
805 sequencesArray = new SequenceI[nseq.size()];
806 nseq.toArray(sequencesArray);
808 return sequencesArray;