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