JAL-3748 allow AlignedCodonFrame.covers to optionally only require coverage for eithe...
[jalview.git] / src / jalview / datamodel / AlignedCodonFrame.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.datamodel;
22
23 import jalview.util.MapList;
24 import jalview.util.MappingUtils;
25
26 import java.util.AbstractList;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 /**
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.
33  */
34 public class AlignedCodonFrame
35 {
36
37   /*
38    * Data bean to hold mappings from one sequence to another
39    */
40   public class SequenceToSequenceMapping
41   {
42     private SequenceI fromSeq;
43
44     private Mapping mapping;
45
46     SequenceToSequenceMapping(SequenceI from, Mapping map)
47     {
48       this.fromSeq = from;
49       this.mapping = map;
50     }
51
52     /**
53      * Readable representation for debugging only, not guaranteed not to change
54      */
55     @Override
56     public String toString()
57     {
58       return String.format("From %s %s", fromSeq.getName(),
59               mapping.toString());
60     }
61
62     /**
63      * Returns a hashCode derived from the hashcodes of the mappings and fromSeq
64      * 
65      * @see SequenceToSequenceMapping#hashCode()
66      */
67     @Override
68     public int hashCode()
69     {
70       return (fromSeq == null ? 0 : fromSeq.hashCode() * 31)
71               + mapping.hashCode();
72     }
73
74     /**
75      * Answers true if the objects hold the same mapping between the same two
76      * sequences
77      * 
78      * @see Mapping#equals
79      */
80     @Override
81     public boolean equals(Object obj)
82     {
83       if (!(obj instanceof SequenceToSequenceMapping))
84       {
85         return false;
86       }
87       SequenceToSequenceMapping that = (SequenceToSequenceMapping) obj;
88       if (this.mapping == null)
89       {
90         return that.mapping == null;
91       }
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);
99     }
100
101     public SequenceI getFromSeq()
102     {
103       return fromSeq;
104     }
105
106     public Mapping getMapping()
107     {
108       return mapping;
109     }
110
111     /**
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.
115      * 
116      * @param seq
117      * @return
118      */
119     public boolean covers(SequenceI seq)
120     {
121       return covers(seq,false,false);
122     }
123     /**
124      * 
125      * @param seq
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)
129      */
130     public boolean covers(SequenceI seq, boolean localCover,boolean either)
131     {
132       List<int[]> mappedRanges = null,otherRanges=null;
133       MapList mapList = mapping.getMap();
134       int mstart=seq.getStart(),mend=seq.getEnd(),ostart,oend;
135               ;
136       if (fromSeq == seq || fromSeq == seq.getDatasetSequence())
137       {
138         if (localCover && fromSeq !=seq)
139         {
140           mstart=fromSeq.getStart();
141           mend=fromSeq.getEnd();
142         }
143         mappedRanges = mapList.getFromRanges();
144         otherRanges=mapList.getToRanges();
145         ostart=mapping.to.getStart();
146         oend=mapping.to.getEnd();
147       }
148       else if (mapping.to == seq || mapping.to == seq.getDatasetSequence())
149       {
150         if (localCover && mapping.to !=seq)
151         {
152           mstart=mapping.to.getStart();
153           mend=mapping.to.getEnd();
154         }
155         mappedRanges = mapList.getToRanges();
156         otherRanges=mapList.getFromRanges();
157         ostart=fromSeq.getStart();
158         oend=fromSeq.getEnd();
159       }
160       else
161       {
162         return false;
163       }
164
165       /*
166        * check that each mapped range lieS with the sequence range
167        * (necessary for circular CDS - example EMBL:J03321:AAA91567)
168        * and mapped length covers (at least) sequence length
169        */
170       int length = countRange(mappedRanges,mstart,mend);
171
172       if (length != -1)
173       {
174         // add 1 to mapped length to allow for a mapped stop codon
175         if (length + 1 >= (mend - mstart + 1))
176         {
177           return true;
178         }
179       }
180       if (either)
181       {
182         // also check coverage of the other range
183         length = countRange(otherRanges, ostart, oend);
184         if (length != -1)
185         {
186           if (length + 1 >= (oend - ostart + 1))
187           {
188             return true;
189           }
190         }
191       }
192       return false;
193     }
194     private int countRange(List<int[]> mappedRanges,int mstart,int mend)
195     {
196       int length=0;
197       for (int[] range : mappedRanges)
198       {
199         int from = Math.min(range[0], range[1]);
200         int to = Math.max(range[0], range[1]);
201         if (from < mstart || to > mend)
202         {
203           return -1;
204         }
205         length += (to - from + 1);
206       }
207       return length;
208     }
209     }
210   }
211
212   private List<SequenceToSequenceMapping> mappings;
213
214   /**
215    * Constructor
216    */
217   public AlignedCodonFrame()
218   {
219     mappings = new ArrayList<>();
220   }
221
222   /**
223    * Adds a mapping between the dataset sequences for the associated dna and
224    * protein sequence objects
225    * 
226    * @param dnaseq
227    * @param aaseq
228    * @param map
229    */
230   public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map)
231   {
232     addMap(dnaseq, aaseq, map, null);
233   }
234
235   /**
236    * Adds a mapping between the dataset sequences for the associated dna and
237    * protein sequence objects
238    * 
239    * @param dnaseq
240    * @param aaseq
241    * @param map
242    * @param mapFromId
243    */
244   public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map,
245           String mapFromId)
246   {
247     // JBPNote DEBUG! THIS !
248     // dnaseq.transferAnnotation(aaseq, mp);
249     // aaseq.transferAnnotation(dnaseq, new Mapping(map.getInverse()));
250
251     SequenceI fromSeq = (dnaseq.getDatasetSequence() == null) ? dnaseq
252             : dnaseq.getDatasetSequence();
253     SequenceI toSeq = (aaseq.getDatasetSequence() == null) ? aaseq
254             : aaseq.getDatasetSequence();
255
256     /*
257      * if we already hold a mapping between these sequences, just add to it 
258      * note that 'adding' a duplicate map does nothing; this protects against
259      * creating duplicate mappings in AlignedCodonFrame
260      */
261     for (SequenceToSequenceMapping ssm : mappings)
262     {
263       if (ssm.fromSeq == fromSeq && ssm.mapping.to == toSeq)
264       {
265         ssm.mapping.map.addMapList(map);
266         return;
267       }
268     }
269
270     /*
271      * otherwise, add a new sequence mapping
272      */
273     Mapping mp = new Mapping(toSeq, map);
274     mp.setMappedFromId(mapFromId);
275     mappings.add(new SequenceToSequenceMapping(fromSeq, mp));
276   }
277
278   public SequenceI[] getdnaSeqs()
279   {
280     // TODO return a list instead?
281     // return dnaSeqs;
282     List<SequenceI> seqs = new ArrayList<>();
283     for (SequenceToSequenceMapping ssm : mappings)
284     {
285       seqs.add(ssm.fromSeq);
286     }
287     return seqs.toArray(new SequenceI[seqs.size()]);
288   }
289
290   public SequenceI[] getAaSeqs()
291   {
292     // TODO not used - remove?
293     List<SequenceI> seqs = new ArrayList<>();
294     for (SequenceToSequenceMapping ssm : mappings)
295     {
296       seqs.add(ssm.mapping.to);
297     }
298     return seqs.toArray(new SequenceI[seqs.size()]);
299   }
300
301   public MapList[] getdnaToProt()
302   {
303     List<MapList> maps = new ArrayList<>();
304     for (SequenceToSequenceMapping ssm : mappings)
305     {
306       maps.add(ssm.mapping.map);
307     }
308     return maps.toArray(new MapList[maps.size()]);
309   }
310
311   public Mapping[] getProtMappings()
312   {
313     List<Mapping> maps = new ArrayList<>();
314     for (SequenceToSequenceMapping ssm : mappings)
315     {
316       maps.add(ssm.mapping);
317     }
318     return maps.toArray(new Mapping[maps.size()]);
319   }
320
321   /**
322    * Returns the first mapping found which is to or from the given sequence, or
323    * null if none is found
324    * 
325    * @param seq
326    * @return
327    */
328   public Mapping getMappingForSequence(SequenceI seq)
329   {
330     SequenceI seqDs = seq.getDatasetSequence();
331     seqDs = seqDs != null ? seqDs : seq;
332
333     for (SequenceToSequenceMapping ssm : mappings)
334     {
335       if (ssm.fromSeq == seqDs || ssm.mapping.to == seqDs)
336       {
337         return ssm.mapping;
338       }
339     }
340     return null;
341   }
342
343   /**
344    * Return the corresponding aligned or dataset aa sequence for given dna
345    * sequence, null if not found.
346    * 
347    * @param sequenceRef
348    * @return
349    */
350   public SequenceI getAaForDnaSeq(SequenceI dnaSeqRef)
351   {
352     SequenceI dnads = dnaSeqRef.getDatasetSequence();
353     for (SequenceToSequenceMapping ssm : mappings)
354     {
355       if (ssm.fromSeq == dnaSeqRef || ssm.fromSeq == dnads)
356       {
357         return ssm.mapping.to;
358       }
359     }
360     return null;
361   }
362
363   /**
364    * Return the corresponding aligned or dataset dna sequence for given amino
365    * acid sequence, or null if not found. returns the sequence from the first
366    * mapping found that involves the protein sequence.
367    * 
368    * @param aaSeqRef
369    * @return
370    */
371   public SequenceI getDnaForAaSeq(SequenceI aaSeqRef)
372   {
373     SequenceI aads = aaSeqRef.getDatasetSequence();
374     for (SequenceToSequenceMapping ssm : mappings)
375     {
376       if (ssm.mapping.to == aaSeqRef || ssm.mapping.to == aads)
377       {
378         return ssm.fromSeq;
379       }
380     }
381     return null;
382   }
383
384   /**
385    * test to see if codon frame involves seq in any way
386    * 
387    * @param seq
388    *          a nucleotide or protein sequence
389    * @return true if a mapping exists to or from this sequence to any translated
390    *         sequence
391    */
392   public boolean involvesSequence(SequenceI seq)
393   {
394     return getAaForDnaSeq(seq) != null || getDnaForAaSeq(seq) != null;
395   }
396
397   /**
398    * Add search results for regions in other sequences that translate or are
399    * translated from a particular position in seq
400    * 
401    * @param seq
402    * @param index
403    *          position in seq
404    * @param results
405    *          where highlighted regions go
406    */
407   public void markMappedRegion(SequenceI seq, int index,
408           SearchResultsI results)
409   {
410     int[] codon;
411     SequenceI ds = seq.getDatasetSequence();
412     for (SequenceToSequenceMapping ssm : mappings)
413     {
414       if (ssm.fromSeq == seq || ssm.fromSeq == ds)
415       {
416         codon = ssm.mapping.map.locateInTo(index, index);
417         if (codon != null)
418         {
419           for (int i = 0; i < codon.length; i += 2)
420           {
421             results.addResult(ssm.mapping.to, codon[i], codon[i + 1]);
422           }
423         }
424       }
425       else if (ssm.mapping.to == seq || ssm.mapping.to == ds)
426       {
427         {
428           codon = ssm.mapping.map.locateInFrom(index, index);
429           if (codon != null)
430           {
431             for (int i = 0; i < codon.length; i += 2)
432             {
433               results.addResult(ssm.fromSeq, codon[i], codon[i + 1]);
434             }
435           }
436         }
437       }
438     }
439   }
440
441   /**
442    * Returns the DNA codon positions (base 1) for the given position (base 1) in
443    * a mapped protein sequence, or null if no mapping is found.
444    * 
445    * Intended for use in aligning cDNA to match aligned protein. Only the first
446    * mapping found is returned, so not suitable for use if multiple protein
447    * sequences are mapped to the same cDNA (but aligning cDNA as protein is
448    * ill-defined for this case anyway).
449    * 
450    * @param seq
451    *          the DNA dataset sequence
452    * @param aaPos
453    *          residue position (base 1) in a protein sequence
454    * @return
455    */
456   public int[] getDnaPosition(SequenceI seq, int aaPos)
457   {
458     /*
459      * Adapted from markMappedRegion().
460      */
461     MapList ml = null;
462     int i = 0;
463     for (SequenceToSequenceMapping ssm : mappings)
464     {
465       if (ssm.fromSeq == seq)
466       {
467         ml = getdnaToProt()[i];
468         break;
469       }
470       i++;
471     }
472     return ml == null ? null : ml.locateInFrom(aaPos, aaPos);
473   }
474
475   /**
476    * Convenience method to return the first aligned sequence in the given
477    * alignment whose dataset has a mapping with the given (aligned or dataset)
478    * sequence.
479    * 
480    * @param seq
481    * 
482    * @param al
483    * @return
484    */
485   public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al)
486   {
487     return findAlignedSequence(seq, al, null);
488   }
489   /**
490    * Convenience method to return the first aligned sequence in the given
491    * alignment whose dataset has a mapping with the given (aligned or dataset)
492    * sequence, and optionally the mapping that relates them 
493    * 
494    * @param seq
495    * @param al
496    * @param map - list to add the mapping to
497    * @return sequence from al that maps to seq
498    */
499   public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al,List<SequenceToSequenceMapping> map)
500   {
501     /*
502      * Search mapped protein ('to') sequences first.
503      */
504     for (SequenceToSequenceMapping ssm : mappings)
505     {
506       int mStart=ssm.getMapping().getMap().getFromLowest(),mEnd=ssm.getMapping().map.getFromHighest();
507       if ((ssm.fromSeq == seq || ssm.fromSeq == seq.getDatasetSequence())
508               && seq.getStart()>=mStart && seq.getEnd()<=mEnd)
509       {
510         for (SequenceI sourceAligned : al.getSequences())
511         {
512           if (ssm.covers(sourceAligned,true,false))
513           {
514             if (map != null)
515             {
516               map.add(ssm);
517             }
518             return sourceAligned;
519           }
520         }
521       }
522     }
523
524     /*
525      * Then try mapped dna sequences.
526      */
527     for (SequenceToSequenceMapping ssm : mappings)
528     {
529       int mStart=ssm.getMapping().getMap().getToLowest(),mEnd=ssm.getMapping().map.getToHighest();
530       if ((ssm.mapping.to == seq
531               || ssm.mapping.to == seq.getDatasetSequence())
532               && seq.getStart()>=mStart && seq.getEnd()<=mEnd)
533       {
534         for (SequenceI sourceAligned : al.getSequences())
535         {
536           if (ssm.covers(sourceAligned,true,true))
537           {
538             if (map != null)
539             {
540               map.add(ssm);
541             }
542             return sourceAligned;
543           }
544         }
545       }
546     }
547
548     return null;
549   }
550
551   /**
552    * Returns the region in the target sequence's dataset that is mapped to the
553    * given position (base 1) in the query sequence's dataset. The region is a
554    * set of start/end position pairs.
555    * 
556    * @param target
557    * @param query
558    * @param queryPos
559    * @return
560    */
561   public int[] getMappedRegion(SequenceI target, SequenceI query,
562           int queryPos)
563   {
564     SequenceI targetDs = target.getDatasetSequence() == null ? target
565             : target.getDatasetSequence();
566     SequenceI queryDs = query.getDatasetSequence() == null ? query
567             : query.getDatasetSequence();
568     if (targetDs == null || queryDs == null /*|| dnaToProt == null*/)
569     {
570       return null;
571     }
572     for (SequenceToSequenceMapping ssm : mappings)
573     {
574       /*
575        * try mapping from target to query
576        */
577       if (ssm.fromSeq == targetDs && ssm.mapping.to == queryDs)
578       {
579         int[] codon = ssm.mapping.map.locateInFrom(queryPos, queryPos);
580         if (codon != null)
581         {
582           return codon;
583         }
584       }
585       /*
586        * else try mapping from query to target
587        */
588       else if (ssm.fromSeq == queryDs && ssm.mapping.to == targetDs)
589       {
590         int[] codon = ssm.mapping.map.locateInTo(queryPos, queryPos);
591         if (codon != null)
592         {
593           return codon;
594         }
595       }
596     }
597     return null;
598   }
599
600   /**
601    * Returns the mapped DNA codons for the given position in a protein sequence,
602    * or null if no mapping is found. Returns a list of (e.g.) ['g', 'c', 't']
603    * codons. There may be more than one codon mapped to the protein if (for
604    * example), there are mappings to cDNA variants.
605    * 
606    * @param protein
607    *          the peptide dataset sequence
608    * @param aaPos
609    *          residue position (base 1) in the peptide sequence
610    * @return
611    */
612   public List<char[]> getMappedCodons(SequenceI protein, int aaPos)
613   {
614     MapList ml = null;
615     SequenceI dnaSeq = null;
616     List<char[]> result = new ArrayList<>();
617
618     for (SequenceToSequenceMapping ssm : mappings)
619     {
620       if (ssm.mapping.to == protein
621               && ssm.mapping.getMap().getFromRatio() == 3)
622       {
623         ml = ssm.mapping.map;
624         dnaSeq = ssm.fromSeq;
625
626         int[] codonPos = ml.locateInFrom(aaPos, aaPos);
627         if (codonPos == null)
628         {
629           return null;
630         }
631
632         /*
633          * Read off the mapped nucleotides (converting to position base 0)
634          */
635         codonPos = MappingUtils.flattenRanges(codonPos);
636         int start = dnaSeq.getStart();
637         char c1 = dnaSeq.getCharAt(codonPos[0] - start);
638         char c2 = dnaSeq.getCharAt(codonPos[1] - start);
639         char c3 = dnaSeq.getCharAt(codonPos[2] - start);
640         result.add(new char[] { c1, c2, c3 });
641       }
642     }
643     return result.isEmpty() ? null : result;
644   }
645
646   /**
647    * Returns any mappings found which are from the given sequence, and to
648    * distinct sequences.
649    * 
650    * @param seq
651    * @return
652    */
653   public List<Mapping> getMappingsFromSequence(SequenceI seq)
654   {
655     List<Mapping> result = new ArrayList<>();
656     List<SequenceI> related = new ArrayList<>();
657     SequenceI seqDs = seq.getDatasetSequence();
658     seqDs = seqDs != null ? seqDs : seq;
659
660     for (SequenceToSequenceMapping ssm : mappings)
661     {
662       final Mapping mapping = ssm.mapping;
663       if (ssm.fromSeq == seqDs)
664       {
665         if (!related.contains(mapping.to))
666         {
667           result.add(mapping);
668           related.add(mapping.to);
669         }
670       }
671     }
672     return result;
673   }
674
675   /**
676    * Test whether the given sequence is substitutable for one or more dummy
677    * sequences in this mapping
678    * 
679    * @param map
680    * @param seq
681    * @return
682    */
683   public boolean isRealisableWith(SequenceI seq)
684   {
685     return realiseWith(seq, false) > 0;
686   }
687
688   /**
689    * Replace any matchable mapped dummy sequences with the given real one.
690    * Returns the count of sequence mappings instantiated.
691    * 
692    * @param seq
693    * @return
694    */
695   public int realiseWith(SequenceI seq)
696   {
697     return realiseWith(seq, true);
698   }
699
700   /**
701    * Returns the number of mapped dummy sequences that could be replaced with
702    * the given real sequence.
703    * 
704    * @param seq
705    *          a dataset sequence
706    * @param doUpdate
707    *          if true, performs replacements, else only counts
708    * @return
709    */
710   protected int realiseWith(SequenceI seq, boolean doUpdate)
711   {
712     SequenceI ds = seq.getDatasetSequence() != null
713             ? seq.getDatasetSequence()
714             : seq;
715     int count = 0;
716
717     /*
718      * check for replaceable DNA ('map from') sequences
719      */
720     for (SequenceToSequenceMapping ssm : mappings)
721     {
722       SequenceI dna = ssm.fromSeq;
723       if (dna instanceof SequenceDummy
724               && dna.getName().equals(ds.getName()))
725       {
726         Mapping mapping = ssm.mapping;
727         int mapStart = mapping.getMap().getFromLowest();
728         int mapEnd = mapping.getMap().getFromHighest();
729         boolean mappable = couldRealiseSequence(dna, ds, mapStart, mapEnd);
730         if (mappable)
731         {
732           count++;
733           if (doUpdate)
734           {
735             // TODO: new method ? ds.realise(dna);
736             // might want to copy database refs as well
737             ds.setSequenceFeatures(dna.getSequenceFeatures());
738             // dnaSeqs[i] = ds;
739             ssm.fromSeq = ds;
740             System.out.println("Realised mapped sequence " + ds.getName());
741           }
742         }
743       }
744
745       /*
746        * check for replaceable protein ('map to') sequences
747        */
748       Mapping mapping = ssm.mapping;
749       SequenceI prot = mapping.getTo();
750       int mapStart = mapping.getMap().getToLowest();
751       int mapEnd = mapping.getMap().getToHighest();
752       boolean mappable = couldRealiseSequence(prot, ds, mapStart, mapEnd);
753       if (mappable)
754       {
755         count++;
756         if (doUpdate)
757         {
758           // TODO: new method ? ds.realise(dna);
759           // might want to copy database refs as well
760           ds.setSequenceFeatures(dna.getSequenceFeatures());
761           ssm.mapping.setTo(ds);
762         }
763       }
764     }
765     return count;
766   }
767
768   /**
769    * Helper method to test whether a 'real' sequence could replace a 'dummy'
770    * sequence in the map. The criteria are that they have the same name, and
771    * that the mapped region overlaps the candidate sequence.
772    * 
773    * @param existing
774    * @param replacement
775    * @param mapStart
776    * @param mapEnd
777    * @return
778    */
779   protected static boolean couldRealiseSequence(SequenceI existing,
780           SequenceI replacement, int mapStart, int mapEnd)
781   {
782     if (existing instanceof SequenceDummy
783             && !(replacement instanceof SequenceDummy)
784             && existing.getName().equals(replacement.getName()))
785     {
786       int start = replacement.getStart();
787       int end = replacement.getEnd();
788       boolean mappingOverlapsSequence = (mapStart >= start
789               && mapStart <= end) || (mapEnd >= start && mapEnd <= end);
790       if (mappingOverlapsSequence)
791       {
792         return true;
793       }
794     }
795     return false;
796   }
797
798   /**
799    * Change any mapping to the given sequence to be to its dataset sequence
800    * instead. For use when mappings are created before their referenced
801    * sequences are instantiated, for example when parsing GFF data.
802    * 
803    * @param seq
804    */
805   public void updateToDataset(SequenceI seq)
806   {
807     if (seq == null || seq.getDatasetSequence() == null)
808     {
809       return;
810     }
811     SequenceI ds = seq.getDatasetSequence();
812
813     for (SequenceToSequenceMapping ssm : mappings)
814     /*
815      * 'from' sequences
816      */
817     {
818       if (ssm.fromSeq == seq)
819       {
820         ssm.fromSeq = ds;
821       }
822
823       /*
824        * 'to' sequences
825        */
826       if (ssm.mapping.to == seq)
827       {
828         ssm.mapping.to = ds;
829       }
830     }
831   }
832
833   /**
834    * Answers true if this object contains no mappings
835    * 
836    * @return
837    */
838   public boolean isEmpty()
839   {
840     return mappings.isEmpty();
841   }
842
843   /**
844    * Method for debug / inspection purposes only, may change in future
845    */
846   @Override
847   public String toString()
848   {
849     return mappings == null ? "null" : mappings.toString();
850   }
851
852   /**
853    * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or
854    * null if none found
855    * 
856    * @param fromSeq
857    *          aligned or dataset sequence
858    * @param toSeq
859    *          aligned or dataset sequence
860    * @return
861    */
862   public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
863   {
864     SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
865             : fromSeq.getDatasetSequence();
866     SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq
867             : toSeq.getDatasetSequence();
868
869     for (SequenceToSequenceMapping mapping : mappings)
870     {
871       SequenceI from = mapping.fromSeq;
872       SequenceI to = mapping.mapping.to;
873       if ((from == dssFrom && to == dssTo)
874               || (from == dssTo && to == dssFrom))
875       {
876         return mapping.mapping;
877       }
878     }
879     return null;
880   }
881
882   /**
883    * Returns a hashcode derived from the list of sequence mappings
884    * 
885    * @see SequenceToSequenceMapping#hashCode()
886    * @see AbstractList#hashCode()
887    */
888   @Override
889   public int hashCode()
890   {
891     return this.mappings.hashCode();
892   }
893
894   /**
895    * Two AlignedCodonFrame objects are equal if they hold the same ordered list
896    * of mappings
897    * 
898    * @see SequenceToSequenceMapping#equals
899    */
900   @Override
901   public boolean equals(Object obj)
902   {
903     if (!(obj instanceof AlignedCodonFrame))
904     {
905       return false;
906     }
907     return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
908   }
909
910   public List<SequenceToSequenceMapping> getMappings()
911   {
912     return mappings;
913   }
914
915   /**
916    * Returns the first mapping found which is between the two given sequences,
917    * and covers the full extent of both.
918    * 
919    * @param seq1
920    * @param seq2
921    * @return
922    */
923   public SequenceToSequenceMapping getCoveringMapping(SequenceI seq1,
924           SequenceI seq2)
925   {
926     for (SequenceToSequenceMapping mapping : mappings)
927     {
928       if (mapping.covers(seq2) && mapping.covers(seq1))
929       {
930         return mapping;
931       }
932     }
933     return null;
934   }
935 }