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