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.datamodel;
23 import java.util.AbstractList;
24 import java.util.ArrayList;
25 import java.util.List;
27 import jalview.util.MapList;
28 import jalview.util.MappingUtils;
31 * Stores mapping between the columns of a protein alignment and a DNA alignment
32 * and a list of individual codon to amino acid mappings between sequences.
34 public class AlignedCodonFrame
38 * Data bean to hold mappings from one sequence to another
40 public class SequenceToSequenceMapping
42 private SequenceI fromSeq;
44 private Mapping mapping;
46 SequenceToSequenceMapping(SequenceI from, Mapping map)
53 * Readable representation for debugging only, not guaranteed not to change
56 public String toString()
58 return String.format("From %s %s", fromSeq.getName(),
63 * Returns a hashCode derived from the hashcodes of the mappings and fromSeq
65 * @see SequenceToSequenceMapping#hashCode()
70 return (fromSeq == null ? 0 : fromSeq.hashCode() * 31)
75 * Answers true if the objects hold the same mapping between the same two
81 public boolean equals(Object obj)
83 if (!(obj instanceof SequenceToSequenceMapping))
87 SequenceToSequenceMapping that = (SequenceToSequenceMapping) obj;
88 if (this.mapping == null)
90 return that.mapping == null;
92 // TODO: can simplify by asserting fromSeq is a dataset sequence
93 return (this.fromSeq == that.fromSeq
94 || (this.fromSeq != null && that.fromSeq != null
95 && this.fromSeq.getDatasetSequence() != null
96 && this.fromSeq.getDatasetSequence() == that.fromSeq
97 .getDatasetSequence()))
98 && this.mapping.equals(that.mapping);
101 public SequenceI getFromSeq()
106 public Mapping getMapping()
112 * Returns true if the mapping covers the full length of the given sequence.
113 * This allows us to distinguish the CDS that codes for a protein from
114 * another overlapping CDS in the parent dna sequence.
119 public boolean covers(SequenceI seq)
121 return covers(seq, false, false);
128 * - when true - compare extent of seq's dataset sequence rather
129 * than the local extent
131 * - when true coverage is required for either seq or the mapped
133 * @return true if mapping covers full length of given sequence (or the
134 * other if either==true)
136 public boolean covers(SequenceI seq, boolean localCover, boolean either)
138 List<int[]> mappedRanges = null, otherRanges = null;
139 MapList mapList = mapping.getMap();
140 int mstart = seq.getStart(), mend = seq.getEnd(), ostart, oend;
142 if (fromSeq == seq || fromSeq == seq.getDatasetSequence())
144 if (localCover && fromSeq != seq)
146 mstart = fromSeq.getStart();
147 mend = fromSeq.getEnd();
149 mappedRanges = mapList.getFromRanges();
150 otherRanges = mapList.getToRanges();
151 ostart = mapping.to.getStart();
152 oend = mapping.to.getEnd();
154 else if (mapping.to == seq || mapping.to == seq.getDatasetSequence())
156 if (localCover && mapping.to != seq)
158 mstart = mapping.to.getStart();
159 mend = mapping.to.getEnd();
161 mappedRanges = mapList.getToRanges();
162 otherRanges = mapList.getFromRanges();
163 ostart = fromSeq.getStart();
164 oend = fromSeq.getEnd();
172 * check that each mapped range lies within the sequence range
173 * (necessary for circular CDS - example EMBL:J03321:AAA91567)
174 * and mapped length covers (at least) sequence length
176 int length = countRange(mappedRanges, mstart, mend);
180 // add 3 to mapped length to allow for a mapped stop codon
181 if (length + 3 >= (mend - mstart + 1))
188 // also check coverage of the other range
189 length = countRange(otherRanges, ostart, oend);
192 if (length + 1 >= (oend - ostart + 1))
201 private int countRange(List<int[]> mappedRanges, int mstart, int mend)
204 for (int[] range : mappedRanges)
206 int from = Math.min(range[0], range[1]);
207 int to = Math.max(range[0], range[1]);
208 if (from < mstart || to > mend)
212 length += (to - from + 1);
218 * Adds any regions mapped to or from position {@code pos} in sequence
219 * {@code seq} to the given search results Note: recommend first using the
220 * .covers(,true,true) to ensure mapping covers both sequences
226 public void markMappedRegion(SequenceI seq, int pos, SearchResultsI sr)
229 SequenceI mappedSeq = null;
230 SequenceI ds = seq.getDatasetSequence();
236 if (this.fromSeq == seq || this.fromSeq == ds)
238 codon = this.mapping.map.locateInTo(pos, pos);
239 mappedSeq = this.mapping.to;
241 else if (this.mapping.to == seq || this.mapping.to == ds)
243 codon = this.mapping.map.locateInFrom(pos, pos);
244 mappedSeq = this.fromSeq;
249 for (int i = 0; i < codon.length; i += 2)
251 sr.addResult(mappedSeq, codon[i], codon[i + 1]);
257 private List<SequenceToSequenceMapping> mappings;
262 public AlignedCodonFrame()
264 mappings = new ArrayList<>();
268 * Adds a mapping between the dataset sequences for the associated dna and
269 * protein sequence objects
275 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map)
277 addMap(dnaseq, aaseq, map, null);
281 * Adds a mapping between the dataset sequences for the associated dna and
282 * protein sequence objects
289 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map,
292 // JBPNote DEBUG! THIS !
293 // dnaseq.transferAnnotation(aaseq, mp);
294 // aaseq.transferAnnotation(dnaseq, new Mapping(map.getInverse()));
296 SequenceI fromSeq = (dnaseq.getDatasetSequence() == null) ? dnaseq
297 : dnaseq.getDatasetSequence();
298 SequenceI toSeq = (aaseq.getDatasetSequence() == null) ? aaseq
299 : aaseq.getDatasetSequence();
302 * if we already hold a mapping between these sequences, just add to it
303 * note that 'adding' a duplicate map does nothing; this protects against
304 * creating duplicate mappings in AlignedCodonFrame
306 for (SequenceToSequenceMapping ssm : mappings)
308 if (ssm.fromSeq == fromSeq && ssm.mapping.to == toSeq)
310 ssm.mapping.map.addMapList(map);
316 * otherwise, add a new sequence mapping
318 Mapping mp = new Mapping(toSeq, map);
319 mp.setMappedFromId(mapFromId);
320 mappings.add(new SequenceToSequenceMapping(fromSeq, mp));
323 public SequenceI[] getdnaSeqs()
325 // TODO return a list instead?
327 List<SequenceI> seqs = new ArrayList<>();
328 for (SequenceToSequenceMapping ssm : mappings)
330 seqs.add(ssm.fromSeq);
332 return seqs.toArray(new SequenceI[seqs.size()]);
335 public SequenceI[] getAaSeqs()
337 // TODO not used - remove?
338 List<SequenceI> seqs = new ArrayList<>();
339 for (SequenceToSequenceMapping ssm : mappings)
341 seqs.add(ssm.mapping.to);
343 return seqs.toArray(new SequenceI[seqs.size()]);
346 public MapList[] getdnaToProt()
348 List<MapList> maps = new ArrayList<>();
349 for (SequenceToSequenceMapping ssm : mappings)
351 maps.add(ssm.mapping.map);
353 return maps.toArray(new MapList[maps.size()]);
356 public Mapping[] getProtMappings()
358 List<Mapping> maps = new ArrayList<>();
359 for (SequenceToSequenceMapping ssm : mappings)
361 maps.add(ssm.mapping);
363 return maps.toArray(new Mapping[maps.size()]);
367 * Returns the first mapping found which is to or from the given sequence, or
368 * null if none is found
373 public Mapping getMappingForSequence(SequenceI seq)
375 SequenceI seqDs = seq.getDatasetSequence();
376 seqDs = seqDs != null ? seqDs : seq;
378 for (SequenceToSequenceMapping ssm : mappings)
380 if (ssm.fromSeq == seqDs || ssm.mapping.to == seqDs)
389 * Return the corresponding aligned or dataset aa sequence for given dna
390 * sequence, null if not found.
395 public SequenceI getAaForDnaSeq(SequenceI dnaSeqRef)
397 SequenceI dnads = dnaSeqRef.getDatasetSequence();
398 for (SequenceToSequenceMapping ssm : mappings)
400 if (ssm.fromSeq == dnaSeqRef || ssm.fromSeq == dnads)
402 return ssm.mapping.to;
409 * Return the corresponding aligned or dataset dna sequence for given amino
410 * acid sequence, or null if not found. returns the sequence from the first
411 * mapping found that involves the protein sequence.
416 public SequenceI getDnaForAaSeq(SequenceI aaSeqRef)
418 SequenceI aads = aaSeqRef.getDatasetSequence();
419 for (SequenceToSequenceMapping ssm : mappings)
421 if (ssm.mapping.to == aaSeqRef || ssm.mapping.to == aads)
430 * test to see if codon frame involves seq in any way
433 * a nucleotide or protein sequence
434 * @return true if a mapping exists to or from this sequence to any translated
437 public boolean involvesSequence(SequenceI seq)
439 return getAaForDnaSeq(seq) != null || getDnaForAaSeq(seq) != null;
443 * Add search results for regions in other sequences that translate or are
444 * translated from a particular position in seq (which may be an aligned or
451 * where highlighted regions go
453 public void markMappedRegion(SequenceI seq, int index,
454 SearchResultsI results)
456 SequenceI ds = seq.getDatasetSequence();
461 for (SequenceToSequenceMapping ssm : mappings)
463 if (ssm.covers(seq, true, true))
465 ssm.markMappedRegion(ds, index, results);
471 * Convenience method to return the first aligned sequence in the given
472 * alignment whose dataset has a mapping with the given (aligned or dataset)
480 public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al)
483 * Search mapped protein ('to') sequences first.
485 for (SequenceToSequenceMapping ssm : mappings)
487 if (ssm.fromSeq == seq || ssm.fromSeq == seq.getDatasetSequence())
489 for (SequenceI sourceAligned : al.getSequences())
491 if (ssm.mapping.to == sourceAligned.getDatasetSequence()
492 || ssm.mapping.to == sourceAligned)
494 return sourceAligned;
501 * Then try mapped dna sequences.
503 for (SequenceToSequenceMapping ssm : mappings)
505 if (ssm.mapping.to == seq
506 || ssm.mapping.to == seq.getDatasetSequence())
508 for (SequenceI sourceAligned : al.getSequences())
510 if (ssm.fromSeq == sourceAligned.getDatasetSequence())
512 return sourceAligned;
522 * Returns the region in the target sequence's dataset that is mapped to the
523 * given position (base 1) in the query sequence's dataset. The region is a
524 * set of start/end position pairs.
531 public int[] getMappedRegion(SequenceI target, SequenceI query,
534 SequenceI targetDs = target.getDatasetSequence() == null ? target
535 : target.getDatasetSequence();
536 SequenceI queryDs = query.getDatasetSequence() == null ? query
537 : query.getDatasetSequence();
538 if (targetDs == null || queryDs == null /*|| dnaToProt == null*/)
542 for (SequenceToSequenceMapping ssm : mappings)
545 * try mapping from target to query
547 if (ssm.fromSeq == targetDs && ssm.mapping.to == queryDs)
549 int[] codon = ssm.mapping.map.locateInFrom(queryPos, queryPos);
556 * else try mapping from query to target
558 else if (ssm.fromSeq == queryDs && ssm.mapping.to == targetDs)
560 int[] codon = ssm.mapping.map.locateInTo(queryPos, queryPos);
571 * Returns the mapped DNA codons for the given position in a protein sequence,
572 * or null if no mapping is found. Returns a list of (e.g.) ['g', 'c', 't']
573 * codons. There may be more than one codon mapped to the protein if (for
574 * example), there are mappings to cDNA variants.
577 * the peptide dataset sequence
579 * residue position (base 1) in the peptide sequence
582 public List<char[]> getMappedCodons(SequenceI protein, int aaPos)
585 SequenceI dnaSeq = null;
586 List<char[]> result = new ArrayList<>();
588 for (SequenceToSequenceMapping ssm : mappings)
590 if (ssm.mapping.to == protein
591 && ssm.mapping.getMap().getFromRatio() == 3)
593 ml = ssm.mapping.map;
594 dnaSeq = ssm.fromSeq;
596 int[] codonPos = ml.locateInFrom(aaPos, aaPos);
597 if (codonPos == null)
603 * Read off the mapped nucleotides (converting to position base 0)
605 codonPos = MappingUtils.flattenRanges(codonPos);
606 int start = dnaSeq.getStart();
607 char c1 = dnaSeq.getCharAt(codonPos[0] - start);
608 char c2 = dnaSeq.getCharAt(codonPos[1] - start);
609 char c3 = dnaSeq.getCharAt(codonPos[2] - start);
610 result.add(new char[] { c1, c2, c3 });
613 return result.isEmpty() ? null : result;
617 * Returns any mappings found which are from the given sequence, and to
618 * distinct sequences.
623 public List<Mapping> getMappingsFromSequence(SequenceI seq)
625 List<Mapping> result = new ArrayList<>();
626 List<SequenceI> related = new ArrayList<>();
627 SequenceI seqDs = seq.getDatasetSequence();
628 seqDs = seqDs != null ? seqDs : seq;
630 for (SequenceToSequenceMapping ssm : mappings)
632 final Mapping mapping = ssm.mapping;
633 if (ssm.fromSeq == seqDs)
635 if (!related.contains(mapping.to))
638 related.add(mapping.to);
646 * Test whether the given sequence is substitutable for one or more dummy
647 * sequences in this mapping
653 public boolean isRealisableWith(SequenceI seq)
655 return realiseWith(seq, false) > 0;
659 * Replace any matchable mapped dummy sequences with the given real one.
660 * Returns the count of sequence mappings instantiated.
665 public int realiseWith(SequenceI seq)
667 return realiseWith(seq, true);
671 * Returns the number of mapped dummy sequences that could be replaced with
672 * the given real sequence.
677 * if true, performs replacements, else only counts
680 protected int realiseWith(SequenceI seq, boolean doUpdate)
682 SequenceI ds = seq.getDatasetSequence() != null
683 ? seq.getDatasetSequence()
688 * check for replaceable DNA ('map from') sequences
690 for (SequenceToSequenceMapping ssm : mappings)
692 SequenceI dna = ssm.fromSeq;
693 if (dna instanceof SequenceDummy
694 && dna.getName().equals(ds.getName()))
696 Mapping mapping = ssm.mapping;
697 int mapStart = mapping.getMap().getFromLowest();
698 int mapEnd = mapping.getMap().getFromHighest();
699 boolean mappable = couldRealiseSequence(dna, ds, mapStart, mapEnd);
705 // TODO: new method ? ds.realise(dna);
706 // might want to copy database refs as well
707 ds.setSequenceFeatures(dna.getSequenceFeatures());
710 System.out.println("Realised mapped sequence " + ds.getName());
716 * check for replaceable protein ('map to') sequences
718 Mapping mapping = ssm.mapping;
719 SequenceI prot = mapping.getTo();
720 int mapStart = mapping.getMap().getToLowest();
721 int mapEnd = mapping.getMap().getToHighest();
722 boolean mappable = couldRealiseSequence(prot, ds, mapStart, mapEnd);
728 // TODO: new method ? ds.realise(dna);
729 // might want to copy database refs as well
730 ds.setSequenceFeatures(dna.getSequenceFeatures());
731 ssm.mapping.setTo(ds);
739 * Helper method to test whether a 'real' sequence could replace a 'dummy'
740 * sequence in the map. The criteria are that they have the same name, and
741 * that the mapped region overlaps the candidate sequence.
749 protected static boolean couldRealiseSequence(SequenceI existing,
750 SequenceI replacement, int mapStart, int mapEnd)
752 if (existing instanceof SequenceDummy
753 && !(replacement instanceof SequenceDummy)
754 && existing.getName().equals(replacement.getName()))
756 int start = replacement.getStart();
757 int end = replacement.getEnd();
758 boolean mappingOverlapsSequence = (mapStart >= start
759 && mapStart <= end) || (mapEnd >= start && mapEnd <= end);
760 if (mappingOverlapsSequence)
769 * Change any mapping to the given sequence to be to its dataset sequence
770 * instead. For use when mappings are created before their referenced
771 * sequences are instantiated, for example when parsing GFF data.
775 public void updateToDataset(SequenceI seq)
777 if (seq == null || seq.getDatasetSequence() == null)
781 SequenceI ds = seq.getDatasetSequence();
783 for (SequenceToSequenceMapping ssm : mappings)
788 if (ssm.fromSeq == seq)
796 if (ssm.mapping.to == seq)
804 * Answers true if this object contains no mappings
808 public boolean isEmpty()
810 return mappings.isEmpty();
814 * Method for debug / inspection purposes only, may change in future
817 public String toString()
819 return mappings == null ? "null" : mappings.toString();
823 * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or
827 * aligned or dataset sequence
829 * aligned or dataset sequence
832 public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
834 SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
835 : fromSeq.getDatasetSequence();
836 SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq
837 : toSeq.getDatasetSequence();
839 for (SequenceToSequenceMapping mapping : mappings)
841 SequenceI from = mapping.fromSeq;
842 SequenceI to = mapping.mapping.to;
843 if ((from == dssFrom && to == dssTo)
844 || (from == dssTo && to == dssFrom))
846 return mapping.mapping;
853 * Returns a hashcode derived from the list of sequence mappings
855 * @see SequenceToSequenceMapping#hashCode()
856 * @see AbstractList#hashCode()
859 public int hashCode()
861 return this.mappings.hashCode();
865 * Two AlignedCodonFrame objects are equal if they hold the same ordered list
868 * @see SequenceToSequenceMapping#equals
871 public boolean equals(Object obj)
873 if (!(obj instanceof AlignedCodonFrame))
877 return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
880 public List<SequenceToSequenceMapping> getMappings()
886 * Returns the first mapping found which is between the two given sequences,
887 * and covers the full extent of both.
893 public SequenceToSequenceMapping getCoveringMapping(SequenceI seq1,
896 for (SequenceToSequenceMapping mapping : mappings)
898 if (mapping.covers(seq2) && mapping.covers(seq1))
907 * Returns the first mapping found which is between the given dataset sequence
908 * and another, is a triplet mapping (3:1 or 1:3), and covers the full extent
909 * of both sequences involved
914 public SequenceToSequenceMapping getCoveringCodonMapping(SequenceI seq)
916 for (SequenceToSequenceMapping mapping : mappings)
918 if (mapping.getMapping().getMap().isTripletMap()
919 && mapping.covers(seq))
921 if (mapping.fromSeq == seq
922 && mapping.covers(mapping.getMapping().getTo()))
926 else if (mapping.getMapping().getTo() == seq
927 && mapping.covers(mapping.fromSeq))