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