df302345d0af5fdd85bc649f8868ef2cd793bcdf
[jalview.git] / src / jalview / analysis / AlignmentUtils.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.analysis;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.LinkedHashMap;
30 import java.util.LinkedHashSet;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Set;
35 import java.util.TreeMap;
36
37 import jalview.datamodel.AlignedCodon;
38 import jalview.datamodel.AlignedCodonFrame;
39 import jalview.datamodel.Alignment;
40 import jalview.datamodel.AlignmentAnnotation;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.DBRefEntry;
43 import jalview.datamodel.DBRefSource;
44 import jalview.datamodel.FeatureProperties;
45 import jalview.datamodel.Mapping;
46 import jalview.datamodel.SearchResults;
47 import jalview.datamodel.Sequence;
48 import jalview.datamodel.SequenceGroup;
49 import jalview.datamodel.SequenceI;
50 import jalview.schemes.ResidueProperties;
51 import jalview.util.DBRefUtils;
52 import jalview.util.MapList;
53 import jalview.util.MappingUtils;
54
55 /**
56  * grab bag of useful alignment manipulation operations Expect these to be
57  * refactored elsewhere at some point.
58  * 
59  * @author jimp
60  * 
61  */
62 public class AlignmentUtils
63 {
64
65   /**
66    * given an existing alignment, create a new alignment including all, or up to
67    * flankSize additional symbols from each sequence's dataset sequence
68    * 
69    * @param core
70    * @param flankSize
71    * @return AlignmentI
72    */
73   public static AlignmentI expandContext(AlignmentI core, int flankSize)
74   {
75     List<SequenceI> sq = new ArrayList<SequenceI>();
76     int maxoffset = 0;
77     for (SequenceI s : core.getSequences())
78     {
79       SequenceI newSeq = s.deriveSequence();
80       final int newSeqStart = newSeq.getStart() - 1;
81       if (newSeqStart > maxoffset
82               && newSeq.getDatasetSequence().getStart() < s.getStart())
83       {
84         maxoffset = newSeqStart;
85       }
86       sq.add(newSeq);
87     }
88     if (flankSize > -1)
89     {
90       maxoffset = Math.min(maxoffset, flankSize);
91     }
92
93     /*
94      * now add offset left and right to create an expanded alignment
95      */
96     for (SequenceI s : sq)
97     {
98       SequenceI ds = s;
99       while (ds.getDatasetSequence() != null)
100       {
101         ds = ds.getDatasetSequence();
102       }
103       int s_end = s.findPosition(s.getStart() + s.getLength());
104       // find available flanking residues for sequence
105       int ustream_ds = s.getStart() - ds.getStart();
106       int dstream_ds = ds.getEnd() - s_end;
107
108       // build new flanked sequence
109
110       // compute gap padding to start of flanking sequence
111       int offset = maxoffset - ustream_ds;
112
113       // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
114       if (flankSize >= 0)
115       {
116         if (flankSize < ustream_ds)
117         {
118           // take up to flankSize residues
119           offset = maxoffset - flankSize;
120           ustream_ds = flankSize;
121         }
122         if (flankSize <= dstream_ds)
123         {
124           dstream_ds = flankSize - 1;
125         }
126       }
127       // TODO use Character.toLowerCase to avoid creating String objects?
128       char[] upstream = new String(ds.getSequence(s.getStart() - 1
129               - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
130       char[] downstream = new String(ds.getSequence(s_end - 1, s_end
131               + dstream_ds)).toLowerCase().toCharArray();
132       char[] coreseq = s.getSequence();
133       char[] nseq = new char[offset + upstream.length + downstream.length
134               + coreseq.length];
135       char c = core.getGapCharacter();
136
137       int p = 0;
138       for (; p < offset; p++)
139       {
140         nseq[p] = c;
141       }
142
143       System.arraycopy(upstream, 0, nseq, p, upstream.length);
144       System.arraycopy(coreseq, 0, nseq, p + upstream.length,
145               coreseq.length);
146       System.arraycopy(downstream, 0, nseq, p + coreseq.length
147               + upstream.length, downstream.length);
148       s.setSequence(new String(nseq));
149       s.setStart(s.getStart() - ustream_ds);
150       s.setEnd(s_end + downstream.length);
151     }
152     AlignmentI newAl = new jalview.datamodel.Alignment(
153             sq.toArray(new SequenceI[0]));
154     for (SequenceI s : sq)
155     {
156       if (s.getAnnotation() != null)
157       {
158         for (AlignmentAnnotation aa : s.getAnnotation())
159         {
160           aa.adjustForAlignment(); // JAL-1712 fix
161           newAl.addAnnotation(aa);
162         }
163       }
164     }
165     newAl.setDataset(core.getDataset());
166     return newAl;
167   }
168
169   /**
170    * Returns the index (zero-based position) of a sequence in an alignment, or
171    * -1 if not found.
172    * 
173    * @param al
174    * @param seq
175    * @return
176    */
177   public static int getSequenceIndex(AlignmentI al, SequenceI seq)
178   {
179     int result = -1;
180     int pos = 0;
181     for (SequenceI alSeq : al.getSequences())
182     {
183       if (alSeq == seq)
184       {
185         result = pos;
186         break;
187       }
188       pos++;
189     }
190     return result;
191   }
192
193   /**
194    * Returns a map of lists of sequences in the alignment, keyed by sequence
195    * name. For use in mapping between different alignment views of the same
196    * sequences.
197    * 
198    * @see jalview.datamodel.AlignmentI#getSequencesByName()
199    */
200   public static Map<String, List<SequenceI>> getSequencesByName(
201           AlignmentI al)
202   {
203     Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
204     for (SequenceI seq : al.getSequences())
205     {
206       String name = seq.getName();
207       if (name != null)
208       {
209         List<SequenceI> seqs = theMap.get(name);
210         if (seqs == null)
211         {
212           seqs = new ArrayList<SequenceI>();
213           theMap.put(name, seqs);
214         }
215         seqs.add(seq);
216       }
217     }
218     return theMap;
219   }
220
221   /**
222    * Build mapping of protein to cDNA alignment. Mappings are made between
223    * sequences where the cDNA translates to the protein sequence. Any new
224    * mappings are added to the protein alignment. Returns true if any mappings
225    * either already exist or were added, else false.
226    * 
227    * @param proteinAlignment
228    * @param cdnaAlignment
229    * @return
230    */
231   public static boolean mapProteinToCdna(
232           final AlignmentI proteinAlignment,
233           final AlignmentI cdnaAlignment)
234   {
235     if (proteinAlignment == null || cdnaAlignment == null)
236     {
237       return false;
238     }
239
240     Set<SequenceI> mappedDna = new HashSet<SequenceI>();
241     Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
242
243     /*
244      * First pass - map sequences where cross-references exist. This include
245      * 1-to-many mappings to support, for example, variant cDNA.
246      */
247     boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
248             cdnaAlignment, mappedDna, mappedProtein, true);
249
250     /*
251      * Second pass - map sequences where no cross-references exist. This only
252      * does 1-to-1 mappings and assumes corresponding sequences are in the same
253      * order in the alignments.
254      */
255     mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
256             mappedDna, mappedProtein, false);
257     return mappingPerformed;
258   }
259
260   /**
261    * Make mappings between compatible sequences (where the cDNA translation
262    * matches the protein).
263    * 
264    * @param proteinAlignment
265    * @param cdnaAlignment
266    * @param mappedDna
267    *          a set of mapped DNA sequences (to add to)
268    * @param mappedProtein
269    *          a set of mapped Protein sequences (to add to)
270    * @param xrefsOnly
271    *          if true, only map sequences where xrefs exist
272    * @return
273    */
274   protected static boolean mapProteinToCdna(
275           final AlignmentI proteinAlignment,
276           final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
277           Set<SequenceI> mappedProtein, boolean xrefsOnly)
278   {
279     boolean mappingPerformed = false;
280     List<SequenceI> thisSeqs = proteinAlignment.getSequences();
281     for (SequenceI aaSeq : thisSeqs)
282     {
283       boolean proteinMapped = false;
284       AlignedCodonFrame acf = new AlignedCodonFrame();
285
286       for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
287       {
288         /*
289          * Always try to map if sequences have xref to each other; this supports
290          * variant cDNA or alternative splicing for a protein sequence.
291          * 
292          * If no xrefs, try to map progressively, assuming that alignments have
293          * mappable sequences in corresponding order. These are not
294          * many-to-many, as that would risk mixing species with similar cDNA
295          * sequences.
296          */
297         if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
298         {
299           continue;
300         }
301
302         /*
303          * Don't map non-xrefd sequences more than once each. This heuristic
304          * allows us to pair up similar sequences in ordered alignments.
305          */
306         if (!xrefsOnly
307                 && (mappedProtein.contains(aaSeq) || mappedDna
308                         .contains(cdnaSeq)))
309         {
310           continue;
311         }
312         if (!mappingExists(proteinAlignment.getCodonFrames(),
313                 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
314         {
315           MapList map = mapProteinToCdna(aaSeq, cdnaSeq);
316           if (map != null)
317           {
318             acf.addMap(cdnaSeq, aaSeq, map);
319             mappingPerformed = true;
320             proteinMapped = true;
321             mappedDna.add(cdnaSeq);
322             mappedProtein.add(aaSeq);
323           }
324         }
325       }
326       if (proteinMapped)
327       {
328         proteinAlignment.addCodonFrame(acf);
329       }
330     }
331     return mappingPerformed;
332   }
333
334   /**
335    * Answers true if the mappings include one between the given (dataset)
336    * sequences.
337    */
338   public static boolean mappingExists(Set<AlignedCodonFrame> set,
339           SequenceI aaSeq, SequenceI cdnaSeq)
340   {
341     if (set != null)
342     {
343       for (AlignedCodonFrame acf : set)
344       {
345         if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
346         {
347           return true;
348         }
349       }
350     }
351     return false;
352   }
353
354   /**
355    * Build a mapping (if possible) of a protein to a cDNA sequence. The cDNA
356    * must be three times the length of the protein, possibly after ignoring
357    * start and/or stop codons, and must translate to the protein. Returns null
358    * if no mapping is determined.
359    * 
360    * @param proteinSeqs
361    * @param cdnaSeq
362    * @return
363    */
364   public static MapList mapProteinToCdna(SequenceI proteinSeq,
365           SequenceI cdnaSeq)
366   {
367     /*
368      * Here we handle either dataset sequence set (desktop) or absent (applet).
369      * Use only the char[] form of the sequence to avoid creating possibly large
370      * String objects.
371      */
372     final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
373     char[] aaSeqChars = proteinDataset != null ? proteinDataset
374             .getSequence() : proteinSeq.getSequence();
375     final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
376     char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
377             : cdnaSeq.getSequence();
378     if (aaSeqChars == null || cdnaSeqChars == null)
379     {
380       return null;
381     }
382
383     /*
384      * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
385      */
386     final int mappedLength = 3 * aaSeqChars.length;
387     int cdnaLength = cdnaSeqChars.length;
388     int cdnaStart = 1;
389     int cdnaEnd = cdnaLength;
390     final int proteinStart = 1;
391     final int proteinEnd = aaSeqChars.length;
392
393     /*
394      * If lengths don't match, try ignoring stop codon.
395      */
396     if (cdnaLength != mappedLength && cdnaLength > 2)
397     {
398       String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
399               .toUpperCase();
400       for (String stop : ResidueProperties.STOP)
401       {
402         if (lastCodon.equals(stop))
403         {
404           cdnaEnd -= 3;
405           cdnaLength -= 3;
406           break;
407         }
408       }
409     }
410
411     /*
412      * If lengths still don't match, try ignoring start codon.
413      */
414     if (cdnaLength != mappedLength
415             && cdnaLength > 2
416             && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
417                     .equals(
418                     ResidueProperties.START))
419     {
420       cdnaStart += 3;
421       cdnaLength -= 3;
422     }
423
424     if (cdnaLength != mappedLength)
425     {
426       return null;
427     }
428     if (!translatesAs(cdnaSeqChars, cdnaStart - 1, aaSeqChars))
429     {
430       return null;
431     }
432     MapList map = new MapList(new int[]
433     { cdnaStart, cdnaEnd }, new int[]
434     { proteinStart, proteinEnd }, 3, 1);
435     return map;
436   }
437
438   /**
439    * Test whether the given cdna sequence, starting at the given offset,
440    * translates to the given amino acid sequence, using the standard translation
441    * table. Designed to fail fast i.e. as soon as a mismatch position is found.
442    * 
443    * @param cdnaSeqChars
444    * @param cdnaStart
445    * @param aaSeqChars
446    * @return
447    */
448   protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
449           char[] aaSeqChars)
450   {
451     int aaResidue = 0;
452     for (int i = cdnaStart; i < cdnaSeqChars.length - 2
453             && aaResidue < aaSeqChars.length; i += 3, aaResidue++)
454     {
455       String codon = String.valueOf(cdnaSeqChars, i, 3);
456       final String translated = ResidueProperties.codonTranslate(
457               codon);
458       /*
459        * ? allow X in protein to match untranslatable in dna ?
460        */
461       final char aaRes = aaSeqChars[aaResidue];
462       if ((translated == null || "STOP".equals(translated)) && aaRes == 'X')
463       {
464         continue;
465       }
466       if (translated == null
467               || !(aaRes == translated.charAt(0)))
468       {
469         // debug
470         // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
471         // + codon + "(" + translated + ") != " + aaRes));
472         return false;
473       }
474     }
475     // fail if we didn't match all of the aa sequence
476     return (aaResidue == aaSeqChars.length);
477   }
478
479   /**
480    * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
481    * currently assumes that we are aligning cDNA to match protein.
482    * 
483    * @param seq
484    *          the sequence to be realigned
485    * @param al
486    *          the alignment whose sequence alignment is to be 'copied'
487    * @param gap
488    *          character string represent a gap in the realigned sequence
489    * @param preserveUnmappedGaps
490    * @param preserveMappedGaps
491    * @return true if the sequence was realigned, false if it could not be
492    */
493   public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
494           String gap, boolean preserveMappedGaps,
495           boolean preserveUnmappedGaps)
496   {
497     /*
498      * Get any mappings from the source alignment to the target (dataset) sequence.
499      */
500     // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
501     // all mappings. Would it help to constrain this?
502     List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
503     if (mappings == null || mappings.isEmpty())
504     {
505       return false;
506     }
507   
508     /*
509      * Locate the aligned source sequence whose dataset sequence is mapped. We
510      * just take the first match here (as we can't align cDNA like more than one
511      * protein sequence).
512      */
513     SequenceI alignFrom = null;
514     AlignedCodonFrame mapping = null;
515     for (AlignedCodonFrame mp : mappings)
516     {
517       alignFrom = mp.findAlignedSequence(seq.getDatasetSequence(), al);
518       if (alignFrom != null)
519       {
520         mapping = mp;
521         break;
522       }
523     }
524   
525     if (alignFrom == null)
526     {
527       return false;
528     }
529     alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
530             preserveMappedGaps, preserveUnmappedGaps);
531     return true;
532   }
533
534   /**
535    * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
536    * match residues and codons. Flags control whether existing gaps in unmapped
537    * (intron) and mapped (exon) regions are preserved or not. Gaps linking intro
538    * and exon are only retained if both flags are set.
539    * 
540    * @param alignTo
541    * @param alignFrom
542    * @param mapping
543    * @param myGap
544    * @param sourceGap
545    * @param preserveUnmappedGaps
546    * @param preserveMappedGaps
547    */
548   public static void alignSequenceAs(SequenceI alignTo,
549           SequenceI alignFrom,
550           AlignedCodonFrame mapping, String myGap, char sourceGap,
551           boolean preserveMappedGaps, boolean preserveUnmappedGaps)
552   {
553     // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
554     final char[] thisSeq = alignTo.getSequence();
555     final char[] thatAligned = alignFrom.getSequence();
556     StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
557   
558     // aligned and dataset sequence positions, all base zero
559     int thisSeqPos = 0;
560     int sourceDsPos = 0;
561
562     int basesWritten = 0;
563     char myGapChar = myGap.charAt(0);
564     int ratio = myGap.length();
565
566     /*
567      * Traverse the aligned protein sequence.
568      */
569     int sourceGapMappedLength = 0;
570     boolean inExon = false;
571     for (char sourceChar : thatAligned)
572     {
573       if (sourceChar == sourceGap)
574       {
575         sourceGapMappedLength += ratio;
576         continue;
577       }
578
579       /*
580        * Found a residue. Locate its mapped codon (start) position.
581        */
582       sourceDsPos++;
583       // Note mapping positions are base 1, our sequence positions base 0
584       int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
585               sourceDsPos);
586       if (mappedPos == null)
587       {
588         /*
589          * Abort realignment if unmapped protein. Or could ignore it??
590          */
591         System.err.println("Can't align: no codon mapping to residue "
592                 + sourceDsPos + "(" + sourceChar + ")");
593         return;
594       }
595
596       int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
597       int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
598       StringBuilder trailingCopiedGap = new StringBuilder();
599
600       /*
601        * Copy dna sequence up to and including this codon. Optionally, include
602        * gaps before the codon starts (in introns) and/or after the codon starts
603        * (in exons).
604        * 
605        * Note this only works for 'linear' splicing, not reverse or interleaved.
606        * But then 'align dna as protein' doesn't make much sense otherwise.
607        */
608       int intronLength = 0;
609       while (basesWritten < mappedCodonEnd && thisSeqPos < thisSeq.length)
610       {
611         final char c = thisSeq[thisSeqPos++];
612         if (c != myGapChar)
613         {
614           basesWritten++;
615
616           if (basesWritten < mappedCodonStart)
617           {
618             /*
619              * Found an unmapped (intron) base. First add in any preceding gaps
620              * (if wanted).
621              */
622             if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
623             {
624               thisAligned.append(trailingCopiedGap.toString());
625               intronLength += trailingCopiedGap.length();
626               trailingCopiedGap = new StringBuilder();
627             }
628             intronLength++;
629             inExon = false;
630           }
631           else
632           {
633             final boolean startOfCodon = basesWritten == mappedCodonStart;
634             int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
635                     preserveUnmappedGaps, sourceGapMappedLength, inExon,
636                     trailingCopiedGap.length(), intronLength, startOfCodon);
637             for (int i = 0; i < gapsToAdd; i++)
638             {
639               thisAligned.append(myGapChar);
640             }
641             sourceGapMappedLength = 0;
642             inExon = true;
643           }
644           thisAligned.append(c);
645           trailingCopiedGap = new StringBuilder();
646         }
647         else
648         {
649           if (inExon && preserveMappedGaps)
650           {
651             trailingCopiedGap.append(myGapChar);
652           }
653           else if (!inExon && preserveUnmappedGaps)
654           {
655             trailingCopiedGap.append(myGapChar);
656           }
657         }
658       }
659     }
660
661     /*
662      * At end of protein sequence. Copy any remaining dna sequence, optionally
663      * including (intron) gaps. We do not copy trailing gaps in protein.
664      */
665     while (thisSeqPos < thisSeq.length)
666     {
667       final char c = thisSeq[thisSeqPos++];
668       if (c != myGapChar || preserveUnmappedGaps)
669       {
670         thisAligned.append(c);
671       }
672     }
673
674     /*
675      * All done aligning, set the aligned sequence.
676      */
677     alignTo.setSequence(new String(thisAligned));
678   }
679
680   /**
681    * Helper method to work out how many gaps to insert when realigning.
682    * 
683    * @param preserveMappedGaps
684    * @param preserveUnmappedGaps
685    * @param sourceGapMappedLength
686    * @param inExon
687    * @param trailingCopiedGap
688    * @param intronLength
689    * @param startOfCodon
690    * @return
691    */
692   protected static int calculateGapsToInsert(boolean preserveMappedGaps,
693           boolean preserveUnmappedGaps, int sourceGapMappedLength,
694           boolean inExon, int trailingGapLength,
695           int intronLength, final boolean startOfCodon)
696   {
697     int gapsToAdd = 0;
698     if (startOfCodon)
699     {
700       /*
701        * Reached start of codon. Ignore trailing gaps in intron unless we are
702        * preserving gaps in both exon and intron. Ignore them anyway if the
703        * protein alignment introduces a gap at least as large as the intronic
704        * region.
705        */
706       if (inExon && !preserveMappedGaps)
707       {
708         trailingGapLength = 0;
709       }
710       if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
711       {
712         trailingGapLength = 0;
713       }
714       if (inExon)
715       {
716         gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
717       }
718       else
719       {
720         if (intronLength + trailingGapLength <= sourceGapMappedLength)
721         {
722           gapsToAdd = sourceGapMappedLength - intronLength;
723         }
724         else
725         {
726           gapsToAdd = Math.min(intronLength + trailingGapLength
727                   - sourceGapMappedLength, trailingGapLength);
728         }
729       }
730     }
731     else
732     {
733       /*
734        * second or third base of codon; check for any gaps in dna
735        */
736       if (!preserveMappedGaps)
737       {
738         trailingGapLength = 0;
739       }
740       gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
741     }
742     return gapsToAdd;
743   }
744
745   /**
746    * Returns a list of sequences mapped from the given sequences and aligned
747    * (gapped) in the same way. For example, the cDNA for aligned protein, where
748    * a single gap in protein generates three gaps in cDNA.
749    * 
750    * @param sequences
751    * @param gapCharacter
752    * @param mappings
753    * @return
754    */
755   public static List<SequenceI> getAlignedTranslation(
756           List<SequenceI> sequences, char gapCharacter,
757           Set<AlignedCodonFrame> mappings)
758   {
759     List<SequenceI> alignedSeqs = new ArrayList<SequenceI>();
760
761     for (SequenceI seq : sequences)
762     {
763       List<SequenceI> mapped = getAlignedTranslation(seq, gapCharacter,
764               mappings);
765       alignedSeqs.addAll(mapped);
766     }
767     return alignedSeqs;
768   }
769
770   /**
771    * Returns sequences aligned 'like' the source sequence, as mapped by the
772    * given mappings. Normally we expect zero or one 'mapped' sequences, but this
773    * will support 1-to-many as well.
774    * 
775    * @param seq
776    * @param gapCharacter
777    * @param mappings
778    * @return
779    */
780   protected static List<SequenceI> getAlignedTranslation(SequenceI seq,
781           char gapCharacter, Set<AlignedCodonFrame> mappings)
782   {
783     List<SequenceI> result = new ArrayList<SequenceI>();
784     for (AlignedCodonFrame mapping : mappings)
785     {
786       if (mapping.involvesSequence(seq))
787       {
788         SequenceI mapped = getAlignedTranslation(seq, gapCharacter, mapping);
789         if (mapped != null)
790         {
791           result.add(mapped);
792         }
793       }
794     }
795     return result;
796   }
797
798   /**
799    * Returns the translation of 'seq' (as held in the mapping) with
800    * corresponding alignment (gaps).
801    * 
802    * @param seq
803    * @param gapCharacter
804    * @param mapping
805    * @return
806    */
807   protected static SequenceI getAlignedTranslation(SequenceI seq,
808           char gapCharacter, AlignedCodonFrame mapping)
809   {
810     String gap = String.valueOf(gapCharacter);
811     boolean toDna = false;
812     int fromRatio = 1;
813     SequenceI mapTo = mapping.getDnaForAaSeq(seq);
814     if (mapTo != null)
815     {
816       // mapping is from protein to nucleotide
817       toDna = true;
818       // should ideally get gap count ratio from mapping
819       gap = String.valueOf(new char[]
820       { gapCharacter, gapCharacter, gapCharacter });
821     }
822     else
823     {
824       // mapping is from nucleotide to protein
825       mapTo = mapping.getAaForDnaSeq(seq);
826       fromRatio = 3;
827     }
828     StringBuilder newseq = new StringBuilder(seq.getLength()
829             * (toDna ? 3 : 1));
830
831     int residueNo = 0; // in seq, base 1
832     int[] phrase = new int[fromRatio];
833     int phraseOffset = 0;
834     int gapWidth = 0;
835     boolean first = true;
836     final Sequence alignedSeq = new Sequence("", "");
837
838     for (char c : seq.getSequence())
839     {
840       if (c == gapCharacter)
841       {
842         gapWidth++;
843         if (gapWidth >= fromRatio)
844         {
845           newseq.append(gap);
846           gapWidth = 0;
847         }
848       }
849       else
850       {
851         phrase[phraseOffset++] = residueNo + 1;
852         if (phraseOffset == fromRatio)
853         {
854           /*
855            * Have read a whole codon (or protein residue), now translate: map
856            * source phrase to positions in target sequence add characters at
857            * these positions to newseq Note mapping positions are base 1, our
858            * sequence positions base 0.
859            */
860           SearchResults sr = new SearchResults();
861           for (int pos : phrase)
862           {
863             mapping.markMappedRegion(seq, pos, sr);
864           }
865           newseq.append(sr.toString());
866           if (first)
867           {
868             first = false;
869             // Hack: Copy sequence dataset, name and description from
870             // SearchResults.match[0].sequence
871             // TODO? carry over sequence names from original 'complement'
872             // alignment
873             SequenceI mappedTo = sr.getResultSequence(0);
874             alignedSeq.setName(mappedTo.getName());
875             alignedSeq.setDescription(mappedTo.getDescription());
876             alignedSeq.setDatasetSequence(mappedTo);
877           }
878           phraseOffset = 0;
879         }
880         residueNo++;
881       }
882     }
883     alignedSeq.setSequence(newseq.toString());
884     return alignedSeq;
885   }
886
887   /**
888    * Realigns the given protein to match the alignment of the dna, using codon
889    * mappings to translate aligned codon positions to protein residues.
890    * 
891    * @param protein
892    *          the alignment whose sequences are realigned by this method
893    * @param dna
894    *          the dna alignment whose alignment we are 'copying'
895    * @return the number of sequences that were realigned
896    */
897   public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
898   {
899     Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
900
901     /*
902      * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
903      * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
904      * comparator keeps the codon positions ordered.
905      */
906     Map<AlignedCodon, Map<SequenceI, String>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, String>>(
907             new CodonComparator());
908     for (SequenceI dnaSeq : dna.getSequences())
909     {
910       for (AlignedCodonFrame mapping : mappings)
911       {
912         Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
913         SequenceI prot = mapping.findAlignedSequence(
914                 dnaSeq.getDatasetSequence(), protein);
915         if (prot != null)
916         {
917           addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
918                   seqMap, alignedCodons);
919         }
920       }
921     }
922     return alignProteinAs(protein, alignedCodons);
923   }
924
925   /**
926    * Update the aligned protein sequences to match the codon alignments given in
927    * the map.
928    * 
929    * @param protein
930    * @param alignedCodons
931    *          an ordered map of codon positions (columns), with sequence/peptide
932    *          values present in each column
933    * @return
934    */
935   protected static int alignProteinAs(AlignmentI protein,
936           Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
937   {
938     /*
939      * Prefill aligned sequences with gaps before inserting aligned protein
940      * residues.
941      */
942     int alignedWidth = alignedCodons.size();
943     char[] gaps = new char[alignedWidth];
944     Arrays.fill(gaps, protein.getGapCharacter());
945     String allGaps = String.valueOf(gaps);
946     for (SequenceI seq : protein.getSequences())
947     {
948       seq.setSequence(allGaps);
949     }
950
951     int column = 0;
952     for (AlignedCodon codon : alignedCodons.keySet())
953     {
954       final Map<SequenceI, String> columnResidues = alignedCodons.get(codon);
955       for (Entry<SequenceI, String> entry : columnResidues
956               .entrySet())
957       {
958         // place translated codon at its column position in sequence
959         entry.getKey().getSequence()[column] = entry.getValue().charAt(0);
960       }
961       column++;
962     }
963     return 0;
964   }
965
966   /**
967    * Populate the map of aligned codons by traversing the given sequence
968    * mapping, locating the aligned positions of mapped codons, and adding those
969    * positions and their translation products to the map.
970    * 
971    * @param dna
972    *          the aligned sequence we are mapping from
973    * @param protein
974    *          the sequence to be aligned to the codons
975    * @param gapChar
976    *          the gap character in the dna sequence
977    * @param seqMap
978    *          a mapping to a sequence translation
979    * @param alignedCodons
980    *          the map we are building up
981    */
982   static void addCodonPositions(SequenceI dna, SequenceI protein,
983           char gapChar,
984           Mapping seqMap,
985           Map<AlignedCodon, Map<SequenceI, String>> alignedCodons)
986   {
987     Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
988     while (codons.hasNext())
989     {
990       AlignedCodon codon = codons.next();
991       Map<SequenceI, String> seqProduct = alignedCodons.get(codon);
992       if (seqProduct == null)
993       {
994         seqProduct = new HashMap<SequenceI, String>();
995         alignedCodons.put(codon, seqProduct);
996       }
997       seqProduct.put(protein, codon.product);
998     }
999   }
1000
1001   /**
1002    * Returns true if a cDNA/Protein mapping either exists, or could be made,
1003    * between at least one pair of sequences in the two alignments. Currently,
1004    * the logic is:
1005    * <ul>
1006    * <li>One alignment must be nucleotide, and the other protein</li>
1007    * <li>At least one pair of sequences must be already mapped, or mappable</li>
1008    * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1009    * <li>The translation may ignore start and stop codons if present in the
1010    * nucleotide</li>
1011    * </ul>
1012    * 
1013    * @param al1
1014    * @param al2
1015    * @return
1016    */
1017   public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1018   {
1019     /*
1020      * Require one nucleotide and one protein
1021      */
1022     if (al1.isNucleotide() == al2.isNucleotide())
1023     {
1024       return false;
1025     }
1026     AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1027     AlignmentI protein = dna == al1 ? al2 : al1;
1028     Set<AlignedCodonFrame> mappings = protein.getCodonFrames();
1029     for (SequenceI dnaSeq : dna.getSequences())
1030     {
1031       for (SequenceI proteinSeq : protein.getSequences())
1032       {
1033         if (isMappable(dnaSeq, proteinSeq, mappings))
1034         {
1035           return true;
1036         }
1037       }
1038     }
1039     return false;
1040   }
1041
1042   /**
1043    * Returns true if the dna sequence is mapped, or could be mapped, to the
1044    * protein sequence.
1045    * 
1046    * @param dnaSeq
1047    * @param proteinSeq
1048    * @param mappings
1049    * @return
1050    */
1051   public static boolean isMappable(SequenceI dnaSeq, SequenceI proteinSeq,
1052           Set<AlignedCodonFrame> mappings)
1053   {
1054     SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq.getDatasetSequence();
1055     SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1056             : proteinSeq.getDatasetSequence();
1057     
1058     /*
1059      * Already mapped?
1060      */
1061     for (AlignedCodonFrame mapping : mappings) {
1062       if ( proteinDs == mapping.getAaForDnaSeq(dnaDs)) {
1063         return true;
1064       }
1065     }
1066
1067     /*
1068      * Just try to make a mapping (it is not yet stored), test whether
1069      * successful.
1070      */
1071     return mapProteinToCdna(proteinDs, dnaDs) != null;
1072   }
1073
1074   /**
1075    * Finds any reference annotations associated with the sequences in
1076    * sequenceScope, that are not already added to the alignment, and adds them
1077    * to the 'candidates' map. Also populates a lookup table of annotation
1078    * labels, keyed by calcId, for use in constructing tooltips or the like.
1079    * 
1080    * @param sequenceScope
1081    *          the sequences to scan for reference annotations
1082    * @param labelForCalcId
1083    *          (optional) map to populate with label for calcId
1084    * @param candidates
1085    *          map to populate with annotations for sequence
1086    * @param al
1087    *          the alignment to check for presence of annotations
1088    */
1089   public static void findAddableReferenceAnnotations(
1090           List<SequenceI> sequenceScope, Map<String, String> labelForCalcId,
1091           final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1092           AlignmentI al)
1093   {
1094     if (sequenceScope == null)
1095     {
1096       return;
1097     }
1098   
1099     /*
1100      * For each sequence in scope, make a list of any annotations on the
1101      * underlying dataset sequence which are not already on the alignment.
1102      * 
1103      * Add to a map of { alignmentSequence, <List of annotations to add> }
1104      */
1105     for (SequenceI seq : sequenceScope)
1106     {
1107       SequenceI dataset = seq.getDatasetSequence();
1108       if (dataset == null)
1109       {
1110         continue;
1111       }
1112       AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1113       if (datasetAnnotations == null)
1114       {
1115         continue;
1116       }
1117       final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1118       for (AlignmentAnnotation dsann : datasetAnnotations)
1119       {
1120         /*
1121          * Find matching annotations on the alignment. If none is found, then
1122          * add this annotation to the list of 'addable' annotations for this
1123          * sequence.
1124          */
1125         final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1126                 .findAnnotations(seq, dsann.getCalcId(),
1127                         dsann.label);
1128         if (!matchedAlignmentAnnotations.iterator().hasNext())
1129         {
1130           result.add(dsann);
1131           if (labelForCalcId != null)
1132           {
1133             labelForCalcId.put(dsann.getCalcId(), dsann.label);
1134           }
1135         }
1136       }
1137       /*
1138        * Save any addable annotations for this sequence
1139        */
1140       if (!result.isEmpty())
1141       {
1142         candidates.put(seq, result);
1143       }
1144     }
1145   }
1146
1147   /**
1148    * Adds annotations to the top of the alignment annotations, in the same order
1149    * as their related sequences.
1150    * 
1151    * @param annotations
1152    *          the annotations to add
1153    * @param alignment
1154    *          the alignment to add them to
1155    * @param selectionGroup
1156    *          current selection group (or null if none)
1157    */
1158   public static void addReferenceAnnotations(
1159           Map<SequenceI, List<AlignmentAnnotation>> annotations,
1160           final AlignmentI alignment, final SequenceGroup selectionGroup)
1161   {
1162     for (SequenceI seq : annotations.keySet())
1163     {
1164       for (AlignmentAnnotation ann : annotations.get(seq))
1165       {
1166         AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1167         int startRes = 0;
1168         int endRes = ann.annotations.length;
1169         if (selectionGroup != null)
1170         {
1171           startRes = selectionGroup.getStartRes();
1172           endRes = selectionGroup.getEndRes();
1173         }
1174         copyAnn.restrict(startRes, endRes);
1175   
1176         /*
1177          * Add to the sequence (sets copyAnn.datasetSequence), unless the
1178          * original annotation is already on the sequence.
1179          */
1180         if (!seq.hasAnnotation(ann))
1181         {
1182           seq.addAlignmentAnnotation(copyAnn);
1183         }
1184         // adjust for gaps
1185         copyAnn.adjustForAlignment();
1186         // add to the alignment and set visible
1187         alignment.addAnnotation(copyAnn);
1188         copyAnn.visible = true;
1189       }
1190     }
1191   }
1192
1193   /**
1194    * Set visibility of alignment annotations of specified types (labels), for
1195    * specified sequences. This supports controls like
1196    * "Show all secondary structure", "Hide all Temp factor", etc.
1197    * 
1198    * @al the alignment to scan for annotations
1199    * @param types
1200    *          the types (labels) of annotations to be updated
1201    * @param forSequences
1202    *          if not null, only annotations linked to one of these sequences are
1203    *          in scope for update; if null, acts on all sequence annotations
1204    * @param anyType
1205    *          if this flag is true, 'types' is ignored (label not checked)
1206    * @param doShow
1207    *          if true, set visibility on, else set off
1208    */
1209   public static void showOrHideSequenceAnnotations(AlignmentI al,
1210           Collection<String> types, List<SequenceI> forSequences,
1211           boolean anyType, boolean doShow)
1212   {
1213     for (AlignmentAnnotation aa : al
1214             .getAlignmentAnnotation())
1215     {
1216       if (anyType || types.contains(aa.label))
1217       {
1218         if ((aa.sequenceRef != null)
1219                 && (forSequences == null || forSequences
1220                         .contains(aa.sequenceRef)))
1221         {
1222           aa.visible = doShow;
1223         }
1224       }
1225     }
1226   }
1227
1228   /**
1229    * Returns true if either sequence has a cross-reference to the other
1230    * 
1231    * @param seq1
1232    * @param seq2
1233    * @return
1234    */
1235   public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1236   {
1237     // Note: moved here from class CrossRef as the latter class has dependencies
1238     // not availability to the applet's classpath
1239     return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1240   }
1241
1242   /**
1243    * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1244    * that sequence name is structured as Source|AccessId.
1245    * 
1246    * @param seq1
1247    * @param seq2
1248    * @return
1249    */
1250   public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1251   {
1252     if (seq1 == null || seq2 == null)
1253     {
1254       return false;
1255     }
1256     String name = seq2.getName();
1257     final DBRefEntry[] xrefs = seq1.getDBRef();
1258     if (xrefs != null)
1259     {
1260       for (DBRefEntry xref : xrefs)
1261       {
1262         String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1263         // case-insensitive test, consistent with DBRefEntry.equalRef()
1264         if (xrefName.equalsIgnoreCase(name))
1265         {
1266           return true;
1267         }
1268       }
1269     }
1270     return false;
1271   }
1272
1273   /**
1274    * Constructs an alignment consisting of the mapped exon regions in the given
1275    * nucleotide sequences, and updates mappings to match.
1276    * 
1277    * @param dna
1278    *          aligned dna sequences
1279    * @param mappings
1280    *          from dna to protein; these are replaced with new mappings
1281    * @return an alignment whose sequences are the exon-only parts of the dna
1282    *         sequences (or null if no exons are found)
1283    */
1284   public static AlignmentI makeExonAlignment(SequenceI[] dna,
1285           Set<AlignedCodonFrame> mappings)
1286   {
1287     Set<AlignedCodonFrame> newMappings = new LinkedHashSet<AlignedCodonFrame>();
1288     List<SequenceI> exonSequences = new ArrayList<SequenceI>();
1289     
1290     for (SequenceI dnaSeq : dna)
1291     {
1292       final SequenceI ds = dnaSeq.getDatasetSequence();
1293       List<AlignedCodonFrame> seqMappings = MappingUtils
1294               .findMappingsForSequence(ds, mappings);
1295       for (AlignedCodonFrame acf : seqMappings)
1296       {
1297         AlignedCodonFrame newMapping = new AlignedCodonFrame();
1298         final List<SequenceI> mappedExons = makeExonSequences(ds, acf,
1299                 newMapping);
1300         if (!mappedExons.isEmpty())
1301         {
1302           exonSequences.addAll(mappedExons);
1303           newMappings.add(newMapping);
1304         }
1305       }
1306     }
1307     AlignmentI al = new Alignment(
1308             exonSequences.toArray(new SequenceI[exonSequences.size()]));
1309     al.setDataset(null);
1310
1311     /*
1312      * Replace the old mappings with the new ones
1313      */
1314     mappings.clear();
1315     mappings.addAll(newMappings);
1316
1317     return al;
1318   }
1319
1320   /**
1321    * Helper method to make exon-only sequences and populate their mappings to
1322    * protein products
1323    * <p>
1324    * For example, if ggCCaTTcGAg has mappings [3, 4, 6, 7, 9, 10] to protein
1325    * then generate a sequence CCTTGA with mapping [1, 6] to the same protein
1326    * residues
1327    * <p>
1328    * Typically eukaryotic dna will include exons encoding for a single peptide
1329    * sequence i.e. return a single result. Bacterial dna may have overlapping
1330    * exon mappings coding for multiple peptides so return multiple results
1331    * (example EMBL KF591215).
1332    * 
1333    * @param dnaSeq
1334    *          a dna dataset sequence
1335    * @param mapping
1336    *          containing one or more mappings of the sequence to protein
1337    * @param newMapping
1338    *          the new mapping to populate, from the exon-only sequences to their
1339    *          mapped protein sequences
1340    * @return
1341    */
1342   protected static List<SequenceI> makeExonSequences(SequenceI dnaSeq,
1343           AlignedCodonFrame mapping, AlignedCodonFrame newMapping)
1344   {
1345     List<SequenceI> exonSequences = new ArrayList<SequenceI>();
1346     List<Mapping> seqMappings = mapping.getMappingsForSequence(dnaSeq);
1347     final char[] dna = dnaSeq.getSequence();
1348     for (Mapping seqMapping : seqMappings)
1349     {
1350       StringBuilder newSequence = new StringBuilder(dnaSeq.getLength());
1351
1352       /*
1353        * Get the codon regions as { [2, 5], [7, 12], [14, 14] etc }
1354        */
1355       final List<int[]> dnaExonRanges = seqMapping.getMap().getFromRanges();
1356       for (int[] range : dnaExonRanges)
1357       {
1358         for (int pos = range[0]; pos <= range[1]; pos++)
1359         {
1360           newSequence.append(dna[pos - 1]);
1361         }
1362       }
1363
1364       SequenceI exon = new Sequence(dnaSeq.getName(),
1365               newSequence.toString());
1366
1367       /*
1368        * Locate any xrefs to CDS database on the protein product and attach to
1369        * the CDS sequence. Also add as a sub-token of the sequence name.
1370        */
1371       // default to "CDS" if we can't locate an actual gene id
1372       String cdsAccId = FeatureProperties
1373               .getCodingFeature(DBRefSource.EMBL);
1374       DBRefEntry[] cdsRefs = DBRefUtils.selectRefs(seqMapping.getTo()
1375               .getDBRef(), DBRefSource.CODINGDBS);
1376       if (cdsRefs != null)
1377       {
1378         for (DBRefEntry cdsRef : cdsRefs)
1379         {
1380           exon.addDBRef(new DBRefEntry(cdsRef));
1381           cdsAccId = cdsRef.getAccessionId();
1382         }
1383       }
1384       exon.setName(exon.getName() + "|" + cdsAccId);
1385       exon.createDatasetSequence();
1386
1387       /*
1388        * Build new mappings - from the same protein regions, but now to
1389        * contiguous exons
1390        */
1391       List<int[]> exonRange = new ArrayList<int[]>();
1392       exonRange.add(new int[]
1393       { 1, newSequence.length() });
1394       MapList map = new MapList(exonRange, seqMapping.getMap()
1395               .getToRanges(),
1396               3, 1);
1397       newMapping.addMap(exon.getDatasetSequence(), seqMapping.getTo(), map);
1398       MapList cdsToDnaMap = new MapList(dnaExonRanges, exonRange, 1, 1);
1399       newMapping.addMap(dnaSeq, exon.getDatasetSequence(), cdsToDnaMap);
1400
1401       exonSequences.add(exon);
1402     }
1403     return exonSequences;
1404   }
1405 }