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 * a list of sources to add matches to
131 void findXrefSourcesForSequence(SequenceI seq, boolean fromDna,
132 List<String> sources)
135 * first find seq's xrefs (dna-to-peptide or peptide-to-dna)
137 DBRefEntry[] rfs = DBRefUtils.selectDbRefs(!fromDna, seq.getDBRefs());
138 addXrefsToSources(rfs, sources);
142 * find sequence's direct (dna-to-dna, peptide-to-peptide) xrefs
144 DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna, seq.getDBRefs());
145 List<SequenceI> rseqs = new ArrayList<SequenceI>();
148 * find sequences in the alignment which xref one of these DBRefs
149 * i.e. is xref-ed to a common sequence identifier
151 searchDatasetXrefs(fromDna, seq, lrfs, rseqs, null);
154 * add those sequences' (dna-to-peptide or peptide-to-dna) dbref sources
156 for (SequenceI rs : rseqs)
158 DBRefEntry[] xrs = DBRefUtils
159 .selectDbRefs(!fromDna, rs.getDBRefs());
160 addXrefsToSources(xrs, sources);
166 * Helper method that adds the source identifiers of some cross-references to
167 * a (non-redundant) list of database sources
172 void addXrefsToSources(DBRefEntry[] xrefs, List<String> sources)
176 for (DBRefEntry ref : xrefs)
179 * avoid duplication e.g. ENSEMBL and Ensembl
181 String source = DBRefUtils.getCanonicalName(ref.getSource());
182 if (!sources.contains(source))
191 * Attempts to find cross-references from the sequences provided in the
192 * constructor to the given source database. Cross-references may be found
194 * <li>in dbrefs on the sequence which hold a mapping to a sequence
196 * <li>provided with a fetched sequence (e.g. ENA translation), or</li>
197 * <li>populated previously after getting cross-references</li>
199 * <li>as other sequences in the alignment which share a dbref identifier with
201 * <li>by fetching from the remote database</li>
203 * The cross-referenced sequences, and mappings to them, are added to the
207 * @return cross-referenced sequences (as dataset sequences)
209 public Alignment findXrefSequences(String source, boolean fromDna)
212 rseqs = new ArrayList<SequenceI>();
213 cf = new AlignedCodonFrame();
214 matcher = new SequenceIdMatcher(
215 dataset.getSequences());
217 for (SequenceI seq : fromSeqs)
220 while (dss.getDatasetSequence() != null)
222 dss = dss.getDatasetSequence();
224 boolean found = false;
225 DBRefEntry[] xrfs = DBRefUtils
226 .selectDbRefs(!fromDna, dss.getDBRefs());
227 if ((xrfs == null || xrfs.length == 0) && dataset != null)
230 * found no suitable dbrefs on sequence - look for sequences in the
231 * alignment which share a dbref with this one
233 DBRefEntry[] lrfs = DBRefUtils.selectDbRefs(fromDna,
237 * find sequences (except this one!), of complementary type,
238 * which have a dbref to an accession id for this sequence,
239 * and add them to the results
241 found = searchDatasetXrefs(fromDna, dss, lrfs, rseqs, cf);
243 if (xrfs == null && !found)
246 * no dbref to source on this sequence or matched
247 * complementary sequence in the dataset
251 List<DBRefEntry> sourceRefs = DBRefUtils.searchRefsForSource(xrfs,
253 Iterator<DBRefEntry> refIterator = sourceRefs.iterator();
254 while (refIterator.hasNext())
256 DBRefEntry xref = refIterator.next();
260 SequenceI mappedTo = xref.getMap().getTo();
261 if (mappedTo != null)
264 * dbref contains the sequence it maps to; add it to the
265 * results unless we have done so already (could happen if
266 * fetching xrefs for sequences which have xrefs in common)
267 * for example: UNIPROT {P0CE19, P0CE20} -> EMBL {J03321, X06707}
271 * problem: matcher.findIdMatch() is lenient - returns a sequence
272 * with a dbref to the search arg e.g. ENST for ENSP - wrong
273 * but findInDataset() matches ENSP when looking for Uniprot...
275 SequenceI matchInDataset = findInDataset(xref);
276 /*matcher.findIdMatch(mappedTo);*/
277 if (matchInDataset != null)
279 if (!rseqs.contains(matchInDataset))
281 rseqs.add(matchInDataset);
283 refIterator.remove();
286 SequenceI rsq = new Sequence(mappedTo);
288 if (xref.getMap().getMap().getFromRatio() != xref.getMap()
289 .getMap().getToRatio())
291 // get sense of map correct for adding to product alignment.
294 // map is from dna seq to a protein product
295 cf.addMap(dss, rsq, xref.getMap().getMap());
299 // map should be from protein seq to its coding dna
300 cf.addMap(rsq, dss, xref.getMap().getMap().getInverse());
308 SequenceI matchedSeq = matcher.findIdMatch(xref.getSource() + "|"
309 + xref.getAccessionId());
310 if (matchedSeq != null)
312 if (constructMapping(seq, matchedSeq, xref, cf, fromDna))
321 // do a bit more work - search for sequences with references matching
322 // xrefs on this sequence.
323 found = searchDataset(fromDna, dss, xref, rseqs, cf, false);
327 refIterator.remove();
332 * fetch from source database any dbrefs we haven't resolved up to here
334 if (!sourceRefs.isEmpty())
336 retrieveCrossRef(sourceRefs, seq, xrfs, fromDna);
340 Alignment ral = null;
341 if (rseqs.size() > 0)
343 ral = new Alignment(rseqs.toArray(new SequenceI[rseqs.size()]));
346 dataset.addCodonFrame(cf);
352 private void retrieveCrossRef(List<DBRefEntry> sourceRefs, SequenceI seq,
353 DBRefEntry[] xrfs, boolean fromDna)
355 ASequenceFetcher sftch = SequenceFetcherFactory.getSequenceFetcher();
356 SequenceI[] retrieved = null;
357 SequenceI dss = null;
360 retrieved = sftch.getSequences(sourceRefs, !fromDna);
361 } catch (Exception e)
364 .println("Problem whilst retrieving cross references for Sequence : "
369 if (retrieved != null)
371 updateDbrefMappings(seq, xrfs, retrieved, cf, fromDna);
372 for (SequenceI retrievedSequence : retrieved)
374 // dataset gets contaminated ccwith non-ds sequences. why ??!
375 // try: Ensembl -> Nuc->Ensembl, Nuc->Uniprot-->Protein->EMBL->
376 SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
377 : retrievedSequence.getDatasetSequence();
378 DBRefEntry[] dbr = retrievedSequence.getDBRefs();
381 for (DBRefEntry dbref : dbr)
383 // find any entry where we should put in the sequence being
384 // cross-referenced into the map
385 Mapping map = dbref.getMap();
388 if (map.getTo() != null && map.getMap() != null)
390 // TODO findInDataset requires exact sequence match but
391 // 'congruent' test is only for the mapped part
392 // maybe not a problem in practice since only ENA provide a
393 // mapping and it is to the full protein translation of CDS
394 SequenceI matched = findInDataset(dbref);
395 // matcher.findIdMatch(map.getTo());
399 * already got an xref to this sequence; update this
400 * map to point to the same sequence, and add
401 * any new dbrefs to it
403 DBRefEntry[] toRefs = map.getTo().getDBRefs();
406 for (DBRefEntry ref : toRefs)
408 matched.addDBRef(ref); // add or update mapping
415 matcher.add(map.getTo());
419 // compare ms with dss and replace with dss in mapping
420 // if map is congruent
421 SequenceI ms = map.getTo();
422 int sf = map.getMap().getToLowest();
423 int st = map.getMap().getToHighest();
424 SequenceI mappedrg = ms.getSubSequence(sf, st);
425 // SequenceI loc = dss.getSubSequence(sf, st);
426 if (mappedrg.getLength() > 0
427 && ms.getSequenceAsString().equals(
428 dss.getSequenceAsString()))
429 // && mappedrg.getSequenceAsString().equals(
430 // loc.getSequenceAsString()))
432 String msg = "Mapping updated from " + ms.getName()
433 + " to retrieved crossreference "
435 System.out.println(msg);
439 * give the reverse reference the inverse mapping
440 * (if it doesn't have one already)
442 setReverseMapping(dss, dbref, cf);
445 * copy sequence features as well, avoiding
446 * duplication (e.g. same variation from two
449 SequenceFeature[] sfs = ms.getSequenceFeatures();
452 for (SequenceFeature feat : sfs)
455 * make a flyweight feature object which ignores Parent
456 * attribute in equality test; this avoids creating many
457 * otherwise duplicate exon features on genomic sequence
459 SequenceFeature newFeature = new SequenceFeature(
463 public boolean equals(Object o)
465 return super.equals(o, true);
468 dss.addSequenceFeature(newFeature);
472 cf.addMap(retrievedDss, map.getTo(), map.getMap());
473 } catch (Exception e)
476 .println("Exception when consolidating Mapped sequence set...");
477 e.printStackTrace(System.err);
483 retrievedSequence.updatePDBIds();
484 rseqs.add(retrievedDss);
485 dataset.addSequence(retrievedDss);
486 matcher.add(retrievedDss);
491 * Sets the inverse sequence mapping in the corresponding dbref of the mapped
492 * to sequence (if any). This is used after fetching a cross-referenced
493 * sequence, if the fetched sequence has a mapping to the original sequence,
494 * to set the mapping in the original sequence's dbref.
497 * the sequence mapped from
501 void setReverseMapping(SequenceI mapFrom, DBRefEntry dbref,
502 AlignedCodonFrame mappings)
504 SequenceI mapTo = dbref.getMap().getTo();
509 DBRefEntry[] dbrefs = mapTo.getDBRefs();
514 for (DBRefEntry toRef : dbrefs)
516 if (toRef.hasMap() && mapFrom == toRef.getMap().getTo())
519 * found the reverse dbref; update its mapping if null
521 if (toRef.getMap().getMap() == null)
523 MapList inverse = dbref.getMap().getMap().getInverse();
524 toRef.getMap().setMap(inverse);
525 mappings.addMap(mapTo, mapFrom, inverse);
532 * Returns the first identical sequence in the dataset if any, else null
537 SequenceI findInDataset(DBRefEntry xref)
539 if (xref == null || !xref.hasMap() || xref.getMap().getTo() == null)
543 SequenceI mapsTo = xref.getMap().getTo();
544 String name = xref.getAccessionId();
545 String name2 = xref.getSource() + "|" + name;
546 SequenceI dss = mapsTo.getDatasetSequence() == null ? mapsTo : mapsTo
547 .getDatasetSequence();
548 for (SequenceI seq : dataset.getSequences())
551 * clumsy alternative to using SequenceIdMatcher which currently
552 * returns sequences with a dbref to the matched accession id
553 * which we don't want
555 if (name.equals(seq.getName()) || seq.getName().startsWith(name2))
557 if (sameSequence(seq, dss))
567 * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
568 * case), else false. This method compares the lengths, then each character in
569 * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
570 * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
576 // TODO move to Sequence / SequenceI
577 static boolean sameSequence(SequenceI seq1, SequenceI seq2)
583 if (seq1 == null || seq2 == null)
587 char[] c1 = seq1.getSequence();
588 char[] c2 = seq2.getSequence();
589 if (c1.length != c2.length)
593 for (int i = 0; i < c1.length; i++)
595 int diff = c1[i] - c2[i];
597 * same char or differ in case only ('a'-'A' == 32)
599 if (diff != 0 && diff != 32 && diff != -32)
608 * Updates any empty mappings in the cross-references with one to a compatible
609 * retrieved sequence if found, and adds any new mappings to the
617 void updateDbrefMappings(SequenceI mapFrom, DBRefEntry[] xrefs,
618 SequenceI[] retrieved, AlignedCodonFrame acf, boolean fromDna)
620 SequenceIdMatcher matcher = new SequenceIdMatcher(retrieved);
621 for (DBRefEntry xref : xrefs)
625 String targetSeqName = xref.getSource() + "|"
626 + xref.getAccessionId();
627 SequenceI[] matches = matcher.findAllIdMatches(targetSeqName);
632 for (SequenceI seq : matches)
634 constructMapping(mapFrom, seq, xref, acf, fromDna);
641 * Tries to make a mapping between sequences. If successful, adds the mapping
642 * to the dbref and the mappings collection and answers true, otherwise
643 * answers false. The following methods of making are mapping are tried in
646 * <li>if 'mapTo' holds a mapping to 'mapFrom', take the inverse; this is, for
647 * example, the case after fetching EMBL cross-references for a Uniprot
649 * <li>else check if the dna translates exactly to the protein (give or take
650 * start and stop codons></li>
651 * <li>else try to map based on CDS features on the dna sequence</li>
660 boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
661 DBRefEntry xref, AlignedCodonFrame mappings, boolean fromDna)
663 MapList mapping = null;
666 * look for a reverse mapping, if found make its inverse
668 if (mapTo.getDBRefs() != null)
670 for (DBRefEntry dbref : mapTo.getDBRefs())
672 String name = dbref.getSource() + "|" + dbref.getAccessionId();
673 if (dbref.hasMap() && mapFrom.getName().startsWith(name))
676 * looks like we've found a map from 'mapTo' to 'mapFrom'
677 * - invert it to make the mapping the other way
679 MapList reverse = dbref.getMap().getMap().getInverse();
680 xref.setMap(new Mapping(mapTo, reverse));
681 mappings.addMap(mapFrom, mapTo, reverse);
689 mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
693 mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
696 mapping = mapping.getInverse();
703 xref.setMap(new Mapping(mapTo, mapping));
706 AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
707 mappings.addMap(mapFrom, mapTo, mapping);
711 mappings.addMap(mapTo, mapFrom, mapping.getInverse());
718 * find references to lrfs in the cross-reference set of each sequence in
719 * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
720 * based on source and accession string only - Map and Version are nulled.
723 * - true if context was searching from Dna sequences, false if
724 * context was searching from Protein sequences
728 * @return true if matches were found.
730 private boolean searchDatasetXrefs(boolean fromDna, SequenceI sequenceI,
731 DBRefEntry[] lrfs, List<SequenceI> rseqs, AlignedCodonFrame cf)
733 boolean found = false;
738 for (int i = 0; i < lrfs.length; i++)
740 DBRefEntry xref = new DBRefEntry(lrfs[i]);
742 xref.setVersion(null);
744 found |= searchDataset(fromDna, sequenceI, xref, rseqs, cf, false);
750 * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
751 * associated sequence to rseqs
754 * true if context was searching for refs *from* dna sequence, false
755 * if context was searching for refs *from* protein sequence
757 * a sequence to ignore (start point of search)
759 * a cross-reference to try to match
761 * result list to add to
763 * a set of sequence mappings to add to
765 * - search all references or only subset
766 * @return true if relationship found and sequence added.
768 boolean searchDataset(boolean fromDna, SequenceI sequenceI,
769 DBRefEntry xrf, List<SequenceI> rseqs, AlignedCodonFrame cf,
772 boolean found = false;
777 if (dataset.getSequences() == null)
779 System.err.println("Empty dataset sequence set - NO VECTOR");
783 synchronized (ds = dataset.getSequences())
785 for (SequenceI nxt : ds)
789 if (nxt.getDatasetSequence() != null)
792 .println("Implementation warning: getProducts passed a dataset alignment without dataset sequences in it!");
794 if (nxt == sequenceI || nxt == sequenceI.getDatasetSequence())
799 * only look at same molecule type if 'direct', or
800 * complementary type if !direct
803 boolean isDna = !nxt.isProtein();
804 if (direct ? (isDna != fromDna) : (isDna == fromDna))
806 // skip this sequence because it is wrong molecule type
811 // look for direct or indirect references in common
812 DBRefEntry[] poss = nxt.getDBRefs();
813 List<DBRefEntry> cands = null;
815 * TODO does this make any sense?
816 * if 'direct', search the dbrefs for xrf
817 * else, filter the dbrefs by type and then search for xrf
818 * - the result is the same isn't it?
822 cands = DBRefUtils.searchRefs(poss, xrf);
826 poss = DBRefUtils.selectDbRefs(!fromDna, poss);
827 cands = DBRefUtils.searchRefs(poss, xrf);
829 if (!cands.isEmpty())
831 if (!rseqs.contains(nxt))
837 // don't search if we aren't given a codon map object
838 for (DBRefEntry candidate : cands)
840 Mapping mapping = candidate.getMap();
843 MapList map = mapping.getMap();
844 if (mapping.getTo() != null
845 && map.getFromRatio() != map.getToRatio())
847 // get sense of map correct for adding to product
851 // map is from dna seq to a protein product
852 cf.addMap(sequenceI, nxt, map);
856 // map should be from protein seq to its coding dna
857 cf.addMap(nxt, sequenceI, map.getInverse());
863 // TODO: add mapping between sequences if necessary