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 List<int[]> mappedRanges = null;
122 MapList mapList = mapping.getMap();
123 if (fromSeq == seq || fromSeq == seq.getDatasetSequence())
125 mappedRanges = mapList.getFromRanges();
127 else if (mapping.to == seq || mapping.to == seq.getDatasetSequence())
129 mappedRanges = mapList.getToRanges();
137 * check that each mapped range lies within the sequence range
138 * (necessary for circular CDS - example EMBL:J03321:AAA91567)
139 * and mapped length covers (at least) sequence length
142 for (int[] range : mappedRanges)
144 int from = Math.min(range[0], range[1]);
145 int to = Math.max(range[0], range[1]);
146 if (from < seq.getStart() || to > seq.getEnd())
150 length += (to - from + 1);
152 // add 1 to mapped length to allow for a mapped stop codon
153 if (length + 1 < (seq.getEnd() - seq.getStart() + 1))
161 * Adds any regions mapped to or from position {@code pos} in sequence
162 * {@code seq} to the given search results
168 public void markMappedRegion(SequenceI seq, int pos, SearchResultsI sr)
171 SequenceI mappedSeq = null;
172 SequenceI ds = seq.getDatasetSequence();
178 if (this.fromSeq == seq || this.fromSeq == ds)
180 codon = this.mapping.map.locateInTo(pos, pos);
181 mappedSeq = this.mapping.to;
183 else if (this.mapping.to == seq || this.mapping.to == ds)
185 codon = this.mapping.map.locateInFrom(pos, pos);
186 mappedSeq = this.fromSeq;
191 for (int i = 0; i < codon.length; i += 2)
193 sr.addResult(mappedSeq, codon[i], codon[i + 1]);
199 private List<SequenceToSequenceMapping> mappings;
204 public AlignedCodonFrame()
206 mappings = new ArrayList<>();
210 * Adds a mapping between the dataset sequences for the associated dna and
211 * protein sequence objects
217 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map)
219 addMap(dnaseq, aaseq, map, null);
223 * Adds a mapping between the dataset sequences for the associated dna and
224 * protein sequence objects
231 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map,
234 // JBPNote DEBUG! THIS !
235 // dnaseq.transferAnnotation(aaseq, mp);
236 // aaseq.transferAnnotation(dnaseq, new Mapping(map.getInverse()));
238 SequenceI fromSeq = (dnaseq.getDatasetSequence() == null) ? dnaseq
239 : dnaseq.getDatasetSequence();
240 SequenceI toSeq = (aaseq.getDatasetSequence() == null) ? aaseq
241 : aaseq.getDatasetSequence();
244 * if we already hold a mapping between these sequences, just add to it
245 * note that 'adding' a duplicate map does nothing; this protects against
246 * creating duplicate mappings in AlignedCodonFrame
248 for (SequenceToSequenceMapping ssm : mappings)
250 if (ssm.fromSeq == fromSeq && ssm.mapping.to == toSeq)
252 ssm.mapping.map.addMapList(map);
258 * otherwise, add a new sequence mapping
260 Mapping mp = new Mapping(toSeq, map);
261 mp.setMappedFromId(mapFromId);
262 mappings.add(new SequenceToSequenceMapping(fromSeq, mp));
265 public SequenceI[] getdnaSeqs()
267 // TODO return a list instead?
269 List<SequenceI> seqs = new ArrayList<>();
270 for (SequenceToSequenceMapping ssm : mappings)
272 seqs.add(ssm.fromSeq);
274 return seqs.toArray(new SequenceI[seqs.size()]);
277 public SequenceI[] getAaSeqs()
279 // TODO not used - remove?
280 List<SequenceI> seqs = new ArrayList<>();
281 for (SequenceToSequenceMapping ssm : mappings)
283 seqs.add(ssm.mapping.to);
285 return seqs.toArray(new SequenceI[seqs.size()]);
288 public MapList[] getdnaToProt()
290 List<MapList> maps = new ArrayList<>();
291 for (SequenceToSequenceMapping ssm : mappings)
293 maps.add(ssm.mapping.map);
295 return maps.toArray(new MapList[maps.size()]);
298 public Mapping[] getProtMappings()
300 List<Mapping> maps = new ArrayList<>();
301 for (SequenceToSequenceMapping ssm : mappings)
303 maps.add(ssm.mapping);
305 return maps.toArray(new Mapping[maps.size()]);
309 * Returns the first mapping found which is to or from the given sequence, or
310 * null if none is found
315 public Mapping getMappingForSequence(SequenceI seq)
317 SequenceI seqDs = seq.getDatasetSequence();
318 seqDs = seqDs != null ? seqDs : seq;
320 for (SequenceToSequenceMapping ssm : mappings)
322 if (ssm.fromSeq == seqDs || ssm.mapping.to == seqDs)
331 * Return the corresponding aligned or dataset aa sequence for given dna
332 * sequence, null if not found.
337 public SequenceI getAaForDnaSeq(SequenceI dnaSeqRef)
339 SequenceI dnads = dnaSeqRef.getDatasetSequence();
340 for (SequenceToSequenceMapping ssm : mappings)
342 if (ssm.fromSeq == dnaSeqRef || ssm.fromSeq == dnads)
344 return ssm.mapping.to;
351 * Return the corresponding aligned or dataset dna sequence for given amino
352 * acid sequence, or null if not found. returns the sequence from the first
353 * mapping found that involves the protein sequence.
358 public SequenceI getDnaForAaSeq(SequenceI aaSeqRef)
360 SequenceI aads = aaSeqRef.getDatasetSequence();
361 for (SequenceToSequenceMapping ssm : mappings)
363 if (ssm.mapping.to == aaSeqRef || ssm.mapping.to == aads)
372 * test to see if codon frame involves seq in any way
375 * a nucleotide or protein sequence
376 * @return true if a mapping exists to or from this sequence to any translated
379 public boolean involvesSequence(SequenceI seq)
381 return getAaForDnaSeq(seq) != null || getDnaForAaSeq(seq) != null;
385 * Add search results for regions in other sequences that translate or are
386 * translated from a particular position in seq
392 * where highlighted regions go
394 public void markMappedRegion(SequenceI seq, int index,
395 SearchResultsI results)
397 SequenceI ds = seq.getDatasetSequence();
398 for (SequenceToSequenceMapping ssm : mappings)
400 ssm.markMappedRegion(ds, index, results);
405 * Convenience method to return the first aligned sequence in the given
406 * alignment whose dataset has a mapping with the given (aligned or dataset)
414 public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al)
417 * Search mapped protein ('to') sequences first.
419 for (SequenceToSequenceMapping ssm : mappings)
421 if (ssm.fromSeq == seq || ssm.fromSeq == seq.getDatasetSequence())
423 for (SequenceI sourceAligned : al.getSequences())
425 if (ssm.mapping.to == sourceAligned.getDatasetSequence()
426 || ssm.mapping.to == sourceAligned)
428 return sourceAligned;
435 * Then try mapped dna sequences.
437 for (SequenceToSequenceMapping ssm : mappings)
439 if (ssm.mapping.to == seq
440 || ssm.mapping.to == seq.getDatasetSequence())
442 for (SequenceI sourceAligned : al.getSequences())
444 if (ssm.fromSeq == sourceAligned.getDatasetSequence())
446 return sourceAligned;
456 * Returns the region in the target sequence's dataset that is mapped to the
457 * given position (base 1) in the query sequence's dataset. The region is a
458 * set of start/end position pairs.
465 public int[] getMappedRegion(SequenceI target, SequenceI query,
468 SequenceI targetDs = target.getDatasetSequence() == null ? target
469 : target.getDatasetSequence();
470 SequenceI queryDs = query.getDatasetSequence() == null ? query
471 : query.getDatasetSequence();
472 if (targetDs == null || queryDs == null /*|| dnaToProt == null*/)
476 for (SequenceToSequenceMapping ssm : mappings)
479 * try mapping from target to query
481 if (ssm.fromSeq == targetDs && ssm.mapping.to == queryDs)
483 int[] codon = ssm.mapping.map.locateInFrom(queryPos, queryPos);
490 * else try mapping from query to target
492 else if (ssm.fromSeq == queryDs && ssm.mapping.to == targetDs)
494 int[] codon = ssm.mapping.map.locateInTo(queryPos, queryPos);
505 * Returns the mapped DNA codons for the given position in a protein sequence,
506 * or null if no mapping is found. Returns a list of (e.g.) ['g', 'c', 't']
507 * codons. There may be more than one codon mapped to the protein if (for
508 * example), there are mappings to cDNA variants.
511 * the peptide dataset sequence
513 * residue position (base 1) in the peptide sequence
516 public List<char[]> getMappedCodons(SequenceI protein, int aaPos)
519 SequenceI dnaSeq = null;
520 List<char[]> result = new ArrayList<>();
522 for (SequenceToSequenceMapping ssm : mappings)
524 if (ssm.mapping.to == protein
525 && ssm.mapping.getMap().getFromRatio() == 3)
527 ml = ssm.mapping.map;
528 dnaSeq = ssm.fromSeq;
530 int[] codonPos = ml.locateInFrom(aaPos, aaPos);
531 if (codonPos == null)
537 * Read off the mapped nucleotides (converting to position base 0)
539 codonPos = MappingUtils.flattenRanges(codonPos);
540 int start = dnaSeq.getStart();
541 char c1 = dnaSeq.getCharAt(codonPos[0] - start);
542 char c2 = dnaSeq.getCharAt(codonPos[1] - start);
543 char c3 = dnaSeq.getCharAt(codonPos[2] - start);
544 result.add(new char[] { c1, c2, c3 });
547 return result.isEmpty() ? null : result;
551 * Returns any mappings found which are from the given sequence, and to
552 * distinct sequences.
557 public List<Mapping> getMappingsFromSequence(SequenceI seq)
559 List<Mapping> result = new ArrayList<>();
560 List<SequenceI> related = new ArrayList<>();
561 SequenceI seqDs = seq.getDatasetSequence();
562 seqDs = seqDs != null ? seqDs : seq;
564 for (SequenceToSequenceMapping ssm : mappings)
566 final Mapping mapping = ssm.mapping;
567 if (ssm.fromSeq == seqDs)
569 if (!related.contains(mapping.to))
572 related.add(mapping.to);
580 * Test whether the given sequence is substitutable for one or more dummy
581 * sequences in this mapping
587 public boolean isRealisableWith(SequenceI seq)
589 return realiseWith(seq, false) > 0;
593 * Replace any matchable mapped dummy sequences with the given real one.
594 * Returns the count of sequence mappings instantiated.
599 public int realiseWith(SequenceI seq)
601 return realiseWith(seq, true);
605 * Returns the number of mapped dummy sequences that could be replaced with
606 * the given real sequence.
611 * if true, performs replacements, else only counts
614 protected int realiseWith(SequenceI seq, boolean doUpdate)
616 SequenceI ds = seq.getDatasetSequence() != null
617 ? seq.getDatasetSequence()
622 * check for replaceable DNA ('map from') sequences
624 for (SequenceToSequenceMapping ssm : mappings)
626 SequenceI dna = ssm.fromSeq;
627 if (dna instanceof SequenceDummy
628 && dna.getName().equals(ds.getName()))
630 Mapping mapping = ssm.mapping;
631 int mapStart = mapping.getMap().getFromLowest();
632 int mapEnd = mapping.getMap().getFromHighest();
633 boolean mappable = couldRealiseSequence(dna, ds, mapStart, mapEnd);
639 // TODO: new method ? ds.realise(dna);
640 // might want to copy database refs as well
641 ds.setSequenceFeatures(dna.getSequenceFeatures());
644 System.out.println("Realised mapped sequence " + ds.getName());
650 * check for replaceable protein ('map to') sequences
652 Mapping mapping = ssm.mapping;
653 SequenceI prot = mapping.getTo();
654 int mapStart = mapping.getMap().getToLowest();
655 int mapEnd = mapping.getMap().getToHighest();
656 boolean mappable = couldRealiseSequence(prot, ds, mapStart, mapEnd);
662 // TODO: new method ? ds.realise(dna);
663 // might want to copy database refs as well
664 ds.setSequenceFeatures(dna.getSequenceFeatures());
665 ssm.mapping.setTo(ds);
673 * Helper method to test whether a 'real' sequence could replace a 'dummy'
674 * sequence in the map. The criteria are that they have the same name, and
675 * that the mapped region overlaps the candidate sequence.
683 protected static boolean couldRealiseSequence(SequenceI existing,
684 SequenceI replacement, int mapStart, int mapEnd)
686 if (existing instanceof SequenceDummy
687 && !(replacement instanceof SequenceDummy)
688 && existing.getName().equals(replacement.getName()))
690 int start = replacement.getStart();
691 int end = replacement.getEnd();
692 boolean mappingOverlapsSequence = (mapStart >= start
693 && mapStart <= end) || (mapEnd >= start && mapEnd <= end);
694 if (mappingOverlapsSequence)
703 * Change any mapping to the given sequence to be to its dataset sequence
704 * instead. For use when mappings are created before their referenced
705 * sequences are instantiated, for example when parsing GFF data.
709 public void updateToDataset(SequenceI seq)
711 if (seq == null || seq.getDatasetSequence() == null)
715 SequenceI ds = seq.getDatasetSequence();
717 for (SequenceToSequenceMapping ssm : mappings)
722 if (ssm.fromSeq == seq)
730 if (ssm.mapping.to == seq)
738 * Answers true if this object contains no mappings
742 public boolean isEmpty()
744 return mappings.isEmpty();
748 * Method for debug / inspection purposes only, may change in future
751 public String toString()
753 return mappings == null ? "null" : mappings.toString();
757 * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or
761 * aligned or dataset sequence
763 * aligned or dataset sequence
766 public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
768 SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
769 : fromSeq.getDatasetSequence();
770 SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq
771 : toSeq.getDatasetSequence();
773 for (SequenceToSequenceMapping mapping : mappings)
775 SequenceI from = mapping.fromSeq;
776 SequenceI to = mapping.mapping.to;
777 if ((from == dssFrom && to == dssTo)
778 || (from == dssTo && to == dssFrom))
780 return mapping.mapping;
787 * Returns a hashcode derived from the list of sequence mappings
789 * @see SequenceToSequenceMapping#hashCode()
790 * @see AbstractList#hashCode()
793 public int hashCode()
795 return this.mappings.hashCode();
799 * Two AlignedCodonFrame objects are equal if they hold the same ordered list
802 * @see SequenceToSequenceMapping#equals
805 public boolean equals(Object obj)
807 if (!(obj instanceof AlignedCodonFrame))
811 return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
814 public List<SequenceToSequenceMapping> getMappings()
820 * Returns the first mapping found which is between the two given sequences,
821 * and covers the full extent of both.
827 public SequenceToSequenceMapping getCoveringMapping(SequenceI seq1,
830 for (SequenceToSequenceMapping mapping : mappings)
832 if (mapping.covers(seq2) && mapping.covers(seq1))
841 * Returns the first mapping found which is between the given sequence and
842 * another, is a triplet mapping (3:1 or 1:3), and covers the full extent of
843 * both sequences involved.
848 public SequenceToSequenceMapping getCoveringCodonMapping(SequenceI seq)
850 for (SequenceToSequenceMapping mapping : mappings)
852 if (mapping.getMapping().getMap().isTripletMap()
853 && mapping.covers(seq))
855 if (mapping.fromSeq == seq
856 && mapping.covers(mapping.getMapping().getTo()))
860 else if (mapping.getMapping().getTo() == seq
861 && mapping.covers(mapping.fromSeq))