JAL-3806 (2.11.2 version) more lax allowance (3 positions) for stop codon
[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 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 3 to mapped length to allow for a mapped stop codon
175         if (length + 3 >= (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    * 
402    * @param sequenceRef
403    * @return null or corresponding aaSeq entry for dnaSeq entry
404    */
405   public SequenceI getDnaForAaSeq(SequenceI aaSeqRef)
406   {
407     SequenceI aads = aaSeqRef.getDatasetSequence();
408     for (SequenceToSequenceMapping ssm : mappings)
409     {
410       if (ssm.mapping.to == aaSeqRef || ssm.mapping.to == aads)
411       {
412         return ssm.fromSeq;
413       }
414     }
415     return null;
416   }
417
418   /**
419    * test to see if codon frame involves seq in any way
420    * 
421    * @param seq
422    *          a nucleotide or protein sequence
423    * @return true if a mapping exists to or from this sequence to any translated
424    *         sequence
425    */
426   public boolean involvesSequence(SequenceI seq)
427   {
428     return getAaForDnaSeq(seq) != null || getDnaForAaSeq(seq) != null;
429   }
430
431   /**
432    * Add search results for regions in other sequences that translate or are
433    * translated from a particular position in seq
434    * 
435    * @param seq
436    * @param index
437    *          position in seq
438    * @param results
439    *          where highlighted regions go
440    */
441   public void markMappedRegion(SequenceI seq, int index,
442           SearchResultsI results)
443   {
444     int[] codon;
445     SequenceI ds = seq.getDatasetSequence();
446     for (SequenceToSequenceMapping ssm : mappings)
447     {
448       if (ssm.fromSeq == seq || ssm.fromSeq == ds)
449       {
450         codon = ssm.mapping.map.locateInTo(index, index);
451         if (codon != null)
452         {
453           for (int i = 0; i < codon.length; i += 2)
454           {
455             results.addResult(ssm.mapping.to, codon[i], codon[i + 1]);
456           }
457         }
458       }
459       else if (ssm.mapping.to == seq || ssm.mapping.to == ds)
460       {
461         {
462           codon = ssm.mapping.map.locateInFrom(index, index);
463           if (codon != null)
464           {
465             for (int i = 0; i < codon.length; i += 2)
466             {
467               results.addResult(ssm.fromSeq, codon[i], codon[i + 1]);
468             }
469           }
470         }
471       }
472     }
473   }
474
475   /**
476    * Returns the DNA codon positions (base 1) for the given position (base 1) in
477    * a mapped protein sequence, or null if no mapping is found.
478    * 
479    * Intended for use in aligning cDNA to match aligned protein. Only the first
480    * mapping found is returned, so not suitable for use if multiple protein
481    * sequences are mapped to the same cDNA (but aligning cDNA as protein is
482    * ill-defined for this case anyway).
483    * 
484    * @param seq
485    *          the DNA dataset sequence
486    * @param aaPos
487    *          residue position (base 1) in a protein sequence
488    * @return
489    */
490   public int[] getDnaPosition(SequenceI seq, int aaPos)
491   {
492     /*
493      * Adapted from markMappedRegion().
494      */
495     MapList ml = null;
496     int i = 0;
497     for (SequenceToSequenceMapping ssm : mappings)
498     {
499       if (ssm.fromSeq == seq)
500       {
501         ml = getdnaToProt()[i];
502         break;
503       }
504       i++;
505     }
506     return ml == null ? null : ml.locateInFrom(aaPos, aaPos);
507   }
508
509   /**
510    * Convenience method to return the first aligned sequence in the given
511    * alignment whose dataset has a mapping with the given (aligned or dataset)
512    * sequence.
513    * 
514    * @param seq
515    * 
516    * @param al
517    * @return
518    */
519   public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al)
520   {
521     /*
522      * Search mapped protein ('to') sequences first.
523      */
524     for (SequenceToSequenceMapping ssm : mappings)
525     {
526       if (ssm.fromSeq == seq || ssm.fromSeq == seq.getDatasetSequence())
527       {
528         for (SequenceI sourceAligned : al.getSequences())
529         {
530           if (ssm.mapping.to == sourceAligned.getDatasetSequence()
531                   || ssm.mapping.to == sourceAligned)
532           {
533             return sourceAligned;
534           }
535         }
536       }
537     }
538
539     /*
540      * Then try mapped dna sequences.
541      */
542     for (SequenceToSequenceMapping ssm : mappings)
543     {
544       if (ssm.mapping.to == seq
545               || ssm.mapping.to == seq.getDatasetSequence())
546       {
547         for (SequenceI sourceAligned : al.getSequences())
548         {
549           if (ssm.fromSeq == sourceAligned.getDatasetSequence())
550           {
551             return sourceAligned;
552           }
553         }
554       }
555     }
556
557     return null;
558   }
559
560   /**
561    * Returns the region in the target sequence's dataset that is mapped to the
562    * given position (base 1) in the query sequence's dataset. The region is a
563    * set of start/end position pairs.
564    * 
565    * @param target
566    * @param query
567    * @param queryPos
568    * @return
569    */
570   public int[] getMappedRegion(SequenceI target, SequenceI query,
571           int queryPos)
572   {
573     SequenceI targetDs = target.getDatasetSequence() == null ? target
574             : target.getDatasetSequence();
575     SequenceI queryDs = query.getDatasetSequence() == null ? query
576             : query.getDatasetSequence();
577     if (targetDs == null || queryDs == null /*|| dnaToProt == null*/)
578     {
579       return null;
580     }
581     for (SequenceToSequenceMapping ssm : mappings)
582     {
583       /*
584        * try mapping from target to query
585        */
586       if (ssm.fromSeq == targetDs && ssm.mapping.to == queryDs)
587       {
588         int[] codon = ssm.mapping.map.locateInFrom(queryPos, queryPos);
589         if (codon != null)
590         {
591           return codon;
592         }
593       }
594       /*
595        * else try mapping from query to target
596        */
597       else if (ssm.fromSeq == queryDs && ssm.mapping.to == targetDs)
598       {
599         int[] codon = ssm.mapping.map.locateInTo(queryPos, queryPos);
600         if (codon != null)
601         {
602           return codon;
603         }
604       }
605     }
606     return null;
607   }
608
609   /**
610    * Returns the mapped DNA codons for the given position in a protein sequence,
611    * or null if no mapping is found. Returns a list of (e.g.) ['g', 'c', 't']
612    * codons. There may be more than one codon mapped to the protein if (for
613    * example), there are mappings to cDNA variants.
614    * 
615    * @param protein
616    *          the peptide dataset sequence
617    * @param aaPos
618    *          residue position (base 1) in the peptide sequence
619    * @return
620    */
621   public List<char[]> getMappedCodons(SequenceI protein, int aaPos)
622   {
623     MapList ml = null;
624     SequenceI dnaSeq = null;
625     List<char[]> result = new ArrayList<>();
626
627     for (SequenceToSequenceMapping ssm : mappings)
628     {
629       if (ssm.mapping.to == protein
630               && ssm.mapping.getMap().getFromRatio() == 3)
631       {
632         ml = ssm.mapping.map;
633         dnaSeq = ssm.fromSeq;
634
635         int[] codonPos = ml.locateInFrom(aaPos, aaPos);
636         if (codonPos == null)
637         {
638           return null;
639         }
640
641         /*
642          * Read off the mapped nucleotides (converting to position base 0)
643          */
644         codonPos = MappingUtils.flattenRanges(codonPos);
645         int start = dnaSeq.getStart();
646         char c1 = dnaSeq.getCharAt(codonPos[0] - start);
647         char c2 = dnaSeq.getCharAt(codonPos[1] - start);
648         char c3 = dnaSeq.getCharAt(codonPos[2] - start);
649         result.add(new char[] { c1, c2, c3 });
650       }
651     }
652     return result.isEmpty() ? null : result;
653   }
654
655   /**
656    * Returns any mappings found which are from the given sequence, and to
657    * distinct sequences.
658    * 
659    * @param seq
660    * @return
661    */
662   public List<Mapping> getMappingsFromSequence(SequenceI seq)
663   {
664     List<Mapping> result = new ArrayList<>();
665     List<SequenceI> related = new ArrayList<>();
666     SequenceI seqDs = seq.getDatasetSequence();
667     seqDs = seqDs != null ? seqDs : seq;
668
669     for (SequenceToSequenceMapping ssm : mappings)
670     {
671       final Mapping mapping = ssm.mapping;
672       if (ssm.fromSeq == seqDs)
673       {
674         if (!related.contains(mapping.to))
675         {
676           result.add(mapping);
677           related.add(mapping.to);
678         }
679       }
680     }
681     return result;
682   }
683
684   /**
685    * Test whether the given sequence is substitutable for one or more dummy
686    * sequences in this mapping
687    * 
688    * @param map
689    * @param seq
690    * @return
691    */
692   public boolean isRealisableWith(SequenceI seq)
693   {
694     return realiseWith(seq, false) > 0;
695   }
696
697   /**
698    * Replace any matchable mapped dummy sequences with the given real one.
699    * Returns the count of sequence mappings instantiated.
700    * 
701    * @param seq
702    * @return
703    */
704   public int realiseWith(SequenceI seq)
705   {
706     return realiseWith(seq, true);
707   }
708
709   /**
710    * Returns the number of mapped dummy sequences that could be replaced with
711    * the given real sequence.
712    * 
713    * @param seq
714    *          a dataset sequence
715    * @param doUpdate
716    *          if true, performs replacements, else only counts
717    * @return
718    */
719   protected int realiseWith(SequenceI seq, boolean doUpdate)
720   {
721     SequenceI ds = seq.getDatasetSequence() != null
722             ? seq.getDatasetSequence()
723             : seq;
724     int count = 0;
725
726     /*
727      * check for replaceable DNA ('map from') sequences
728      */
729     for (SequenceToSequenceMapping ssm : mappings)
730     {
731       SequenceI dna = ssm.fromSeq;
732       if (dna instanceof SequenceDummy
733               && dna.getName().equals(ds.getName()))
734       {
735         Mapping mapping = ssm.mapping;
736         int mapStart = mapping.getMap().getFromLowest();
737         int mapEnd = mapping.getMap().getFromHighest();
738         boolean mappable = couldRealiseSequence(dna, ds, mapStart, mapEnd);
739         if (mappable)
740         {
741           count++;
742           if (doUpdate)
743           {
744             // TODO: new method ? ds.realise(dna);
745             // might want to copy database refs as well
746             ds.setSequenceFeatures(dna.getSequenceFeatures());
747             // dnaSeqs[i] = ds;
748             ssm.fromSeq = ds;
749             System.out.println("Realised mapped sequence " + ds.getName());
750           }
751         }
752       }
753
754       /*
755        * check for replaceable protein ('map to') sequences
756        */
757       Mapping mapping = ssm.mapping;
758       SequenceI prot = mapping.getTo();
759       int mapStart = mapping.getMap().getToLowest();
760       int mapEnd = mapping.getMap().getToHighest();
761       boolean mappable = couldRealiseSequence(prot, ds, mapStart, mapEnd);
762       if (mappable)
763       {
764         count++;
765         if (doUpdate)
766         {
767           // TODO: new method ? ds.realise(dna);
768           // might want to copy database refs as well
769           ds.setSequenceFeatures(dna.getSequenceFeatures());
770           ssm.mapping.setTo(ds);
771         }
772       }
773     }
774     return count;
775   }
776
777   /**
778    * Helper method to test whether a 'real' sequence could replace a 'dummy'
779    * sequence in the map. The criteria are that they have the same name, and
780    * that the mapped region overlaps the candidate sequence.
781    * 
782    * @param existing
783    * @param replacement
784    * @param mapStart
785    * @param mapEnd
786    * @return
787    */
788   protected static boolean couldRealiseSequence(SequenceI existing,
789           SequenceI replacement, int mapStart, int mapEnd)
790   {
791     if (existing instanceof SequenceDummy
792             && !(replacement instanceof SequenceDummy)
793             && existing.getName().equals(replacement.getName()))
794     {
795       int start = replacement.getStart();
796       int end = replacement.getEnd();
797       boolean mappingOverlapsSequence = (mapStart >= start
798               && mapStart <= end) || (mapEnd >= start && mapEnd <= end);
799       if (mappingOverlapsSequence)
800       {
801         return true;
802       }
803     }
804     return false;
805   }
806
807   /**
808    * Change any mapping to the given sequence to be to its dataset sequence
809    * instead. For use when mappings are created before their referenced
810    * sequences are instantiated, for example when parsing GFF data.
811    * 
812    * @param seq
813    */
814   public void updateToDataset(SequenceI seq)
815   {
816     if (seq == null || seq.getDatasetSequence() == null)
817     {
818       return;
819     }
820     SequenceI ds = seq.getDatasetSequence();
821
822     for (SequenceToSequenceMapping ssm : mappings)
823     /*
824      * 'from' sequences
825      */
826     {
827       if (ssm.fromSeq == seq)
828       {
829         ssm.fromSeq = ds;
830       }
831
832       /*
833        * 'to' sequences
834        */
835       if (ssm.mapping.to == seq)
836       {
837         ssm.mapping.to = ds;
838       }
839     }
840   }
841
842   /**
843    * Answers true if this object contains no mappings
844    * 
845    * @return
846    */
847   public boolean isEmpty()
848   {
849     return mappings.isEmpty();
850   }
851
852   /**
853    * Method for debug / inspection purposes only, may change in future
854    */
855   @Override
856   public String toString()
857   {
858     return mappings == null ? "null" : mappings.toString();
859   }
860
861   /**
862    * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or
863    * null if none found
864    * 
865    * @param fromSeq
866    *          aligned or dataset sequence
867    * @param toSeq
868    *          aligned or dataset sequence
869    * @return
870    */
871   public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
872   {
873     SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
874             : fromSeq.getDatasetSequence();
875     SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq
876             : toSeq.getDatasetSequence();
877
878     for (SequenceToSequenceMapping mapping : mappings)
879     {
880       SequenceI from = mapping.fromSeq;
881       SequenceI to = mapping.mapping.to;
882       if ((from == dssFrom && to == dssTo)
883               || (from == dssTo && to == dssFrom))
884       {
885         return mapping.mapping;
886       }
887     }
888     return null;
889   }
890
891   /**
892    * Returns a hashcode derived from the list of sequence mappings
893    * 
894    * @see SequenceToSequenceMapping#hashCode()
895    * @see AbstractList#hashCode()
896    */
897   @Override
898   public int hashCode()
899   {
900     return this.mappings.hashCode();
901   }
902
903   /**
904    * Two AlignedCodonFrame objects are equal if they hold the same ordered list
905    * of mappings
906    * 
907    * @see SequenceToSequenceMapping#
908    */
909   @Override
910   public boolean equals(Object obj)
911   {
912     if (!(obj instanceof AlignedCodonFrame))
913     {
914       return false;
915     }
916     return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
917   }
918
919   public List<SequenceToSequenceMapping> getMappings()
920   {
921     return mappings;
922   }
923 }