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