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 jalview.util.MapList;
24 import jalview.util.MappingUtils;
26 import java.util.AbstractList;
27 import java.util.ArrayList;
28 import java.util.List;
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);
126 * @param localCover - when true - compare extent of seq's dataset sequence rather than the local extent
127 * @return true if mapping covers full length of given sequence
129 public boolean covers(SequenceI seq, boolean localCover)
131 List<int[]> mappedRanges = null;
132 MapList mapList = mapping.getMap();
133 int mstart=seq.getStart(),mend=seq.getEnd()
135 if (fromSeq == seq || fromSeq == seq.getDatasetSequence())
137 if (localCover && fromSeq !=seq)
139 mstart=fromSeq.getStart();
140 mend=fromSeq.getEnd();
142 mappedRanges = mapList.getFromRanges();
144 else if (mapping.to == seq || mapping.to == seq.getDatasetSequence())
146 if (localCover && mapping.to !=seq)
148 mstart=mapping.to.getStart();
149 mend=mapping.to.getEnd();
151 mappedRanges = mapList.getToRanges();
159 * check that each mapped range lieS with the sequence range
160 * (necessary for circular CDS - example EMBL:J03321:AAA91567)
161 * and mapped length covers (at least) sequence length
164 for (int[] range : mappedRanges)
166 int from = Math.min(range[0], range[1]);
167 int to = Math.max(range[0], range[1]);
168 if (from < mstart || to > mend)
172 length += (to - from + 1);
174 // add 1 to mapped length to allow for a mapped stop codon
175 if (length + 1 < (mend - mstart + 1))
183 private List<SequenceToSequenceMapping> mappings;
188 public AlignedCodonFrame()
190 mappings = new ArrayList<>();
194 * Adds a mapping between the dataset sequences for the associated dna and
195 * protein sequence objects
201 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map)
203 addMap(dnaseq, aaseq, map, null);
207 * Adds a mapping between the dataset sequences for the associated dna and
208 * protein sequence objects
215 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map,
218 // JBPNote DEBUG! THIS !
219 // dnaseq.transferAnnotation(aaseq, mp);
220 // aaseq.transferAnnotation(dnaseq, new Mapping(map.getInverse()));
222 SequenceI fromSeq = (dnaseq.getDatasetSequence() == null) ? dnaseq
223 : dnaseq.getDatasetSequence();
224 SequenceI toSeq = (aaseq.getDatasetSequence() == null) ? aaseq
225 : aaseq.getDatasetSequence();
228 * if we already hold a mapping between these sequences, just add to it
229 * note that 'adding' a duplicate map does nothing; this protects against
230 * creating duplicate mappings in AlignedCodonFrame
232 for (SequenceToSequenceMapping ssm : mappings)
234 if (ssm.fromSeq == fromSeq && ssm.mapping.to == toSeq)
236 ssm.mapping.map.addMapList(map);
242 * otherwise, add a new sequence mapping
244 Mapping mp = new Mapping(toSeq, map);
245 mp.setMappedFromId(mapFromId);
246 mappings.add(new SequenceToSequenceMapping(fromSeq, mp));
249 public SequenceI[] getdnaSeqs()
251 // TODO return a list instead?
253 List<SequenceI> seqs = new ArrayList<>();
254 for (SequenceToSequenceMapping ssm : mappings)
256 seqs.add(ssm.fromSeq);
258 return seqs.toArray(new SequenceI[seqs.size()]);
261 public SequenceI[] getAaSeqs()
263 // TODO not used - remove?
264 List<SequenceI> seqs = new ArrayList<>();
265 for (SequenceToSequenceMapping ssm : mappings)
267 seqs.add(ssm.mapping.to);
269 return seqs.toArray(new SequenceI[seqs.size()]);
272 public MapList[] getdnaToProt()
274 List<MapList> maps = new ArrayList<>();
275 for (SequenceToSequenceMapping ssm : mappings)
277 maps.add(ssm.mapping.map);
279 return maps.toArray(new MapList[maps.size()]);
282 public Mapping[] getProtMappings()
284 List<Mapping> maps = new ArrayList<>();
285 for (SequenceToSequenceMapping ssm : mappings)
287 maps.add(ssm.mapping);
289 return maps.toArray(new Mapping[maps.size()]);
293 * Returns the first mapping found which is to or from the given sequence, or
294 * null if none is found
299 public Mapping getMappingForSequence(SequenceI seq)
301 SequenceI seqDs = seq.getDatasetSequence();
302 seqDs = seqDs != null ? seqDs : seq;
304 for (SequenceToSequenceMapping ssm : mappings)
306 if (ssm.fromSeq == seqDs || ssm.mapping.to == seqDs)
315 * Return the corresponding aligned or dataset aa sequence for given dna
316 * sequence, null if not found.
321 public SequenceI getAaForDnaSeq(SequenceI dnaSeqRef)
323 SequenceI dnads = dnaSeqRef.getDatasetSequence();
324 for (SequenceToSequenceMapping ssm : mappings)
326 if (ssm.fromSeq == dnaSeqRef || ssm.fromSeq == dnads)
328 return ssm.mapping.to;
335 * Return the corresponding aligned or dataset dna sequence for given amino
336 * acid sequence, or null if not found. returns the sequence from the first
337 * mapping found that involves the protein sequence.
342 public SequenceI getDnaForAaSeq(SequenceI aaSeqRef)
344 SequenceI aads = aaSeqRef.getDatasetSequence();
345 for (SequenceToSequenceMapping ssm : mappings)
347 if (ssm.mapping.to == aaSeqRef || ssm.mapping.to == aads)
356 * test to see if codon frame involves seq in any way
359 * a nucleotide or protein sequence
360 * @return true if a mapping exists to or from this sequence to any translated
363 public boolean involvesSequence(SequenceI seq)
365 return getAaForDnaSeq(seq) != null || getDnaForAaSeq(seq) != null;
369 * Add search results for regions in other sequences that translate or are
370 * translated from a particular position in seq
376 * where highlighted regions go
378 public void markMappedRegion(SequenceI seq, int index,
379 SearchResultsI results)
382 SequenceI ds = seq.getDatasetSequence();
383 for (SequenceToSequenceMapping ssm : mappings)
385 if (ssm.fromSeq == seq || ssm.fromSeq == ds)
387 codon = ssm.mapping.map.locateInTo(index, index);
390 for (int i = 0; i < codon.length; i += 2)
392 results.addResult(ssm.mapping.to, codon[i], codon[i + 1]);
396 else if (ssm.mapping.to == seq || ssm.mapping.to == ds)
399 codon = ssm.mapping.map.locateInFrom(index, index);
402 for (int i = 0; i < codon.length; i += 2)
404 results.addResult(ssm.fromSeq, codon[i], codon[i + 1]);
413 * Returns the DNA codon positions (base 1) for the given position (base 1) in
414 * a mapped protein sequence, or null if no mapping is found.
416 * Intended for use in aligning cDNA to match aligned protein. Only the first
417 * mapping found is returned, so not suitable for use if multiple protein
418 * sequences are mapped to the same cDNA (but aligning cDNA as protein is
419 * ill-defined for this case anyway).
422 * the DNA dataset sequence
424 * residue position (base 1) in a protein sequence
427 public int[] getDnaPosition(SequenceI seq, int aaPos)
430 * Adapted from markMappedRegion().
434 for (SequenceToSequenceMapping ssm : mappings)
436 if (ssm.fromSeq == seq)
438 ml = getdnaToProt()[i];
443 return ml == null ? null : ml.locateInFrom(aaPos, aaPos);
447 * Convenience method to return the first aligned sequence in the given
448 * alignment whose dataset has a mapping with the given (aligned or dataset)
456 public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al)
458 return findAlignedSequence(seq, al, null);
461 * Convenience method to return the first aligned sequence in the given
462 * alignment whose dataset has a mapping with the given (aligned or dataset)
463 * sequence, and optionally the mapping that relates them
467 * @param map - list to add the mapping to
468 * @return sequence from al that maps to seq
470 public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al,List<SequenceToSequenceMapping> map)
473 * Search mapped protein ('to') sequences first.
475 for (SequenceToSequenceMapping ssm : mappings)
477 if (ssm.fromSeq == seq || ssm.fromSeq == seq.getDatasetSequence())
479 for (SequenceI sourceAligned : al.getSequences())
481 if (ssm.covers(sourceAligned,true))
487 return sourceAligned;
494 * Then try mapped dna sequences.
496 for (SequenceToSequenceMapping ssm : mappings)
498 if (ssm.mapping.to == seq
499 || ssm.mapping.to == seq.getDatasetSequence())
501 for (SequenceI sourceAligned : al.getSequences())
503 if (ssm.covers(sourceAligned,true))
509 return sourceAligned;
519 * Returns the region in the target sequence's dataset that is mapped to the
520 * given position (base 1) in the query sequence's dataset. The region is a
521 * set of start/end position pairs.
528 public int[] getMappedRegion(SequenceI target, SequenceI query,
531 SequenceI targetDs = target.getDatasetSequence() == null ? target
532 : target.getDatasetSequence();
533 SequenceI queryDs = query.getDatasetSequence() == null ? query
534 : query.getDatasetSequence();
535 if (targetDs == null || queryDs == null /*|| dnaToProt == null*/)
539 for (SequenceToSequenceMapping ssm : mappings)
542 * try mapping from target to query
544 if (ssm.fromSeq == targetDs && ssm.mapping.to == queryDs)
546 int[] codon = ssm.mapping.map.locateInFrom(queryPos, queryPos);
553 * else try mapping from query to target
555 else if (ssm.fromSeq == queryDs && ssm.mapping.to == targetDs)
557 int[] codon = ssm.mapping.map.locateInTo(queryPos, queryPos);
568 * Returns the mapped DNA codons for the given position in a protein sequence,
569 * or null if no mapping is found. Returns a list of (e.g.) ['g', 'c', 't']
570 * codons. There may be more than one codon mapped to the protein if (for
571 * example), there are mappings to cDNA variants.
574 * the peptide dataset sequence
576 * residue position (base 1) in the peptide sequence
579 public List<char[]> getMappedCodons(SequenceI protein, int aaPos)
582 SequenceI dnaSeq = null;
583 List<char[]> result = new ArrayList<>();
585 for (SequenceToSequenceMapping ssm : mappings)
587 if (ssm.mapping.to == protein
588 && ssm.mapping.getMap().getFromRatio() == 3)
590 ml = ssm.mapping.map;
591 dnaSeq = ssm.fromSeq;
593 int[] codonPos = ml.locateInFrom(aaPos, aaPos);
594 if (codonPos == null)
600 * Read off the mapped nucleotides (converting to position base 0)
602 codonPos = MappingUtils.flattenRanges(codonPos);
603 int start = dnaSeq.getStart();
604 char c1 = dnaSeq.getCharAt(codonPos[0] - start);
605 char c2 = dnaSeq.getCharAt(codonPos[1] - start);
606 char c3 = dnaSeq.getCharAt(codonPos[2] - start);
607 result.add(new char[] { c1, c2, c3 });
610 return result.isEmpty() ? null : result;
614 * Returns any mappings found which are from the given sequence, and to
615 * distinct sequences.
620 public List<Mapping> getMappingsFromSequence(SequenceI seq)
622 List<Mapping> result = new ArrayList<>();
623 List<SequenceI> related = new ArrayList<>();
624 SequenceI seqDs = seq.getDatasetSequence();
625 seqDs = seqDs != null ? seqDs : seq;
627 for (SequenceToSequenceMapping ssm : mappings)
629 final Mapping mapping = ssm.mapping;
630 if (ssm.fromSeq == seqDs)
632 if (!related.contains(mapping.to))
635 related.add(mapping.to);
643 * Test whether the given sequence is substitutable for one or more dummy
644 * sequences in this mapping
650 public boolean isRealisableWith(SequenceI seq)
652 return realiseWith(seq, false) > 0;
656 * Replace any matchable mapped dummy sequences with the given real one.
657 * Returns the count of sequence mappings instantiated.
662 public int realiseWith(SequenceI seq)
664 return realiseWith(seq, true);
668 * Returns the number of mapped dummy sequences that could be replaced with
669 * the given real sequence.
674 * if true, performs replacements, else only counts
677 protected int realiseWith(SequenceI seq, boolean doUpdate)
679 SequenceI ds = seq.getDatasetSequence() != null
680 ? seq.getDatasetSequence()
685 * check for replaceable DNA ('map from') sequences
687 for (SequenceToSequenceMapping ssm : mappings)
689 SequenceI dna = ssm.fromSeq;
690 if (dna instanceof SequenceDummy
691 && dna.getName().equals(ds.getName()))
693 Mapping mapping = ssm.mapping;
694 int mapStart = mapping.getMap().getFromLowest();
695 int mapEnd = mapping.getMap().getFromHighest();
696 boolean mappable = couldRealiseSequence(dna, ds, mapStart, mapEnd);
702 // TODO: new method ? ds.realise(dna);
703 // might want to copy database refs as well
704 ds.setSequenceFeatures(dna.getSequenceFeatures());
707 System.out.println("Realised mapped sequence " + ds.getName());
713 * check for replaceable protein ('map to') sequences
715 Mapping mapping = ssm.mapping;
716 SequenceI prot = mapping.getTo();
717 int mapStart = mapping.getMap().getToLowest();
718 int mapEnd = mapping.getMap().getToHighest();
719 boolean mappable = couldRealiseSequence(prot, ds, mapStart, mapEnd);
725 // TODO: new method ? ds.realise(dna);
726 // might want to copy database refs as well
727 ds.setSequenceFeatures(dna.getSequenceFeatures());
728 ssm.mapping.setTo(ds);
736 * Helper method to test whether a 'real' sequence could replace a 'dummy'
737 * sequence in the map. The criteria are that they have the same name, and
738 * that the mapped region overlaps the candidate sequence.
746 protected static boolean couldRealiseSequence(SequenceI existing,
747 SequenceI replacement, int mapStart, int mapEnd)
749 if (existing instanceof SequenceDummy
750 && !(replacement instanceof SequenceDummy)
751 && existing.getName().equals(replacement.getName()))
753 int start = replacement.getStart();
754 int end = replacement.getEnd();
755 boolean mappingOverlapsSequence = (mapStart >= start
756 && mapStart <= end) || (mapEnd >= start && mapEnd <= end);
757 if (mappingOverlapsSequence)
766 * Change any mapping to the given sequence to be to its dataset sequence
767 * instead. For use when mappings are created before their referenced
768 * sequences are instantiated, for example when parsing GFF data.
772 public void updateToDataset(SequenceI seq)
774 if (seq == null || seq.getDatasetSequence() == null)
778 SequenceI ds = seq.getDatasetSequence();
780 for (SequenceToSequenceMapping ssm : mappings)
785 if (ssm.fromSeq == seq)
793 if (ssm.mapping.to == seq)
801 * Answers true if this object contains no mappings
805 public boolean isEmpty()
807 return mappings.isEmpty();
811 * Method for debug / inspection purposes only, may change in future
814 public String toString()
816 return mappings == null ? "null" : mappings.toString();
820 * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or
824 * aligned or dataset sequence
826 * aligned or dataset sequence
829 public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
831 SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
832 : fromSeq.getDatasetSequence();
833 SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq
834 : toSeq.getDatasetSequence();
836 for (SequenceToSequenceMapping mapping : mappings)
838 SequenceI from = mapping.fromSeq;
839 SequenceI to = mapping.mapping.to;
840 if ((from == dssFrom && to == dssTo)
841 || (from == dssTo && to == dssFrom))
843 return mapping.mapping;
850 * Returns a hashcode derived from the list of sequence mappings
852 * @see SequenceToSequenceMapping#hashCode()
853 * @see AbstractList#hashCode()
856 public int hashCode()
858 return this.mappings.hashCode();
862 * Two AlignedCodonFrame objects are equal if they hold the same ordered list
865 * @see SequenceToSequenceMapping#equals
868 public boolean equals(Object obj)
870 if (!(obj instanceof AlignedCodonFrame))
874 return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
877 public List<SequenceToSequenceMapping> getMappings()
883 * Returns the first mapping found which is between the two given sequences,
884 * and covers the full extent of both.
890 public SequenceToSequenceMapping getCoveringMapping(SequenceI seq1,
893 for (SequenceToSequenceMapping mapping : mappings)
895 if (mapping.covers(seq2) && mapping.covers(seq1))