2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
\r
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
\r
5 * This program is free software; you can redistribute it and/or
\r
6 * modify it under the terms of the GNU General Public License
\r
7 * as published by the Free Software Foundation; either version 2
\r
8 * of the License, or (at your option) any later version.
\r
10 * This program is distributed in the hope that it will be useful,
\r
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
13 * GNU General Public License for more details.
\r
15 * You should have received a copy of the GNU General Public License
\r
16 * along with this program; if not, write to the Free Software
\r
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
\r
21 import jalview.analysis.AlignSeq;
\r
22 import jalview.bin.Cache;
\r
23 import jalview.datamodel.AlignmentI;
\r
24 import jalview.datamodel.DBRefEntry;
\r
25 import jalview.datamodel.DBRefSource;
\r
26 import jalview.datamodel.Mapping;
\r
27 import jalview.datamodel.SequenceFeature;
\r
28 import jalview.datamodel.SequenceI;
\r
29 import jalview.gui.AlignFrame;
\r
30 import jalview.gui.CutAndPasteTransfer;
\r
31 import jalview.gui.Desktop;
\r
32 import jalview.gui.IProgressIndicator;
\r
33 import jalview.gui.OOMWarning;
\r
35 import java.lang.reflect.Array;
\r
36 import java.util.Enumeration;
\r
37 import java.util.Hashtable;
\r
38 import java.util.StringTokenizer;
\r
39 import java.util.Vector;
\r
41 import org.biojava.dasobert.dasregistry.DasSource;
\r
43 import uk.ac.ebi.picr.model.UPEntry;
\r
46 * Implements a runnable for validating a sequence against external databases
\r
47 * and then propagating references and features onto the sequence(s)
\r
50 * @version $Revision$
\r
52 public class DBRefFetcher implements Runnable
\r
54 SequenceI[] dataset;
\r
56 IProgressIndicator af;
\r
58 CutAndPasteTransfer output = new CutAndPasteTransfer();
\r
60 StringBuffer sbuffer = new StringBuffer();
\r
62 boolean running = false;
\r
65 * picr client instance
\r
67 uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
\r
69 // /This will be a collection of Vectors of sequenceI refs.
\r
70 // The key will be the seq name or accession id of the seq
\r
75 SequenceFetcher sfetcher;
\r
77 public DBRefFetcher()
\r
82 * Creates a new SequenceFeatureFetcher object and fetches from the currently
\r
83 * selected set of databases.
\r
86 * fetch references for these sequences
\r
88 * the parent alignframe for progress bar monitoring.
\r
90 public DBRefFetcher(SequenceI[] seqs, AlignFrame af)
\r
92 this(seqs, af, null);
\r
96 * Creates a new SequenceFeatureFetcher object and fetches from the currently
\r
97 * selected set of databases.
\r
100 * fetch references for these sequences
\r
102 * the parent alignframe for progress bar monitoring.
\r
104 * array of database source strings to query references from
\r
106 public DBRefFetcher(SequenceI[] seqs, AlignFrame af, String[] sources)
\r
109 SequenceI[] ds = new SequenceI[seqs.length];
\r
110 for (int i = 0; i < seqs.length; i++)
\r
112 if (seqs[i].getDatasetSequence() != null)
\r
113 ds[i] = seqs[i].getDatasetSequence();
\r
118 // TODO Jalview 2.5 lots of this code should be in the gui package!
\r
119 sfetcher = jalview.gui.SequenceFetcher.getSequenceFetcherSingleton(af);
\r
120 if (sources == null)
\r
122 // af.featureSettings_actionPerformed(null);
\r
123 String[] defdb = null, otherdb = sfetcher
\r
124 .getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
\r
125 Vector selsources = new Vector(), dasselsrc = (af.featureSettings != null) ? af.featureSettings
\r
126 .getSelectedSources()
\r
127 : new jalview.gui.DasSourceBrowser().getSelectedSources();
\r
128 Enumeration en = dasselsrc.elements();
\r
129 while (en.hasMoreElements())
\r
131 DasSource src = (DasSource) en.nextElement();
\r
132 selsources.addElement(src.getNickname());
\r
135 for (int o = 0; otherdb != null && o < otherdb.length; o++)
\r
137 if (!selsources.contains(otherdb[o]))
\r
146 // select appropriate databases based on alignFrame context.
\r
147 if (af.getViewport().getAlignment().isNucleotide())
\r
149 defdb = DBRefSource.DNACODINGDBS;
\r
153 defdb = DBRefSource.PROTEINDBS;
\r
155 // append the selected sequence sources to the default dbs
\r
156 dbSources = new String[defdb.length + osel];
\r
157 System.arraycopy(defdb, 0, dbSources, 0, defdb.length);
\r
158 for (int o = 0, op = defdb.length; otherdb != null
\r
159 && o < otherdb.length; o++)
\r
161 if (otherdb[o] != null)
\r
163 dbSources[op++] = otherdb[o];
\r
169 // we assume the caller knows what they're doing and ensured that all the
\r
170 // db source names are valid
\r
171 dbSources = sources;
\r
176 * retrieve all the das sequence sources and add them to the list of db
\r
177 * sources to retrieve from
\r
179 public void appendAllDasSources()
\r
181 if (dbSources == null)
\r
183 dbSources = new String[]
\r
186 // append additional sources
\r
187 String[] otherdb = sfetcher
\r
188 .getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
\r
189 if (otherdb != null && otherdb.length > 0)
\r
191 String[] newsrc = new String[dbSources.length + otherdb.length];
\r
192 System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
\r
194 .arraycopy(otherdb, 0, newsrc, dbSources.length,
\r
196 dbSources = newsrc;
\r
201 * start the fetcher thread
\r
203 * @param waitTillFinished
\r
204 * true to block until the fetcher has finished
\r
206 public void fetchDBRefs(boolean waitTillFinished)
\r
208 Thread thread = new Thread(this);
\r
212 if (waitTillFinished)
\r
219 } catch (Exception ex)
\r
227 * The sequence will be added to a vector of sequences belonging to key which
\r
228 * could be either seq name or dbref id
\r
235 void addSeqId(SequenceI seq, String key)
\r
237 key = key.toUpperCase();
\r
240 if (seqRefs.containsKey(key))
\r
242 seqs = (Vector) seqRefs.get(key);
\r
244 if (seqs != null && !seqs.contains(seq))
\r
246 seqs.addElement(seq);
\r
248 else if (seqs == null)
\r
250 seqs = new Vector();
\r
251 seqs.addElement(seq);
\r
257 seqs = new Vector();
\r
258 seqs.addElement(seq);
\r
261 seqRefs.put(key, seqs);
\r
269 if (dbSources == null)
\r
271 throw new Error("Implementation error. Must initialise dbSources");
\r
274 long startTime = System.currentTimeMillis();
\r
275 af.setProgressBar("Fetching db refs", startTime);
\r
278 if (Cache.getDefault("DBREFFETCH_USEPICR", false))
\r
280 picrClient = new uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator()
\r
281 .getAccessionMapperPort();
\r
283 } catch (Exception e)
\r
285 System.err.println("Couldn't locate PICR service instance.\n");
\r
286 e.printStackTrace();
\r
289 Vector sdataset = new Vector();
\r
290 for (int s = 0; s < dataset.length; s++)
\r
292 sdataset.addElement(dataset[s]);
\r
294 while (sdataset.size() > 0 && db < dbSources.length)
\r
296 int maxqlen = 1; // default number of queries made to at one time
\r
297 System.err.println("Verifying against " + dbSources[db]);
\r
298 jalview.ws.seqfetcher.DbSourceProxy dbsource = sfetcher
\r
299 .getSourceProxy(dbSources[db]);
\r
300 if (dbsource == null)
\r
302 System.err.println("No proxy for " + dbSources[db]);
\r
306 if (dbsource.getDbSourceProperties()
\r
307 .containsKey(DBRefSource.MULTIACC))
\r
309 maxqlen = ((Integer) dbsource.getDbSourceProperties().get(
\r
310 DBRefSource.MULTIACC)).intValue();
\r
316 // iterate through db for each remaining un-verified sequence
\r
317 SequenceI[] currSeqs = new SequenceI[sdataset.size()];
\r
318 sdataset.copyInto(currSeqs);// seqs that are to be validated against
\r
320 Vector queries = new Vector(); // generated queries curSeq
\r
321 seqRefs = new Hashtable();
\r
325 while (queries.size() > 0 || seqIndex < currSeqs.length)
\r
327 if (queries.size() > 0)
\r
329 // Still queries to make for current seqIndex
\r
330 StringBuffer queryString = new StringBuffer("");
\r
331 int numq = 0, nqSize = (maxqlen > queries.size()) ? queries
\r
334 while (queries.size() > 0 && numq < nqSize)
\r
336 String query = (String) queries.elementAt(0);
\r
337 if (dbsource.isValidReference(query))
\r
339 queryString.append((numq == 0) ? "" : dbsource
\r
340 .getAccessionSeparator());
\r
341 queryString.append(query);
\r
344 // remove the extracted query string
\r
345 queries.removeElementAt(0);
\r
347 // make the queries and process the response
\r
348 AlignmentI retrieved = null;
\r
351 if (jalview.bin.Cache.log.isDebugEnabled())
\r
353 jalview.bin.Cache.log.debug("Querying "
\r
354 + dbsource.getDbName() + " with : '"
\r
355 + queryString.toString() + "'");
\r
357 retrieved = dbsource.getSequenceRecords(queryString.toString());
\r
358 } catch (Exception ex)
\r
360 ex.printStackTrace();
\r
361 } catch (OutOfMemoryError err)
\r
363 new OOMWarning("retrieving database references ("
\r
364 + queryString.toString() + ")", err);
\r
366 if (retrieved != null)
\r
368 transferReferences(sdataset, dbSources[db], retrieved);
\r
373 // make some more strings for use as queries
\r
374 for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
\r
376 SequenceI sequence = dataset[seqIndex];
\r
377 DBRefEntry[] uprefs = jalview.util.DBRefUtils.selectRefs(
\r
378 sequence.getDBRef(), new String[]
\r
379 { dbSources[db] }); // jalview.datamodel.DBRefSource.UNIPROT
\r
381 // check for existing dbrefs to use
\r
382 if (uprefs != null && uprefs.length > 0)
\r
384 for (int j = 0; j < uprefs.length; j++)
\r
386 addSeqId(sequence, uprefs[j].getAccessionId());
\r
388 .addElement(uprefs[j].getAccessionId()
\r
394 // generate queries from sequence ID string
\r
395 StringTokenizer st = new StringTokenizer(sequence.getName(),
\r
397 while (st.hasMoreTokens())
\r
399 String token = st.nextToken();
\r
400 UPEntry[] presp = null;
\r
401 if (picrClient != null)
\r
403 // resolve the string against PICR to recover valid IDs
\r
407 .getUPIForAccession(token, null, picrClient
\r
408 .getMappedDatabaseNames(), null, true);
\r
409 } catch (Exception e)
\r
411 System.err.println("Exception with Picr for '" + token
\r
413 e.printStackTrace();
\r
416 if (presp != null && presp.length > 0)
\r
418 for (int id = 0; id < presp.length; id++)
\r
420 // construct sequences from response if sequences are
\r
421 // present, and do a transferReferences
\r
422 // otherwise transfer non sequence x-references directly.
\r
425 .println("Validated ID against PICR... (for what its worth):"
\r
427 addSeqId(sequence, token);
\r
428 queries.addElement(token.toUpperCase());
\r
433 // System.out.println("Not querying source with token="+token+"\n");
\r
434 addSeqId(sequence, token);
\r
435 queries.addElement(token.toUpperCase());
\r
442 // advance to next database
\r
444 } // all databases have been queries.
\r
445 if (sbuffer.length() > 0)
\r
448 .setText("Your sequences have been verified against known sequence databases. Some of the ids have been\n"
\r
449 + "altered, most likely the start/end residue will have been updated.\n"
\r
450 + "Save your alignment to maintain the updated id.\n\n"
\r
451 + sbuffer.toString());
\r
452 Desktop.addInternalFrame(output, "Sequence names updated ", 600, 300);
\r
453 // The above is the dataset, we must now find out the index
\r
454 // of the viewed sequence
\r
458 af.setProgressBar("DBRef search completed", startTime);
\r
459 // promptBeforeBlast();
\r
466 * Verify local sequences in seqRefs against the retrieved sequence database
\r
470 void transferReferences(Vector sdataset, String dbSource,
\r
471 AlignmentI retrievedAl) // File
\r
474 if (retrievedAl == null || retrievedAl.getHeight() == 0)
\r
478 SequenceI[] retrieved = recoverDbSequences(retrievedAl
\r
479 .getSequencesArray());
\r
480 SequenceI sequence = null;
\r
481 boolean transferred = false;
\r
482 StringBuffer messages = new StringBuffer();
\r
484 // Vector entries = new Uniprot().getUniprotEntries(file);
\r
486 int i, iSize = retrieved.length; // entries == null ? 0 : entries.size();
\r
487 // UniprotEntry entry;
\r
488 for (i = 0; i < iSize; i++)
\r
490 SequenceI entry = retrieved[i]; // (UniprotEntry) entries.elementAt(i);
\r
492 // Work out which sequences this sequence matches,
\r
493 // taking into account all accessionIds and names in the file
\r
494 Vector sequenceMatches = new Vector();
\r
495 // look for corresponding accession ids
\r
496 DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(entry
\r
497 .getDBRef(), new String[]
\r
499 for (int j = 0; j < entryRefs.length; j++)
\r
501 String accessionId = entryRefs[j].getAccessionId(); // .getAccession().elementAt(j).toString();
\r
502 // match up on accessionId
\r
503 if (seqRefs.containsKey(accessionId.toUpperCase()))
\r
505 Vector seqs = (Vector) seqRefs.get(accessionId);
\r
506 for (int jj = 0; jj < seqs.size(); jj++)
\r
508 sequence = (SequenceI) seqs.elementAt(jj);
\r
509 if (!sequenceMatches.contains(sequence))
\r
511 sequenceMatches.addElement(sequence);
\r
516 if (sequenceMatches.size() == 0)
\r
518 // failed to match directly on accessionId==query so just compare all
\r
519 // sequences to entry
\r
520 Enumeration e = seqRefs.keys();
\r
521 while (e.hasMoreElements())
\r
523 Vector sqs = (Vector) seqRefs.get(e.nextElement());
\r
524 if (sqs != null && sqs.size() > 0)
\r
526 Enumeration sqe = sqs.elements();
\r
527 while (sqe.hasMoreElements())
\r
529 sequenceMatches.addElement(sqe.nextElement());
\r
534 // look for corresponding names
\r
535 // this is uniprot specific ?
\r
536 // could be useful to extend this so we try to find any 'significant'
\r
537 // information in common between two sequence objects.
\r
539 * DBRefEntry[] entryRefs =
\r
540 * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
\r
541 * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
\r
542 * name = entry.getName().elementAt(j).toString(); if
\r
543 * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
\r
544 * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
\r
545 * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
\r
546 * sequenceMatches.addElement(sequence); } } } }
\r
548 // sequenceMatches now contains the set of all sequences associated with
\r
549 // the returned db record
\r
550 String entrySeq = entry.getSequenceAsString().toUpperCase();
\r
551 for (int m = 0; m < sequenceMatches.size(); m++)
\r
553 sequence = (SequenceI) sequenceMatches.elementAt(m);
\r
554 // only update start and end positions and shift features if there are
\r
555 // no existing references
\r
556 // TODO: test for legacy where uniprot or EMBL refs exist but no
\r
557 // mappings are made (but content matches retrieved set)
\r
558 boolean updateRefFrame = sequence.getDBRef() == null
\r
559 || sequence.getDBRef().length == 0;
\r
560 // verify sequence against the entry sequence
\r
562 String nonGapped = AlignSeq.extractGaps("-. ",
\r
563 sequence.getSequenceAsString()).toUpperCase();
\r
565 int absStart = entrySeq.indexOf(nonGapped);
\r
566 int mapStart = entry.getStart();
\r
567 jalview.datamodel.Mapping mp;
\r
569 if (absStart == -1)
\r
571 // Is local sequence contained in dataset sequence?
\r
572 absStart = nonGapped.indexOf(entrySeq);
\r
573 if (absStart == -1)
\r
574 { // verification failed.
\r
575 messages.append(sequence.getName()
\r
576 + " SEQUENCE NOT %100 MATCH \n");
\r
579 transferred = true;
\r
580 sbuffer.append(sequence.getName() + " HAS " + absStart
\r
581 + " PREFIXED RESIDUES COMPARED TO " + dbSource + "\n");
\r
583 // + " - ANY SEQUENCE FEATURES"
\r
584 // + " HAVE BEEN ADJUSTED ACCORDINGLY \n");
\r
586 // create valid mapping between matching region of local sequence and
\r
587 // the mapped sequence
\r
588 mp = new Mapping(null, new int[]
\r
589 { sequence.getStart() + absStart,
\r
590 sequence.getStart() + absStart + entrySeq.length() - 1 },
\r
592 { entry.getStart(),
\r
593 entry.getStart() + entrySeq.length() - 1 }, 1, 1);
\r
594 updateRefFrame = false; // mapping is based on current start/end so
\r
595 // don't modify start and end
\r
599 transferred = true;
\r
600 // update start and end of local sequence to place it in entry's
\r
601 // reference frame.
\r
602 // apply identity map map from whole of local sequence to matching
\r
603 // region of database
\r
605 mp = null; // Mapping.getIdentityMap();
\r
606 // new Mapping(null,
\r
607 // new int[] { absStart+sequence.getStart(),
\r
608 // absStart+sequence.getStart()+entrySeq.length()-1},
\r
609 // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
\r
610 // relocate local features for updated start
\r
611 if (updateRefFrame && sequence.getSequenceFeatures() != null)
\r
613 SequenceFeature[] sf = sequence.getSequenceFeatures();
\r
614 int start = sequence.getStart();
\r
615 int end = sequence.getEnd();
\r
616 int startShift = 1 - absStart - start; // how much the features are
\r
617 // to be shifted by
\r
618 for (int sfi = 0; sfi < sf.length; sfi++)
\r
620 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
\r
622 // shift feature along by absstart
\r
623 sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
\r
624 sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
\r
630 System.out.println("Adding dbrefs to " + sequence.getName()
\r
631 + " from " + dbSource + " sequence : " + entry.getName());
\r
632 sequence.transferAnnotation(entry, mp);
\r
633 // unknownSequences.remove(sequence);
\r
634 int absEnd = absStart + nonGapped.length();
\r
636 if (updateRefFrame)
\r
638 // finally, update local sequence reference frame if we're allowed
\r
639 sequence.setStart(absStart);
\r
640 sequence.setEnd(absEnd);
\r
642 // and remove it from the rest
\r
643 // TODO: decide if we should remove annotated sequence from set
\r
644 sdataset.remove(sequence);
\r
645 // TODO: should we make a note of sequences that have received new DB
\r
646 // ids, so we can query all enabled DAS servers for them ?
\r
651 // report the ID/sequence mismatches
\r
652 sbuffer.append(messages);
\r
657 * loop thru and collect additional sequences in Map.
\r
659 * @param sequencesArray
\r
662 private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
\r
664 Vector nseq = new Vector();
\r
665 for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
\r
667 nseq.addElement(sequencesArray[i]);
\r
668 DBRefEntry dbr[] = sequencesArray[i].getDBRef();
\r
669 jalview.datamodel.Mapping map = null;
\r
670 for (int r = 0; (dbr != null) && r < dbr.length; r++)
\r
672 if ((map = dbr[r].getMap()) != null)
\r
674 if (map.getTo() != null && !nseq.contains(map.getTo()))
\r
676 nseq.addElement(map.getTo());
\r
681 if (nseq.size() > 0)
\r
683 sequencesArray = new SequenceI[nseq.size()];
\r
684 nseq.toArray(sequencesArray);
\r
686 return sequencesArray;
\r