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 private List<SequenceToSequenceMapping> mappings;
166 public AlignedCodonFrame()
168 mappings = new ArrayList<>();
172 * Adds a mapping between the dataset sequences for the associated dna and
173 * protein sequence objects
179 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map)
181 addMap(dnaseq, aaseq, map, null);
185 * Adds a mapping between the dataset sequences for the associated dna and
186 * protein sequence objects
193 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map,
196 // JBPNote DEBUG! THIS !
197 // dnaseq.transferAnnotation(aaseq, mp);
198 // aaseq.transferAnnotation(dnaseq, new Mapping(map.getInverse()));
200 SequenceI fromSeq = (dnaseq.getDatasetSequence() == null) ? dnaseq
201 : dnaseq.getDatasetSequence();
202 SequenceI toSeq = (aaseq.getDatasetSequence() == null) ? aaseq
203 : aaseq.getDatasetSequence();
206 * if we already hold a mapping between these sequences, just add to it
207 * note that 'adding' a duplicate map does nothing; this protects against
208 * creating duplicate mappings in AlignedCodonFrame
210 for (SequenceToSequenceMapping ssm : mappings)
212 if (ssm.fromSeq == fromSeq && ssm.mapping.to == toSeq)
214 ssm.mapping.map.addMapList(map);
220 * otherwise, add a new sequence mapping
222 Mapping mp = new Mapping(toSeq, map);
223 mp.setMappedFromId(mapFromId);
224 mappings.add(new SequenceToSequenceMapping(fromSeq, mp));
227 public SequenceI[] getdnaSeqs()
229 // TODO return a list instead?
231 List<SequenceI> seqs = new ArrayList<>();
232 for (SequenceToSequenceMapping ssm : mappings)
234 seqs.add(ssm.fromSeq);
236 return seqs.toArray(new SequenceI[seqs.size()]);
239 public SequenceI[] getAaSeqs()
241 // TODO not used - remove?
242 List<SequenceI> seqs = new ArrayList<>();
243 for (SequenceToSequenceMapping ssm : mappings)
245 seqs.add(ssm.mapping.to);
247 return seqs.toArray(new SequenceI[seqs.size()]);
250 public MapList[] getdnaToProt()
252 List<MapList> maps = new ArrayList<>();
253 for (SequenceToSequenceMapping ssm : mappings)
255 maps.add(ssm.mapping.map);
257 return maps.toArray(new MapList[maps.size()]);
260 public Mapping[] getProtMappings()
262 List<Mapping> maps = new ArrayList<>();
263 for (SequenceToSequenceMapping ssm : mappings)
265 maps.add(ssm.mapping);
267 return maps.toArray(new Mapping[maps.size()]);
271 * Returns the first mapping found which is to or from the given sequence, or
272 * null if none is found
277 public Mapping getMappingForSequence(SequenceI seq)
279 SequenceI seqDs = seq.getDatasetSequence();
280 seqDs = seqDs != null ? seqDs : seq;
282 for (SequenceToSequenceMapping ssm : mappings)
284 if (ssm.fromSeq == seqDs || ssm.mapping.to == seqDs)
293 * Return the corresponding aligned or dataset aa sequence for given dna
294 * sequence, null if not found.
299 public SequenceI getAaForDnaSeq(SequenceI dnaSeqRef)
301 SequenceI dnads = dnaSeqRef.getDatasetSequence();
302 for (SequenceToSequenceMapping ssm : mappings)
304 if (ssm.fromSeq == dnaSeqRef || ssm.fromSeq == dnads)
306 return ssm.mapping.to;
313 * Return the corresponding aligned or dataset dna sequence for given amino
314 * acid sequence, or null if not found. returns the sequence from the first
315 * mapping found that involves the protein sequence.
320 public SequenceI getDnaForAaSeq(SequenceI aaSeqRef)
322 SequenceI aads = aaSeqRef.getDatasetSequence();
323 for (SequenceToSequenceMapping ssm : mappings)
325 if (ssm.mapping.to == aaSeqRef || ssm.mapping.to == aads)
334 * test to see if codon frame involves seq in any way
337 * a nucleotide or protein sequence
338 * @return true if a mapping exists to or from this sequence to any translated
341 public boolean involvesSequence(SequenceI seq)
343 return getAaForDnaSeq(seq) != null || getDnaForAaSeq(seq) != null;
347 * Add search results for regions in other sequences that translate or are
348 * translated from a particular position in seq
354 * where highlighted regions go
356 public void markMappedRegion(SequenceI seq, int index,
357 SearchResultsI results)
360 SequenceI ds = seq.getDatasetSequence();
361 for (SequenceToSequenceMapping ssm : mappings)
363 if (ssm.fromSeq == seq || ssm.fromSeq == ds)
365 codon = ssm.mapping.map.locateInTo(index, index);
368 for (int i = 0; i < codon.length; i += 2)
370 results.addResult(ssm.mapping.to, codon[i], codon[i + 1]);
374 else if (ssm.mapping.to == seq || ssm.mapping.to == ds)
377 codon = ssm.mapping.map.locateInFrom(index, index);
380 for (int i = 0; i < codon.length; i += 2)
382 results.addResult(ssm.fromSeq, codon[i], codon[i + 1]);
391 * Returns the DNA codon positions (base 1) for the given position (base 1) in
392 * a mapped protein sequence, or null if no mapping is found.
394 * Intended for use in aligning cDNA to match aligned protein. Only the first
395 * mapping found is returned, so not suitable for use if multiple protein
396 * sequences are mapped to the same cDNA (but aligning cDNA as protein is
397 * ill-defined for this case anyway).
400 * the DNA dataset sequence
402 * residue position (base 1) in a protein sequence
405 public int[] getDnaPosition(SequenceI seq, int aaPos)
408 * Adapted from markMappedRegion().
412 for (SequenceToSequenceMapping ssm : mappings)
414 if (ssm.fromSeq == seq)
416 ml = getdnaToProt()[i];
421 return ml == null ? null : ml.locateInFrom(aaPos, aaPos);
425 * Convenience method to return the first aligned sequence in the given
426 * alignment whose dataset has a mapping with the given (aligned or dataset)
434 public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al)
437 * Search mapped protein ('to') sequences first.
439 for (SequenceToSequenceMapping ssm : mappings)
441 if (ssm.fromSeq == seq || ssm.fromSeq == seq.getDatasetSequence())
443 for (SequenceI sourceAligned : al.getSequences())
445 if (ssm.mapping.to == sourceAligned.getDatasetSequence()
446 || ssm.mapping.to == sourceAligned)
448 return sourceAligned;
455 * Then try mapped dna sequences.
457 for (SequenceToSequenceMapping ssm : mappings)
459 if (ssm.mapping.to == seq
460 || ssm.mapping.to == seq.getDatasetSequence())
462 for (SequenceI sourceAligned : al.getSequences())
464 if (ssm.fromSeq == sourceAligned.getDatasetSequence())
466 return sourceAligned;
476 * Returns the region in the target sequence's dataset that is mapped to the
477 * given position (base 1) in the query sequence's dataset. The region is a
478 * set of start/end position pairs.
485 public int[] getMappedRegion(SequenceI target, SequenceI query,
488 SequenceI targetDs = target.getDatasetSequence() == null ? target
489 : target.getDatasetSequence();
490 SequenceI queryDs = query.getDatasetSequence() == null ? query
491 : query.getDatasetSequence();
492 if (targetDs == null || queryDs == null /*|| dnaToProt == null*/)
496 for (SequenceToSequenceMapping ssm : mappings)
499 * try mapping from target to query
501 if (ssm.fromSeq == targetDs && ssm.mapping.to == queryDs)
503 int[] codon = ssm.mapping.map.locateInFrom(queryPos, queryPos);
510 * else try mapping from query to target
512 else if (ssm.fromSeq == queryDs && ssm.mapping.to == targetDs)
514 int[] codon = ssm.mapping.map.locateInTo(queryPos, queryPos);
525 * Returns the mapped DNA codons for the given position in a protein sequence,
526 * or null if no mapping is found. Returns a list of (e.g.) ['g', 'c', 't']
527 * codons. There may be more than one codon mapped to the protein if (for
528 * example), there are mappings to cDNA variants.
531 * the peptide dataset sequence
533 * residue position (base 1) in the peptide sequence
536 public List<char[]> getMappedCodons(SequenceI protein, int aaPos)
539 SequenceI dnaSeq = null;
540 List<char[]> result = new ArrayList<>();
542 for (SequenceToSequenceMapping ssm : mappings)
544 if (ssm.mapping.to == protein
545 && ssm.mapping.getMap().getFromRatio() == 3)
547 ml = ssm.mapping.map;
548 dnaSeq = ssm.fromSeq;
550 int[] codonPos = ml.locateInFrom(aaPos, aaPos);
551 if (codonPos == null)
557 * Read off the mapped nucleotides (converting to position base 0)
559 codonPos = MappingUtils.flattenRanges(codonPos);
560 int start = dnaSeq.getStart();
561 char c1 = dnaSeq.getCharAt(codonPos[0] - start);
562 char c2 = dnaSeq.getCharAt(codonPos[1] - start);
563 char c3 = dnaSeq.getCharAt(codonPos[2] - start);
564 result.add(new char[] { c1, c2, c3 });
567 return result.isEmpty() ? null : result;
571 * Returns any mappings found which are from the given sequence, and to
572 * distinct sequences.
577 public List<Mapping> getMappingsFromSequence(SequenceI seq)
579 List<Mapping> result = new ArrayList<>();
580 List<SequenceI> related = new ArrayList<>();
581 SequenceI seqDs = seq.getDatasetSequence();
582 seqDs = seqDs != null ? seqDs : seq;
584 for (SequenceToSequenceMapping ssm : mappings)
586 final Mapping mapping = ssm.mapping;
587 if (ssm.fromSeq == seqDs)
589 if (!related.contains(mapping.to))
592 related.add(mapping.to);
600 * Test whether the given sequence is substitutable for one or more dummy
601 * sequences in this mapping
607 public boolean isRealisableWith(SequenceI seq)
609 return realiseWith(seq, false) > 0;
613 * Replace any matchable mapped dummy sequences with the given real one.
614 * Returns the count of sequence mappings instantiated.
619 public int realiseWith(SequenceI seq)
621 return realiseWith(seq, true);
625 * Returns the number of mapped dummy sequences that could be replaced with
626 * the given real sequence.
631 * if true, performs replacements, else only counts
634 protected int realiseWith(SequenceI seq, boolean doUpdate)
636 SequenceI ds = seq.getDatasetSequence() != null
637 ? seq.getDatasetSequence()
642 * check for replaceable DNA ('map from') sequences
644 for (SequenceToSequenceMapping ssm : mappings)
646 SequenceI dna = ssm.fromSeq;
647 if (dna instanceof SequenceDummy
648 && dna.getName().equals(ds.getName()))
650 Mapping mapping = ssm.mapping;
651 int mapStart = mapping.getMap().getFromLowest();
652 int mapEnd = mapping.getMap().getFromHighest();
653 boolean mappable = couldRealiseSequence(dna, ds, mapStart, mapEnd);
659 // TODO: new method ? ds.realise(dna);
660 // might want to copy database refs as well
661 ds.setSequenceFeatures(dna.getSequenceFeatures());
664 System.out.println("Realised mapped sequence " + ds.getName());
670 * check for replaceable protein ('map to') sequences
672 Mapping mapping = ssm.mapping;
673 SequenceI prot = mapping.getTo();
674 int mapStart = mapping.getMap().getToLowest();
675 int mapEnd = mapping.getMap().getToHighest();
676 boolean mappable = couldRealiseSequence(prot, ds, mapStart, mapEnd);
682 // TODO: new method ? ds.realise(dna);
683 // might want to copy database refs as well
684 ds.setSequenceFeatures(dna.getSequenceFeatures());
685 ssm.mapping.setTo(ds);
693 * Helper method to test whether a 'real' sequence could replace a 'dummy'
694 * sequence in the map. The criteria are that they have the same name, and
695 * that the mapped region overlaps the candidate sequence.
703 protected static boolean couldRealiseSequence(SequenceI existing,
704 SequenceI replacement, int mapStart, int mapEnd)
706 if (existing instanceof SequenceDummy
707 && !(replacement instanceof SequenceDummy)
708 && existing.getName().equals(replacement.getName()))
710 int start = replacement.getStart();
711 int end = replacement.getEnd();
712 boolean mappingOverlapsSequence = (mapStart >= start
713 && mapStart <= end) || (mapEnd >= start && mapEnd <= end);
714 if (mappingOverlapsSequence)
723 * Change any mapping to the given sequence to be to its dataset sequence
724 * instead. For use when mappings are created before their referenced
725 * sequences are instantiated, for example when parsing GFF data.
729 public void updateToDataset(SequenceI seq)
731 if (seq == null || seq.getDatasetSequence() == null)
735 SequenceI ds = seq.getDatasetSequence();
737 for (SequenceToSequenceMapping ssm : mappings)
742 if (ssm.fromSeq == seq)
750 if (ssm.mapping.to == seq)
758 * Answers true if this object contains no mappings
762 public boolean isEmpty()
764 return mappings.isEmpty();
768 * Method for debug / inspection purposes only, may change in future
771 public String toString()
773 return mappings == null ? "null" : mappings.toString();
777 * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or
781 * aligned or dataset sequence
783 * aligned or dataset sequence
786 public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
788 SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
789 : fromSeq.getDatasetSequence();
790 SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq
791 : toSeq.getDatasetSequence();
793 for (SequenceToSequenceMapping mapping : mappings)
795 SequenceI from = mapping.fromSeq;
796 SequenceI to = mapping.mapping.to;
797 if ((from == dssFrom && to == dssTo)
798 || (from == dssTo && to == dssFrom))
800 return mapping.mapping;
807 * Returns a hashcode derived from the list of sequence mappings
809 * @see SequenceToSequenceMapping#hashCode()
810 * @see AbstractList#hashCode()
813 public int hashCode()
815 return this.mappings.hashCode();
819 * Two AlignedCodonFrame objects are equal if they hold the same ordered list
822 * @see SequenceToSequenceMapping#equals
825 public boolean equals(Object obj)
827 if (!(obj instanceof AlignedCodonFrame))
831 return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
834 public List<SequenceToSequenceMapping> getMappings()
840 * Returns the first mapping found which is between the two given sequences,
841 * and covers the full extent of both.
847 public SequenceToSequenceMapping getCoveringMapping(SequenceI seq1,
850 for (SequenceToSequenceMapping mapping : mappings)
852 if (mapping.covers(seq2) && mapping.covers(seq1))