JAL-3187 save and restore flags for show complement features
[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   private List<SequenceToSequenceMapping> mappings;
113
114   /**
115    * Constructor
116    */
117   public AlignedCodonFrame()
118   {
119     mappings = new ArrayList<>();
120   }
121
122   /**
123    * Adds a mapping between the dataset sequences for the associated dna and
124    * protein sequence objects
125    * 
126    * @param dnaseq
127    * @param aaseq
128    * @param map
129    */
130   public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map)
131   {
132     addMap(dnaseq, aaseq, map, null);
133   }
134
135   /**
136    * Adds a mapping between the dataset sequences for the associated dna and
137    * protein sequence objects
138    * 
139    * @param dnaseq
140    * @param aaseq
141    * @param map
142    * @param mapFromId
143    */
144   public void addMap(SequenceI dnaseq, SequenceI aaseq, MapList map,
145           String mapFromId)
146   {
147     // JBPNote DEBUG! THIS !
148     // dnaseq.transferAnnotation(aaseq, mp);
149     // aaseq.transferAnnotation(dnaseq, new Mapping(map.getInverse()));
150
151     SequenceI fromSeq = (dnaseq.getDatasetSequence() == null) ? dnaseq
152             : dnaseq.getDatasetSequence();
153     SequenceI toSeq = (aaseq.getDatasetSequence() == null) ? aaseq
154             : aaseq.getDatasetSequence();
155
156     /*
157      * if we already hold a mapping between these sequences, just add to it 
158      * note that 'adding' a duplicate map does nothing; this protects against
159      * creating duplicate mappings in AlignedCodonFrame
160      */
161     for (SequenceToSequenceMapping ssm : mappings)
162     {
163       if (ssm.fromSeq == fromSeq && ssm.mapping.to == toSeq)
164       {
165         ssm.mapping.map.addMapList(map);
166         return;
167       }
168     }
169
170     /*
171      * otherwise, add a new sequence mapping
172      */
173     Mapping mp = new Mapping(toSeq, map);
174     mp.setMappedFromId(mapFromId);
175     mappings.add(new SequenceToSequenceMapping(fromSeq, mp));
176   }
177
178   public SequenceI[] getdnaSeqs()
179   {
180     // TODO return a list instead?
181     // return dnaSeqs;
182     List<SequenceI> seqs = new ArrayList<>();
183     for (SequenceToSequenceMapping ssm : mappings)
184     {
185       seqs.add(ssm.fromSeq);
186     }
187     return seqs.toArray(new SequenceI[seqs.size()]);
188   }
189
190   public SequenceI[] getAaSeqs()
191   {
192     // TODO not used - remove?
193     List<SequenceI> seqs = new ArrayList<>();
194     for (SequenceToSequenceMapping ssm : mappings)
195     {
196       seqs.add(ssm.mapping.to);
197     }
198     return seqs.toArray(new SequenceI[seqs.size()]);
199   }
200
201   public MapList[] getdnaToProt()
202   {
203     List<MapList> maps = new ArrayList<>();
204     for (SequenceToSequenceMapping ssm : mappings)
205     {
206       maps.add(ssm.mapping.map);
207     }
208     return maps.toArray(new MapList[maps.size()]);
209   }
210
211   public Mapping[] getProtMappings()
212   {
213     List<Mapping> maps = new ArrayList<>();
214     for (SequenceToSequenceMapping ssm : mappings)
215     {
216       maps.add(ssm.mapping);
217     }
218     return maps.toArray(new Mapping[maps.size()]);
219   }
220
221   /**
222    * Returns the first mapping found which is to or from the given sequence, or
223    * null.
224    * 
225    * @param seq
226    * @return
227    */
228   public Mapping getMappingForSequence(SequenceI seq, boolean cdsOnly)
229   {
230     SequenceI seqDs = seq.getDatasetSequence();
231     seqDs = seqDs != null ? seqDs : seq;
232
233     for (SequenceToSequenceMapping ssm : mappings)
234     {
235       if (ssm.fromSeq == seqDs || ssm.mapping.to == seqDs)
236       {
237         if (!cdsOnly || ssm.fromSeq.getName().startsWith("CDS")
238                 || ssm.mapping.to.getName().startsWith("CDS"))
239         {
240           return ssm.mapping;
241         }
242       }
243     }
244     return null;
245   }
246
247   /**
248    * Return the corresponding aligned or dataset aa sequence for given dna
249    * sequence, null if not found.
250    * 
251    * @param sequenceRef
252    * @return
253    */
254   public SequenceI getAaForDnaSeq(SequenceI dnaSeqRef)
255   {
256     SequenceI dnads = dnaSeqRef.getDatasetSequence();
257     for (SequenceToSequenceMapping ssm : mappings)
258     {
259       if (ssm.fromSeq == dnaSeqRef || ssm.fromSeq == dnads)
260       {
261         return ssm.mapping.to;
262       }
263     }
264     return null;
265   }
266
267   /**
268    * 
269    * @param sequenceRef
270    * @return null or corresponding aaSeq entry for dnaSeq entry
271    */
272   public SequenceI getDnaForAaSeq(SequenceI aaSeqRef)
273   {
274     SequenceI aads = aaSeqRef.getDatasetSequence();
275     for (SequenceToSequenceMapping ssm : mappings)
276     {
277       if (ssm.mapping.to == aaSeqRef || ssm.mapping.to == aads)
278       {
279         return ssm.fromSeq;
280       }
281     }
282     return null;
283   }
284
285   /**
286    * test to see if codon frame involves seq in any way
287    * 
288    * @param seq
289    *          a nucleotide or protein sequence
290    * @return true if a mapping exists to or from this sequence to any translated
291    *         sequence
292    */
293   public boolean involvesSequence(SequenceI seq)
294   {
295     return getAaForDnaSeq(seq) != null || getDnaForAaSeq(seq) != null;
296   }
297
298   /**
299    * Add search results for regions in other sequences that translate or are
300    * translated from a particular position in seq
301    * 
302    * @param seq
303    * @param index
304    *          position in seq
305    * @param results
306    *          where highlighted regions go
307    */
308   public void markMappedRegion(SequenceI seq, int index,
309           SearchResultsI results)
310   {
311     int[] codon;
312     SequenceI ds = seq.getDatasetSequence();
313     for (SequenceToSequenceMapping ssm : mappings)
314     {
315       if (ssm.fromSeq == seq || ssm.fromSeq == ds)
316       {
317         codon = ssm.mapping.map.locateInTo(index, index);
318         if (codon != null)
319         {
320           for (int i = 0; i < codon.length; i += 2)
321           {
322             results.addResult(ssm.mapping.to, codon[i], codon[i + 1]);
323           }
324         }
325       }
326       else if (ssm.mapping.to == seq || ssm.mapping.to == ds)
327       {
328         {
329           codon = ssm.mapping.map.locateInFrom(index, index);
330           if (codon != null)
331           {
332             for (int i = 0; i < codon.length; i += 2)
333             {
334               results.addResult(ssm.fromSeq, codon[i], codon[i + 1]);
335             }
336           }
337         }
338       }
339     }
340   }
341
342   /**
343    * Returns the DNA codon positions (base 1) for the given position (base 1) in
344    * a mapped protein sequence, or null if no mapping is found.
345    * 
346    * Intended for use in aligning cDNA to match aligned protein. Only the first
347    * mapping found is returned, so not suitable for use if multiple protein
348    * sequences are mapped to the same cDNA (but aligning cDNA as protein is
349    * ill-defined for this case anyway).
350    * 
351    * @param seq
352    *          the DNA dataset sequence
353    * @param aaPos
354    *          residue position (base 1) in a protein sequence
355    * @return
356    */
357   public int[] getDnaPosition(SequenceI seq, int aaPos)
358   {
359     /*
360      * Adapted from markMappedRegion().
361      */
362     MapList ml = null;
363     int i = 0;
364     for (SequenceToSequenceMapping ssm : mappings)
365     {
366       if (ssm.fromSeq == seq)
367       {
368         ml = getdnaToProt()[i];
369         break;
370       }
371       i++;
372     }
373     return ml == null ? null : ml.locateInFrom(aaPos, aaPos);
374   }
375
376   /**
377    * Convenience method to return the first aligned sequence in the given
378    * alignment whose dataset has a mapping with the given (aligned or dataset)
379    * sequence.
380    * 
381    * @param seq
382    * 
383    * @param al
384    * @return
385    */
386   public SequenceI findAlignedSequence(SequenceI seq, AlignmentI al)
387   {
388     /*
389      * Search mapped protein ('to') sequences first.
390      */
391     for (SequenceToSequenceMapping ssm : mappings)
392     {
393       if (ssm.fromSeq == seq || ssm.fromSeq == seq.getDatasetSequence())
394       {
395         for (SequenceI sourceAligned : al.getSequences())
396         {
397           if (ssm.mapping.to == sourceAligned.getDatasetSequence()
398                   || ssm.mapping.to == sourceAligned)
399           {
400             return sourceAligned;
401           }
402         }
403       }
404     }
405
406     /*
407      * Then try mapped dna sequences.
408      */
409     for (SequenceToSequenceMapping ssm : mappings)
410     {
411       if (ssm.mapping.to == seq
412               || ssm.mapping.to == seq.getDatasetSequence())
413       {
414         for (SequenceI sourceAligned : al.getSequences())
415         {
416           if (ssm.fromSeq == sourceAligned.getDatasetSequence())
417           {
418             return sourceAligned;
419           }
420         }
421       }
422     }
423
424     return null;
425   }
426
427   /**
428    * Returns the region in the target sequence's dataset that is mapped to the
429    * given position (base 1) in the query sequence's dataset. The region is a
430    * set of start/end position pairs.
431    * 
432    * @param target
433    * @param query
434    * @param queryPos
435    * @return
436    */
437   public int[] getMappedRegion(SequenceI target, SequenceI query,
438           int queryPos)
439   {
440     SequenceI targetDs = target.getDatasetSequence() == null ? target
441             : target.getDatasetSequence();
442     SequenceI queryDs = query.getDatasetSequence() == null ? query
443             : query.getDatasetSequence();
444     if (targetDs == null || queryDs == null /*|| dnaToProt == null*/)
445     {
446       return null;
447     }
448     for (SequenceToSequenceMapping ssm : mappings)
449     {
450       /*
451        * try mapping from target to query
452        */
453       if (ssm.fromSeq == targetDs && ssm.mapping.to == queryDs)
454       {
455         int[] codon = ssm.mapping.map.locateInFrom(queryPos, queryPos);
456         if (codon != null)
457         {
458           return codon;
459         }
460       }
461       /*
462        * else try mapping from query to target
463        */
464       else if (ssm.fromSeq == queryDs && ssm.mapping.to == targetDs)
465       {
466         int[] codon = ssm.mapping.map.locateInTo(queryPos, queryPos);
467         if (codon != null)
468         {
469           return codon;
470         }
471       }
472     }
473     return null;
474   }
475
476   /**
477    * Returns the mapped DNA codons for the given position in a protein sequence,
478    * or null if no mapping is found. Returns a list of (e.g.) ['g', 'c', 't']
479    * codons. There may be more than one codon mapped to the protein if (for
480    * example), there are mappings to cDNA variants.
481    * 
482    * @param protein
483    *          the peptide dataset sequence
484    * @param aaPos
485    *          residue position (base 1) in the peptide sequence
486    * @return
487    */
488   public List<char[]> getMappedCodons(SequenceI protein, int aaPos)
489   {
490     MapList ml = null;
491     SequenceI dnaSeq = null;
492     List<char[]> result = new ArrayList<>();
493
494     for (SequenceToSequenceMapping ssm : mappings)
495     {
496       if (ssm.mapping.to == protein
497               && ssm.mapping.getMap().getFromRatio() == 3)
498       {
499         ml = ssm.mapping.map;
500         dnaSeq = ssm.fromSeq;
501
502         int[] codonPos = ml.locateInFrom(aaPos, aaPos);
503         if (codonPos == null)
504         {
505           return null;
506         }
507
508         /*
509          * Read off the mapped nucleotides (converting to position base 0)
510          */
511         codonPos = MappingUtils.flattenRanges(codonPos);
512         int start = dnaSeq.getStart();
513         char c1 = dnaSeq.getCharAt(codonPos[0] - start);
514         char c2 = dnaSeq.getCharAt(codonPos[1] - start);
515         char c3 = dnaSeq.getCharAt(codonPos[2] - start);
516         result.add(new char[] { c1, c2, c3 });
517       }
518     }
519     return result.isEmpty() ? null : result;
520   }
521
522   /**
523    * Returns any mappings found which are from the given sequence, and to
524    * distinct sequences.
525    * 
526    * @param seq
527    * @return
528    */
529   public List<Mapping> getMappingsFromSequence(SequenceI seq)
530   {
531     List<Mapping> result = new ArrayList<>();
532     List<SequenceI> related = new ArrayList<>();
533     SequenceI seqDs = seq.getDatasetSequence();
534     seqDs = seqDs != null ? seqDs : seq;
535
536     for (SequenceToSequenceMapping ssm : mappings)
537     {
538       final Mapping mapping = ssm.mapping;
539       if (ssm.fromSeq == seqDs)
540       {
541         if (!related.contains(mapping.to))
542         {
543           result.add(mapping);
544           related.add(mapping.to);
545         }
546       }
547     }
548     return result;
549   }
550
551   /**
552    * Test whether the given sequence is substitutable for one or more dummy
553    * sequences in this mapping
554    * 
555    * @param map
556    * @param seq
557    * @return
558    */
559   public boolean isRealisableWith(SequenceI seq)
560   {
561     return realiseWith(seq, false) > 0;
562   }
563
564   /**
565    * Replace any matchable mapped dummy sequences with the given real one.
566    * Returns the count of sequence mappings instantiated.
567    * 
568    * @param seq
569    * @return
570    */
571   public int realiseWith(SequenceI seq)
572   {
573     return realiseWith(seq, true);
574   }
575
576   /**
577    * Returns the number of mapped dummy sequences that could be replaced with
578    * the given real sequence.
579    * 
580    * @param seq
581    *          a dataset sequence
582    * @param doUpdate
583    *          if true, performs replacements, else only counts
584    * @return
585    */
586   protected int realiseWith(SequenceI seq, boolean doUpdate)
587   {
588     SequenceI ds = seq.getDatasetSequence() != null
589             ? seq.getDatasetSequence()
590             : seq;
591     int count = 0;
592
593     /*
594      * check for replaceable DNA ('map from') sequences
595      */
596     for (SequenceToSequenceMapping ssm : mappings)
597     {
598       SequenceI dna = ssm.fromSeq;
599       if (dna instanceof SequenceDummy
600               && dna.getName().equals(ds.getName()))
601       {
602         Mapping mapping = ssm.mapping;
603         int mapStart = mapping.getMap().getFromLowest();
604         int mapEnd = mapping.getMap().getFromHighest();
605         boolean mappable = couldRealiseSequence(dna, ds, mapStart, mapEnd);
606         if (mappable)
607         {
608           count++;
609           if (doUpdate)
610           {
611             // TODO: new method ? ds.realise(dna);
612             // might want to copy database refs as well
613             ds.setSequenceFeatures(dna.getSequenceFeatures());
614             // dnaSeqs[i] = ds;
615             ssm.fromSeq = ds;
616             System.out.println("Realised mapped sequence " + ds.getName());
617           }
618         }
619       }
620
621       /*
622        * check for replaceable protein ('map to') sequences
623        */
624       Mapping mapping = ssm.mapping;
625       SequenceI prot = mapping.getTo();
626       int mapStart = mapping.getMap().getToLowest();
627       int mapEnd = mapping.getMap().getToHighest();
628       boolean mappable = couldRealiseSequence(prot, ds, mapStart, mapEnd);
629       if (mappable)
630       {
631         count++;
632         if (doUpdate)
633         {
634           // TODO: new method ? ds.realise(dna);
635           // might want to copy database refs as well
636           ds.setSequenceFeatures(dna.getSequenceFeatures());
637           ssm.mapping.setTo(ds);
638         }
639       }
640     }
641     return count;
642   }
643
644   /**
645    * Helper method to test whether a 'real' sequence could replace a 'dummy'
646    * sequence in the map. The criteria are that they have the same name, and
647    * that the mapped region overlaps the candidate sequence.
648    * 
649    * @param existing
650    * @param replacement
651    * @param mapStart
652    * @param mapEnd
653    * @return
654    */
655   protected static boolean couldRealiseSequence(SequenceI existing,
656           SequenceI replacement, int mapStart, int mapEnd)
657   {
658     if (existing instanceof SequenceDummy
659             && !(replacement instanceof SequenceDummy)
660             && existing.getName().equals(replacement.getName()))
661     {
662       int start = replacement.getStart();
663       int end = replacement.getEnd();
664       boolean mappingOverlapsSequence = (mapStart >= start
665               && mapStart <= end) || (mapEnd >= start && mapEnd <= end);
666       if (mappingOverlapsSequence)
667       {
668         return true;
669       }
670     }
671     return false;
672   }
673
674   /**
675    * Change any mapping to the given sequence to be to its dataset sequence
676    * instead. For use when mappings are created before their referenced
677    * sequences are instantiated, for example when parsing GFF data.
678    * 
679    * @param seq
680    */
681   public void updateToDataset(SequenceI seq)
682   {
683     if (seq == null || seq.getDatasetSequence() == null)
684     {
685       return;
686     }
687     SequenceI ds = seq.getDatasetSequence();
688
689     for (SequenceToSequenceMapping ssm : mappings)
690     /*
691      * 'from' sequences
692      */
693     {
694       if (ssm.fromSeq == seq)
695       {
696         ssm.fromSeq = ds;
697       }
698
699       /*
700        * 'to' sequences
701        */
702       if (ssm.mapping.to == seq)
703       {
704         ssm.mapping.to = ds;
705       }
706     }
707   }
708
709   /**
710    * Answers true if this object contains no mappings
711    * 
712    * @return
713    */
714   public boolean isEmpty()
715   {
716     return mappings.isEmpty();
717   }
718
719   /**
720    * Method for debug / inspection purposes only, may change in future
721    */
722   @Override
723   public String toString()
724   {
725     return mappings == null ? "null" : mappings.toString();
726   }
727
728   /**
729    * Returns the first mapping found that is between 'fromSeq' and 'toSeq', or
730    * null if none found
731    * 
732    * @param fromSeq
733    *          aligned or dataset sequence
734    * @param toSeq
735    *          aligned or dataset sequence
736    * @return
737    */
738   public Mapping getMappingBetween(SequenceI fromSeq, SequenceI toSeq)
739   {
740     SequenceI dssFrom = fromSeq.getDatasetSequence() == null ? fromSeq
741             : fromSeq.getDatasetSequence();
742     SequenceI dssTo = toSeq.getDatasetSequence() == null ? toSeq
743             : toSeq.getDatasetSequence();
744
745     for (SequenceToSequenceMapping mapping : mappings)
746     {
747       SequenceI from = mapping.fromSeq;
748       SequenceI to = mapping.mapping.to;
749       if ((from == dssFrom && to == dssTo)
750               || (from == dssTo && to == dssFrom))
751       {
752         return mapping.mapping;
753       }
754     }
755     return null;
756   }
757
758   /**
759    * Returns a hashcode derived from the list of sequence mappings
760    * 
761    * @see SequenceToSequenceMapping#hashCode()
762    * @see AbstractList#hashCode()
763    */
764   @Override
765   public int hashCode()
766   {
767     return this.mappings.hashCode();
768   }
769
770   /**
771    * Two AlignedCodonFrame objects are equal if they hold the same ordered list
772    * of mappings
773    * 
774    * @see SequenceToSequenceMapping#
775    */
776   @Override
777   public boolean equals(Object obj)
778   {
779     if (!(obj instanceof AlignedCodonFrame))
780     {
781       return false;
782     }
783     return this.mappings.equals(((AlignedCodonFrame) obj).mappings);
784   }
785
786   public List<SequenceToSequenceMapping> getMappings()
787   {
788     return mappings;
789   }
790 }