2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3 * Copyright (C) 2014 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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 import jalview.analysis.AlignSeq;
22 import jalview.bin.Cache;
23 import jalview.datamodel.AlignmentI;
24 import jalview.datamodel.DBRefEntry;
25 import jalview.datamodel.DBRefSource;
26 import jalview.datamodel.Mapping;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.CutAndPasteTransfer;
31 import jalview.gui.Desktop;
32 import jalview.gui.IProgressIndicator;
33 import jalview.gui.OOMWarning;
34 import jalview.util.MessageManager;
35 import jalview.ws.dbsources.das.api.jalviewSourceI;
36 import jalview.ws.seqfetcher.DbSourceProxy;
38 import java.util.ArrayList;
39 import java.util.Enumeration;
40 import java.util.Hashtable;
41 import java.util.List;
42 import java.util.StringTokenizer;
43 import java.util.Vector;
45 import uk.ac.ebi.picr.model.UPEntry;
48 * Implements a runnable for validating a sequence against external databases
49 * and then propagating references and features onto the sequence(s)
54 public class DBRefFetcher implements Runnable
58 IProgressIndicator af;
60 CutAndPasteTransfer output = new CutAndPasteTransfer();
62 StringBuffer sbuffer = new StringBuffer();
64 boolean running = false;
67 * picr client instance
69 uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
71 // /This will be a collection of Vectors of sequenceI refs.
72 // The key will be the seq name or accession id of the seq
75 DbSourceProxy[] dbSources;
77 SequenceFetcher sfetcher;
79 private SequenceI[] alseqs;
86 * Creates a new SequenceFeatureFetcher object and fetches from the currently
87 * selected set of databases.
90 * fetch references for these sequences
92 * the parent alignframe for progress bar monitoring.
94 public DBRefFetcher(SequenceI[] seqs, AlignFrame af)
100 * Creates a new SequenceFeatureFetcher object and fetches from the currently
101 * selected set of databases.
104 * fetch references for these sequences
106 * the parent alignframe for progress bar monitoring.
108 * array of database source strings to query references from
110 public DBRefFetcher(SequenceI[] seqs, AlignFrame af,
111 DbSourceProxy[] sources)
114 alseqs = new SequenceI[seqs.length];
115 SequenceI[] ds = new SequenceI[seqs.length];
116 for (int i = 0; i < seqs.length; i++)
119 if (seqs[i].getDatasetSequence() != null)
120 ds[i] = seqs[i].getDatasetSequence();
125 // TODO Jalview 2.5 lots of this code should be in the gui package!
126 sfetcher = jalview.gui.SequenceFetcher.getSequenceFetcherSingleton(af);
129 // af.featureSettings_actionPerformed(null);
130 String[] defdb = null, otherdb = sfetcher
131 .getDbInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
132 List<DbSourceProxy> selsources = new ArrayList<DbSourceProxy>();
133 Vector dasselsrc = (af.featureSettings != null) ? af.featureSettings
134 .getSelectedSources() : new jalview.gui.DasSourceBrowser()
135 .getSelectedSources();
136 Enumeration<jalviewSourceI> en = dasselsrc.elements();
137 while (en.hasMoreElements())
139 jalviewSourceI src = en.nextElement();
140 List<DbSourceProxy> sp = src.getSequenceSourceProxies();
143 selsources.addAll(sp);
146 Cache.log.debug("Added many Db Sources for :" + src.getTitle());
150 // select appropriate databases based on alignFrame context.
151 if (af.getViewport().getAlignment().isNucleotide())
153 defdb = DBRefSource.DNACODINGDBS;
157 defdb = DBRefSource.PROTEINDBS;
159 List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
160 for (String ddb : defdb)
162 List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
163 if (srcesfordb != null)
165 srces.addAll(srcesfordb);
169 // append the selected sequence sources to the default dbs
170 srces.addAll(selsources);
171 dbSources = srces.toArray(new DbSourceProxy[0]);
175 // we assume the caller knows what they're doing and ensured that all the
176 // db source names are valid
182 * retrieve all the das sequence sources and add them to the list of db
183 * sources to retrieve from
185 public void appendAllDasSources()
187 if (dbSources == null)
189 dbSources = new DbSourceProxy[0];
191 // append additional sources
192 DbSourceProxy[] otherdb = sfetcher
193 .getDbSourceProxyInstances(jalview.ws.dbsources.das.datamodel.DasSequenceSource.class);
194 if (otherdb != null && otherdb.length > 0)
196 DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
198 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
199 System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
205 * start the fetcher thread
207 * @param waitTillFinished
208 * true to block until the fetcher has finished
210 public void fetchDBRefs(boolean waitTillFinished)
212 Thread thread = new Thread(this);
216 if (waitTillFinished)
223 } catch (Exception ex)
231 * The sequence will be added to a vector of sequences belonging to key which
232 * could be either seq name or dbref id
239 void addSeqId(SequenceI seq, String key)
241 key = key.toUpperCase();
244 if (seqRefs.containsKey(key))
246 seqs = (Vector) seqRefs.get(key);
248 if (seqs != null && !seqs.contains(seq))
250 seqs.addElement(seq);
252 else if (seqs == null)
255 seqs.addElement(seq);
262 seqs.addElement(seq);
265 seqRefs.put(key, seqs);
273 if (dbSources == null)
275 throw new Error("Implementation error. Must initialise dbSources");
278 long startTime = System.currentTimeMillis();
279 af.setProgressBar("Fetching db refs", startTime);
282 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
284 picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
285 .getAccessionMapperPort();
287 } catch (Exception e)
289 System.err.println("Couldn't locate PICR service instance.\n");
293 Vector sdataset = new Vector();
294 for (int s = 0; s < dataset.length; s++)
296 sdataset.addElement(dataset[s]);
298 while (sdataset.size() > 0 && db < dbSources.length)
300 int maxqlen = 1; // default number of queries made to at one time
301 System.err.println("Verifying against " + dbSources[db].getDbName());
304 // iterate through db for each remaining un-verified sequence
305 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
306 sdataset.copyInto(currSeqs);// seqs that are to be validated against
308 Vector queries = new Vector(); // generated queries curSeq
309 seqRefs = new Hashtable();
313 jalview.ws.seqfetcher.DbSourceProxy dbsource = dbSources[db];
315 // for moment, we dumbly iterate over all retrieval sources for a
316 // particular database
317 // TODO: introduce multithread multisource queries and logic to remove a
318 // query from other sources if any source for a database returns a
320 if (dbsource.getDbSourceProperties().containsKey(
321 DBRefSource.MULTIACC))
323 maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
324 DBRefSource.MULTIACC)).intValue();
330 while (queries.size() > 0 || seqIndex < currSeqs.length)
332 if (queries.size() > 0)
334 // Still queries to make for current seqIndex
335 StringBuffer queryString = new StringBuffer("");
336 int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
339 while (queries.size() > 0 && numq < nqSize)
341 String query = (String) queries.elementAt(0);
342 if (dbsource.isValidReference(query))
344 queryString.append((numq == 0) ? "" : dbsource
345 .getAccessionSeparator());
346 queryString.append(query);
349 // remove the extracted query string
350 queries.removeElementAt(0);
352 // make the queries and process the response
353 AlignmentI retrieved = null;
356 if (jalview.bin.Cache.log.isDebugEnabled())
358 jalview.bin.Cache.log.debug("Querying "
359 + dbsource.getDbName() + " with : '"
360 + queryString.toString() + "'");
362 retrieved = dbsource.getSequenceRecords(queryString
364 } catch (Exception ex)
366 ex.printStackTrace();
367 } catch (OutOfMemoryError err)
369 new OOMWarning("retrieving database references ("
370 + queryString.toString() + ")", err);
372 if (retrieved != null)
374 transferReferences(sdataset, dbsource.getDbSource(),
380 // make some more strings for use as queries
381 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
383 SequenceI sequence = dataset[seqIndex];
384 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
385 sequence.getDBRef(), new String[]
386 { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
388 // check for existing dbrefs to use
389 if (uprefs != null && uprefs.length > 0)
391 for (int j = 0; j < uprefs.length; j++)
393 addSeqId(sequence, uprefs[j].getAccessionId());
394 queries.addElement(uprefs[j].getAccessionId()
400 // generate queries from sequence ID string
401 StringTokenizer st = new StringTokenizer(
402 sequence.getName(), "|");
403 while (st.hasMoreTokens())
405 String token = st.nextToken();
406 UPEntry[] presp = null;
407 if (picrClient != null)
409 // resolve the string against PICR to recover valid IDs
412 presp = picrClient.getUPIForAccession(token, null,
413 picrClient.getMappedDatabaseNames(), null,
415 } catch (Exception e)
417 System.err.println("Exception with Picr for '"
422 if (presp != null && presp.length > 0)
424 for (int id = 0; id < presp.length; id++)
426 // construct sequences from response if sequences are
427 // present, and do a transferReferences
428 // otherwise transfer non sequence x-references directly.
431 .println("Validated ID against PICR... (for what its worth):"
433 addSeqId(sequence, token);
434 queries.addElement(token.toUpperCase());
439 // System.out.println("Not querying source with token="+token+"\n");
440 addSeqId(sequence, token);
441 queries.addElement(token.toUpperCase());
449 // advance to next database
451 } // all databases have been queries.
452 if (sbuffer.length() > 0)
454 output.setText(MessageManager.getString("label.your_sequences_have_been_verified")
455 + sbuffer.toString());
456 Desktop.addInternalFrame(output, MessageManager.getString("label.sequence_names_updated"), 600, 300);
457 // The above is the dataset, we must now find out the index
458 // of the viewed sequence
462 af.setProgressBar(MessageManager.getString("label.dbref_search_completed"), startTime);
463 // promptBeforeBlast();
470 * Verify local sequences in seqRefs against the retrieved sequence database
474 void transferReferences(Vector sdataset, String dbSource,
475 AlignmentI retrievedAl) // File
478 if (retrievedAl == null || retrievedAl.getHeight() == 0)
482 SequenceI[] retrieved = recoverDbSequences(retrievedAl
483 .getSequencesArray());
484 SequenceI sequence = null;
485 boolean transferred = false;
486 StringBuffer messages = new StringBuffer();
488 // Vector entries = new Uniprot().getUniprotEntries(file);
490 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
491 // UniprotEntry entry;
492 for (i = 0; i < iSize; i++)
494 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
496 // Work out which sequences this sequence matches,
497 // taking into account all accessionIds and names in the file
498 Vector sequenceMatches = new Vector();
499 // look for corresponding accession ids
500 DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
501 entry.getDBRef(), new String[]
503 if (entryRefs == null)
506 .println("Dud dbSource string ? no entryrefs selected for "
507 + dbSource + " on " + entry.getName());
510 for (int j = 0; j < entryRefs.length; j++)
512 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
513 // match up on accessionId
514 if (seqRefs.containsKey(accessionId.toUpperCase()))
516 Vector seqs = (Vector) seqRefs.get(accessionId);
517 for (int jj = 0; jj < seqs.size(); jj++)
519 sequence = (SequenceI) seqs.elementAt(jj);
520 if (!sequenceMatches.contains(sequence))
522 sequenceMatches.addElement(sequence);
527 if (sequenceMatches.size() == 0)
529 // failed to match directly on accessionId==query so just compare all
530 // sequences to entry
531 Enumeration e = seqRefs.keys();
532 while (e.hasMoreElements())
534 Vector sqs = (Vector) seqRefs.get(e.nextElement());
535 if (sqs != null && sqs.size() > 0)
537 Enumeration sqe = sqs.elements();
538 while (sqe.hasMoreElements())
540 sequenceMatches.addElement(sqe.nextElement());
545 // look for corresponding names
546 // this is uniprot specific ?
547 // could be useful to extend this so we try to find any 'significant'
548 // information in common between two sequence objects.
550 * DBRefEntry[] entryRefs =
551 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
552 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
553 * name = entry.getName().elementAt(j).toString(); if
554 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
555 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
556 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
557 * sequenceMatches.addElement(sequence); } } } }
559 // sequenceMatches now contains the set of all sequences associated with
560 // the returned db record
561 String entrySeq = entry.getSequenceAsString().toUpperCase();
562 for (int m = 0; m < sequenceMatches.size(); m++)
564 sequence = (SequenceI) sequenceMatches.elementAt(m);
565 // only update start and end positions and shift features if there are
566 // no existing references
567 // TODO: test for legacy where uniprot or EMBL refs exist but no
568 // mappings are made (but content matches retrieved set)
569 boolean updateRefFrame = sequence.getDBRef() == null
570 || sequence.getDBRef().length == 0;
571 // verify sequence against the entry sequence
573 String nonGapped = AlignSeq.extractGaps("-. ",
574 sequence.getSequenceAsString()).toUpperCase();
576 int absStart = entrySeq.indexOf(nonGapped);
577 int mapStart = entry.getStart();
578 jalview.datamodel.Mapping mp;
582 // Is local sequence contained in dataset sequence?
583 absStart = nonGapped.indexOf(entrySeq);
585 { // verification failed.
586 messages.append(sequence.getName()
587 + " SEQUENCE NOT %100 MATCH \n");
591 sbuffer.append(sequence.getName() + " HAS " + absStart
592 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
594 // + " - ANY SEQUENCE FEATURES"
595 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
597 // create valid mapping between matching region of local sequence and
598 // the mapped sequence
599 mp = new Mapping(null, new int[]
600 { sequence.getStart() + absStart,
601 sequence.getStart() + absStart + entrySeq.length() - 1 },
604 entry.getStart() + entrySeq.length() - 1 }, 1, 1);
605 updateRefFrame = false; // mapping is based on current start/end so
606 // don't modify start and end
611 // update start and end of local sequence to place it in entry's
613 // apply identity map map from whole of local sequence to matching
614 // region of database
616 mp = null; // Mapping.getIdentityMap();
618 // new int[] { absStart+sequence.getStart(),
619 // absStart+sequence.getStart()+entrySeq.length()-1},
620 // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
621 // relocate local features for updated start
624 if (sequence.getSequenceFeatures() != null)
626 SequenceFeature[] sf = sequence.getSequenceFeatures();
627 int start = sequence.getStart();
628 int end = sequence.getEnd();
629 int startShift = 1 - absStart - start; // how much the features
632 for (int sfi = 0; sfi < sf.length; sfi++)
634 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
636 // shift feature along by absstart
637 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
638 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
645 System.out.println("Adding dbrefs to " + sequence.getName()
646 + " from " + dbSource + " sequence : " + entry.getName());
647 sequence.transferAnnotation(entry, mp);
648 // unknownSequences.remove(sequence);
649 int absEnd = absStart + nonGapped.length();
653 // finally, update local sequence reference frame if we're allowed
654 sequence.setStart(absStart);
655 sequence.setEnd(absEnd);
656 // search for alignment sequences to update coordinate frame for
657 for (int alsq = 0; alsq < alseqs.length; alsq++)
659 if (alseqs[alsq].getDatasetSequence() == sequence)
661 String ngAlsq = AlignSeq.extractGaps("-. ",
662 alseqs[alsq].getSequenceAsString()).toUpperCase();
663 int oldstrt = alseqs[alsq].getStart();
664 alseqs[alsq].setStart(sequence.getSequenceAsString()
665 .toUpperCase().indexOf(ngAlsq)
666 + sequence.getStart());
667 if (oldstrt != alseqs[alsq].getStart())
669 alseqs[alsq].setEnd(ngAlsq.length()
670 + alseqs[alsq].getStart() - 1);
674 // TODO: search for all other references to this dataset sequence, and
676 // TODO: update all AlCodonMappings which involve this alignment
677 // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
680 // and remove it from the rest
681 // TODO: decide if we should remove annotated sequence from set
682 sdataset.remove(sequence);
683 // TODO: should we make a note of sequences that have received new DB
684 // ids, so we can query all enabled DAS servers for them ?
689 // report the ID/sequence mismatches
690 sbuffer.append(messages);
695 * loop thru and collect additional sequences in Map.
697 * @param sequencesArray
700 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
702 Vector nseq = new Vector();
703 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
705 nseq.addElement(sequencesArray[i]);
706 DBRefEntry dbr[] = sequencesArray[i].getDBRef();
707 jalview.datamodel.Mapping map = null;
708 for (int r = 0; (dbr != null) && r < dbr.length; r++)
710 if ((map = dbr[r].getMap()) != null)
712 if (map.getTo() != null && !nseq.contains(map.getTo()))
714 nseq.addElement(map.getTo());
721 sequencesArray = new SequenceI[nseq.size()];
722 nseq.toArray(sequencesArray);
724 return sequencesArray;