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.api.FeatureSettingsModelI;
25 import jalview.bin.Cache;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.DBRefEntry;
28 import jalview.datamodel.DBRefSource;
29 import jalview.datamodel.Mapping;
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.DBRefUtils;
37 import jalview.util.MessageManager;
38 import jalview.ws.seqfetcher.DbSourceProxy;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Enumeration;
43 import java.util.HashMap;
44 import java.util.Hashtable;
45 import java.util.List;
47 import java.util.StringTokenizer;
48 import java.util.Vector;
50 import uk.ac.ebi.picr.model.UPEntry;
51 import uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator;
54 * Implements a runnable for validating a sequence against external databases
55 * and then propagating references and features onto the sequence(s)
60 public class DBRefFetcher implements Runnable
62 private static final String NEWLINE = System.lineSeparator();
64 public static final String TRIM_RETRIEVED_SEQUENCES = "TRIM_FETCHED_DATASET_SEQS";
66 public interface FetchFinishedListenerI
73 IProgressIndicator progressWindow;
75 CutAndPasteTransfer output = new CutAndPasteTransfer();
77 boolean running = false;
80 * picr client instance
82 uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
84 // This will be a collection of Vectors of sequenceI refs.
85 // The key will be the seq name or accession id of the seq
86 Hashtable<String, Vector<SequenceI>> seqRefs;
88 DbSourceProxy[] dbSources;
90 SequenceFetcher sfetcher;
92 private List<FetchFinishedListenerI> listeners;
94 private SequenceI[] alseqs;
97 * when true - retrieved sequences will be trimmed to cover longest derived
100 private boolean trimDsSeqs = true;
103 * Creates a new DBRefFetcher object and fetches from the currently selected
104 * set of databases, if this is null then it fetches based on feature settings
107 * fetch references for these SequenceI array
108 * @param progressIndicatorFrame
109 * the frame for progress bar monitoring
111 * array of DbSourceProxy to query references form
112 * @param featureSettings
113 * FeatureSettings to get alternative DbSourceProxy from
114 * @param isNucleotide
115 * indicates if the array of SequenceI are Nucleotides or not
117 public DBRefFetcher(SequenceI[] seqs,
118 IProgressIndicator progressIndicatorFrame,
119 DbSourceProxy[] sources, FeatureSettings featureSettings,
120 boolean isNucleotide)
122 listeners = new ArrayList<>();
123 this.progressWindow = progressIndicatorFrame;
124 alseqs = new SequenceI[seqs.length];
125 SequenceI[] ds = new SequenceI[seqs.length];
126 for (int i = 0; i < seqs.length; i++)
129 if (seqs[i].getDatasetSequence() != null)
131 ds[i] = seqs[i].getDatasetSequence();
139 // TODO Jalview 2.5 lots of this code should be in the gui package!
140 sfetcher = jalview.gui.SequenceFetcher
141 .getSequenceFetcherSingleton(progressIndicatorFrame);
142 // set default behaviour for transferring excess sequence data to the
144 trimDsSeqs = Cache.getDefault(TRIM_RETRIEVED_SEQUENCES, true);
147 setDatabaseSources(featureSettings, isNucleotide);
151 // we assume the caller knows what they're doing and ensured that all the
152 // db source names are valid
158 * Helper method to configure the list of database sources to query
160 * @param featureSettings
161 * @param forNucleotide
163 void setDatabaseSources(FeatureSettings featureSettings,
164 boolean forNucleotide)
166 // af.featureSettings_actionPerformed(null);
167 String[] defdb = null;
168 List<DbSourceProxy> selsources = new ArrayList<>();
169 // select appropriate databases based on alignFrame context.
172 defdb = DBRefSource.DNACODINGDBS;
176 defdb = DBRefSource.PROTEINDBS;
178 List<DbSourceProxy> srces = new ArrayList<>();
179 for (String ddb : defdb)
181 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
182 if (srcesfordb != null)
184 for (DbSourceProxy src : srcesfordb)
186 if (!srces.contains(src))
188 srces.addAll(srcesfordb);
193 // append the PDB data source, since it is 'special', catering for both
194 // nucleotide and protein
195 // srces.addAll(sfetcher.getSourceProxy(DBRefSource.PDB));
197 srces.addAll(selsources);
198 dbSources = srces.toArray(new DbSourceProxy[srces.size()]);
202 * Constructor with only sequences provided
206 public DBRefFetcher(SequenceI[] sequences)
208 this(sequences, null, null, null, false);
212 * Add a listener to be notified when sequence fetching is complete
216 public void addListener(FetchFinishedListenerI l)
222 * start the fetcher thread
224 * @param waitTillFinished
225 * true to block until the fetcher has finished
227 public void fetchDBRefs(boolean waitTillFinished)
229 // TODO can we not simply write
230 // if (waitTillFinished) { run(); } else { new Thread(this).start(); }
232 Thread thread = new Thread(this);
236 if (waitTillFinished)
243 } catch (Exception ex)
251 * The sequence will be added to a vector of sequences belonging to key which
252 * could be either seq name or dbref id
259 void addSeqId(SequenceI seq, String key)
261 key = key.toUpperCase();
263 Vector<SequenceI> seqs;
264 if (seqRefs.containsKey(key))
266 seqs = seqRefs.get(key);
268 if (seqs != null && !seqs.contains(seq))
270 seqs.addElement(seq);
272 else if (seqs == null)
274 seqs = new Vector<>();
275 seqs.addElement(seq);
281 seqs = new Vector<>();
282 seqs.addElement(seq);
285 seqRefs.put(key, seqs);
294 if (dbSources == null)
296 throw new Error(MessageManager
297 .getString("error.implementation_error_must_init_dbsources"));
300 long startTime = System.currentTimeMillis();
301 if (progressWindow != null)
303 progressWindow.setProgressBar(
304 MessageManager.getString("status.fetching_db_refs"),
309 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
311 picrClient = new AccessionMapperServiceLocator()
312 .getAccessionMapperPort();
314 } catch (Exception e)
316 System.err.println("Couldn't locate PICR service instance.\n");
320 Vector<SequenceI> sdataset = new Vector<>(
321 Arrays.asList(dataset));
322 List<String> warningMessages = new ArrayList<>();
324 // clear any old feature display settings recorded from past sessions
325 featureDisplaySettings = null;
328 while (sdataset.size() > 0 && db < dbSources.length)
330 int maxqlen = 1; // default number of queries made at one time
331 System.out.println("Verifying against " + dbSources[db].getDbName());
333 // iterate through db for each remaining un-verified sequence
334 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
335 sdataset.copyInto(currSeqs);// seqs that are to be validated against
337 Vector<String> queries = new Vector<>(); // generated queries curSeq
338 seqRefs = new Hashtable<>();
342 DbSourceProxy dbsource = dbSources[db];
343 // for moment, we dumbly iterate over all retrieval sources for a
344 // particular database
345 // TODO: introduce multithread multisource queries and logic to remove a
346 // query from other sources if any source for a database returns a
348 maxqlen = dbsource.getMaximumQueryCount();
350 while (queries.size() > 0 || seqIndex < currSeqs.length)
352 if (queries.size() > 0)
354 // Still queries to make for current seqIndex
355 StringBuffer queryString = new StringBuffer("");
357 int nqSize = (maxqlen > queries.size()) ? queries.size()
360 while (queries.size() > 0 && numq < nqSize)
362 String query = queries.elementAt(0);
363 if (dbsource.isValidReference(query))
366 (numq == 0) ? "" : dbsource.getAccessionSeparator());
367 queryString.append(query);
370 // remove the extracted query string
371 queries.removeElementAt(0);
373 // make the queries and process the response
374 AlignmentI retrieved = null;
377 if (Cache.log.isDebugEnabled())
379 Cache.log.debug("Querying " + dbsource.getDbName()
380 + " with : '" + queryString.toString() + "'");
382 retrieved = dbsource.getSequenceRecords(queryString.toString());
383 } catch (Exception ex)
385 ex.printStackTrace();
386 } catch (OutOfMemoryError err)
388 new OOMWarning("retrieving database references ("
389 + queryString.toString() + ")", err);
391 if (retrieved != null)
393 transferReferences(sdataset, dbsource, retrieved,
394 trimDsSeqs, warningMessages);
399 // make some more strings for use as queries
400 for (int i = 0; (seqIndex < dataset.length)
401 && (i < 50); seqIndex++, i++)
403 SequenceI sequence = dataset[seqIndex];
404 DBRefEntry[] uprefs = DBRefUtils
405 .selectRefs(sequence.getDBRefs(), new String[]
406 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
408 // check for existing dbrefs to use
409 if (uprefs != null && uprefs.length > 0)
411 for (int j = 0; j < uprefs.length; j++)
413 addSeqId(sequence, uprefs[j].getAccessionId());
415 uprefs[j].getAccessionId().toUpperCase());
420 // generate queries from sequence ID string
421 StringTokenizer st = new StringTokenizer(sequence.getName(),
423 while (st.hasMoreTokens())
425 String token = st.nextToken();
426 UPEntry[] presp = null;
427 if (picrClient != null)
429 // resolve the string against PICR to recover valid IDs
432 presp = picrClient.getUPIForAccession(token, null,
433 picrClient.getMappedDatabaseNames(), null,
435 } catch (Exception e)
438 "Exception with Picr for '" + token + "'\n");
442 if (presp != null && presp.length > 0)
444 for (int id = 0; id < presp.length; id++)
446 // construct sequences from response if sequences are
447 // present, and do a transferReferences
448 // otherwise transfer non sequence x-references directly.
451 "Validated ID against PICR... (for what its worth):"
453 addSeqId(sequence, token);
454 queries.addElement(token.toUpperCase());
459 // System.out.println("Not querying source with
460 // token="+token+"\n");
461 addSeqId(sequence, token);
462 queries.addElement(token.toUpperCase());
469 // advance to next database
471 } // all databases have been queried
472 if (!warningMessages.isEmpty())
474 StringBuilder sb = new StringBuilder(warningMessages.size() * 30);
475 sb.append(MessageManager
476 .getString("label.your_sequences_have_been_verified"));
477 for (String msg : warningMessages)
479 sb.append(msg).append(NEWLINE);
481 output.setText(sb.toString());
483 Desktop.addInternalFrame(output,
484 MessageManager.getString("label.sequences_updated"), 600,
486 // The above is the dataset, we must now find out the index
487 // of the viewed sequence
490 if (progressWindow != null)
492 progressWindow.setProgressBar(
493 MessageManager.getString("label.dbref_search_completed"),
497 for (FetchFinishedListenerI listener : listeners)
505 * Verify local sequences in seqRefs against the retrieved sequence database
506 * records. Returns true if any sequence was modified as a result (start/end
507 * changed and/or sequence enlarged), else false.
510 * dataset sequences we are retrieving for
512 * database source we are retrieving from
514 * retrieved sequences as alignment
515 * @param trimDatasetSeqs
516 * if true, sequences will not be enlarged to match longer retrieved
517 * sequences, only their start/end adjusted
518 * @param warningMessages
519 * a list of messages to add to
521 boolean transferReferences(Vector<SequenceI> sdataset,
522 DbSourceProxy dbSourceProxy,
523 AlignmentI retrievedAl, boolean trimDatasetSeqs,
524 List<String> warningMessages)
526 // System.out.println("trimming ? " + trimDatasetSeqs);
527 if (retrievedAl == null || retrievedAl.getHeight() == 0)
532 String dbSource = dbSourceProxy.getDbName();
533 boolean modified = false;
534 SequenceI[] retrieved = recoverDbSequences(
535 retrievedAl.getSequencesArray());
536 SequenceI sequence = null;
538 for (SequenceI retrievedSeq : retrieved)
540 // Work out which sequences this sequence matches,
541 // taking into account all accessionIds and names in the file
542 Vector<SequenceI> sequenceMatches = new Vector<>();
543 // look for corresponding accession ids
544 DBRefEntry[] entryRefs = DBRefUtils
545 .selectRefs(retrievedSeq.getDBRefs(), new String[]
547 if (entryRefs == null)
550 .println("Dud dbSource string ? no entryrefs selected for "
551 + dbSource + " on " + retrievedSeq.getName());
554 for (int j = 0; j < entryRefs.length; j++)
556 String accessionId = entryRefs[j].getAccessionId();
557 // match up on accessionId
558 if (seqRefs.containsKey(accessionId.toUpperCase()))
560 Vector<SequenceI> seqs = seqRefs.get(accessionId);
561 for (int jj = 0; jj < seqs.size(); jj++)
563 sequence = seqs.elementAt(jj);
564 if (!sequenceMatches.contains(sequence))
566 sequenceMatches.addElement(sequence);
571 if (sequenceMatches.isEmpty())
573 // failed to match directly on accessionId==query so just compare all
574 // sequences to entry
575 Enumeration<String> e = seqRefs.keys();
576 while (e.hasMoreElements())
578 Vector<SequenceI> sqs = seqRefs.get(e.nextElement());
579 if (sqs != null && sqs.size() > 0)
581 Enumeration<SequenceI> sqe = sqs.elements();
582 while (sqe.hasMoreElements())
584 sequenceMatches.addElement(sqe.nextElement());
589 // look for corresponding names
590 // this is uniprot specific ?
591 // could be useful to extend this so we try to find any 'significant'
592 // information in common between two sequence objects.
594 * DBRefEntry[] entryRefs =
595 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
596 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
597 * name = entry.getName().elementAt(j).toString(); if
598 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
599 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
600 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
601 * sequenceMatches.addElement(sequence); } } } }
603 if (sequenceMatches.size() > 0)
605 addFeatureSettings(dbSourceProxy);
607 // sequenceMatches now contains the set of all sequences associated with
608 // the returned db record
609 final String retrievedSeqString = retrievedSeq.getSequenceAsString();
610 String entrySeq = retrievedSeqString.toUpperCase();
611 for (int m = 0; m < sequenceMatches.size(); m++)
613 sequence = sequenceMatches.elementAt(m);
614 // only update start and end positions and shift features if there are
615 // no existing references
616 // TODO: test for legacy where uniprot or EMBL refs exist but no
617 // mappings are made (but content matches retrieved set)
618 boolean updateRefFrame = sequence.getDBRefs() == null
619 || sequence.getDBRefs().length == 0;
621 // verify sequence against the entry sequence
624 final int sequenceStart = sequence.getStart();
626 boolean remoteEnclosesLocal = false;
627 String nonGapped = AlignSeq
628 .extractGaps("-. ", sequence.getSequenceAsString())
630 int absStart = entrySeq.indexOf(nonGapped);
633 // couldn't find local sequence in sequence from database, so check if
634 // the database sequence is a subsequence of local sequence
635 absStart = nonGapped.indexOf(entrySeq);
638 // verification failed. couldn't find any relationship between
639 // entrySeq and local sequence
640 // messages suppressed as many-to-many matches are confusing
641 // String msg = sequence.getName()
642 // + " Sequence not 100% match with "
643 // + retrievedSeq.getName();
644 // addWarningMessage(warningMessages, msg);
648 * retrieved sequence is a proper subsequence of local sequence
650 String msg = sequence.getName() + " has " + absStart
651 + " prefixed residues compared to "
652 + retrievedSeq.getName();
653 addWarningMessage(warningMessages, msg);
656 * So create a mapping to the external entry from the matching region of
657 * the local sequence, and leave local start/end untouched.
659 mp = new Mapping(null,
661 { sequenceStart + absStart,
662 sequenceStart + absStart + entrySeq.length() - 1 },
664 { retrievedSeq.getStart(),
665 retrievedSeq.getStart() + entrySeq.length() - 1 },
667 updateRefFrame = false;
672 * local sequence is a subsequence of (or matches) retrieved sequence
674 remoteEnclosesLocal = true;
680 * relocate existing sequence features by offset
682 int startShift = absStart - sequenceStart + 1;
685 modified |= sequence.getFeatures().shiftFeatures(1,
691 System.out.println("Adding dbrefs to " + sequence.getName()
692 + " from " + dbSource + " sequence : "
693 + retrievedSeq.getName());
694 sequence.transferAnnotation(retrievedSeq, mp);
696 absStart += retrievedSeq.getStart();
697 int absEnd = absStart + nonGapped.length() - 1;
698 if (!trimDatasetSeqs)
701 * update start position and/or expand to longer retrieved sequence
703 if (!retrievedSeqString.equals(sequence.getSequenceAsString())
704 && remoteEnclosesLocal)
706 sequence.setSequence(retrievedSeqString);
708 addWarningMessage(warningMessages,
709 "Sequence for " + sequence.getName() + " expanded from "
710 + retrievedSeq.getName());
712 if (sequence.getStart() != retrievedSeq.getStart())
714 sequence.setStart(retrievedSeq.getStart());
716 if (absStart != sequenceStart)
718 addWarningMessage(warningMessages,
719 "Start/end position for " + sequence.getName()
720 + " updated from " + retrievedSeq.getName());
726 // finally, update local sequence reference frame if we're allowed
729 // just fix start/end
730 if (sequence.getStart() != absStart
731 || sequence.getEnd() != absEnd)
733 sequence.setStart(absStart);
734 sequence.setEnd(absEnd);
736 addWarningMessage(warningMessages,
737 "Start/end for " + sequence.getName()
738 + " updated from " + retrievedSeq.getName());
741 // search for alignment sequences to update coordinate frame for
742 for (int alsq = 0; alsq < alseqs.length; alsq++)
744 if (alseqs[alsq].getDatasetSequence() == sequence)
746 String ngAlsq = AlignSeq
748 alseqs[alsq].getSequenceAsString())
750 int oldstrt = alseqs[alsq].getStart();
751 alseqs[alsq].setStart(sequence.getSequenceAsString()
752 .toUpperCase().indexOf(ngAlsq) + sequence.getStart());
753 if (oldstrt != alseqs[alsq].getStart())
756 ngAlsq.length() + alseqs[alsq].getStart() - 1);
761 // TODO: search for all other references to this dataset sequence, and
763 // TODO: update all AlCodonMappings which involve this alignment
764 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
767 // and remove it from the rest
768 // TODO: decide if we should remove annotated sequence from set
769 sdataset.remove(sequence);
775 Map<String, FeatureSettingsModelI> featureDisplaySettings = null;
777 private void addFeatureSettings(DbSourceProxy dbSourceProxy)
779 FeatureSettingsModelI fsettings = dbSourceProxy
780 .getFeatureColourScheme();
781 if (fsettings != null)
783 if (featureDisplaySettings == null)
785 featureDisplaySettings = new HashMap<>();
787 featureDisplaySettings.put(dbSourceProxy.getDbName(), fsettings);
793 * @return any feature settings associated with sources that have provided sequences
795 public List<FeatureSettingsModelI>getFeatureSettingsModels()
797 return featureDisplaySettings == null
798 ? Arrays.asList(new FeatureSettingsModelI[0])
799 : Arrays.asList(featureDisplaySettings.values()
800 .toArray(new FeatureSettingsModelI[1]));
803 * Adds the message to the list unless it already contains it
808 void addWarningMessage(List<String> messageList, String msg)
810 if (!messageList.contains(msg))
812 messageList.add(msg);
817 * loop thru and collect additional sequences in Map.
819 * @param sequencesArray
822 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
824 Vector<SequenceI> nseq = new Vector<>();
825 for (int i = 0; sequencesArray != null
826 && i < sequencesArray.length; i++)
828 nseq.addElement(sequencesArray[i]);
829 DBRefEntry[] dbr = sequencesArray[i].getDBRefs();
831 for (int r = 0; (dbr != null) && r < dbr.length; r++)
833 if ((map = dbr[r].getMap()) != null)
835 if (map.getTo() != null && !nseq.contains(map.getTo()))
837 nseq.addElement(map.getTo());
844 sequencesArray = new SequenceI[nseq.size()];
845 nseq.toArray(sequencesArray);
847 return sequencesArray;