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.DasSourceBrowser;
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.dbsources.das.api.jalviewSourceI;
39 import jalview.ws.dbsources.das.datamodel.DasSequenceSource;
40 import jalview.ws.seqfetcher.DbSourceProxy;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Enumeration;
45 import java.util.Hashtable;
46 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<FetchFinishedListenerI>();
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<DbSourceProxy>();
169 Vector<jalviewSourceI> dasselsrc = (featureSettings != null)
170 ? featureSettings.getSelectedSources()
171 : new DasSourceBrowser().getSelectedSources();
173 for (jalviewSourceI src : dasselsrc)
175 List<DbSourceProxy> sp = src.getSequenceSourceProxies();
178 selsources.addAll(sp);
181 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
185 // select appropriate databases based on alignFrame context.
188 defdb = DBRefSource.DNACODINGDBS;
192 defdb = DBRefSource.PROTEINDBS;
194 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
195 for (String ddb : defdb)
197 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
198 if (srcesfordb != null)
200 for (DbSourceProxy src : srcesfordb)
202 if (!srces.contains(src))
204 srces.addAll(srcesfordb);
209 // append the PDB data source, since it is 'special', catering for both
210 // nucleotide and protein
211 // srces.addAll(sfetcher.getSourceProxy(DBRefSource.PDB));
213 srces.addAll(selsources);
214 dbSources = srces.toArray(new DbSourceProxy[srces.size()]);
218 * Constructor with only sequences provided
222 public DBRefFetcher(SequenceI[] sequences)
224 this(sequences, null, null, null, false);
228 * Add a listener to be notified when sequence fetching is complete
232 public void addListener(FetchFinishedListenerI l)
238 * retrieve all the das sequence sources and add them to the list of db
239 * sources to retrieve from
241 public void appendAllDasSources()
243 if (dbSources == null)
245 dbSources = new DbSourceProxy[0];
247 // append additional sources
248 DbSourceProxy[] otherdb = sfetcher
249 .getDbSourceProxyInstances(DasSequenceSource.class);
250 if (otherdb != null && otherdb.length > 0)
252 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
254 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
255 System.arraycopy(otherdb, 0, newsrc, dbSources.length,
262 * start the fetcher thread
264 * @param waitTillFinished
265 * true to block until the fetcher has finished
267 public void fetchDBRefs(boolean waitTillFinished)
269 // TODO can we not simply write
270 // if (waitTillFinished) { run(); } else { new Thread(this).start(); }
272 Thread thread = new Thread(this);
276 if (waitTillFinished)
283 } catch (Exception ex)
291 * The sequence will be added to a vector of sequences belonging to key which
292 * could be either seq name or dbref id
299 void addSeqId(SequenceI seq, String key)
301 key = key.toUpperCase();
303 Vector<SequenceI> seqs;
304 if (seqRefs.containsKey(key))
306 seqs = seqRefs.get(key);
308 if (seqs != null && !seqs.contains(seq))
310 seqs.addElement(seq);
312 else if (seqs == null)
314 seqs = new Vector<SequenceI>();
315 seqs.addElement(seq);
321 seqs = new Vector<SequenceI>();
322 seqs.addElement(seq);
325 seqRefs.put(key, seqs);
334 if (dbSources == null)
336 throw new Error(MessageManager
337 .getString("error.implementation_error_must_init_dbsources"));
340 long startTime = System.currentTimeMillis();
341 if (progressWindow != null)
343 progressWindow.setProgressBar(
344 MessageManager.getString("status.fetching_db_refs"),
349 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
351 picrClient = new AccessionMapperServiceLocator()
352 .getAccessionMapperPort();
354 } catch (Exception e)
356 System.err.println("Couldn't locate PICR service instance.\n");
360 Vector<SequenceI> sdataset = new Vector<SequenceI>(
361 Arrays.asList(dataset));
362 List<String> warningMessages = new ArrayList<String>();
365 while (sdataset.size() > 0 && db < dbSources.length)
367 int maxqlen = 1; // default number of queries made at one time
368 System.out.println("Verifying against " + dbSources[db].getDbName());
370 // iterate through db for each remaining un-verified sequence
371 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
372 sdataset.copyInto(currSeqs);// seqs that are to be validated against
374 Vector<String> queries = new Vector<String>(); // generated queries curSeq
375 seqRefs = new Hashtable<String, Vector<SequenceI>>();
379 DbSourceProxy dbsource = dbSources[db];
380 // for moment, we dumbly iterate over all retrieval sources for a
381 // particular database
382 // TODO: introduce multithread multisource queries and logic to remove a
383 // query from other sources if any source for a database returns a
385 maxqlen = dbsource.getMaximumQueryCount();
387 while (queries.size() > 0 || seqIndex < currSeqs.length)
389 if (queries.size() > 0)
391 // Still queries to make for current seqIndex
392 StringBuffer queryString = new StringBuffer("");
394 int nqSize = (maxqlen > queries.size()) ? queries.size()
397 while (queries.size() > 0 && numq < nqSize)
399 String query = queries.elementAt(0);
400 if (dbsource.isValidReference(query))
403 (numq == 0) ? "" : dbsource.getAccessionSeparator());
404 queryString.append(query);
407 // remove the extracted query string
408 queries.removeElementAt(0);
410 // make the queries and process the response
411 AlignmentI retrieved = null;
414 if (Cache.log.isDebugEnabled())
416 Cache.log.debug("Querying " + dbsource.getDbName()
417 + " with : '" + queryString.toString() + "'");
419 retrieved = dbsource.getSequenceRecords(queryString.toString());
420 } catch (Exception ex)
422 ex.printStackTrace();
423 } catch (OutOfMemoryError err)
425 new OOMWarning("retrieving database references ("
426 + queryString.toString() + ")", err);
428 if (retrieved != null)
430 transferReferences(sdataset, dbsource.getDbSource(), retrieved,
431 trimDsSeqs, warningMessages);
436 // make some more strings for use as queries
437 for (int i = 0; (seqIndex < dataset.length)
438 && (i < 50); seqIndex++, i++)
440 SequenceI sequence = dataset[seqIndex];
441 DBRefEntry[] uprefs = DBRefUtils
442 .selectRefs(sequence.getDBRefs(), new String[]
443 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
445 // check for existing dbrefs to use
446 if (uprefs != null && uprefs.length > 0)
448 for (int j = 0; j < uprefs.length; j++)
450 addSeqId(sequence, uprefs[j].getAccessionId());
452 uprefs[j].getAccessionId().toUpperCase());
457 // generate queries from sequence ID string
458 StringTokenizer st = new StringTokenizer(sequence.getName(),
460 while (st.hasMoreTokens())
462 String token = st.nextToken();
463 UPEntry[] presp = null;
464 if (picrClient != null)
466 // resolve the string against PICR to recover valid IDs
469 presp = picrClient.getUPIForAccession(token, null,
470 picrClient.getMappedDatabaseNames(), null,
472 } catch (Exception e)
475 "Exception with Picr for '" + token + "'\n");
479 if (presp != null && presp.length > 0)
481 for (int id = 0; id < presp.length; id++)
483 // construct sequences from response if sequences are
484 // present, and do a transferReferences
485 // otherwise transfer non sequence x-references directly.
488 "Validated ID against PICR... (for what its worth):"
490 addSeqId(sequence, token);
491 queries.addElement(token.toUpperCase());
496 // System.out.println("Not querying source with
497 // token="+token+"\n");
498 addSeqId(sequence, token);
499 queries.addElement(token.toUpperCase());
506 // advance to next database
508 } // all databases have been queried
509 if (!warningMessages.isEmpty())
511 StringBuilder sb = new StringBuilder(warningMessages.size() * 30);
512 sb.append(MessageManager
513 .getString("label.your_sequences_have_been_verified"));
514 for (String msg : warningMessages)
516 sb.append(msg).append(NEWLINE);
518 output.setText(sb.toString());
520 Desktop.addInternalFrame(output,
521 MessageManager.getString("label.sequences_updated"), 600,
523 // The above is the dataset, we must now find out the index
524 // of the viewed sequence
527 if (progressWindow != null)
529 progressWindow.setProgressBar(
530 MessageManager.getString("label.dbref_search_completed"),
534 for (FetchFinishedListenerI listener : listeners)
542 * Verify local sequences in seqRefs against the retrieved sequence database
543 * records. Returns true if any sequence was modified as a result (start/end
544 * changed and/or sequence enlarged), else false.
547 * dataset sequences we are retrieving for
549 * database source we are retrieving from
551 * retrieved sequences as alignment
552 * @param trimDatasetSeqs
553 * if true, sequences will not be enlarged to match longer retrieved
554 * sequences, only their start/end adjusted
555 * @param warningMessages
556 * a list of messages to add to
558 boolean transferReferences(Vector<SequenceI> sdataset, String dbSource,
559 AlignmentI retrievedAl, boolean trimDatasetSeqs,
560 List<String> warningMessages)
562 // System.out.println("trimming ? " + trimDatasetSeqs);
563 if (retrievedAl == null || retrievedAl.getHeight() == 0)
568 boolean modified = false;
569 SequenceI[] retrieved = recoverDbSequences(
570 retrievedAl.getSequencesArray());
571 SequenceI sequence = null;
573 for (SequenceI retrievedSeq : retrieved)
575 // Work out which sequences this sequence matches,
576 // taking into account all accessionIds and names in the file
577 Vector<SequenceI> sequenceMatches = new Vector<SequenceI>();
578 // look for corresponding accession ids
579 DBRefEntry[] entryRefs = DBRefUtils
580 .selectRefs(retrievedSeq.getDBRefs(), new String[]
582 if (entryRefs == null)
585 .println("Dud dbSource string ? no entryrefs selected for "
586 + dbSource + " on " + retrievedSeq.getName());
589 for (int j = 0; j < entryRefs.length; j++)
591 String accessionId = entryRefs[j].getAccessionId();
592 // match up on accessionId
593 if (seqRefs.containsKey(accessionId.toUpperCase()))
595 Vector<SequenceI> seqs = seqRefs.get(accessionId);
596 for (int jj = 0; jj < seqs.size(); jj++)
598 sequence = seqs.elementAt(jj);
599 if (!sequenceMatches.contains(sequence))
601 sequenceMatches.addElement(sequence);
606 if (sequenceMatches.isEmpty())
608 // failed to match directly on accessionId==query so just compare all
609 // sequences to entry
610 Enumeration<String> e = seqRefs.keys();
611 while (e.hasMoreElements())
613 Vector<SequenceI> sqs = seqRefs.get(e.nextElement());
614 if (sqs != null && sqs.size() > 0)
616 Enumeration<SequenceI> sqe = sqs.elements();
617 while (sqe.hasMoreElements())
619 sequenceMatches.addElement(sqe.nextElement());
624 // look for corresponding names
625 // this is uniprot specific ?
626 // could be useful to extend this so we try to find any 'significant'
627 // information in common between two sequence objects.
629 * DBRefEntry[] entryRefs =
630 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
631 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
632 * name = entry.getName().elementAt(j).toString(); if
633 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
634 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
635 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
636 * sequenceMatches.addElement(sequence); } } } }
638 // sequenceMatches now contains the set of all sequences associated with
639 // the returned db record
640 final String retrievedSeqString = retrievedSeq.getSequenceAsString();
641 String entrySeq = retrievedSeqString.toUpperCase();
642 for (int m = 0; m < sequenceMatches.size(); m++)
644 sequence = sequenceMatches.elementAt(m);
645 // only update start and end positions and shift features if there are
646 // no existing references
647 // TODO: test for legacy where uniprot or EMBL refs exist but no
648 // mappings are made (but content matches retrieved set)
649 boolean updateRefFrame = sequence.getDBRefs() == null
650 || sequence.getDBRefs().length == 0;
652 // verify sequence against the entry sequence
655 final int sequenceStart = sequence.getStart();
657 boolean remoteEnclosesLocal = false;
658 String nonGapped = AlignSeq
659 .extractGaps("-. ", sequence.getSequenceAsString())
661 int absStart = entrySeq.indexOf(nonGapped);
664 // couldn't find local sequence in sequence from database, so check if
665 // the database sequence is a subsequence of local sequence
666 absStart = nonGapped.indexOf(entrySeq);
669 // verification failed. couldn't find any relationship between
670 // entrySeq and local sequence
671 // messages suppressed as many-to-many matches are confusing
672 // String msg = sequence.getName()
673 // + " Sequence not 100% match with "
674 // + retrievedSeq.getName();
675 // addWarningMessage(warningMessages, msg);
679 * retrieved sequence is a proper subsequence of local sequence
681 String msg = sequence.getName() + " has " + absStart
682 + " prefixed residues compared to "
683 + retrievedSeq.getName();
684 addWarningMessage(warningMessages, msg);
687 * So create a mapping to the external entry from the matching region of
688 * the local sequence, and leave local start/end untouched.
690 mp = new Mapping(null,
692 { sequenceStart + absStart,
693 sequenceStart + absStart + entrySeq.length() - 1 },
695 { retrievedSeq.getStart(),
696 retrievedSeq.getStart() + entrySeq.length() - 1 },
698 updateRefFrame = false;
703 * local sequence is a subsequence of (or matches) retrieved sequence
705 remoteEnclosesLocal = true;
711 * relocate existing sequence features by offset
713 int startShift = absStart - sequenceStart + 1;
716 modified |= sequence.getFeatures().shiftFeatures(startShift);
721 System.out.println("Adding dbrefs to " + sequence.getName()
722 + " from " + dbSource + " sequence : "
723 + retrievedSeq.getName());
724 sequence.transferAnnotation(retrievedSeq, mp);
726 absStart += retrievedSeq.getStart();
727 int absEnd = absStart + nonGapped.length() - 1;
728 if (!trimDatasetSeqs)
731 * update start position and/or expand to longer retrieved sequence
733 if (!retrievedSeqString.equals(sequence.getSequenceAsString())
734 && remoteEnclosesLocal)
736 sequence.setSequence(retrievedSeqString);
738 addWarningMessage(warningMessages,
739 "Sequence for " + sequence.getName() + " expanded from "
740 + retrievedSeq.getName());
742 if (sequence.getStart() != retrievedSeq.getStart())
744 sequence.setStart(retrievedSeq.getStart());
746 if (absStart != sequenceStart)
748 addWarningMessage(warningMessages,
749 "Start/end position for " + sequence.getName()
750 + " updated from " + retrievedSeq.getName());
756 // finally, update local sequence reference frame if we're allowed
759 // just fix start/end
760 if (sequence.getStart() != absStart
761 || sequence.getEnd() != absEnd)
763 sequence.setStart(absStart);
764 sequence.setEnd(absEnd);
766 addWarningMessage(warningMessages,
767 "Start/end for " + sequence.getName()
768 + " updated from " + retrievedSeq.getName());
771 // search for alignment sequences to update coordinate frame for
772 for (int alsq = 0; alsq < alseqs.length; alsq++)
774 if (alseqs[alsq].getDatasetSequence() == sequence)
776 String ngAlsq = AlignSeq
778 alseqs[alsq].getSequenceAsString())
780 int oldstrt = alseqs[alsq].getStart();
781 alseqs[alsq].setStart(sequence.getSequenceAsString()
782 .toUpperCase().indexOf(ngAlsq) + sequence.getStart());
783 if (oldstrt != alseqs[alsq].getStart())
786 ngAlsq.length() + alseqs[alsq].getStart() - 1);
791 // TODO: search for all other references to this dataset sequence, and
793 // TODO: update all AlCodonMappings which involve this alignment
794 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
797 // and remove it from the rest
798 // TODO: decide if we should remove annotated sequence from set
799 sdataset.remove(sequence);
800 // TODO: should we make a note of sequences that have received new DB
801 // ids, so we can query all enabled DAS servers for them ?
808 * Adds the message to the list unless it already contains it
813 void addWarningMessage(List<String> messageList, String msg)
815 if (!messageList.contains(msg))
817 messageList.add(msg);
822 * loop thru and collect additional sequences in Map.
824 * @param sequencesArray
827 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
829 Vector<SequenceI> nseq = new Vector<SequenceI>();
830 for (int i = 0; sequencesArray != null
831 && i < sequencesArray.length; i++)
833 nseq.addElement(sequencesArray[i]);
834 DBRefEntry[] dbr = sequencesArray[i].getDBRefs();
836 for (int r = 0; (dbr != null) && r < dbr.length; r++)
838 if ((map = dbr[r].getMap()) != null)
840 if (map.getTo() != null && !nseq.contains(map.getTo()))
842 nseq.addElement(map.getTo());
849 sequencesArray = new SequenceI[nseq.size()];
850 nseq.toArray(sequencesArray);
852 return sequencesArray;