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.
21 package jalview.analysis;
23 import jalview.datamodel.AlignedCodonFrame;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.Mapping;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.util.DBRefUtils;
32 import jalview.util.MapList;
33 import jalview.ws.SequenceFetcherFactory;
34 import jalview.ws.seqfetcher.ASequenceFetcher;
36 import java.util.ArrayList;
37 import java.util.Iterator;
38 import java.util.List;
41 * Functions for cross-referencing sequence databases.
49 * the dataset of the alignment for which we are searching for
50 * cross-references; in some cases we may resolve xrefs by
51 * searching in the dataset
53 private AlignmentI dataset;
56 * the sequences for which we are seeking cross-references
58 private SequenceI[] fromSeqs;
61 * matcher built from dataset
63 SequenceIdMatcher matcher;
66 * sequences found by cross-ref searches to fromSeqs
68 List<SequenceI> rseqs;
71 * mappings constructed
79 * the sequences for which we are seeking cross-references
81 * the containing alignment dataset (may be searched to resolve
84 public CrossRef(SequenceI[] seqs, AlignmentI ds)
87 dataset = ds.getDataset() == null ? ds : ds.getDataset();
91 * Returns a list of distinct database sources for which sequences have either
93 * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
94 * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
95 * reference from another sequence in the dataset which has a cross-reference
96 * to a direct DBRefEntry on the given sequence</li>
100 * - when true, cross-references *from* dna returned. When false,
101 * cross-references *from* protein are returned
104 public List<String> findXrefSourcesForSequences(boolean dna)
106 List<String> sources = new ArrayList<String>();
107 for (SequenceI seq : fromSeqs)
111 findXrefSourcesForSequence(seq, dna, sources);
118 * Returns a list of distinct database sources for which a sequence has either
120 * <li>a (dna-to-protein or protein-to-dna) cross-reference</li>
121 * <li>an indirect cross-reference - a (dna-to-protein or protein-to-dna)
122 * reference from another sequence in the dataset which has a cross-reference
123 * to a direct DBRefEntry on the given sequence</li>
127 * the sequence whose dbrefs we are searching against
129 * when true, context is DNA - so sources identifying protein
130 * products will be returned.
132 * a list of sources to add matches to
134 void findXrefSourcesForSequence(SequenceI seq, boolean fromDna,
135 List<String> sources)
138 * first find seq's xrefs (dna-to-peptide or peptide-to-dna)
140 DBRefEntry[] rfs = DBRefUtils.selectDbRefs(!fromDna, seq.getDBRefs());
141 addXrefsToSources(rfs, sources);
145 * find sequence's direct (dna-to-dna, peptide-to-peptide) xrefs
147 DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna, seq.getDBRefs());
148 List<SequenceI> rseqs = new ArrayList<SequenceI>();
151 * find sequences in the alignment which xref one of these DBRefs
152 * i.e. is xref-ed to a common sequence identifier
154 searchDatasetXrefs(fromDna, seq, lrfs, rseqs, null);
157 * add those sequences' (dna-to-peptide or peptide-to-dna) dbref sources
159 for (SequenceI rs : rseqs)
161 DBRefEntry[] xrs = DBRefUtils
162 .selectDbRefs(!fromDna, rs.getDBRefs());
163 addXrefsToSources(xrs, sources);
169 * Helper method that adds the source identifiers of some cross-references to
170 * a (non-redundant) list of database sources
175 void addXrefsToSources(DBRefEntry[] xrefs, List<String> sources)
179 for (DBRefEntry ref : xrefs)
182 * avoid duplication e.g. ENSEMBL and Ensembl
184 String source = DBRefUtils.getCanonicalName(ref.getSource());
185 if (!sources.contains(source))
194 * Attempts to find cross-references from the sequences provided in the
195 * constructor to the given source database. Cross-references may be found
197 * <li>in dbrefs on the sequence which hold a mapping to a sequence
199 * <li>provided with a fetched sequence (e.g. ENA translation), or</li>
200 * <li>populated previously after getting cross-references</li>
202 * <li>as other sequences in the alignment which share a dbref identifier with
204 * <li>by fetching from the remote database</li>
206 * The cross-referenced sequences, and mappings to them, are added to the
210 * @return cross-referenced sequences (as dataset sequences)
212 public Alignment findXrefSequences(String source, boolean fromDna)
215 rseqs = new ArrayList<SequenceI>();
216 cf = new AlignedCodonFrame();
217 matcher = new SequenceIdMatcher(
218 dataset.getSequences());
220 for (SequenceI seq : fromSeqs)
223 while (dss.getDatasetSequence() != null)
225 dss = dss.getDatasetSequence();
227 boolean found = false;
228 DBRefEntry[] xrfs = DBRefUtils
229 .selectDbRefs(!fromDna, dss.getDBRefs());
230 if ((xrfs == null || xrfs.length == 0) && dataset != null)
233 * found no suitable dbrefs on sequence - look for sequences in the
234 * alignment which share a dbref with this one
236 DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna,
240 * find sequences (except this one!), of complementary type,
241 * which have a dbref to an accession id for this sequence,
242 * and add them to the results
244 found = searchDatasetXrefs(fromDna, dss, lrfs, rseqs, cf);
246 if (xrfs == null && !found)
249 * no dbref to source on this sequence or matched
250 * complementary sequence in the dataset
254 List<DBRefEntry> sourceRefs = DBRefUtils.searchRefsForSource(xrfs,
256 Iterator<DBRefEntry> refIterator = sourceRefs.iterator();
257 while (refIterator.hasNext())
259 DBRefEntry xref = refIterator.next();
263 SequenceI mappedTo = xref.getMap().getTo();
264 if (mappedTo != null)
267 * dbref contains the sequence it maps to; add it to the
268 * results unless we have done so already (could happen if
269 * fetching xrefs for sequences which have xrefs in common)
270 * for example: UNIPROT {P0CE19, P0CE20} -> EMBL {J03321, X06707}
274 * problem: matcher.findIdMatch() is lenient - returns a sequence
275 * with a dbref to the search arg e.g. ENST for ENSP - wrong
276 * but findInDataset() matches ENSP when looking for Uniprot...
278 SequenceI matchInDataset = findInDataset(xref);
279 /*matcher.findIdMatch(mappedTo);*/
280 if (matchInDataset != null)
282 if (!rseqs.contains(matchInDataset))
284 rseqs.add(matchInDataset);
286 refIterator.remove();
289 SequenceI rsq = new Sequence(mappedTo);
291 if (xref.getMap().getMap().getFromRatio() != xref.getMap()
292 .getMap().getToRatio())
294 // get sense of map correct for adding to product alignment.
297 // map is from dna seq to a protein product
298 cf.addMap(dss, rsq, xref.getMap().getMap());
302 // map should be from protein seq to its coding dna
303 cf.addMap(rsq, dss, xref.getMap().getMap().getInverse());
311 SequenceI matchedSeq = matcher.findIdMatch(xref.getSource() + "|"
312 + xref.getAccessionId());
313 if (matchedSeq != null)
315 if (constructMapping(seq, matchedSeq, xref, cf, fromDna))
324 // do a bit more work - search for sequences with references matching
325 // xrefs on this sequence.
326 found = searchDataset(fromDna, dss, xref, rseqs, cf, false);
330 refIterator.remove();
335 * fetch from source database any dbrefs we haven't resolved up to here
337 if (!sourceRefs.isEmpty())
339 retrieveCrossRef(sourceRefs, seq, xrfs, fromDna);
343 Alignment ral = null;
344 if (rseqs.size() > 0)
346 ral = new Alignment(rseqs.toArray(new SequenceI[rseqs.size()]));
349 dataset.addCodonFrame(cf);
355 private void retrieveCrossRef(List<DBRefEntry> sourceRefs, SequenceI seq,
356 DBRefEntry[] xrfs, boolean fromDna)
358 ASequenceFetcher sftch = SequenceFetcherFactory.getSequenceFetcher();
359 SequenceI[] retrieved = null;
360 SequenceI dss = null;
363 retrieved = sftch.getSequences(sourceRefs, !fromDna);
364 } catch (Exception e)
367 .println("Problem whilst retrieving cross references for Sequence : "
372 if (retrieved != null)
374 updateDbrefMappings(seq, xrfs, retrieved, cf, fromDna);
375 for (SequenceI retrievedSequence : retrieved)
377 // dataset gets contaminated ccwith non-ds sequences. why ??!
378 // try: Ensembl -> Nuc->Ensembl, Nuc->Uniprot-->Protein->EMBL->
379 SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
380 : retrievedSequence.getDatasetSequence();
381 DBRefEntry[] dbr = retrievedSequence.getDBRefs();
384 for (DBRefEntry dbref : dbr)
386 // find any entry where we should put in the sequence being
387 // cross-referenced into the map
388 Mapping map = dbref.getMap();
391 if (map.getTo() != null && map.getMap() != null)
393 // TODO findInDataset requires exact sequence match but
394 // 'congruent' test is only for the mapped part
395 // maybe not a problem in practice since only ENA provide a
396 // mapping and it is to the full protein translation of CDS
397 SequenceI matched = findInDataset(dbref);
398 // matcher.findIdMatch(map.getTo());
402 * already got an xref to this sequence; update this
403 * map to point to the same sequence, and add
404 * any new dbrefs to it
406 DBRefEntry[] toRefs = map.getTo().getDBRefs();
409 for (DBRefEntry ref : toRefs)
411 matched.addDBRef(ref); // add or update mapping
418 matcher.add(map.getTo());
422 // compare ms with dss and replace with dss in mapping
423 // if map is congruent
424 SequenceI ms = map.getTo();
425 int sf = map.getMap().getToLowest();
426 int st = map.getMap().getToHighest();
427 SequenceI mappedrg = ms.getSubSequence(sf, st);
428 // SequenceI loc = dss.getSubSequence(sf, st);
429 if (mappedrg.getLength() > 0
430 && ms.getSequenceAsString().equals(
431 dss.getSequenceAsString()))
432 // && mappedrg.getSequenceAsString().equals(
433 // loc.getSequenceAsString()))
435 String msg = "Mapping updated from " + ms.getName()
436 + " to retrieved crossreference "
438 System.out.println(msg);
442 * give the reverse reference the inverse mapping
443 * (if it doesn't have one already)
445 setReverseMapping(dss, dbref, cf);
448 * copy sequence features as well, avoiding
449 * duplication (e.g. same variation from two
452 SequenceFeature[] sfs = ms.getSequenceFeatures();
455 for (SequenceFeature feat : sfs)
458 * make a flyweight feature object which ignores Parent
459 * attribute in equality test; this avoids creating many
460 * otherwise duplicate exon features on genomic sequence
462 SequenceFeature newFeature = new SequenceFeature(
466 public boolean equals(Object o)
468 return super.equals(o, true);
471 dss.addSequenceFeature(newFeature);
475 cf.addMap(retrievedDss, map.getTo(), map.getMap());
476 } catch (Exception e)
479 .println("Exception when consolidating Mapped sequence set...");
480 e.printStackTrace(System.err);
486 retrievedSequence.updatePDBIds();
487 rseqs.add(retrievedDss);
488 dataset.addSequence(retrievedDss);
489 matcher.add(retrievedDss);
494 * Sets the inverse sequence mapping in the corresponding dbref of the mapped
495 * to sequence (if any). This is used after fetching a cross-referenced
496 * sequence, if the fetched sequence has a mapping to the original sequence,
497 * to set the mapping in the original sequence's dbref.
500 * the sequence mapped from
504 void setReverseMapping(SequenceI mapFrom, DBRefEntry dbref,
505 AlignedCodonFrame mappings)
507 SequenceI mapTo = dbref.getMap().getTo();
512 DBRefEntry[] dbrefs = mapTo.getDBRefs();
517 for (DBRefEntry toRef : dbrefs)
519 if (toRef.hasMap() && mapFrom == toRef.getMap().getTo())
522 * found the reverse dbref; update its mapping if null
524 if (toRef.getMap().getMap() == null)
526 MapList inverse = dbref.getMap().getMap().getInverse();
527 toRef.getMap().setMap(inverse);
528 mappings.addMap(mapTo, mapFrom, inverse);
535 * Returns the first identical sequence in the dataset if any, else null
540 SequenceI findInDataset(DBRefEntry xref)
542 if (xref == null || !xref.hasMap() || xref.getMap().getTo() == null)
546 SequenceI mapsTo = xref.getMap().getTo();
547 String name = xref.getAccessionId();
548 String name2 = xref.getSource() + "|" + name;
549 SequenceI dss = mapsTo.getDatasetSequence() == null ? mapsTo : mapsTo
550 .getDatasetSequence();
551 for (SequenceI seq : dataset.getSequences())
554 * clumsy alternative to using SequenceIdMatcher which currently
555 * returns sequences with a dbref to the matched accession id
556 * which we don't want
558 if (name.equals(seq.getName()) || seq.getName().startsWith(name2))
560 if (sameSequence(seq, dss))
570 * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
571 * case), else false. This method compares the lengths, then each character in
572 * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
573 * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
579 // TODO move to Sequence / SequenceI
580 static boolean sameSequence(SequenceI seq1, SequenceI seq2)
586 if (seq1 == null || seq2 == null)
590 char[] c1 = seq1.getSequence();
591 char[] c2 = seq2.getSequence();
592 if (c1.length != c2.length)
596 for (int i = 0; i < c1.length; i++)
598 int diff = c1[i] - c2[i];
600 * same char or differ in case only ('a'-'A' == 32)
602 if (diff != 0 && diff != 32 && diff != -32)
611 * Updates any empty mappings in the cross-references with one to a compatible
612 * retrieved sequence if found, and adds any new mappings to the
620 void updateDbrefMappings(SequenceI mapFrom, DBRefEntry[] xrefs,
621 SequenceI[] retrieved, AlignedCodonFrame acf, boolean fromDna)
623 SequenceIdMatcher matcher = new SequenceIdMatcher(retrieved);
624 for (DBRefEntry xref : xrefs)
628 String targetSeqName = xref.getSource() + "|"
629 + xref.getAccessionId();
630 SequenceI[] matches = matcher.findAllIdMatches(targetSeqName);
635 for (SequenceI seq : matches)
637 constructMapping(mapFrom, seq, xref, acf, fromDna);
644 * Tries to make a mapping between sequences. If successful, adds the mapping
645 * to the dbref and the mappings collection and answers true, otherwise
646 * answers false. The following methods of making are mapping are tried in
649 * <li>if 'mapTo' holds a mapping to 'mapFrom', take the inverse; this is, for
650 * example, the case after fetching EMBL cross-references for a Uniprot
652 * <li>else check if the dna translates exactly to the protein (give or take
653 * start and stop codons></li>
654 * <li>else try to map based on CDS features on the dna sequence</li>
663 boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
664 DBRefEntry xref, AlignedCodonFrame mappings, boolean fromDna)
666 MapList mapping = null;
669 * look for a reverse mapping, if found make its inverse
671 if (mapTo.getDBRefs() != null)
673 for (DBRefEntry dbref : mapTo.getDBRefs())
675 String name = dbref.getSource() + "|" + dbref.getAccessionId();
676 if (dbref.hasMap() && mapFrom.getName().startsWith(name))
679 * looks like we've found a map from 'mapTo' to 'mapFrom'
680 * - invert it to make the mapping the other way
682 MapList reverse = dbref.getMap().getMap().getInverse();
683 xref.setMap(new Mapping(mapTo, reverse));
684 mappings.addMap(mapFrom, mapTo, reverse);
692 mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
696 mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
699 mapping = mapping.getInverse();
706 xref.setMap(new Mapping(mapTo, mapping));
709 AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
710 mappings.addMap(mapFrom, mapTo, mapping);
714 mappings.addMap(mapTo, mapFrom, mapping.getInverse());
721 * find references to lrfs in the cross-reference set of each sequence in
722 * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
723 * based on source and accession string only - Map and Version are nulled.
726 * - true if context was searching from Dna sequences, false if
727 * context was searching from Protein sequences
731 * @return true if matches were found.
733 private boolean searchDatasetXrefs(boolean fromDna, SequenceI sequenceI,
734 DBRefEntry[] lrfs, List<SequenceI> rseqs, AlignedCodonFrame cf)
736 boolean found = false;
741 for (int i = 0; i < lrfs.length; i++)
743 DBRefEntry xref = new DBRefEntry(lrfs[i]);
745 xref.setVersion(null);
747 found |= searchDataset(fromDna, sequenceI, xref, rseqs, cf, false);
753 * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
754 * associated sequence to rseqs
757 * true if context was searching for refs *from* dna sequence, false
758 * if context was searching for refs *from* protein sequence
760 * a sequence to ignore (start point of search)
762 * a cross-reference to try to match
764 * result list to add to
766 * a set of sequence mappings to add to
768 * - indicates the type of relationship between returned sequences,
769 * xrf, and sequenceI that is required.
771 * <li>direct implies xrf is a primary reference for sequenceI AND
772 * the sequences to be located (eg a uniprot ID for a protein
773 * sequence, and a uniprot ref on a transcript sequence).</li>
774 * <li>indirect means xrf is a cross reference with respect to
775 * sequenceI or all the returned sequences (eg a genomic reference
776 * associated with a locus and one or more transcripts)</li>
778 * @return true if relationship found and sequence added.
780 boolean searchDataset(boolean fromDna, SequenceI sequenceI,
781 DBRefEntry xrf, List<SequenceI> rseqs, AlignedCodonFrame cf,
784 boolean found = false;
789 if (dataset.getSequences() == null)
791 System.err.println("Empty dataset sequence set - NO VECTOR");
795 synchronized (ds = dataset.getSequences())
797 for (SequenceI nxt : ds)
801 if (nxt.getDatasetSequence() != null)
804 .println("Implementation warning: getProducts passed a dataset alignment without dataset sequences in it!");
806 if (nxt == sequenceI || nxt == sequenceI.getDatasetSequence())
811 * only look at same molecule type if 'direct', or
812 * complementary type if !direct
815 boolean isDna = !nxt.isProtein();
816 if (direct ? (isDna != fromDna) : (isDna == fromDna))
818 // skip this sequence because it is wrong molecule type
823 // look for direct or indirect references in common
824 DBRefEntry[] poss = nxt.getDBRefs();
825 List<DBRefEntry> cands = null;
827 * TODO does this make any sense?
828 * if 'direct', search the dbrefs for xrf
829 * else, filter the dbrefs by type and then search for xrf
830 * - the result is the same isn't it?
834 cands = DBRefUtils.searchRefs(poss, xrf);
838 poss = DBRefUtils.selectDbRefs(!fromDna, poss);
839 cands = DBRefUtils.searchRefs(poss, xrf);
841 if (!cands.isEmpty())
843 if (!rseqs.contains(nxt))
849 // don't search if we aren't given a codon map object
850 for (DBRefEntry candidate : cands)
852 Mapping mapping = candidate.getMap();
855 MapList map = mapping.getMap();
856 if (mapping.getTo() != null
857 && map.getFromRatio() != map.getToRatio())
859 // get sense of map correct for adding to product
863 // map is from dna seq to a protein product
864 cf.addMap(sequenceI, nxt, map);
868 // map should be from protein seq to its coding dna
869 cf.addMap(nxt, sequenceI, map.getInverse());
875 // TODO: add mapping between sequences if necessary