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 = seq.getDatasetSequence() == null ? seq : seq
361 .getDatasetSequence();
364 retrieved = sftch.getSequences(sourceRefs, !fromDna);
365 } catch (Exception e)
368 .println("Problem whilst retrieving cross references for Sequence : "
373 if (retrieved != null)
375 updateDbrefMappings(seq, xrfs, retrieved, cf, fromDna);
376 for (SequenceI retrievedSequence : retrieved)
378 // dataset gets contaminated ccwith non-ds sequences. why ??!
379 // try: Ensembl -> Nuc->Ensembl, Nuc->Uniprot-->Protein->EMBL->
380 SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
381 : retrievedSequence.getDatasetSequence();
382 DBRefEntry[] dbr = retrievedSequence.getDBRefs();
385 for (DBRefEntry dbref : dbr)
387 // find any entry where we should put in the sequence being
388 // cross-referenced into the map
389 Mapping map = dbref.getMap();
392 if (map.getTo() != null && map.getMap() != null)
394 // TODO findInDataset requires exact sequence match but
395 // 'congruent' test is only for the mapped part
396 // maybe not a problem in practice since only ENA provide a
397 // mapping and it is to the full protein translation of CDS
398 SequenceI matched = findInDataset(dbref);
399 // matcher.findIdMatch(map.getTo());
403 * already got an xref to this sequence; update this
404 * map to point to the same sequence, and add
405 * any new dbrefs to it
407 DBRefEntry[] toRefs = map.getTo().getDBRefs();
410 for (DBRefEntry ref : toRefs)
412 matched.addDBRef(ref); // add or update mapping
419 matcher.add(map.getTo());
423 // compare ms with dss and replace with dss in mapping
424 // if map is congruent
425 SequenceI ms = map.getTo();
426 int sf = map.getMap().getToLowest();
427 int st = map.getMap().getToHighest();
428 SequenceI mappedrg = ms.getSubSequence(sf, st);
429 // SequenceI loc = dss.getSubSequence(sf, st);
430 if (mappedrg.getLength() > 0
431 && ms.getSequenceAsString().equals(
432 dss.getSequenceAsString()))
433 // && mappedrg.getSequenceAsString().equals(
434 // loc.getSequenceAsString()))
436 String msg = "Mapping updated from " + ms.getName()
437 + " to retrieved crossreference "
439 System.out.println(msg);
443 * give the reverse reference the inverse mapping
444 * (if it doesn't have one already)
446 setReverseMapping(dss, dbref, cf);
449 * copy sequence features as well, avoiding
450 * duplication (e.g. same variation from two
453 SequenceFeature[] sfs = ms.getSequenceFeatures();
456 for (SequenceFeature feat : sfs)
459 * make a flyweight feature object which ignores Parent
460 * attribute in equality test; this avoids creating many
461 * otherwise duplicate exon features on genomic sequence
463 SequenceFeature newFeature = new SequenceFeature(
467 public boolean equals(Object o)
469 return super.equals(o, true);
472 dss.addSequenceFeature(newFeature);
476 cf.addMap(retrievedDss, map.getTo(), map.getMap());
477 } catch (Exception e)
480 .println("Exception when consolidating Mapped sequence set...");
481 e.printStackTrace(System.err);
487 retrievedSequence.updatePDBIds();
488 rseqs.add(retrievedDss);
489 dataset.addSequence(retrievedDss);
490 matcher.add(retrievedDss);
495 * Sets the inverse sequence mapping in the corresponding dbref of the mapped
496 * to sequence (if any). This is used after fetching a cross-referenced
497 * sequence, if the fetched sequence has a mapping to the original sequence,
498 * to set the mapping in the original sequence's dbref.
501 * the sequence mapped from
505 void setReverseMapping(SequenceI mapFrom, DBRefEntry dbref,
506 AlignedCodonFrame mappings)
508 SequenceI mapTo = dbref.getMap().getTo();
513 DBRefEntry[] dbrefs = mapTo.getDBRefs();
518 for (DBRefEntry toRef : dbrefs)
520 if (toRef.hasMap() && mapFrom == toRef.getMap().getTo())
523 * found the reverse dbref; update its mapping if null
525 if (toRef.getMap().getMap() == null)
527 MapList inverse = dbref.getMap().getMap().getInverse();
528 toRef.getMap().setMap(inverse);
529 mappings.addMap(mapTo, mapFrom, inverse);
536 * Returns the first identical sequence in the dataset if any, else null
541 SequenceI findInDataset(DBRefEntry xref)
543 if (xref == null || !xref.hasMap() || xref.getMap().getTo() == null)
547 SequenceI mapsTo = xref.getMap().getTo();
548 String name = xref.getAccessionId();
549 String name2 = xref.getSource() + "|" + name;
550 SequenceI dss = mapsTo.getDatasetSequence() == null ? mapsTo : mapsTo
551 .getDatasetSequence();
552 for (SequenceI seq : dataset.getSequences())
555 * clumsy alternative to using SequenceIdMatcher which currently
556 * returns sequences with a dbref to the matched accession id
557 * which we don't want
559 if (name.equals(seq.getName()) || seq.getName().startsWith(name2))
561 if (sameSequence(seq, dss))
571 * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
572 * case), else false. This method compares the lengths, then each character in
573 * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
574 * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
580 // TODO move to Sequence / SequenceI
581 static boolean sameSequence(SequenceI seq1, SequenceI seq2)
587 if (seq1 == null || seq2 == null)
591 char[] c1 = seq1.getSequence();
592 char[] c2 = seq2.getSequence();
593 if (c1.length != c2.length)
597 for (int i = 0; i < c1.length; i++)
599 int diff = c1[i] - c2[i];
601 * same char or differ in case only ('a'-'A' == 32)
603 if (diff != 0 && diff != 32 && diff != -32)
612 * Updates any empty mappings in the cross-references with one to a compatible
613 * retrieved sequence if found, and adds any new mappings to the
621 void updateDbrefMappings(SequenceI mapFrom, DBRefEntry[] xrefs,
622 SequenceI[] retrieved, AlignedCodonFrame acf, boolean fromDna)
624 SequenceIdMatcher matcher = new SequenceIdMatcher(retrieved);
625 for (DBRefEntry xref : xrefs)
629 String targetSeqName = xref.getSource() + "|"
630 + xref.getAccessionId();
631 SequenceI[] matches = matcher.findAllIdMatches(targetSeqName);
636 for (SequenceI seq : matches)
638 constructMapping(mapFrom, seq, xref, acf, fromDna);
645 * Tries to make a mapping between sequences. If successful, adds the mapping
646 * to the dbref and the mappings collection and answers true, otherwise
647 * answers false. The following methods of making are mapping are tried in
650 * <li>if 'mapTo' holds a mapping to 'mapFrom', take the inverse; this is, for
651 * example, the case after fetching EMBL cross-references for a Uniprot
653 * <li>else check if the dna translates exactly to the protein (give or take
654 * start and stop codons></li>
655 * <li>else try to map based on CDS features on the dna sequence</li>
664 boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
665 DBRefEntry xref, AlignedCodonFrame mappings, boolean fromDna)
667 MapList mapping = null;
670 * look for a reverse mapping, if found make its inverse
672 if (mapTo.getDBRefs() != null)
674 for (DBRefEntry dbref : mapTo.getDBRefs())
676 String name = dbref.getSource() + "|" + dbref.getAccessionId();
677 if (dbref.hasMap() && mapFrom.getName().startsWith(name))
680 * looks like we've found a map from 'mapTo' to 'mapFrom'
681 * - invert it to make the mapping the other way
683 MapList reverse = dbref.getMap().getMap().getInverse();
684 xref.setMap(new Mapping(mapTo, reverse));
685 mappings.addMap(mapFrom, mapTo, reverse);
693 mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
697 mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
700 mapping = mapping.getInverse();
707 xref.setMap(new Mapping(mapTo, mapping));
710 AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
711 mappings.addMap(mapFrom, mapTo, mapping);
715 mappings.addMap(mapTo, mapFrom, mapping.getInverse());
722 * find references to lrfs in the cross-reference set of each sequence in
723 * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
724 * based on source and accession string only - Map and Version are nulled.
727 * - true if context was searching from Dna sequences, false if
728 * context was searching from Protein sequences
732 * @return true if matches were found.
734 private boolean searchDatasetXrefs(boolean fromDna, SequenceI sequenceI,
735 DBRefEntry[] lrfs, List<SequenceI> rseqs, AlignedCodonFrame cf)
737 boolean found = false;
742 for (int i = 0; i < lrfs.length; i++)
744 DBRefEntry xref = new DBRefEntry(lrfs[i]);
746 xref.setVersion(null);
748 found |= searchDataset(fromDna, sequenceI, xref, rseqs, cf, false);
754 * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
755 * associated sequence to rseqs
758 * true if context was searching for refs *from* dna sequence, false
759 * if context was searching for refs *from* protein sequence
761 * a sequence to ignore (start point of search)
763 * a cross-reference to try to match
765 * result list to add to
767 * a set of sequence mappings to add to
769 * - indicates the type of relationship between returned sequences,
770 * xrf, and sequenceI that is required.
772 * <li>direct implies xrf is a primary reference for sequenceI AND
773 * the sequences to be located (eg a uniprot ID for a protein
774 * sequence, and a uniprot ref on a transcript sequence).</li>
775 * <li>indirect means xrf is a cross reference with respect to
776 * sequenceI or all the returned sequences (eg a genomic reference
777 * associated with a locus and one or more transcripts)</li>
779 * @return true if relationship found and sequence added.
781 boolean searchDataset(boolean fromDna, SequenceI sequenceI,
782 DBRefEntry xrf, List<SequenceI> rseqs, AlignedCodonFrame cf,
785 boolean found = false;
790 if (dataset.getSequences() == null)
792 System.err.println("Empty dataset sequence set - NO VECTOR");
796 synchronized (ds = dataset.getSequences())
798 for (SequenceI nxt : ds)
802 if (nxt.getDatasetSequence() != null)
805 .println("Implementation warning: CrossRef initialised with a dataset alignment with non-dataset sequences in it! ("
806 + nxt.getDisplayId(true)
807 + " has ds reference "
808 + nxt.getDatasetSequence().getDisplayId(true)
811 if (nxt == sequenceI || nxt == sequenceI.getDatasetSequence())
816 * only look at same molecule type if 'direct', or
817 * complementary type if !direct
820 boolean isDna = !nxt.isProtein();
821 if (direct ? (isDna != fromDna) : (isDna == fromDna))
823 // skip this sequence because it is wrong molecule type
828 // look for direct or indirect references in common
829 DBRefEntry[] poss = nxt.getDBRefs();
830 List<DBRefEntry> cands = null;
832 // todo: indirect specifies we select either direct references to nxt
833 // that match xrf which is indirect to sequenceI, or indirect
834 // references to nxt that match xrf which is direct to sequenceI
835 cands = DBRefUtils.searchRefs(poss, xrf);
838 // poss = DBRefUtils.selectDbRefs(nxt.isProtein()!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