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> foundSeqs = 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, foundSeqs, null);
157 * add those sequences' (dna-to-peptide or peptide-to-dna) dbref sources
159 for (SequenceI rs : foundSeqs)
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(), xref.getMap()
303 // map should be from protein seq to its coding dna
304 cf.addMap(rsq, dss, xref.getMap().getMap().getInverse(),
305 xref.getMap().getMappedFromId());
313 SequenceI matchedSeq = matcher.findIdMatch(xref.getSource() + "|"
314 + xref.getAccessionId());
315 if (matchedSeq != null)
317 if (constructMapping(seq, matchedSeq, xref, cf, fromDna))
326 // do a bit more work - search for sequences with references matching
327 // xrefs on this sequence.
328 found = searchDataset(fromDna, dss, xref, rseqs, cf, false);
332 refIterator.remove();
337 * fetch from source database any dbrefs we haven't resolved up to here
339 if (!sourceRefs.isEmpty())
341 retrieveCrossRef(sourceRefs, seq, xrfs, fromDna);
345 Alignment ral = null;
346 if (rseqs.size() > 0)
348 ral = new Alignment(rseqs.toArray(new SequenceI[rseqs.size()]));
351 dataset.addCodonFrame(cf);
357 private void retrieveCrossRef(List<DBRefEntry> sourceRefs, SequenceI seq,
358 DBRefEntry[] xrfs, boolean fromDna)
360 ASequenceFetcher sftch = SequenceFetcherFactory.getSequenceFetcher();
361 SequenceI[] retrieved = null;
362 SequenceI dss = seq.getDatasetSequence() == null ? seq : seq
363 .getDatasetSequence();
366 retrieved = sftch.getSequences(sourceRefs, !fromDna);
367 } catch (Exception e)
370 .println("Problem whilst retrieving cross references for Sequence : "
375 if (retrieved != null)
377 updateDbrefMappings(seq, xrfs, retrieved, cf, fromDna);
378 for (SequenceI retrievedSequence : retrieved)
380 // dataset gets contaminated ccwith non-ds sequences. why ??!
381 // try: Ensembl -> Nuc->Ensembl, Nuc->Uniprot-->Protein->EMBL->
382 SequenceI retrievedDss = retrievedSequence.getDatasetSequence() == null ? retrievedSequence
383 : retrievedSequence.getDatasetSequence();
384 DBRefEntry[] dbr = retrievedSequence.getDBRefs();
387 for (DBRefEntry dbref : dbr)
389 // find any entry where we should put in the sequence being
390 // cross-referenced into the map
391 Mapping map = dbref.getMap();
394 if (map.getTo() != null && map.getMap() != null)
396 // TODO findInDataset requires exact sequence match but
397 // 'congruent' test is only for the mapped part
398 // maybe not a problem in practice since only ENA provide a
399 // mapping and it is to the full protein translation of CDS
400 SequenceI matched = findInDataset(dbref);
401 // matcher.findIdMatch(map.getTo());
405 * already got an xref to this sequence; update this
406 * map to point to the same sequence, and add
407 * any new dbrefs to it
409 DBRefEntry[] toRefs = map.getTo().getDBRefs();
412 for (DBRefEntry ref : toRefs)
414 matched.addDBRef(ref); // add or update mapping
421 matcher.add(map.getTo());
425 // compare ms with dss and replace with dss in mapping
426 // if map is congruent
427 SequenceI ms = map.getTo();
428 int sf = map.getMap().getToLowest();
429 int st = map.getMap().getToHighest();
430 SequenceI mappedrg = ms.getSubSequence(sf, st);
431 // SequenceI loc = dss.getSubSequence(sf, st);
432 if (mappedrg.getLength() > 0
433 && ms.getSequenceAsString().equals(
434 dss.getSequenceAsString()))
435 // && mappedrg.getSequenceAsString().equals(
436 // loc.getSequenceAsString()))
438 String msg = "Mapping updated from " + ms.getName()
439 + " to retrieved crossreference "
441 System.out.println(msg);
445 * give the reverse reference the inverse mapping
446 * (if it doesn't have one already)
448 setReverseMapping(dss, dbref, cf);
451 * copy sequence features as well, avoiding
452 * duplication (e.g. same variation from two
455 SequenceFeature[] sfs = ms.getSequenceFeatures();
458 for (SequenceFeature feat : sfs)
461 * make a flyweight feature object which ignores Parent
462 * attribute in equality test; this avoids creating many
463 * otherwise duplicate exon features on genomic sequence
465 SequenceFeature newFeature = new SequenceFeature(
469 public boolean equals(Object o)
471 return super.equals(o, true);
474 dss.addSequenceFeature(newFeature);
478 cf.addMap(retrievedDss, map.getTo(), map.getMap());
479 } catch (Exception e)
482 .println("Exception when consolidating Mapped sequence set...");
483 e.printStackTrace(System.err);
489 retrievedSequence.updatePDBIds();
490 rseqs.add(retrievedDss);
491 dataset.addSequence(retrievedDss);
492 matcher.add(retrievedDss);
497 * Sets the inverse sequence mapping in the corresponding dbref of the mapped
498 * to sequence (if any). This is used after fetching a cross-referenced
499 * sequence, if the fetched sequence has a mapping to the original sequence,
500 * to set the mapping in the original sequence's dbref.
503 * the sequence mapped from
507 void setReverseMapping(SequenceI mapFrom, DBRefEntry dbref,
508 AlignedCodonFrame mappings)
510 SequenceI mapTo = dbref.getMap().getTo();
515 DBRefEntry[] dbrefs = mapTo.getDBRefs();
520 for (DBRefEntry toRef : dbrefs)
522 if (toRef.hasMap() && mapFrom == toRef.getMap().getTo())
525 * found the reverse dbref; update its mapping if null
527 if (toRef.getMap().getMap() == null)
529 MapList inverse = dbref.getMap().getMap().getInverse();
530 toRef.getMap().setMap(inverse);
531 mappings.addMap(mapTo, mapFrom, inverse);
538 * Returns the first identical sequence in the dataset if any, else null
543 SequenceI findInDataset(DBRefEntry xref)
545 if (xref == null || !xref.hasMap() || xref.getMap().getTo() == null)
549 SequenceI mapsTo = xref.getMap().getTo();
550 String name = xref.getAccessionId();
551 String name2 = xref.getSource() + "|" + name;
552 SequenceI dss = mapsTo.getDatasetSequence() == null ? mapsTo : mapsTo
553 .getDatasetSequence();
554 for (SequenceI seq : dataset.getSequences())
557 * clumsy alternative to using SequenceIdMatcher which currently
558 * returns sequences with a dbref to the matched accession id
559 * which we don't want
561 if (name.equals(seq.getName()) || seq.getName().startsWith(name2))
563 if (sameSequence(seq, dss))
573 * Answers true if seq1 and seq2 contain exactly the same characters (ignoring
574 * case), else false. This method compares the lengths, then each character in
575 * turn, in order to 'fail fast'. For case-sensitive comparison, it would be
576 * possible to use Arrays.equals(seq1.getSequence(), seq2.getSequence()).
582 // TODO move to Sequence / SequenceI
583 static boolean sameSequence(SequenceI seq1, SequenceI seq2)
589 if (seq1 == null || seq2 == null)
593 char[] c1 = seq1.getSequence();
594 char[] c2 = seq2.getSequence();
595 if (c1.length != c2.length)
599 for (int i = 0; i < c1.length; i++)
601 int diff = c1[i] - c2[i];
603 * same char or differ in case only ('a'-'A' == 32)
605 if (diff != 0 && diff != 32 && diff != -32)
614 * Updates any empty mappings in the cross-references with one to a compatible
615 * retrieved sequence if found, and adds any new mappings to the
623 void updateDbrefMappings(SequenceI mapFrom, DBRefEntry[] xrefs,
624 SequenceI[] retrieved, AlignedCodonFrame acf, boolean fromDna)
626 SequenceIdMatcher idMatcher = new SequenceIdMatcher(retrieved);
627 for (DBRefEntry xref : xrefs)
631 String targetSeqName = xref.getSource() + "|"
632 + xref.getAccessionId();
633 SequenceI[] matches = idMatcher.findAllIdMatches(targetSeqName);
638 for (SequenceI seq : matches)
640 constructMapping(mapFrom, seq, xref, acf, fromDna);
647 * Tries to make a mapping between sequences. If successful, adds the mapping
648 * to the dbref and the mappings collection and answers true, otherwise
649 * answers false. The following methods of making are mapping are tried in
652 * <li>if 'mapTo' holds a mapping to 'mapFrom', take the inverse; this is, for
653 * example, the case after fetching EMBL cross-references for a Uniprot
655 * <li>else check if the dna translates exactly to the protein (give or take
656 * start and stop codons></li>
657 * <li>else try to map based on CDS features on the dna sequence</li>
666 boolean constructMapping(SequenceI mapFrom, SequenceI mapTo,
667 DBRefEntry xref, AlignedCodonFrame mappings, boolean fromDna)
669 MapList mapping = null;
672 * look for a reverse mapping, if found make its inverse
674 if (mapTo.getDBRefs() != null)
676 for (DBRefEntry dbref : mapTo.getDBRefs())
678 String name = dbref.getSource() + "|" + dbref.getAccessionId();
679 if (dbref.hasMap() && mapFrom.getName().startsWith(name))
682 * looks like we've found a map from 'mapTo' to 'mapFrom'
683 * - invert it to make the mapping the other way
685 MapList reverse = dbref.getMap().getMap().getInverse();
686 xref.setMap(new Mapping(mapTo, reverse));
687 mappings.addMap(mapFrom, mapTo, reverse);
695 mapping = AlignmentUtils.mapCdnaToProtein(mapTo, mapFrom);
699 mapping = AlignmentUtils.mapCdnaToProtein(mapFrom, mapTo);
702 mapping = mapping.getInverse();
709 xref.setMap(new Mapping(mapTo, mapping));
712 * and add a reverse DbRef with the inverse mapping
714 if (mapFrom.getDatasetSequence() != null
715 && mapFrom.getDatasetSequence().getSourceDBRef() != null)
717 DBRefEntry dbref = new DBRefEntry(mapFrom.getDatasetSequence()
719 dbref.setMap(new Mapping(mapFrom.getDatasetSequence(), mapping
721 mapTo.addDBRef(dbref);
726 AlignmentUtils.computeProteinFeatures(mapFrom, mapTo, mapping);
727 mappings.addMap(mapFrom, mapTo, mapping);
731 mappings.addMap(mapTo, mapFrom, mapping.getInverse());
738 * find references to lrfs in the cross-reference set of each sequence in
739 * dataset (that is not equal to sequenceI) Identifies matching DBRefEntry
740 * based on source and accession string only - Map and Version are nulled.
743 * - true if context was searching from Dna sequences, false if
744 * context was searching from Protein sequences
748 * @return true if matches were found.
750 private boolean searchDatasetXrefs(boolean fromDna, SequenceI sequenceI,
751 DBRefEntry[] lrfs, List<SequenceI> foundSeqs, AlignedCodonFrame cf)
753 boolean found = false;
758 for (int i = 0; i < lrfs.length; i++)
760 DBRefEntry xref = new DBRefEntry(lrfs[i]);
762 xref.setVersion(null);
764 found |= searchDataset(fromDna, sequenceI, xref, foundSeqs, cf, false);
770 * Searches dataset for DBRefEntrys matching the given one (xrf) and adds the
771 * associated sequence to rseqs
774 * true if context was searching for refs *from* dna sequence, false
775 * if context was searching for refs *from* protein sequence
777 * a sequence to ignore (start point of search)
779 * a cross-reference to try to match
781 * result list to add to
783 * a set of sequence mappings to add to
785 * - indicates the type of relationship between returned sequences,
786 * xrf, and sequenceI that is required.
788 * <li>direct implies xrf is a primary reference for sequenceI AND
789 * the sequences to be located (eg a uniprot ID for a protein
790 * sequence, and a uniprot ref on a transcript sequence).</li>
791 * <li>indirect means xrf is a cross reference with respect to
792 * sequenceI or all the returned sequences (eg a genomic reference
793 * associated with a locus and one or more transcripts)</li>
795 * @return true if relationship found and sequence added.
797 boolean searchDataset(boolean fromDna, SequenceI fromSeq,
798 DBRefEntry xrf, List<SequenceI> foundSeqs, AlignedCodonFrame mappings,
801 boolean found = false;
806 if (dataset.getSequences() == null)
808 System.err.println("Empty dataset sequence set - NO VECTOR");
812 synchronized (ds = dataset.getSequences())
814 for (SequenceI nxt : ds)
818 if (nxt.getDatasetSequence() != null)
821 .println("Implementation warning: CrossRef initialised with a dataset alignment with non-dataset sequences in it! ("
822 + nxt.getDisplayId(true)
823 + " has ds reference "
824 + nxt.getDatasetSequence().getDisplayId(true)
827 if (nxt == fromSeq || nxt == fromSeq.getDatasetSequence())
832 * only look at same molecule type if 'direct', or
833 * complementary type if !direct
836 boolean isDna = !nxt.isProtein();
837 if (direct ? (isDna != fromDna) : (isDna == fromDna))
839 // skip this sequence because it is wrong molecule type
844 // look for direct or indirect references in common
845 DBRefEntry[] poss = nxt.getDBRefs();
846 List<DBRefEntry> cands = null;
848 // todo: indirect specifies we select either direct references to nxt
849 // that match xrf which is indirect to sequenceI, or indirect
850 // references to nxt that match xrf which is direct to sequenceI
851 cands = DBRefUtils.searchRefs(poss, xrf);
854 // poss = DBRefUtils.selectDbRefs(nxt.isProtein()!fromDna, poss);
855 // cands = DBRefUtils.searchRefs(poss, xrf);
857 if (!cands.isEmpty())
859 if (!foundSeqs.contains(nxt))
863 if (mappings != null && !direct)
866 * if the matched sequence has mapped dbrefs to
867 * protein product / cdna, add equivalent mappings to
868 * our source sequence
870 for (DBRefEntry candidate : cands)
872 Mapping mapping = candidate.getMap();
875 MapList map = mapping.getMap();
876 if (mapping.getTo() != null
877 && map.getFromRatio() != map.getToRatio())
880 * add a mapping, as from dna to peptide sequence
882 if (map.getFromRatio() == 3)
884 mappings.addMap(nxt, fromSeq, map);
888 mappings.addMap(nxt, fromSeq, map.getInverse());