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