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);
126 * @param localCover - when true - compare extent of seq's dataset sequence rather than the local extent
127 * @param either - when true coverage is required for either seq or the mapped sequence
128 * @return true if mapping covers full length of given sequence (or the other if either==true)
130 public boolean covers(SequenceI seq, boolean localCover,boolean either)
132 List<int[]> mappedRanges = null,otherRanges=null;
133 MapList mapList = mapping.getMap();
134 int mstart=seq.getStart(),mend=seq.getEnd(),ostart,oend;
136 if (fromSeq == seq || fromSeq == seq.getDatasetSequence())
138 if (localCover && fromSeq !=seq)
140 mstart=fromSeq.getStart();
141 mend=fromSeq.getEnd();
143 mappedRanges = mapList.getFromRanges();
144 otherRanges=mapList.getToRanges();
145 ostart=mapping.to.getStart();
146 oend=mapping.to.getEnd();
148 else if (mapping.to == seq || mapping.to == seq.getDatasetSequence())
150 if (localCover && mapping.to !=seq)
152 mstart=mapping.to.getStart();
153 mend=mapping.to.getEnd();
155 mappedRanges = mapList.getToRanges();
156 otherRanges=mapList.getFromRanges();
157 ostart=fromSeq.getStart();
158 oend=fromSeq.getEnd();
166 * check that each mapped range lies within the sequence range
167 * (necessary for circular CDS - example EMBL:J03321:AAA91567)
168 * and mapped length covers (at least) sequence length
170 int length = countRange(mappedRanges,mstart,mend);
174 // add 3 to mapped length to allow for a mapped stop codon
175 if (length + 3 >= (mend - mstart + 1))
182 // also check coverage of the other range
183 length = countRange(otherRanges, ostart, oend);
186 if (length + 1 >= (oend - ostart + 1))
194 private int countRange(List<int[]> mappedRanges,int mstart,int mend)
197 for (int[] range : mappedRanges)
199 int from = Math.min(range[0], range[1]);
200 int to = Math.max(range[0], range[1]);
201 if (from < mstart || to > mend)
205 length += (to - from + 1);
211 * Adds any regions mapped to or from position {@code pos} in sequence
212 * {@code seq} to the given search results
213 * Note: recommend first using the .covers(,true,true) to ensure mapping covers both sequences
218 public void markMappedRegion(SequenceI seq, int pos, SearchResultsI sr)
221 SequenceI mappedSeq = null;
222 SequenceI ds = seq.getDatasetSequence();
228 if (this.fromSeq == seq || this.fromSeq == ds)
230 codon = this.mapping.map.locateInTo(pos, pos);
231 mappedSeq = this.mapping.to;
233 else if (this.mapping.to == seq || this.mapping.to == ds)
235 codon = this.mapping.map.locateInFrom(pos, pos);
236 mappedSeq = this.fromSeq;
241 for (int i = 0; i < codon.length; i += 2)
243 sr.addResult(mappedSeq, codon[i], codon[i + 1]);
249 private List<SequenceToSequenceMapping> mappings;
254 public AlignedCodonFrame()
256 mappings = new ArrayList<>();
260 * Adds a mapping between the dataset sequences for the associated dna and
261 * protein sequence objects
267 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map)
269 addMap(dnaseq, aaseq, map, null);
273 * Adds a mapping between the dataset sequences for the associated dna and
274 * protein sequence objects
281 public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map,
284 // JBPNote DEBUG! THIS !
285 // dnaseq.transferAnnotation(aaseq, mp);
286 // aaseq.transferAnnotation(dnaseq, new Mapping(map.getInverse()));
288 SequenceI fromSeq = (dnaseq.getDatasetSequence() == null) ? dnaseq
289 : dnaseq.getDatasetSequence();
290 SequenceI toSeq = (aaseq.getDatasetSequence() == null) ? aaseq
291 : aaseq.getDatasetSequence();
294 * if we already hold a mapping between these sequences, just add to it
295 * note that 'adding' a duplicate map does nothing; this protects against
296 * creating duplicate mappings in AlignedCodonFrame
298 for (SequenceToSequenceMapping ssm : mappings)
300 if (ssm.fromSeq == fromSeq && ssm.mapping.to == toSeq)
302 ssm.mapping.map.addMapList(map);
308 * otherwise, add a new sequence mapping
310 Mapping mp = new Mapping(toSeq, map);
311 mp.setMappedFromId(mapFromId);
312 mappings.add(new SequenceToSequenceMapping(fromSeq, mp));
315 public SequenceI[] getdnaSeqs()
317 // TODO return a list instead?
319 List<SequenceI> seqs = new ArrayList<>();
320 for (SequenceToSequenceMapping ssm : mappings)
322 seqs.add(ssm.fromSeq);
324 return seqs.toArray(new SequenceI[seqs.size()]);
327 public SequenceI[] getAaSeqs()
329 // TODO not used - remove?
330 List<SequenceI> seqs = new ArrayList<>();
331 for (SequenceToSequenceMapping ssm : mappings)
333 seqs.add(ssm.mapping.to);
335 return seqs.toArray(new SequenceI[seqs.size()]);
338 public MapList[] getdnaToProt()
340 List<MapList> maps = new ArrayList<>();
341 for (SequenceToSequenceMapping ssm : mappings)
343 maps.add(ssm.mapping.map);
345 return maps.toArray(new MapList[maps.size()]);
348 public Mapping[] getProtMappings()
350 List<Mapping> maps = new ArrayList<>();
351 for (SequenceToSequenceMapping ssm : mappings)
353 maps.add(ssm.mapping);
355 return maps.toArray(new Mapping[maps.size()]);
359 * Returns the first mapping found which is to or from the given sequence, or
360 * null if none is found
365 public Mapping getMappingForSequence(SequenceI seq)
367 SequenceI seqDs = seq.getDatasetSequence();
368 seqDs = seqDs != null ? seqDs : seq;
370 for (SequenceToSequenceMapping ssm : mappings)
372 if (ssm.fromSeq == seqDs || ssm.mapping.to == seqDs)
381 * Return the corresponding aligned or dataset aa sequence for given dna
382 * sequence, null if not found.
387 public SequenceI getAaForDnaSeq(SequenceI dnaSeqRef)
389 SequenceI dnads = dnaSeqRef.getDatasetSequence();
390 for (SequenceToSequenceMapping ssm : mappings)
392 if (ssm.fromSeq == dnaSeqRef || ssm.fromSeq == dnads)
394 return ssm.mapping.to;
401 * Return the corresponding aligned or dataset dna sequence for given amino
402 * acid sequence, or null if not found. returns the sequence from the first
403 * mapping found that involves the protein sequence.
408 public SequenceI getDnaForAaSeq(SequenceI aaSeqRef)
410 SequenceI aads = aaSeqRef.getDatasetSequence();
411 for (SequenceToSequenceMapping ssm : mappings)
413 if (ssm.mapping.to == aaSeqRef || ssm.mapping.to == aads)
422 * test to see if codon frame involves seq in any way
425 * a nucleotide or protein sequence
426 * @return true if a mapping exists to or from this sequence to any translated
429 public boolean involvesSequence(SequenceI seq)
431 return getAaForDnaSeq(seq) != null || getDnaForAaSeq(seq) != null;
435 * Add search results for regions in other sequences that translate or are
436 * translated from a particular position in seq (which may be an aligned or
443 * where highlighted regions go
445 public void markMappedRegion(SequenceI seq, int index,
446 SearchResultsI results)
448 SequenceI ds = seq.getDatasetSequence();
453 for (SequenceToSequenceMapping ssm : mappings)
455 if (ssm.covers(seq,true,true)) {
456 ssm.markMappedRegion(ds, index, results);
462 * Convenience method to return the first aligned sequence in the given
463 * alignment whose dataset has a mapping with the given (aligned or dataset)
471 public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al)
474 * Search mapped protein ('to') sequences first.
476 for (SequenceToSequenceMapping ssm : mappings)
478 if (ssm.fromSeq == seq || ssm.fromSeq == seq.getDatasetSequence())
480 for (SequenceI sourceAligned : al.getSequences())
482 if (ssm.mapping.to == sourceAligned.getDatasetSequence()
483 || ssm.mapping.to == sourceAligned)
485 return sourceAligned;
492 * Then try mapped dna sequences.
494 for (SequenceToSequenceMapping ssm : mappings)
496 if (ssm.mapping.to == seq
497 || ssm.mapping.to == seq.getDatasetSequence())
499 for (SequenceI sourceAligned : al.getSequences())
501 if (ssm.fromSeq == sourceAligned.getDatasetSequence())
503 return sourceAligned;
513 * Returns the region in the target sequence's dataset that is mapped to the
514 * given position (base 1) in the query sequence's dataset. The region is a
515 * set of start/end position pairs.
522 public int[] getMappedRegion(SequenceI target, SequenceI query,
525 SequenceI targetDs = target.getDatasetSequence() == null ? target
526 : target.getDatasetSequence();
527 SequenceI queryDs = query.getDatasetSequence() == null ? query
528 : query.getDatasetSequence();
529 if (targetDs == null || queryDs == null /*|| dnaToProt == null*/)
533 for (SequenceToSequenceMapping ssm : mappings)
536 * try mapping from target to query
538 if (ssm.fromSeq == targetDs && ssm.mapping.to == queryDs)
540 int[] codon = ssm.mapping.map.locateInFrom(queryPos, queryPos);
547 * else try mapping from query to target
549 else if (ssm.fromSeq == queryDs && ssm.mapping.to == targetDs)
551 int[] codon = ssm.mapping.map.locateInTo(queryPos, queryPos);
562 * Returns the mapped DNA codons for the given position in a protein sequence,
563 * or null if no mapping is found. Returns a list of (e.g.) ['g', 'c', 't']
564 * codons. There may be more than one codon mapped to the protein if (for
565 * example), there are mappings to cDNA variants.
568 * the peptide dataset sequence
570 * residue position (base 1) in the peptide sequence
573 public List<char[]> getMappedCodons(SequenceI protein, int aaPos)
576 SequenceI dnaSeq = null;
577 List<char[]> result = new ArrayList<>();
579 for (SequenceToSequenceMapping ssm : mappings)
581 if (ssm.mapping.to == protein
582 && ssm.mapping.getMap().getFromRatio() == 3)
584 ml = ssm.mapping.map;
585 dnaSeq = ssm.fromSeq;
587 int[] codonPos = ml.locateInFrom(aaPos, aaPos);
588 if (codonPos == null)
594 * Read off the mapped nucleotides (converting to position base 0)
596 codonPos = MappingUtils.flattenRanges(codonPos);
597 int start = dnaSeq.getStart();
598 char c1 = dnaSeq.getCharAt(codonPos[0] - start);
599 char c2 = dnaSeq.getCharAt(codonPos[1] - start);
600 char c3 = dnaSeq.getCharAt(codonPos[2] - start);
601 result.add(new char[] { c1, c2, c3 });
604 return result.isEmpty() ? null : result;
608 * Returns any mappings found which are from the given sequence, and to
609 * distinct sequences.
614 public List<Mapping> getMappingsFromSequence(SequenceI seq)
616 List<Mapping> result = new ArrayList<>();
617 List<SequenceI> related = new ArrayList<>();
618 SequenceI seqDs = seq.getDatasetSequence();
619 seqDs = seqDs != null ? seqDs : seq;
621 for (SequenceToSequenceMapping ssm : mappings)
623 final Mapping mapping = ssm.mapping;
624 if (ssm.fromSeq == seqDs)
626 if (!related.contains(mapping.to))
629 related.add(mapping.to);
637 * Test whether the given sequence is substitutable for one or more dummy
638 * sequences in this mapping
644 public boolean isRealisableWith(SequenceI seq)
646 return realiseWith(seq, false) > 0;
650 * Replace any matchable mapped dummy sequences with the given real one.
651 * Returns the count of sequence mappings instantiated.
656 public int realiseWith(SequenceI seq)
658 return realiseWith(seq, true);
662 * Returns the number of mapped dummy sequences that could be replaced with
663 * the given real sequence.
668 * if true, performs replacements, else only counts
671 protected int realiseWith(SequenceI seq, boolean doUpdate)
673 SequenceI ds = seq.getDatasetSequence() != null
674 ? seq.getDatasetSequence()
679 * check for replaceable DNA ('map from') sequences
681 for (SequenceToSequenceMapping ssm : mappings)
683 SequenceI dna = ssm.fromSeq;
684 if (dna instanceof SequenceDummy
685 && dna.getName().equals(ds.getName()))
687 Mapping mapping = ssm.mapping;
688 int mapStart = mapping.getMap().getFromLowest();
689 int mapEnd = mapping.getMap().getFromHighest();
690 boolean mappable = couldRealiseSequence(dna, ds, mapStart, mapEnd);
696 // TODO: new method ? ds.realise(dna);
697 // might want to copy database refs as well
698 ds.setSequenceFeatures(dna.getSequenceFeatures());
701 System.out.println("Realised mapped sequence " + ds.getName());
707 * check for replaceable protein ('map to') sequences
709 Mapping mapping = ssm.mapping;
710 SequenceI prot = mapping.getTo();
711 int mapStart = mapping.getMap().getToLowest();
712 int mapEnd = mapping.getMap().getToHighest();
713 boolean mappable = couldRealiseSequence(prot, ds, mapStart, mapEnd);
719 // TODO: new method ? ds.realise(dna);
720 // might want to copy database refs as well
721 ds.setSequenceFeatures(dna.getSequenceFeatures());
722 ssm.mapping.setTo(ds);
730 * Helper method to test whether a 'real' sequence could replace a 'dummy'
731 * sequence in the map. The criteria are that they have the same name, and
732 * that the mapped region overlaps the candidate sequence.
740 protected static boolean couldRealiseSequence(SequenceI existing,
741 SequenceI replacement, int mapStart, int mapEnd)
743 if (existing instanceof SequenceDummy
744 && !(replacement instanceof SequenceDummy)
745 && existing.getName().equals(replacement.getName()))
747 int start = replacement.getStart();
748 int end = replacement.getEnd();
749 boolean mappingOverlapsSequence = (mapStart >= start
750 && mapStart <= end) || (mapEnd >= start && mapEnd <= end);
751 if (mappingOverlapsSequence)
760 * Change any mapping to the given sequence to be to its dataset sequence
761 * instead. For use when mappings are created before their referenced
762 * sequences are instantiated, for example when parsing GFF data.
766 public void updateToDataset(SequenceI seq)
768 if (seq == null || seq.getDatasetSequence() == null)
772 SequenceI ds = seq.getDatasetSequence();
774 for (SequenceToSequenceMapping ssm : mappings)
779 if (ssm.fromSeq == seq)
787 if (ssm.mapping.to == seq)
795 * Answers true if this object contains no mappings
799 public boolean isEmpty()
801 return mappings.isEmpty();
805 * Method for debug / inspection purposes only, may change in future
808 public String toString()
810 return mappings == null ? "null" : mappings.toString();
814 * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or
818 * aligned or dataset sequence
820 * aligned or dataset sequence
823 public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
825 SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
826 : fromSeq.getDatasetSequence();
827 SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq
828 : toSeq.getDatasetSequence();
830 for (SequenceToSequenceMapping mapping : mappings)
832 SequenceI from = mapping.fromSeq;
833 SequenceI to = mapping.mapping.to;
834 if ((from == dssFrom && to == dssTo)
835 || (from == dssTo && to == dssFrom))
837 return mapping.mapping;
844 * Returns a hashcode derived from the list of sequence mappings
846 * @see SequenceToSequenceMapping#hashCode()
847 * @see AbstractList#hashCode()
850 public int hashCode()
852 return this.mappings.hashCode();
856 * Two AlignedCodonFrame objects are equal if they hold the same ordered list
859 * @see SequenceToSequenceMapping#equals
862 public boolean equals(Object obj)
864 if (!(obj instanceof AlignedCodonFrame))
868 return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
871 public List<SequenceToSequenceMapping> getMappings()
877 * Returns the first mapping found which is between the two given sequences,
878 * and covers the full extent of both.
884 public SequenceToSequenceMapping getCoveringMapping(SequenceI seq1,
887 for (SequenceToSequenceMapping mapping : mappings)
889 if (mapping.covers(seq2) && mapping.covers(seq1))
898 * Returns the first mapping found which is between the given dataset sequence
899 * and another, is a triplet mapping (3:1 or 1:3), and covers the full extent
900 * of both sequences involved
905 public SequenceToSequenceMapping getCoveringCodonMapping(SequenceI seq)
907 for (SequenceToSequenceMapping mapping : mappings)
909 if (mapping.getMapping().getMap().isTripletMap()
910 && mapping.covers(seq))
912 if (mapping.fromSeq == seq
913 && mapping.covers(mapping.getMapping().getTo()))
917 else if (mapping.getMapping().getTo() == seq
918 && mapping.covers(mapping.fromSeq))