7116af9f1237dbaa45ca4cf008491158d19ce6ac
[jalview.git] / src / jalview / analysis / AlignmentUtils.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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.analysis;
22
23 import jalview.datamodel.AlignedCodonFrame;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.SequenceI;
27 import jalview.schemes.ResidueProperties;
28 import jalview.util.MapList;
29
30 import java.util.ArrayList;
31 import java.util.LinkedHashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35
36 /**
37  * grab bag of useful alignment manipulation operations Expect these to be
38  * refactored elsewhere at some point.
39  * 
40  * @author jimp
41  * 
42  */
43 public class AlignmentUtils
44 {
45
46   /**
47    * Represents the 3 possible results of trying to map one alignment to
48    * another.
49    */
50   public enum MappingResult
51   {
52     Mapped, NotMapped, AlreadyMapped
53   }
54
55   /**
56    * given an existing alignment, create a new alignment including all, or up to
57    * flankSize additional symbols from each sequence's dataset sequence
58    * 
59    * @param core
60    * @param flankSize
61    * @return AlignmentI
62    */
63   public static AlignmentI expandContext(AlignmentI core, int flankSize)
64   {
65     List<SequenceI> sq = new ArrayList<SequenceI>();
66     int maxoffset = 0;
67     for (SequenceI s : core.getSequences())
68     {
69       SequenceI newSeq = s.deriveSequence();
70       if (newSeq.getStart() > maxoffset
71               && newSeq.getDatasetSequence().getStart() < s.getStart())
72       {
73         maxoffset = newSeq.getStart();
74       }
75       sq.add(newSeq);
76     }
77     if (flankSize > -1)
78     {
79       maxoffset = flankSize;
80     }
81     // now add offset to create a new expanded alignment
82     for (SequenceI s : sq)
83     {
84       SequenceI ds = s;
85       while (ds.getDatasetSequence() != null)
86       {
87         ds = ds.getDatasetSequence();
88       }
89       int s_end = s.findPosition(s.getStart() + s.getLength());
90       // find available flanking residues for sequence
91       int ustream_ds = s.getStart() - ds.getStart(), dstream_ds = ds
92               .getEnd() - s_end;
93
94       // build new flanked sequence
95
96       // compute gap padding to start of flanking sequence
97       int offset = maxoffset - ustream_ds;
98
99       // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
100       if (flankSize >= 0)
101       {
102         if (flankSize < ustream_ds)
103         {
104           // take up to flankSize residues
105           offset = maxoffset - flankSize;
106           ustream_ds = flankSize;
107         }
108         if (flankSize < dstream_ds)
109         {
110           dstream_ds = flankSize;
111         }
112       }
113       char[] upstream = new String(ds.getSequence(s.getStart() - 1
114               - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
115       char[] downstream = new String(ds.getSequence(s_end - 1, s_end + 1
116               + dstream_ds)).toLowerCase().toCharArray();
117       char[] coreseq = s.getSequence();
118       char[] nseq = new char[offset + upstream.length + downstream.length
119               + coreseq.length];
120       char c = core.getGapCharacter();
121       // TODO could lowercase the flanking regions
122       int p = 0;
123       for (; p < offset; p++)
124       {
125         nseq[p] = c;
126       }
127       // s.setSequence(new String(upstream).toLowerCase()+new String(coreseq) +
128       // new String(downstream).toLowerCase());
129       System.arraycopy(upstream, 0, nseq, p, upstream.length);
130       System.arraycopy(coreseq, 0, nseq, p + upstream.length,
131               coreseq.length);
132       System.arraycopy(downstream, 0, nseq, p + coreseq.length
133               + upstream.length, downstream.length);
134       s.setSequence(new String(nseq));
135       s.setStart(s.getStart() - ustream_ds);
136       s.setEnd(s_end + downstream.length);
137     }
138     AlignmentI newAl = new jalview.datamodel.Alignment(
139             sq.toArray(new SequenceI[0]));
140     for (SequenceI s : sq)
141     {
142       if (s.getAnnotation() != null)
143       {
144         for (AlignmentAnnotation aa : s.getAnnotation())
145         {
146           newAl.addAnnotation(aa);
147         }
148       }
149     }
150     newAl.setDataset(core.getDataset());
151     return newAl;
152   }
153
154   /**
155    * Returns the index (zero-based position) of a sequence in an alignment, or
156    * -1 if not found.
157    * 
158    * @param al
159    * @param seq
160    * @return
161    */
162   public static int getSequenceIndex(AlignmentI al, SequenceI seq)
163   {
164     int result = -1;
165     int pos = 0;
166     for (SequenceI alSeq : al.getSequences())
167     {
168       if (alSeq == seq)
169       {
170         result = pos;
171         break;
172       }
173       pos++;
174     }
175     return result;
176   }
177
178   /**
179    * Returns a map of lists of sequences in the alignment, keyed by sequence
180    * name. For use in mapping between different alignment views of the same
181    * sequences.
182    * 
183    * @see jalview.datamodel.AlignmentI#getSequencesByName()
184    */
185   public static Map<String, List<SequenceI>> getSequencesByName(
186           AlignmentI al)
187   {
188     Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
189     for (SequenceI seq : al.getSequences())
190     {
191       String name = seq.getName();
192       if (name != null)
193       {
194         List<SequenceI> seqs = theMap.get(name);
195         if (seqs == null)
196         {
197           seqs = new ArrayList<SequenceI>();
198           theMap.put(name, seqs);
199         }
200         seqs.add(seq);
201       }
202     }
203     return theMap;
204   }
205
206   /**
207    * Build mapping of protein to cDNA alignment. Mappings are made between
208    * sequences which have the same name and compatible lengths. Has a 3-valued
209    * result: either Mapped (at least one sequence mapping was created),
210    * AlreadyMapped (all possible sequence mappings already exist), or NotMapped
211    * (no possible sequence mappings exist).
212    * 
213    * @param proteinAlignment
214    * @param cdnaAlignment
215    * @return
216    */
217   public static MappingResult mapProteinToCdna(
218           final AlignmentI proteinAlignment,
219           final AlignmentI cdnaAlignment)
220   {
221     boolean mappingPossible = false;
222     boolean mappingPerformed = false;
223
224     List<SequenceI> thisSeqs = proteinAlignment.getSequences();
225   
226     /*
227      * Build a look-up of cDNA sequences by name, for matching purposes.
228      */
229     Map<String, List<SequenceI>> cdnaSeqs = cdnaAlignment
230             .getSequencesByName();
231   
232     for (SequenceI aaSeq : thisSeqs)
233     {
234       AlignedCodonFrame acf = new AlignedCodonFrame();
235       List<SequenceI> candidates = cdnaSeqs.get(aaSeq.getName());
236       if (candidates == null)
237       {
238         /*
239          * No cDNA sequence with matching name, so no mapping possible for this
240          * protein sequence
241          */
242         continue;
243       }
244       mappingPossible = true;
245       for (SequenceI cdnaSeq : candidates)
246       {
247         if (!mappingExists(proteinAlignment.getCodonFrames(),
248                 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
249         {
250           MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
251           if (map != null)
252           {
253             acf.addMap(cdnaSeq, aaSeq, map);
254             mappingPerformed = true;
255           }
256         }
257       }
258       proteinAlignment.addCodonFrame(acf);
259     }
260
261     /*
262      * If at least one mapping was possible but none was done, then the
263      * alignments are already as mapped as they can be.
264      */
265     if (mappingPossible && !mappingPerformed)
266     {
267       return MappingResult.AlreadyMapped;
268     }
269     else
270     {
271       return mappingPerformed ? MappingResult.Mapped
272               : MappingResult.NotMapped;
273     }
274   }
275
276   /**
277    * Answers true if the mappings include one between the given (dataset)
278    * sequences.
279    */
280   public static boolean mappingExists(Set<AlignedCodonFrame> set,
281           SequenceI aaSeq, SequenceI cdnaSeq)
282   {
283     if (set != null)
284     {
285       for (AlignedCodonFrame acf : set)
286       {
287         if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
288         {
289           return true;
290         }
291       }
292     }
293     return false;
294   }
295
296   /**
297    * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
298    * must be three times the length of the protein, possibly after ignoring
299    * start and/or stop codons. Returns null if no mapping is determined.
300    * 
301    * @param proteinSeqs
302    * @param cdnaSeq
303    * @return
304    */
305   public static MapList mapProteinToCdna(SequenceI proteinSeq,
306           SequenceI cdnaSeq)
307   {
308     String aaSeqString = proteinSeq.getDatasetSequence()
309             .getSequenceAsString();
310     String cdnaSeqString = cdnaSeq.getDatasetSequence()
311             .getSequenceAsString();
312     if (aaSeqString == null || cdnaSeqString == null)
313     {
314       return null;
315     }
316
317     final int mappedLength = 3 * aaSeqString.length();
318     int cdnaLength = cdnaSeqString.length();
319     int cdnaStart = 1;
320     int cdnaEnd = cdnaLength;
321     final int proteinStart = 1;
322     final int proteinEnd = aaSeqString.length();
323
324     /*
325      * If lengths don't match, try ignoring stop codon.
326      */
327     if (cdnaLength != mappedLength)
328     {
329       for (Object stop : ResidueProperties.STOP)
330       {
331         if (cdnaSeqString.toUpperCase().endsWith((String) stop))
332         {
333           cdnaEnd -= 3;
334           cdnaLength -= 3;
335           break;
336         }
337       }
338     }
339
340     /*
341      * If lengths still don't match, try ignoring start codon.
342      */
343     if (cdnaLength != mappedLength
344             && cdnaSeqString.toUpperCase().startsWith(
345                     ResidueProperties.START))
346     {
347       cdnaStart += 3;
348       cdnaLength -= 3;
349     }
350
351     if (cdnaLength == mappedLength)
352     {
353       MapList map = new MapList(new int[]
354       { cdnaStart, cdnaEnd }, new int[]
355       { proteinStart, proteinEnd }, 3, 1);
356       return map;
357     }
358     else
359     {
360       return null;
361     }
362   }
363
364   /**
365    * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
366    * currently assumes that we are aligning cDNA to match protein.
367    * 
368    * @param seq
369    *          the sequence to be realigned
370    * @param al
371    *          the alignment whose sequence alignment is to be 'copied'
372    * @param gap
373    *          character string represent a gap in the realigned sequence
374    * @param preserveUnmappedGaps
375    * @param preserveMappedGaps
376    * @return true if the sequence was realigned, false if it could not be
377    */
378   public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
379           String gap, boolean preserveMappedGaps,
380           boolean preserveUnmappedGaps)
381   {
382     /*
383      * Get any mappings from the source alignment to the target (dataset) sequence.
384      */
385     // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
386     // all mappings. Would it help to constrain this?
387     List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
388     if (mappings == null)
389     {
390       return false;
391     }
392   
393     /*
394      * Locate the aligned source sequence whose dataset sequence is mapped. We
395      * just take the first match here (as we can't align cDNA like more than one
396      * protein sequence).
397      */
398     SequenceI alignFrom = null;
399     AlignedCodonFrame mapping = null;
400     for (AlignedCodonFrame mp : mappings)
401     {
402       alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
403       if (alignFrom != null)
404       {
405         mapping = mp;
406         break;
407       }
408     }
409   
410     if (alignFrom == null)
411     {
412       return false;
413     }
414     alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
415             preserveMappedGaps, preserveUnmappedGaps);
416     return true;
417   }
418
419   /**
420    * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
421    * match residues and codons. Flags control whether existing gaps in unmapped
422    * (intron) and mapped (exon) regions are preserved or not. Gaps linking intro
423    * and exon are only retained if both flags are set.
424    * 
425    * @param alignTo
426    * @param alignFrom
427    * @param mapping
428    * @param myGap
429    * @param sourceGap
430    * @param preserveUnmappedGaps
431    * @param preserveMappedGaps
432    */
433   public static void alignSequenceAs(SequenceI alignTo,
434           SequenceI alignFrom,
435           AlignedCodonFrame mapping, String myGap, char sourceGap,
436           boolean preserveMappedGaps, boolean preserveUnmappedGaps)
437   {
438     // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
439     final char[] thisSeq = alignTo.getSequence();
440     final char[] thatAligned = alignFrom.getSequence();
441     StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
442   
443     // aligned and dataset sequence positions, all base zero
444     int thisSeqPos = 0;
445     int sourceDsPos = 0;
446
447     int basesWritten = 0;
448     char myGapChar = myGap.charAt(0);
449     int ratio = myGap.length();
450
451     /*
452      * Traverse the aligned protein sequence.
453      */
454     int sourceGapMappedLength = 0;
455     boolean inExon = false;
456     for (char sourceChar : thatAligned)
457     {
458       if (sourceChar == sourceGap)
459       {
460         sourceGapMappedLength += ratio;
461         continue;
462       }
463
464       /*
465        * Found a residue. Locate its mapped codon (start) position.
466        */
467       sourceDsPos++;
468       // Note mapping positions are base 1, our sequence positions base 0
469       int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
470               sourceDsPos);
471       if (mappedPos == null)
472       {
473         /*
474          * Abort realignment if unmapped protein. Or could ignore it??
475          */
476         System.err.println("Can't align: no codon mapping to residue "
477                 + sourceDsPos + "(" + sourceChar + ")");
478         return;
479       }
480
481       int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
482       int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
483       StringBuilder trailingCopiedGap = new StringBuilder();
484
485       /*
486        * Copy dna sequence up to and including this codon. Optionally, include
487        * gaps before the codon starts (in introns) and/or after the codon starts
488        * (in exons).
489        * 
490        * Note this only works for 'linear' splicing, not reverse or interleaved.
491        * But then 'align dna as protein' doesn't make much sense otherwise.
492        */
493       int intronLength = 0;
494       while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
495       {
496         final char c = thisSeq[thisSeqPos++];
497         if (c != myGapChar)
498         {
499           basesWritten++;
500
501           if (basesWritten < mappedCodonStart)
502           {
503             /*
504              * Found an unmapped (intron) base. First add in any preceding gaps
505              * (if wanted).
506              */
507             if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
508             {
509               thisAligned.append(trailingCopiedGap.toString());
510               intronLength += trailingCopiedGap.length();
511               trailingCopiedGap = new StringBuilder();
512             }
513             intronLength++;
514             inExon = false;
515           }
516           else
517           {
518             final boolean startOfCodon = basesWritten == mappedCodonStart;
519             int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
520                     preserveUnmappedGaps, sourceGapMappedLength, inExon,
521                     trailingCopiedGap.length(), intronLength, startOfCodon);
522             for (int i = 0; i < gapsToAdd; i++)
523             {
524               thisAligned.append(myGapChar);
525             }
526             sourceGapMappedLength = 0;
527             inExon = true;
528           }
529           thisAligned.append(c);
530           trailingCopiedGap = new StringBuilder();
531         }
532         else
533         {
534           if (inExon && preserveMappedGaps)
535           {
536             trailingCopiedGap.append(myGapChar);
537           }
538           else if (!inExon && preserveUnmappedGaps)
539           {
540             trailingCopiedGap.append(myGapChar);
541           }
542         }
543       }
544     }
545
546     /*
547      * At end of protein sequence. Copy any remaining dna sequence, optionally
548      * including (intron) gaps. We do not copy trailing gaps in protein.
549      */
550     while (thisSeqPos < thisSeq.length)
551     {
552       final char c = thisSeq[thisSeqPos++];
553       if (c != myGapChar || preserveUnmappedGaps)
554       {
555         thisAligned.append(c);
556       }
557     }
558
559     /*
560      * All done aligning, set the aligned sequence.
561      */
562     alignTo.setSequence(new String(thisAligned));
563   }
564
565   /**
566    * Helper method to work out how many gaps to insert when realigning.
567    * 
568    * @param preserveMappedGaps
569    * @param preserveUnmappedGaps
570    * @param sourceGapMappedLength
571    * @param inExon
572    * @param trailingCopiedGap
573    * @param intronLength
574    * @param startOfCodon
575    * @return
576    */
577   protected static int calculateGapsToInsert(boolean preserveMappedGaps,
578           boolean preserveUnmappedGaps, int sourceGapMappedLength,
579           boolean inExon, int trailingGapLength,
580           int intronLength, final boolean startOfCodon)
581   {
582     int gapsToAdd = 0;
583     if (startOfCodon)
584     {
585       /*
586        * Reached start of codon. Ignore trailing gaps in intron unless we are
587        * preserving gaps in both exon and intron. Ignore them anyway if the
588        * protein alignment introduces a gap at least as large as the intronic
589        * region.
590        */
591       if (inExon && !preserveMappedGaps)
592       {
593         trailingGapLength = 0;
594       }
595       if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
596       {
597         trailingGapLength = 0;
598       }
599       if (inExon)
600       {
601         gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
602       }
603       else
604       {
605         if (intronLength + trailingGapLength <= sourceGapMappedLength)
606         {
607           gapsToAdd = sourceGapMappedLength - intronLength;
608         }
609         else
610         {
611           gapsToAdd = Math.min(intronLength + trailingGapLength
612                   - sourceGapMappedLength, trailingGapLength);
613         }
614       }
615     }
616     else
617     {
618       /*
619        * second or third base of codon; check for any gaps in dna
620        */
621       if (!preserveMappedGaps)
622       {
623         trailingGapLength = 0;
624       }
625       gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
626     }
627     return gapsToAdd;
628   }
629 }