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