JAL-2049 set sequence feature group to "Jalview" for computed protein
[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 static jalview.io.gff.GffConstants.CLINICAL_SIGNIFICANCE;
24
25 import jalview.datamodel.AlignedCodon;
26 import jalview.datamodel.AlignedCodonFrame;
27 import jalview.datamodel.Alignment;
28 import jalview.datamodel.AlignmentAnnotation;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.DBRefEntry;
31 import jalview.datamodel.IncompleteCodonException;
32 import jalview.datamodel.Mapping;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceGroup;
36 import jalview.datamodel.SequenceI;
37 import jalview.io.gff.SequenceOntologyFactory;
38 import jalview.io.gff.SequenceOntologyI;
39 import jalview.schemes.ResidueProperties;
40 import jalview.util.Comparison;
41 import jalview.util.MapList;
42 import jalview.util.MappingUtils;
43 import jalview.util.StringUtils;
44
45 import java.io.UnsupportedEncodingException;
46 import java.net.URLEncoder;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collection;
50 import java.util.Collections;
51 import java.util.Comparator;
52 import java.util.HashMap;
53 import java.util.HashSet;
54 import java.util.Iterator;
55 import java.util.LinkedHashMap;
56 import java.util.List;
57 import java.util.Map;
58 import java.util.Map.Entry;
59 import java.util.NoSuchElementException;
60 import java.util.Set;
61 import java.util.TreeMap;
62
63 /**
64  * grab bag of useful alignment manipulation operations Expect these to be
65  * refactored elsewhere at some point.
66  * 
67  * @author jimp
68  * 
69  */
70 public class AlignmentUtils
71 {
72
73   private static final String SEQUENCE_VARIANT = "sequence_variant:";
74   private static final String ID = "ID";
75
76   /**
77    * A data model to hold the 'normal' base value at a position, and an optional
78    * sequence variant feature
79    */
80   static class DnaVariant
81   {
82     String base;
83
84     SequenceFeature variant;
85
86     DnaVariant(String nuc)
87     {
88       base = nuc;
89     }
90
91     DnaVariant(String nuc, SequenceFeature var)
92     {
93       base = nuc;
94       variant = var;
95     }
96   }
97
98   /**
99    * given an existing alignment, create a new alignment including all, or up to
100    * flankSize additional symbols from each sequence's dataset sequence
101    * 
102    * @param core
103    * @param flankSize
104    * @return AlignmentI
105    */
106   public static AlignmentI expandContext(AlignmentI core, int flankSize)
107   {
108     List<SequenceI> sq = new ArrayList<SequenceI>();
109     int maxoffset = 0;
110     for (SequenceI s : core.getSequences())
111     {
112       SequenceI newSeq = s.deriveSequence();
113       final int newSeqStart = newSeq.getStart() - 1;
114       if (newSeqStart > maxoffset
115               && newSeq.getDatasetSequence().getStart() < s.getStart())
116       {
117         maxoffset = newSeqStart;
118       }
119       sq.add(newSeq);
120     }
121     if (flankSize > -1)
122     {
123       maxoffset = Math.min(maxoffset, flankSize);
124     }
125
126     /*
127      * now add offset left and right to create an expanded alignment
128      */
129     for (SequenceI s : sq)
130     {
131       SequenceI ds = s;
132       while (ds.getDatasetSequence() != null)
133       {
134         ds = ds.getDatasetSequence();
135       }
136       int s_end = s.findPosition(s.getStart() + s.getLength());
137       // find available flanking residues for sequence
138       int ustream_ds = s.getStart() - ds.getStart();
139       int dstream_ds = ds.getEnd() - s_end;
140
141       // build new flanked sequence
142
143       // compute gap padding to start of flanking sequence
144       int offset = maxoffset - ustream_ds;
145
146       // padding is gapChar x ( maxoffset - min(ustream_ds, flank)
147       if (flankSize >= 0)
148       {
149         if (flankSize < ustream_ds)
150         {
151           // take up to flankSize residues
152           offset = maxoffset - flankSize;
153           ustream_ds = flankSize;
154         }
155         if (flankSize <= dstream_ds)
156         {
157           dstream_ds = flankSize - 1;
158         }
159       }
160       // TODO use Character.toLowerCase to avoid creating String objects?
161       char[] upstream = new String(ds.getSequence(s.getStart() - 1
162               - ustream_ds, s.getStart() - 1)).toLowerCase().toCharArray();
163       char[] downstream = new String(ds.getSequence(s_end - 1, s_end
164               + dstream_ds)).toLowerCase().toCharArray();
165       char[] coreseq = s.getSequence();
166       char[] nseq = new char[offset + upstream.length + downstream.length
167               + coreseq.length];
168       char c = core.getGapCharacter();
169
170       int p = 0;
171       for (; p < offset; p++)
172       {
173         nseq[p] = c;
174       }
175
176       System.arraycopy(upstream, 0, nseq, p, upstream.length);
177       System.arraycopy(coreseq, 0, nseq, p + upstream.length,
178               coreseq.length);
179       System.arraycopy(downstream, 0, nseq, p + coreseq.length
180               + upstream.length, downstream.length);
181       s.setSequence(new String(nseq));
182       s.setStart(s.getStart() - ustream_ds);
183       s.setEnd(s_end + downstream.length);
184     }
185     AlignmentI newAl = new jalview.datamodel.Alignment(
186             sq.toArray(new SequenceI[0]));
187     for (SequenceI s : sq)
188     {
189       if (s.getAnnotation() != null)
190       {
191         for (AlignmentAnnotation aa : s.getAnnotation())
192         {
193           aa.adjustForAlignment(); // JAL-1712 fix
194           newAl.addAnnotation(aa);
195         }
196       }
197     }
198     newAl.setDataset(core.getDataset());
199     return newAl;
200   }
201
202   /**
203    * Returns the index (zero-based position) of a sequence in an alignment, or
204    * -1 if not found.
205    * 
206    * @param al
207    * @param seq
208    * @return
209    */
210   public static int getSequenceIndex(AlignmentI al, SequenceI seq)
211   {
212     int result = -1;
213     int pos = 0;
214     for (SequenceI alSeq : al.getSequences())
215     {
216       if (alSeq == seq)
217       {
218         result = pos;
219         break;
220       }
221       pos++;
222     }
223     return result;
224   }
225
226   /**
227    * Returns a map of lists of sequences in the alignment, keyed by sequence
228    * name. For use in mapping between different alignment views of the same
229    * sequences.
230    * 
231    * @see jalview.datamodel.AlignmentI#getSequencesByName()
232    */
233   public static Map<String, List<SequenceI>> getSequencesByName(
234           AlignmentI al)
235   {
236     Map<String, List<SequenceI>> theMap = new LinkedHashMap<String, List<SequenceI>>();
237     for (SequenceI seq : al.getSequences())
238     {
239       String name = seq.getName();
240       if (name != null)
241       {
242         List<SequenceI> seqs = theMap.get(name);
243         if (seqs == null)
244         {
245           seqs = new ArrayList<SequenceI>();
246           theMap.put(name, seqs);
247         }
248         seqs.add(seq);
249       }
250     }
251     return theMap;
252   }
253
254   /**
255    * Build mapping of protein to cDNA alignment. Mappings are made between
256    * sequences where the cDNA translates to the protein sequence. Any new
257    * mappings are added to the protein alignment. Returns true if any mappings
258    * either already exist or were added, else false.
259    * 
260    * @param proteinAlignment
261    * @param cdnaAlignment
262    * @return
263    */
264   public static boolean mapProteinAlignmentToCdna(
265           final AlignmentI proteinAlignment, final AlignmentI cdnaAlignment)
266   {
267     if (proteinAlignment == null || cdnaAlignment == null)
268     {
269       return false;
270     }
271
272     Set<SequenceI> mappedDna = new HashSet<SequenceI>();
273     Set<SequenceI> mappedProtein = new HashSet<SequenceI>();
274
275     /*
276      * First pass - map sequences where cross-references exist. This include
277      * 1-to-many mappings to support, for example, variant cDNA.
278      */
279     boolean mappingPerformed = mapProteinToCdna(proteinAlignment,
280             cdnaAlignment, mappedDna, mappedProtein, true);
281
282     /*
283      * Second pass - map sequences where no cross-references exist. This only
284      * does 1-to-1 mappings and assumes corresponding sequences are in the same
285      * order in the alignments.
286      */
287     mappingPerformed |= mapProteinToCdna(proteinAlignment, cdnaAlignment,
288             mappedDna, mappedProtein, false);
289     return mappingPerformed;
290   }
291
292   /**
293    * Make mappings between compatible sequences (where the cDNA translation
294    * matches the protein).
295    * 
296    * @param proteinAlignment
297    * @param cdnaAlignment
298    * @param mappedDna
299    *          a set of mapped DNA sequences (to add to)
300    * @param mappedProtein
301    *          a set of mapped Protein sequences (to add to)
302    * @param xrefsOnly
303    *          if true, only map sequences where xrefs exist
304    * @return
305    */
306   protected static boolean mapProteinToCdna(
307           final AlignmentI proteinAlignment,
308           final AlignmentI cdnaAlignment, Set<SequenceI> mappedDna,
309           Set<SequenceI> mappedProtein, boolean xrefsOnly)
310   {
311     boolean mappingExistsOrAdded = false;
312     List<SequenceI> thisSeqs = proteinAlignment.getSequences();
313     for (SequenceI aaSeq : thisSeqs)
314     {
315       boolean proteinMapped = false;
316       AlignedCodonFrame acf = new AlignedCodonFrame();
317
318       for (SequenceI cdnaSeq : cdnaAlignment.getSequences())
319       {
320         /*
321          * Always try to map if sequences have xref to each other; this supports
322          * variant cDNA or alternative splicing for a protein sequence.
323          * 
324          * If no xrefs, try to map progressively, assuming that alignments have
325          * mappable sequences in corresponding order. These are not
326          * many-to-many, as that would risk mixing species with similar cDNA
327          * sequences.
328          */
329         if (xrefsOnly && !AlignmentUtils.haveCrossRef(aaSeq, cdnaSeq))
330         {
331           continue;
332         }
333
334         /*
335          * Don't map non-xrefd sequences more than once each. This heuristic
336          * allows us to pair up similar sequences in ordered alignments.
337          */
338         if (!xrefsOnly
339                 && (mappedProtein.contains(aaSeq) || mappedDna
340                         .contains(cdnaSeq)))
341         {
342           continue;
343         }
344         if (mappingExists(proteinAlignment.getCodonFrames(),
345                 aaSeq.getDatasetSequence(), cdnaSeq.getDatasetSequence()))
346         {
347           mappingExistsOrAdded = true;
348         }
349         else
350         {
351           MapList map = mapCdnaToProtein(aaSeq, cdnaSeq);
352           if (map != null)
353           {
354             acf.addMap(cdnaSeq, aaSeq, map);
355             mappingExistsOrAdded = true;
356             proteinMapped = true;
357             mappedDna.add(cdnaSeq);
358             mappedProtein.add(aaSeq);
359           }
360         }
361       }
362       if (proteinMapped)
363       {
364         proteinAlignment.addCodonFrame(acf);
365       }
366     }
367     return mappingExistsOrAdded;
368   }
369
370   /**
371    * Answers true if the mappings include one between the given (dataset)
372    * sequences.
373    */
374   public static boolean mappingExists(List<AlignedCodonFrame> mappings,
375           SequenceI aaSeq, SequenceI cdnaSeq)
376   {
377     if (mappings != null)
378     {
379       for (AlignedCodonFrame acf : mappings)
380       {
381         if (cdnaSeq == acf.getDnaForAaSeq(aaSeq))
382         {
383           return true;
384         }
385       }
386     }
387     return false;
388   }
389
390   /**
391    * Builds a mapping (if possible) of a cDNA to a protein sequence.
392    * <ul>
393    * <li>first checks if the cdna translates exactly to the protein sequence</li>
394    * <li>else checks for translation after removing a STOP codon</li>
395    * <li>else checks for translation after removing a START codon</li>
396    * <li>if that fails, inspect CDS features on the cDNA sequence</li>
397    * </ul>
398    * Returns null if no mapping is determined.
399    * 
400    * @param proteinSeq
401    *          the aligned protein sequence
402    * @param cdnaSeq
403    *          the aligned cdna sequence
404    * @return
405    */
406   public static MapList mapCdnaToProtein(SequenceI proteinSeq,
407           SequenceI cdnaSeq)
408   {
409     /*
410      * Here we handle either dataset sequence set (desktop) or absent (applet).
411      * Use only the char[] form of the sequence to avoid creating possibly large
412      * String objects.
413      */
414     final SequenceI proteinDataset = proteinSeq.getDatasetSequence();
415     char[] aaSeqChars = proteinDataset != null ? proteinDataset
416             .getSequence() : proteinSeq.getSequence();
417     final SequenceI cdnaDataset = cdnaSeq.getDatasetSequence();
418     char[] cdnaSeqChars = cdnaDataset != null ? cdnaDataset.getSequence()
419             : cdnaSeq.getSequence();
420     if (aaSeqChars == null || cdnaSeqChars == null)
421     {
422       return null;
423     }
424
425     /*
426      * cdnaStart/End, proteinStartEnd are base 1 (for dataset sequence mapping)
427      */
428     final int mappedLength = 3 * aaSeqChars.length;
429     int cdnaLength = cdnaSeqChars.length;
430     int cdnaStart = cdnaSeq.getStart();
431     int cdnaEnd = cdnaSeq.getEnd();
432     final int proteinStart = proteinSeq.getStart();
433     final int proteinEnd = proteinSeq.getEnd();
434
435     /*
436      * If lengths don't match, try ignoring stop codon (if present)
437      */
438     if (cdnaLength != mappedLength && cdnaLength > 2)
439     {
440       String lastCodon = String.valueOf(cdnaSeqChars, cdnaLength - 3, 3)
441               .toUpperCase();
442       for (String stop : ResidueProperties.STOP)
443       {
444         if (lastCodon.equals(stop))
445         {
446           cdnaEnd -= 3;
447           cdnaLength -= 3;
448           break;
449         }
450       }
451     }
452
453     /*
454      * If lengths still don't match, try ignoring start codon.
455      */
456     int startOffset = 0;
457     if (cdnaLength != mappedLength
458             && cdnaLength > 2
459             && String.valueOf(cdnaSeqChars, 0, 3).toUpperCase()
460                     .equals(ResidueProperties.START))
461     {
462       startOffset += 3;
463       cdnaStart += 3;
464       cdnaLength -= 3;
465     }
466
467     if (translatesAs(cdnaSeqChars, startOffset, aaSeqChars))
468     {
469       /*
470        * protein is translation of dna (+/- start/stop codons)
471        */
472       MapList map = new MapList(new int[] { cdnaStart, cdnaEnd }, new int[]
473       { proteinStart, proteinEnd }, 3, 1);
474       return map;
475     }
476
477     /*
478      * translation failed - try mapping CDS annotated regions of dna
479      */
480     return mapCdsToProtein(cdnaSeq, proteinSeq);
481   }
482
483   /**
484    * Test whether the given cdna sequence, starting at the given offset,
485    * translates to the given amino acid sequence, using the standard translation
486    * table. Designed to fail fast i.e. as soon as a mismatch position is found.
487    * 
488    * @param cdnaSeqChars
489    * @param cdnaStart
490    * @param aaSeqChars
491    * @return
492    */
493   protected static boolean translatesAs(char[] cdnaSeqChars, int cdnaStart,
494           char[] aaSeqChars)
495   {
496     if (cdnaSeqChars == null || aaSeqChars == null)
497     {
498       return false;
499     }
500
501     int aaPos = 0;
502     int dnaPos = cdnaStart;
503     for (; dnaPos < cdnaSeqChars.length - 2
504             && aaPos < aaSeqChars.length; dnaPos += 3, aaPos++)
505     {
506       String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
507       final String translated = ResidueProperties.codonTranslate(codon);
508
509       /*
510        * allow * in protein to match untranslatable in dna
511        */
512       final char aaRes = aaSeqChars[aaPos];
513       if ((translated == null || "STOP".equals(translated)) && aaRes == '*')
514       {
515         continue;
516       }
517       if (translated == null || !(aaRes == translated.charAt(0)))
518       {
519         // debug
520         // System.out.println(("Mismatch at " + i + "/" + aaResidue + ": "
521         // + codon + "(" + translated + ") != " + aaRes));
522         return false;
523       }
524     }
525
526     /*
527      * check we matched all of the protein sequence
528      */
529     if (aaPos != aaSeqChars.length)
530     {
531       return false;
532     }
533
534     /*
535      * check we matched all of the dna except
536      * for optional trailing STOP codon
537      */
538     if (dnaPos == cdnaSeqChars.length)
539     {
540       return true;
541     }
542     if (dnaPos == cdnaSeqChars.length - 3)
543     {
544       String codon = String.valueOf(cdnaSeqChars, dnaPos, 3);
545       if ("STOP".equals(ResidueProperties.codonTranslate(codon)))
546       {
547         return true;
548       }
549     }
550     return false;
551   }
552
553   /**
554    * Align sequence 'seq' to match the alignment of a mapped sequence. Note this
555    * currently assumes that we are aligning cDNA to match protein.
556    * 
557    * @param seq
558    *          the sequence to be realigned
559    * @param al
560    *          the alignment whose sequence alignment is to be 'copied'
561    * @param gap
562    *          character string represent a gap in the realigned sequence
563    * @param preserveUnmappedGaps
564    * @param preserveMappedGaps
565    * @return true if the sequence was realigned, false if it could not be
566    */
567   public static boolean alignSequenceAs(SequenceI seq, AlignmentI al,
568           String gap, boolean preserveMappedGaps,
569           boolean preserveUnmappedGaps)
570   {
571     /*
572      * Get any mappings from the source alignment to the target (dataset)
573      * sequence.
574      */
575     // TODO there may be one AlignedCodonFrame per dataset sequence, or one with
576     // all mappings. Would it help to constrain this?
577     List<AlignedCodonFrame> mappings = al.getCodonFrame(seq);
578     if (mappings == null || mappings.isEmpty())
579     {
580       return false;
581     }
582
583     /*
584      * Locate the aligned source sequence whose dataset sequence is mapped. We
585      * just take the first match here (as we can't align like more than one
586      * sequence).
587      */
588     SequenceI alignFrom = null;
589     AlignedCodonFrame mapping = null;
590     for (AlignedCodonFrame mp : mappings)
591     {
592       alignFrom = mp.findAlignedSequence(seq, al);
593       if (alignFrom != null)
594       {
595         mapping = mp;
596         break;
597       }
598     }
599
600     if (alignFrom == null)
601     {
602       return false;
603     }
604     alignSequenceAs(seq, alignFrom, mapping, gap, al.getGapCharacter(),
605             preserveMappedGaps, preserveUnmappedGaps);
606     return true;
607   }
608
609   /**
610    * Align sequence 'alignTo' the same way as 'alignFrom', using the mapping to
611    * match residues and codons. Flags control whether existing gaps in unmapped
612    * (intron) and mapped (exon) regions are preserved or not. Gaps between
613    * intron and exon are only retained if both flags are set.
614    * 
615    * @param alignTo
616    * @param alignFrom
617    * @param mapping
618    * @param myGap
619    * @param sourceGap
620    * @param preserveUnmappedGaps
621    * @param preserveMappedGaps
622    */
623   public static void alignSequenceAs(SequenceI alignTo,
624           SequenceI alignFrom, AlignedCodonFrame mapping, String myGap,
625           char sourceGap, boolean preserveMappedGaps,
626           boolean preserveUnmappedGaps)
627   {
628     // TODO generalise to work for Protein-Protein, dna-dna, dna-protein
629
630     // aligned and dataset sequence positions, all base zero
631     int thisSeqPos = 0;
632     int sourceDsPos = 0;
633
634     int basesWritten = 0;
635     char myGapChar = myGap.charAt(0);
636     int ratio = myGap.length();
637
638     int fromOffset = alignFrom.getStart() - 1;
639     int toOffset = alignTo.getStart() - 1;
640     int sourceGapMappedLength = 0;
641     boolean inExon = false;
642     final char[] thisSeq = alignTo.getSequence();
643     final char[] thatAligned = alignFrom.getSequence();
644     StringBuilder thisAligned = new StringBuilder(2 * thisSeq.length);
645
646     /*
647      * Traverse the 'model' aligned sequence
648      */
649     for (char sourceChar : thatAligned)
650     {
651       if (sourceChar == sourceGap)
652       {
653         sourceGapMappedLength += ratio;
654         continue;
655       }
656
657       /*
658        * Found a non-gap character. Locate its mapped region if any.
659        */
660       sourceDsPos++;
661       // Note mapping positions are base 1, our sequence positions base 0
662       int[] mappedPos = mapping.getMappedRegion(alignTo, alignFrom,
663               sourceDsPos + fromOffset);
664       if (mappedPos == null)
665       {
666         /*
667          * unmapped position; treat like a gap
668          */
669         sourceGapMappedLength += ratio;
670         // System.err.println("Can't align: no codon mapping to residue "
671         // + sourceDsPos + "(" + sourceChar + ")");
672         // return;
673         continue;
674       }
675
676       int mappedCodonStart = mappedPos[0]; // position (1...) of codon start
677       int mappedCodonEnd = mappedPos[mappedPos.length - 1]; // codon end pos
678       StringBuilder trailingCopiedGap = new StringBuilder();
679
680       /*
681        * Copy dna sequence up to and including this codon. Optionally, include
682        * gaps before the codon starts (in introns) and/or after the codon starts
683        * (in exons).
684        * 
685        * Note this only works for 'linear' splicing, not reverse or interleaved.
686        * But then 'align dna as protein' doesn't make much sense otherwise.
687        */
688       int intronLength = 0;
689       while (basesWritten + toOffset < mappedCodonEnd
690               && thisSeqPos < thisSeq.length)
691       {
692         final char c = thisSeq[thisSeqPos++];
693         if (c != myGapChar)
694         {
695           basesWritten++;
696           int sourcePosition = basesWritten + toOffset;
697           if (sourcePosition < mappedCodonStart)
698           {
699             /*
700              * Found an unmapped (intron) base. First add in any preceding gaps
701              * (if wanted).
702              */
703             if (preserveUnmappedGaps && trailingCopiedGap.length() > 0)
704             {
705               thisAligned.append(trailingCopiedGap.toString());
706               intronLength += trailingCopiedGap.length();
707               trailingCopiedGap = new StringBuilder();
708             }
709             intronLength++;
710             inExon = false;
711           }
712           else
713           {
714             final boolean startOfCodon = sourcePosition == mappedCodonStart;
715             int gapsToAdd = calculateGapsToInsert(preserveMappedGaps,
716                     preserveUnmappedGaps, sourceGapMappedLength, inExon,
717                     trailingCopiedGap.length(), intronLength, startOfCodon);
718             for (int i = 0; i < gapsToAdd; i++)
719             {
720               thisAligned.append(myGapChar);
721             }
722             sourceGapMappedLength = 0;
723             inExon = true;
724           }
725           thisAligned.append(c);
726           trailingCopiedGap = new StringBuilder();
727         }
728         else
729         {
730           if (inExon && preserveMappedGaps)
731           {
732             trailingCopiedGap.append(myGapChar);
733           }
734           else if (!inExon && preserveUnmappedGaps)
735           {
736             trailingCopiedGap.append(myGapChar);
737           }
738         }
739       }
740     }
741
742     /*
743      * At end of model aligned sequence. Copy any remaining target sequence, optionally
744      * including (intron) gaps.
745      */
746     while (thisSeqPos < thisSeq.length)
747     {
748       final char c = thisSeq[thisSeqPos++];
749       if (c != myGapChar || preserveUnmappedGaps)
750       {
751         thisAligned.append(c);
752       }
753       sourceGapMappedLength--;
754     }
755
756     /*
757      * finally add gaps to pad for any trailing source gaps or
758      * unmapped characters
759      */
760     if (preserveUnmappedGaps)
761     {
762       while (sourceGapMappedLength > 0)
763       {
764         thisAligned.append(myGapChar);
765         sourceGapMappedLength--;
766       }
767     }
768
769     /*
770      * All done aligning, set the aligned sequence.
771      */
772     alignTo.setSequence(new String(thisAligned));
773   }
774
775   /**
776    * Helper method to work out how many gaps to insert when realigning.
777    * 
778    * @param preserveMappedGaps
779    * @param preserveUnmappedGaps
780    * @param sourceGapMappedLength
781    * @param inExon
782    * @param trailingCopiedGap
783    * @param intronLength
784    * @param startOfCodon
785    * @return
786    */
787   protected static int calculateGapsToInsert(boolean preserveMappedGaps,
788           boolean preserveUnmappedGaps, int sourceGapMappedLength,
789           boolean inExon, int trailingGapLength, int intronLength,
790           final boolean startOfCodon)
791   {
792     int gapsToAdd = 0;
793     if (startOfCodon)
794     {
795       /*
796        * Reached start of codon. Ignore trailing gaps in intron unless we are
797        * preserving gaps in both exon and intron. Ignore them anyway if the
798        * protein alignment introduces a gap at least as large as the intronic
799        * region.
800        */
801       if (inExon && !preserveMappedGaps)
802       {
803         trailingGapLength = 0;
804       }
805       if (!inExon && !(preserveMappedGaps && preserveUnmappedGaps))
806       {
807         trailingGapLength = 0;
808       }
809       if (inExon)
810       {
811         gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
812       }
813       else
814       {
815         if (intronLength + trailingGapLength <= sourceGapMappedLength)
816         {
817           gapsToAdd = sourceGapMappedLength - intronLength;
818         }
819         else
820         {
821           gapsToAdd = Math.min(intronLength + trailingGapLength
822                   - sourceGapMappedLength, trailingGapLength);
823         }
824       }
825     }
826     else
827     {
828       /*
829        * second or third base of codon; check for any gaps in dna
830        */
831       if (!preserveMappedGaps)
832       {
833         trailingGapLength = 0;
834       }
835       gapsToAdd = Math.max(sourceGapMappedLength, trailingGapLength);
836     }
837     return gapsToAdd;
838   }
839
840   /**
841    * Realigns the given protein to match the alignment of the dna, using codon
842    * mappings to translate aligned codon positions to protein residues.
843    * 
844    * @param protein
845    *          the alignment whose sequences are realigned by this method
846    * @param dna
847    *          the dna alignment whose alignment we are 'copying'
848    * @return the number of sequences that were realigned
849    */
850   public static int alignProteinAsDna(AlignmentI protein, AlignmentI dna)
851   {
852     List<SequenceI> unmappedProtein = new ArrayList<SequenceI>();
853     Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = buildCodonColumnsMap(
854             protein, dna, unmappedProtein);
855     return alignProteinAs(protein, alignedCodons, unmappedProtein);
856   }
857
858   /**
859    * Builds a map whose key is an aligned codon position (3 alignment column
860    * numbers base 0), and whose value is a map from protein sequence to each
861    * protein's peptide residue for that codon. The map generates an ordering of
862    * the codons, and allows us to read off the peptides at each position in
863    * order to assemble 'aligned' protein sequences.
864    * 
865    * @param protein
866    *          the protein alignment
867    * @param dna
868    *          the coding dna alignment
869    * @param unmappedProtein
870    *          any unmapped proteins are added to this list
871    * @return
872    */
873   protected static Map<AlignedCodon, Map<SequenceI, AlignedCodon>> buildCodonColumnsMap(
874           AlignmentI protein, AlignmentI dna,
875           List<SequenceI> unmappedProtein)
876   {
877     /*
878      * maintain a list of any proteins with no mappings - these will be
879      * rendered 'as is' in the protein alignment as we can't align them
880      */
881     unmappedProtein.addAll(protein.getSequences());
882
883     List<AlignedCodonFrame> mappings = protein.getCodonFrames();
884
885     /*
886      * Map will hold, for each aligned codon position e.g. [3, 5, 6], a map of
887      * {dnaSequence, {proteinSequence, codonProduct}} at that position. The
888      * comparator keeps the codon positions ordered.
889      */
890     Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons = new TreeMap<AlignedCodon, Map<SequenceI, AlignedCodon>>(
891             new CodonComparator());
892
893     for (SequenceI dnaSeq : dna.getSequences())
894     {
895       for (AlignedCodonFrame mapping : mappings)
896       {
897         SequenceI prot = mapping.findAlignedSequence(dnaSeq, protein);
898         if (prot != null)
899         {
900           Mapping seqMap = mapping.getMappingForSequence(dnaSeq);
901           addCodonPositions(dnaSeq, prot, protein.getGapCharacter(),
902                   seqMap, alignedCodons);
903           unmappedProtein.remove(prot);
904         }
905       }
906     }
907
908     /*
909      * Finally add any unmapped peptide start residues (e.g. for incomplete
910      * codons) as if at the codon position before the second residue
911      */
912     // TODO resolve JAL-2022 so this fudge can be removed
913     int mappedSequenceCount = protein.getHeight() - unmappedProtein.size();
914     addUnmappedPeptideStarts(alignedCodons, mappedSequenceCount);
915     
916     return alignedCodons;
917   }
918
919   /**
920    * Scans for any protein mapped from position 2 (meaning unmapped start
921    * position e.g. an incomplete codon), and synthesizes a 'codon' for it at the
922    * preceding position in the alignment
923    * 
924    * @param alignedCodons
925    *          the codon-to-peptide map
926    * @param mappedSequenceCount
927    *          the number of distinct sequences in the map
928    */
929   protected static void addUnmappedPeptideStarts(
930           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
931           int mappedSequenceCount)
932   {
933     // TODO delete this ugly hack once JAL-2022 is resolved
934     // i.e. we can model startPhase > 0 (incomplete start codon)
935
936     List<SequenceI> sequencesChecked = new ArrayList<SequenceI>();
937     AlignedCodon lastCodon = null;
938     Map<SequenceI, AlignedCodon> toAdd = new HashMap<SequenceI, AlignedCodon>();
939
940     for (Entry<AlignedCodon, Map<SequenceI, AlignedCodon>> entry : alignedCodons
941             .entrySet())
942     {
943       for (Entry<SequenceI, AlignedCodon> sequenceCodon : entry.getValue()
944               .entrySet())
945       {
946         SequenceI seq = sequenceCodon.getKey();
947         if (sequencesChecked.contains(seq))
948         {
949           continue;
950         }
951         sequencesChecked.add(seq);
952         AlignedCodon codon = sequenceCodon.getValue();
953         if (codon.peptideCol > 1)
954         {
955           System.err
956                   .println("Problem mapping protein with >1 unmapped start positions: "
957                           + seq.getName());
958         }
959         else if (codon.peptideCol == 1)
960         {
961           /*
962            * first position (peptideCol == 0) was unmapped - add it
963            */
964           if (lastCodon != null)
965           {
966             AlignedCodon firstPeptide = new AlignedCodon(lastCodon.pos1,
967                     lastCodon.pos2, lastCodon.pos3, String.valueOf(seq
968                             .getCharAt(0)), 0);
969             toAdd.put(seq, firstPeptide);
970           }
971           else
972           {
973             /*
974              * unmapped residue at start of alignment (no prior column) -
975              * 'insert' at nominal codon [0, 0, 0]
976              */
977             AlignedCodon firstPeptide = new AlignedCodon(0, 0, 0,
978                     String.valueOf(seq.getCharAt(0)), 0);
979             toAdd.put(seq, firstPeptide);
980           }
981         }
982         if (sequencesChecked.size() == mappedSequenceCount)
983         {
984           // no need to check past first mapped position in all sequences
985           break;
986         }
987       }
988       lastCodon = entry.getKey();
989     }
990
991     /*
992      * add any new codons safely after iterating over the map
993      */
994     for (Entry<SequenceI, AlignedCodon> startCodon : toAdd.entrySet())
995     {
996       addCodonToMap(alignedCodons, startCodon.getValue(),
997               startCodon.getKey());
998     }
999   }
1000
1001   /**
1002    * Update the aligned protein sequences to match the codon alignments given in
1003    * the map.
1004    * 
1005    * @param protein
1006    * @param alignedCodons
1007    *          an ordered map of codon positions (columns), with sequence/peptide
1008    *          values present in each column
1009    * @param unmappedProtein
1010    * @return
1011    */
1012   protected static int alignProteinAs(AlignmentI protein,
1013           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1014           List<SequenceI> unmappedProtein)
1015   {
1016     /*
1017      * Prefill aligned sequences with gaps before inserting aligned protein
1018      * residues.
1019      */
1020     int alignedWidth = alignedCodons.size();
1021     char[] gaps = new char[alignedWidth];
1022     Arrays.fill(gaps, protein.getGapCharacter());
1023     String allGaps = String.valueOf(gaps);
1024     for (SequenceI seq : protein.getSequences())
1025     {
1026       if (!unmappedProtein.contains(seq))
1027       {
1028         seq.setSequence(allGaps);
1029       }
1030     }
1031
1032     int column = 0;
1033     for (AlignedCodon codon : alignedCodons.keySet())
1034     {
1035       final Map<SequenceI, AlignedCodon> columnResidues = alignedCodons
1036               .get(codon);
1037       for (Entry<SequenceI, AlignedCodon> entry : columnResidues.entrySet())
1038       {
1039         // place translated codon at its column position in sequence
1040         entry.getKey().getSequence()[column] = entry.getValue().product
1041                 .charAt(0);
1042       }
1043       column++;
1044     }
1045     return 0;
1046   }
1047
1048   /**
1049    * Populate the map of aligned codons by traversing the given sequence
1050    * mapping, locating the aligned positions of mapped codons, and adding those
1051    * positions and their translation products to the map.
1052    * 
1053    * @param dna
1054    *          the aligned sequence we are mapping from
1055    * @param protein
1056    *          the sequence to be aligned to the codons
1057    * @param gapChar
1058    *          the gap character in the dna sequence
1059    * @param seqMap
1060    *          a mapping to a sequence translation
1061    * @param alignedCodons
1062    *          the map we are building up
1063    */
1064   static void addCodonPositions(SequenceI dna, SequenceI protein,
1065           char gapChar, Mapping seqMap,
1066           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons)
1067   {
1068     Iterator<AlignedCodon> codons = seqMap.getCodonIterator(dna, gapChar);
1069
1070     /*
1071      * add codon positions, and their peptide translations, to the alignment
1072      * map, while remembering the first codon mapped
1073      */
1074     while (codons.hasNext())
1075     {
1076       try
1077       {
1078         AlignedCodon codon = codons.next();
1079         addCodonToMap(alignedCodons, codon, protein);
1080       } catch (IncompleteCodonException e)
1081       {
1082         // possible incomplete trailing codon - ignore
1083       } catch (NoSuchElementException e)
1084       {
1085         // possibly peptide lacking STOP
1086       }
1087     }
1088   }
1089
1090   /**
1091    * Helper method to add a codon-to-peptide entry to the aligned codons map
1092    * 
1093    * @param alignedCodons
1094    * @param codon
1095    * @param protein
1096    */
1097   protected static void addCodonToMap(
1098           Map<AlignedCodon, Map<SequenceI, AlignedCodon>> alignedCodons,
1099           AlignedCodon codon, SequenceI protein)
1100   {
1101     Map<SequenceI, AlignedCodon> seqProduct = alignedCodons.get(codon);
1102     if (seqProduct == null)
1103     {
1104       seqProduct = new HashMap<SequenceI, AlignedCodon>();
1105       alignedCodons.put(codon, seqProduct);
1106     }
1107     seqProduct.put(protein, codon);
1108   }
1109
1110   /**
1111    * Returns true if a cDNA/Protein mapping either exists, or could be made,
1112    * between at least one pair of sequences in the two alignments. Currently,
1113    * the logic is:
1114    * <ul>
1115    * <li>One alignment must be nucleotide, and the other protein</li>
1116    * <li>At least one pair of sequences must be already mapped, or mappable</li>
1117    * <li>Mappable means the nucleotide translation matches the protein sequence</li>
1118    * <li>The translation may ignore start and stop codons if present in the
1119    * nucleotide</li>
1120    * </ul>
1121    * 
1122    * @param al1
1123    * @param al2
1124    * @return
1125    */
1126   public static boolean isMappable(AlignmentI al1, AlignmentI al2)
1127   {
1128     if (al1 == null || al2 == null)
1129     {
1130       return false;
1131     }
1132
1133     /*
1134      * Require one nucleotide and one protein
1135      */
1136     if (al1.isNucleotide() == al2.isNucleotide())
1137     {
1138       return false;
1139     }
1140     AlignmentI dna = al1.isNucleotide() ? al1 : al2;
1141     AlignmentI protein = dna == al1 ? al2 : al1;
1142     List<AlignedCodonFrame> mappings = protein.getCodonFrames();
1143     for (SequenceI dnaSeq : dna.getSequences())
1144     {
1145       for (SequenceI proteinSeq : protein.getSequences())
1146       {
1147         if (isMappable(dnaSeq, proteinSeq, mappings))
1148         {
1149           return true;
1150         }
1151       }
1152     }
1153     return false;
1154   }
1155
1156   /**
1157    * Returns true if the dna sequence is mapped, or could be mapped, to the
1158    * protein sequence.
1159    * 
1160    * @param dnaSeq
1161    * @param proteinSeq
1162    * @param mappings
1163    * @return
1164    */
1165   protected static boolean isMappable(SequenceI dnaSeq,
1166           SequenceI proteinSeq, List<AlignedCodonFrame> mappings)
1167   {
1168     if (dnaSeq == null || proteinSeq == null)
1169     {
1170       return false;
1171     }
1172
1173     SequenceI dnaDs = dnaSeq.getDatasetSequence() == null ? dnaSeq : dnaSeq
1174             .getDatasetSequence();
1175     SequenceI proteinDs = proteinSeq.getDatasetSequence() == null ? proteinSeq
1176             : proteinSeq.getDatasetSequence();
1177
1178     for (AlignedCodonFrame mapping : mappings)
1179     {
1180       if (proteinDs == mapping.getAaForDnaSeq(dnaDs))
1181       {
1182         /*
1183          * already mapped
1184          */
1185         return true;
1186       }
1187     }
1188
1189     /*
1190      * Just try to make a mapping (it is not yet stored), test whether
1191      * successful.
1192      */
1193     return mapCdnaToProtein(proteinDs, dnaDs) != null;
1194   }
1195
1196   /**
1197    * Finds any reference annotations associated with the sequences in
1198    * sequenceScope, that are not already added to the alignment, and adds them
1199    * to the 'candidates' map. Also populates a lookup table of annotation
1200    * labels, keyed by calcId, for use in constructing tooltips or the like.
1201    * 
1202    * @param sequenceScope
1203    *          the sequences to scan for reference annotations
1204    * @param labelForCalcId
1205    *          (optional) map to populate with label for calcId
1206    * @param candidates
1207    *          map to populate with annotations for sequence
1208    * @param al
1209    *          the alignment to check for presence of annotations
1210    */
1211   public static void findAddableReferenceAnnotations(
1212           List<SequenceI> sequenceScope,
1213           Map<String, String> labelForCalcId,
1214           final Map<SequenceI, List<AlignmentAnnotation>> candidates,
1215           AlignmentI al)
1216   {
1217     if (sequenceScope == null)
1218     {
1219       return;
1220     }
1221
1222     /*
1223      * For each sequence in scope, make a list of any annotations on the
1224      * underlying dataset sequence which are not already on the alignment.
1225      * 
1226      * Add to a map of { alignmentSequence, <List of annotations to add> }
1227      */
1228     for (SequenceI seq : sequenceScope)
1229     {
1230       SequenceI dataset = seq.getDatasetSequence();
1231       if (dataset == null)
1232       {
1233         continue;
1234       }
1235       AlignmentAnnotation[] datasetAnnotations = dataset.getAnnotation();
1236       if (datasetAnnotations == null)
1237       {
1238         continue;
1239       }
1240       final List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1241       for (AlignmentAnnotation dsann : datasetAnnotations)
1242       {
1243         /*
1244          * Find matching annotations on the alignment. If none is found, then
1245          * add this annotation to the list of 'addable' annotations for this
1246          * sequence.
1247          */
1248         final Iterable<AlignmentAnnotation> matchedAlignmentAnnotations = al
1249                 .findAnnotations(seq, dsann.getCalcId(), dsann.label);
1250         if (!matchedAlignmentAnnotations.iterator().hasNext())
1251         {
1252           result.add(dsann);
1253           if (labelForCalcId != null)
1254           {
1255             labelForCalcId.put(dsann.getCalcId(), dsann.label);
1256           }
1257         }
1258       }
1259       /*
1260        * Save any addable annotations for this sequence
1261        */
1262       if (!result.isEmpty())
1263       {
1264         candidates.put(seq, result);
1265       }
1266     }
1267   }
1268
1269   /**
1270    * Adds annotations to the top of the alignment annotations, in the same order
1271    * as their related sequences.
1272    * 
1273    * @param annotations
1274    *          the annotations to add
1275    * @param alignment
1276    *          the alignment to add them to
1277    * @param selectionGroup
1278    *          current selection group (or null if none)
1279    */
1280   public static void addReferenceAnnotations(
1281           Map<SequenceI, List<AlignmentAnnotation>> annotations,
1282           final AlignmentI alignment, final SequenceGroup selectionGroup)
1283   {
1284     for (SequenceI seq : annotations.keySet())
1285     {
1286       for (AlignmentAnnotation ann : annotations.get(seq))
1287       {
1288         AlignmentAnnotation copyAnn = new AlignmentAnnotation(ann);
1289         int startRes = 0;
1290         int endRes = ann.annotations.length;
1291         if (selectionGroup != null)
1292         {
1293           startRes = selectionGroup.getStartRes();
1294           endRes = selectionGroup.getEndRes();
1295         }
1296         copyAnn.restrict(startRes, endRes);
1297
1298         /*
1299          * Add to the sequence (sets copyAnn.datasetSequence), unless the
1300          * original annotation is already on the sequence.
1301          */
1302         if (!seq.hasAnnotation(ann))
1303         {
1304           seq.addAlignmentAnnotation(copyAnn);
1305         }
1306         // adjust for gaps
1307         copyAnn.adjustForAlignment();
1308         // add to the alignment and set visible
1309         alignment.addAnnotation(copyAnn);
1310         copyAnn.visible = true;
1311       }
1312     }
1313   }
1314
1315   /**
1316    * Set visibility of alignment annotations of specified types (labels), for
1317    * specified sequences. This supports controls like
1318    * "Show all secondary structure", "Hide all Temp factor", etc.
1319    * 
1320    * @al the alignment to scan for annotations
1321    * @param types
1322    *          the types (labels) of annotations to be updated
1323    * @param forSequences
1324    *          if not null, only annotations linked to one of these sequences are
1325    *          in scope for update; if null, acts on all sequence annotations
1326    * @param anyType
1327    *          if this flag is true, 'types' is ignored (label not checked)
1328    * @param doShow
1329    *          if true, set visibility on, else set off
1330    */
1331   public static void showOrHideSequenceAnnotations(AlignmentI al,
1332           Collection<String> types, List<SequenceI> forSequences,
1333           boolean anyType, boolean doShow)
1334   {
1335     for (AlignmentAnnotation aa : al.getAlignmentAnnotation())
1336     {
1337       if (anyType || types.contains(aa.label))
1338       {
1339         if ((aa.sequenceRef != null)
1340                 && (forSequences == null || forSequences
1341                         .contains(aa.sequenceRef)))
1342         {
1343           aa.visible = doShow;
1344         }
1345       }
1346     }
1347   }
1348
1349   /**
1350    * Returns true if either sequence has a cross-reference to the other
1351    * 
1352    * @param seq1
1353    * @param seq2
1354    * @return
1355    */
1356   public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1357   {
1358     // Note: moved here from class CrossRef as the latter class has dependencies
1359     // not availability to the applet's classpath
1360     return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1361   }
1362
1363   /**
1364    * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1365    * that sequence name is structured as Source|AccessionId.
1366    * 
1367    * @param seq1
1368    * @param seq2
1369    * @return
1370    */
1371   public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1372   {
1373     if (seq1 == null || seq2 == null)
1374     {
1375       return false;
1376     }
1377     String name = seq2.getName();
1378     final DBRefEntry[] xrefs = seq1.getDBRefs();
1379     if (xrefs != null)
1380     {
1381       for (DBRefEntry xref : xrefs)
1382       {
1383         String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1384         // case-insensitive test, consistent with DBRefEntry.equalRef()
1385         if (xrefName.equalsIgnoreCase(name))
1386         {
1387           return true;
1388         }
1389       }
1390     }
1391     return false;
1392   }
1393
1394   /**
1395    * Constructs an alignment consisting of the mapped (CDS) regions in the given
1396    * nucleotide sequences, and updates mappings to match. The CDS sequences are
1397    * added to the original alignment's dataset, which is shared by the new
1398    * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1399    * added to the alignment dataset.
1400    * 
1401    * @param dna
1402    *          aligned dna sequences
1403    * @param mappings
1404    *          from dna to protein
1405    * @param al
1406    * @return an alignment whose sequences are the cds-only parts of the dna
1407    *         sequences (or null if no mappings are found)
1408    */
1409   public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1410           List<AlignedCodonFrame> mappings, AlignmentI al)
1411   {
1412     List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1413     
1414     for (SequenceI seq : dna)
1415     {
1416       AlignedCodonFrame cdsMappings = new AlignedCodonFrame();
1417       List<AlignedCodonFrame> seqMappings = MappingUtils
1418               .findMappingsForSequence(seq, mappings);
1419       List<AlignedCodonFrame> alignmentMappings = al.getCodonFrames();
1420       for (AlignedCodonFrame mapping : seqMappings)
1421       {
1422         for (Mapping aMapping : mapping.getMappingsFromSequence(seq))
1423         {
1424           SequenceI cdsSeq = makeCdsSequence(seq.getDatasetSequence(),
1425                   aMapping);
1426           cdsSeqs.add(cdsSeq);
1427     
1428           /*
1429            * add a mapping from CDS to the (unchanged) mapped to range
1430            */
1431           List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1432               cdsSeq.getLength() });
1433           MapList map = new MapList(cdsRange, aMapping.getMap()
1434                   .getToRanges(), aMapping.getMap().getFromRatio(),
1435                   aMapping.getMap().getToRatio());
1436           cdsMappings.addMap(cdsSeq, aMapping.getTo(), map);
1437
1438           /*
1439            * add another mapping from original 'from' range to CDS
1440            */
1441           map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
1442                   1);
1443           cdsMappings.addMap(seq.getDatasetSequence(), cdsSeq, map);
1444
1445           alignmentMappings.add(cdsMappings);
1446
1447           /*
1448            * transfer any features on dna that overlap the CDS
1449            */
1450           transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
1451         }
1452       }
1453     }
1454
1455     /*
1456      * add CDS seqs to shared dataset
1457      */
1458     Alignment dataset = al.getDataset();
1459     for (SequenceI seq : cdsSeqs)
1460     {
1461       if (!dataset.getSequences().contains(seq.getDatasetSequence()))
1462       {
1463         dataset.addSequence(seq.getDatasetSequence());
1464       }
1465     }
1466     AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1467             .size()]));
1468     cds.setDataset(dataset);
1469
1470     return cds;
1471   }
1472
1473   /**
1474    * Helper method that makes a CDS sequence as defined by the mappings from the
1475    * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1476    * forward or reverse strand).
1477    * 
1478    * @param seq
1479    * @param mapping
1480    * @return
1481    */
1482   static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1483   {
1484     char[] seqChars = seq.getSequence();
1485     List<int[]> fromRanges = mapping.getMap().getFromRanges();
1486     int cdsWidth = MappingUtils.getLength(fromRanges);
1487     char[] newSeqChars = new char[cdsWidth];
1488
1489     int newPos = 0;
1490     for (int[] range : fromRanges)
1491     {
1492       if (range[0] <= range[1])
1493       {
1494         // forward strand mapping - just copy the range
1495         int length = range[1] - range[0] + 1;
1496         System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1497                 length);
1498         newPos += length;
1499       }
1500       else
1501       {
1502         // reverse strand mapping - copy and complement one by one
1503         for (int i = range[0]; i >= range[1]; i--)
1504         {
1505           newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1506         }
1507       }
1508     }
1509
1510     SequenceI newSeq = new Sequence(seq.getName() + "|"
1511             + mapping.getTo().getName(), newSeqChars, 1, newPos);
1512     newSeq.createDatasetSequence();
1513     return newSeq;
1514   }
1515
1516   /**
1517    * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1518    * feature start/end ranges, optionally omitting specified feature types.
1519    * Returns the number of features copied.
1520    * 
1521    * @param fromSeq
1522    * @param toSeq
1523    * @param select
1524    *          if not null, only features of this type are copied (including
1525    *          subtypes in the Sequence Ontology)
1526    * @param mapping
1527    *          the mapping from 'fromSeq' to 'toSeq'
1528    * @param omitting
1529    */
1530   public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1531           MapList mapping, String select, String... omitting)
1532   {
1533     SequenceI copyTo = toSeq;
1534     while (copyTo.getDatasetSequence() != null)
1535     {
1536       copyTo = copyTo.getDatasetSequence();
1537     }
1538
1539     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1540     int count = 0;
1541     SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1542     if (sfs != null)
1543     {
1544       for (SequenceFeature sf : sfs)
1545       {
1546         String type = sf.getType();
1547         if (select != null && !so.isA(type, select))
1548         {
1549           continue;
1550         }
1551         boolean omit = false;
1552         for (String toOmit : omitting)
1553         {
1554           if (type.equals(toOmit))
1555           {
1556             omit = true;
1557           }
1558         }
1559         if (omit)
1560         {
1561           continue;
1562         }
1563
1564         /*
1565          * locate the mapped range - null if either start or end is
1566          * not mapped (no partial overlaps are calculated)
1567          */
1568         int start = sf.getBegin();
1569         int end = sf.getEnd();
1570         int[] mappedTo = mapping.locateInTo(start, end);
1571         /*
1572          * if whole exon range doesn't map, try interpreting it
1573          * as 5' or 3' exon overlapping the CDS range
1574          */
1575         if (mappedTo == null)
1576         {
1577           mappedTo = mapping.locateInTo(end, end);
1578           if (mappedTo != null)
1579           {
1580             /*
1581              * end of exon is in CDS range - 5' overlap
1582              * to a range from the start of the peptide
1583              */
1584             mappedTo[0] = 1;
1585           }
1586         }
1587         if (mappedTo == null)
1588         {
1589           mappedTo = mapping.locateInTo(start, start);
1590           if (mappedTo != null)
1591           {
1592             /*
1593              * start of exon is in CDS range - 3' overlap
1594              * to a range up to the end of the peptide
1595              */
1596             mappedTo[1] = toSeq.getLength();
1597           }
1598         }
1599         if (mappedTo != null)
1600         {
1601           SequenceFeature copy = new SequenceFeature(sf);
1602           copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1603           copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1604           copyTo.addSequenceFeature(copy);
1605           count++;
1606         }
1607       }
1608     }
1609     return count;
1610   }
1611
1612   /**
1613    * Returns a mapping from dna to protein by inspecting sequence features of
1614    * type "CDS" on the dna.
1615    * 
1616    * @param dnaSeq
1617    * @param proteinSeq
1618    * @return
1619    */
1620   public static MapList mapCdsToProtein(SequenceI dnaSeq,
1621           SequenceI proteinSeq)
1622   {
1623     List<int[]> ranges = findCdsPositions(dnaSeq);
1624     int mappedDnaLength = MappingUtils.getLength(ranges);
1625
1626     int proteinLength = proteinSeq.getLength();
1627     int proteinStart = proteinSeq.getStart();
1628     int proteinEnd = proteinSeq.getEnd();
1629
1630     /*
1631      * incomplete start codon may mean X at start of peptide
1632      * we ignore both for mapping purposes
1633      */
1634     if (proteinSeq.getCharAt(0) == 'X')
1635     {
1636       // todo JAL-2022 support startPhase > 0
1637       proteinStart++;
1638       proteinLength--;
1639     }
1640     List<int[]> proteinRange = new ArrayList<int[]>();
1641
1642     /*
1643      * dna length should map to protein (or protein plus stop codon)
1644      */
1645     int codesForResidues = mappedDnaLength / 3;
1646     if (codesForResidues == (proteinLength + 1))
1647     {
1648       // assuming extra codon is for STOP and not in peptide
1649       codesForResidues--;
1650     }
1651     if (codesForResidues == proteinLength)
1652     {
1653       proteinRange.add(new int[] { proteinStart, proteinEnd });
1654       return new MapList(ranges, proteinRange, 3, 1);
1655     }
1656     return null;
1657   }
1658
1659   /**
1660    * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
1661    * start/end positions of sequence features of type "CDS" (or a sub-type of
1662    * CDS in the Sequence Ontology). The ranges are sorted into ascending start
1663    * position order, so this method is only valid for linear CDS in the same
1664    * sense as the protein product.
1665    * 
1666    * @param dnaSeq
1667    * @return
1668    */
1669   public static List<int[]> findCdsPositions(SequenceI dnaSeq)
1670   {
1671     List<int[]> result = new ArrayList<int[]>();
1672     SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
1673     if (sfs == null)
1674     {
1675       return result;
1676     }
1677
1678     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1679     int startPhase = 0;
1680
1681     for (SequenceFeature sf : sfs)
1682     {
1683       /*
1684        * process a CDS feature (or a sub-type of CDS)
1685        */
1686       if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1687       {
1688         int phase = 0;
1689         try
1690         {
1691           phase = Integer.parseInt(sf.getPhase());
1692         } catch (NumberFormatException e)
1693         {
1694           // ignore
1695         }
1696         /*
1697          * phase > 0 on first codon means 5' incomplete - skip to the start
1698          * of the next codon; example ENST00000496384
1699          */
1700         int begin = sf.getBegin();
1701         int end = sf.getEnd();
1702         if (result.isEmpty())
1703         {
1704           begin += phase;
1705           if (begin > end)
1706           {
1707             // shouldn't happen!
1708             System.err
1709                     .println("Error: start phase extends beyond start CDS in "
1710                             + dnaSeq.getName());
1711           }
1712         }
1713         result.add(new int[] { begin, end });
1714       }
1715     }
1716
1717     /*
1718      * remove 'startPhase' positions (usually 0) from the first range 
1719      * so we begin at the start of a complete codon
1720      */
1721     if (!result.isEmpty())
1722     {
1723       // TODO JAL-2022 correctly model start phase > 0
1724       result.get(0)[0] += startPhase;
1725     }
1726
1727     /*
1728      * Finally sort ranges by start position. This avoids a dependency on 
1729      * keeping features in order on the sequence (if they are in order anyway,
1730      * the sort will have almost no work to do). The implicit assumption is CDS
1731      * ranges are assembled in order. Other cases should not use this method,
1732      * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
1733      */
1734     Collections.sort(result, new Comparator<int[]>()
1735     {
1736       @Override
1737       public int compare(int[] o1, int[] o2)
1738       {
1739         return Integer.compare(o1[0], o2[0]);
1740       }
1741     });
1742     return result;
1743   }
1744
1745   /**
1746    * Maps exon features from dna to protein, and computes variants in peptide
1747    * product generated by variants in dna, and adds them as sequence_variant
1748    * features on the protein sequence. Returns the number of variant features
1749    * added.
1750    * 
1751    * @param dnaSeq
1752    * @param peptide
1753    * @param dnaToProtein
1754    */
1755   public static int computeProteinFeatures(SequenceI dnaSeq,
1756           SequenceI peptide, MapList dnaToProtein)
1757   {
1758     while (dnaSeq.getDatasetSequence() != null)
1759     {
1760       dnaSeq = dnaSeq.getDatasetSequence();
1761     }
1762     while (peptide.getDatasetSequence() != null)
1763     {
1764       peptide = peptide.getDatasetSequence();
1765     }
1766
1767     transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
1768
1769     /*
1770      * compute protein variants from dna variants and codon mappings;
1771      * NB - alternatively we could retrieve this using the REST service e.g.
1772      * http://rest.ensembl.org/overlap/translation
1773      * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
1774      * which would be a bit slower but possibly more reliable
1775      */
1776
1777     /*
1778      * build a map with codon variations for each potentially varying peptide
1779      */
1780     LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
1781             dnaSeq, dnaToProtein);
1782
1783     /*
1784      * scan codon variations, compute peptide variants and add to peptide sequence
1785      */
1786     int count = 0;
1787     for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
1788     {
1789       int peptidePos = variant.getKey();
1790       List<DnaVariant>[] codonVariants = variant.getValue();
1791       count += computePeptideVariants(peptide, peptidePos, codonVariants);
1792     }
1793
1794     /*
1795      * sort to get sequence features in start position order
1796      * - would be better to store in Sequence as a TreeSet or NCList?
1797      */
1798     Arrays.sort(peptide.getSequenceFeatures(),
1799             new Comparator<SequenceFeature>()
1800             {
1801               @Override
1802               public int compare(SequenceFeature o1, SequenceFeature o2)
1803               {
1804                 int c = Integer.compare(o1.getBegin(), o2.getBegin());
1805                 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
1806                         : c;
1807               }
1808             });
1809     return count;
1810   }
1811
1812   /**
1813    * Computes non-synonymous peptide variants from codon variants and adds them
1814    * as sequence_variant features on the protein sequence (one feature per
1815    * allele variant). Selected attributes (variant id, clinical significance)
1816    * are copied over to the new features.
1817    * 
1818    * @param peptide
1819    *          the protein sequence
1820    * @param peptidePos
1821    *          the position to compute peptide variants for
1822    * @param codonVariants
1823    *          a list of dna variants per codon position
1824    * @return the number of features added
1825    */
1826   static int computePeptideVariants(SequenceI peptide, int peptidePos,
1827           List<DnaVariant>[] codonVariants)
1828   {
1829     String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
1830     int count = 0;
1831     String base1 = codonVariants[0].get(0).base;
1832     String base2 = codonVariants[1].get(0).base;
1833     String base3 = codonVariants[2].get(0).base;
1834
1835     /*
1836      * variants in first codon base
1837      */
1838     for (DnaVariant var : codonVariants[0])
1839     {
1840       if (var.variant != null)
1841       {
1842         String alleles = (String) var.variant.getValue("alleles");
1843         if (alleles != null)
1844         {
1845           for (String base : alleles.split(","))
1846           {
1847             String codon = base + base2 + base3;
1848             if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1849             {
1850               count++;
1851             }
1852           }
1853         }
1854       }
1855     }
1856
1857     /*
1858      * variants in second codon base
1859      */
1860     for (DnaVariant var : codonVariants[1])
1861     {
1862       if (var.variant != null)
1863       {
1864         String alleles = (String) var.variant.getValue("alleles");
1865         if (alleles != null)
1866         {
1867           for (String base : alleles.split(","))
1868           {
1869             String codon = base1 + base + base3;
1870             if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1871             {
1872               count++;
1873             }
1874           }
1875         }
1876       }
1877     }
1878
1879     /*
1880      * variants in third codon base
1881      */
1882     for (DnaVariant var : codonVariants[2])
1883     {
1884       if (var.variant != null)
1885       {
1886         String alleles = (String) var.variant.getValue("alleles");
1887         if (alleles != null)
1888         {
1889           for (String base : alleles.split(","))
1890           {
1891             String codon = base1 + base2 + base;
1892             if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1893             {
1894               count++;
1895             }
1896           }
1897         }
1898       }
1899     }
1900
1901     return count;
1902   }
1903
1904   /**
1905    * Helper method that adds a peptide variant feature, provided the given codon
1906    * translates to a value different to the current residue (is a non-synonymous
1907    * variant). ID and clinical_significance attributes of the dna variant (if
1908    * present) are copied to the new feature.
1909    * 
1910    * @param peptide
1911    * @param peptidePos
1912    * @param residue
1913    * @param var
1914    * @param codon
1915    * @return true if a feature was added, else false
1916    */
1917   static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
1918           String residue, DnaVariant var, String codon)
1919   {
1920     /*
1921      * get peptide translation of codon e.g. GAT -> D
1922      * note that variants which are not single alleles,
1923      * e.g. multibase variants or HGMD_MUTATION etc
1924      * are currently ignored here
1925      */
1926     String trans = codon.contains("-") ? "-"
1927             : (codon.length() > 3 ? null : ResidueProperties
1928                     .codonTranslate(codon));
1929     if (trans != null && !trans.equals(residue))
1930     {
1931       String residue3Char = StringUtils
1932               .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
1933       String trans3Char = StringUtils
1934               .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
1935       String desc = "p." + residue3Char + peptidePos + trans3Char;
1936       // set score to 0f so 'graduated colour' option is offered! JAL-2060
1937       SequenceFeature sf = new SequenceFeature(
1938               SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
1939               peptidePos, 0f, "Jalview");
1940       StringBuilder attributes = new StringBuilder(32);
1941       String id = (String) var.variant.getValue(ID);
1942       if (id != null)
1943       {
1944         if (id.startsWith(SEQUENCE_VARIANT))
1945         {
1946           id = id.substring(SEQUENCE_VARIANT.length());
1947         }
1948         sf.setValue(ID, id);
1949         attributes.append(ID).append("=").append(id);
1950         // TODO handle other species variants
1951         StringBuilder link = new StringBuilder(32);
1952         try
1953         {
1954           link.append(desc).append(" ").append(id)
1955                   .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
1956                   .append(URLEncoder.encode(id, "UTF-8"));
1957           sf.addLink(link.toString());
1958         } catch (UnsupportedEncodingException e)
1959         {
1960           // as if
1961         }
1962       }
1963       String clinSig = (String) var.variant
1964               .getValue(CLINICAL_SIGNIFICANCE);
1965       if (clinSig != null)
1966       {
1967         sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
1968         attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
1969                 .append(clinSig);
1970       }
1971       peptide.addSequenceFeature(sf);
1972       if (attributes.length() > 0)
1973       {
1974         sf.setAttributes(attributes.toString());
1975       }
1976       return true;
1977     }
1978     return false;
1979   }
1980
1981   /**
1982    * Builds a map whose key is position in the protein sequence, and value is a
1983    * list of the base and all variants for each corresponding codon position
1984    * 
1985    * @param dnaSeq
1986    * @param dnaToProtein
1987    * @return
1988    */
1989   static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
1990           SequenceI dnaSeq, MapList dnaToProtein)
1991   {
1992     /*
1993      * map from peptide position to all variants of the codon which codes for it
1994      * LinkedHashMap ensures we keep the peptide features in sequence order
1995      */
1996     LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
1997     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1998
1999     SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2000     if (dnaFeatures == null)
2001     {
2002       return variants;
2003     }
2004
2005     int dnaStart = dnaSeq.getStart();
2006     int[] lastCodon = null;
2007     int lastPeptidePostion = 0;
2008
2009     /*
2010      * build a map of codon variations for peptides
2011      */
2012     for (SequenceFeature sf : dnaFeatures)
2013     {
2014       int dnaCol = sf.getBegin();
2015       if (dnaCol != sf.getEnd())
2016       {
2017         // not handling multi-locus variant features
2018         continue;
2019       }
2020       if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2021       {
2022         int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2023         if (mapsTo == null)
2024         {
2025           // feature doesn't lie within coding region
2026           continue;
2027         }
2028         int peptidePosition = mapsTo[0];
2029         List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2030         if (codonVariants == null)
2031         {
2032           codonVariants = new ArrayList[3];
2033           codonVariants[0] = new ArrayList<DnaVariant>();
2034           codonVariants[1] = new ArrayList<DnaVariant>();
2035           codonVariants[2] = new ArrayList<DnaVariant>();
2036           variants.put(peptidePosition, codonVariants);
2037         }
2038
2039         /*
2040          * extract dna variants to a string array
2041          */
2042         String alls = (String) sf.getValue("alleles");
2043         if (alls == null)
2044         {
2045           continue;
2046         }
2047         String[] alleles = alls.toUpperCase().split(",");
2048         int i = 0;
2049         for (String allele : alleles)
2050         {
2051           alleles[i++] = allele.trim(); // lose any space characters "A, G"
2052         }
2053
2054         /*
2055          * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2056          */
2057         int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2058                 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2059                         peptidePosition, peptidePosition));
2060         lastPeptidePostion = peptidePosition;
2061         lastCodon = codon;
2062
2063         /*
2064          * save nucleotide (and any variant) for each codon position
2065          */
2066         for (int codonPos = 0; codonPos < 3; codonPos++)
2067         {
2068           String nucleotide = String.valueOf(
2069                   dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2070                   .toUpperCase();
2071           List<DnaVariant> codonVariant = codonVariants[codonPos];
2072           if (codon[codonPos] == dnaCol)
2073           {
2074             if (!codonVariant.isEmpty()
2075                     && codonVariant.get(0).variant == null)
2076             {
2077               /*
2078                * already recorded base value, add this variant
2079                */
2080               codonVariant.get(0).variant = sf;
2081             }
2082             else
2083             {
2084               /*
2085                * add variant with base value
2086                */
2087               codonVariant.add(new DnaVariant(nucleotide, sf));
2088             }
2089           }
2090           else if (codonVariant.isEmpty())
2091           {
2092             /*
2093              * record (possibly non-varying) base value
2094              */
2095             codonVariant.add(new DnaVariant(nucleotide));
2096           }
2097         }
2098       }
2099     }
2100     return variants;
2101   }
2102
2103   /**
2104    * Makes an alignment with a copy of the given sequences, adding in any
2105    * non-redundant sequences which are mapped to by the cross-referenced
2106    * sequences.
2107    * 
2108    * @param seqs
2109    * @param xrefs
2110    * @return
2111    */
2112   public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2113           SequenceI[] xrefs)
2114   {
2115     AlignmentI copy = new Alignment(new Alignment(seqs));
2116
2117     SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2118     if (xrefs != null)
2119     {
2120       for (SequenceI xref : xrefs)
2121       {
2122         DBRefEntry[] dbrefs = xref.getDBRefs();
2123         if (dbrefs != null)
2124         {
2125           for (DBRefEntry dbref : dbrefs)
2126           {
2127             if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2128             {
2129               continue;
2130             }
2131             SequenceI mappedTo = dbref.getMap().getTo();
2132             SequenceI match = matcher.findIdMatch(mappedTo);
2133             if (match == null)
2134             {
2135               matcher.add(mappedTo);
2136               copy.addSequence(mappedTo);
2137             }
2138           }
2139         }
2140       }
2141     }
2142     return copy;
2143   }
2144
2145   /**
2146    * Try to align sequences in 'unaligned' to match the alignment of their
2147    * mapped regions in 'aligned'. For example, could use this to align CDS
2148    * sequences which are mapped to their parent cDNA sequences.
2149    * 
2150    * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2151    * dna-to-protein or protein-to-dna use alternative methods.
2152    * 
2153    * @param unaligned
2154    *          sequences to be aligned
2155    * @param aligned
2156    *          holds aligned sequences and their mappings
2157    * @return
2158    */
2159   public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2160   {
2161     List<SequenceI> unmapped = new ArrayList<SequenceI>();
2162     Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2163             unaligned, aligned, unmapped);
2164     int width = columnMap.size();
2165     char gap = unaligned.getGapCharacter();
2166     int realignedCount = 0;
2167
2168     for (SequenceI seq : unaligned.getSequences())
2169     {
2170       if (!unmapped.contains(seq))
2171       {
2172         char[] newSeq = new char[width];
2173         Arrays.fill(newSeq, gap);
2174         int newCol = 0;
2175         int lastCol = 0;
2176
2177         /*
2178          * traverse the map to find columns populated
2179          * by our sequence
2180          */
2181         for (Integer column : columnMap.keySet())
2182         {
2183           Character c = columnMap.get(column).get(seq);
2184           if (c != null)
2185           {
2186             /*
2187              * sequence has a character at this position
2188              * 
2189              */
2190             newSeq[newCol] = c;
2191             lastCol = newCol;
2192           }
2193           newCol++;
2194         }
2195         
2196         /*
2197          * trim trailing gaps
2198          */
2199         if (lastCol < width)
2200         {
2201           char[] tmp = new char[lastCol + 1];
2202           System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2203           newSeq = tmp;
2204         }
2205         seq.setSequence(String.valueOf(newSeq));
2206         realignedCount++;
2207       }
2208     }
2209     return realignedCount;
2210   }
2211
2212   /**
2213    * Returns a map whose key is alignment column number (base 1), and whose
2214    * values are a map of sequence characters in that column.
2215    * 
2216    * @param unaligned
2217    * @param aligned
2218    * @param unmapped
2219    * @return
2220    */
2221   static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2222           AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2223   {
2224     /*
2225      * Map will hold, for each aligned column position, a map of
2226      * {unalignedSequence, sequenceCharacter} at that position.
2227      * TreeMap keeps the entries in ascending column order. 
2228      */
2229     Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2230
2231     /*
2232      * r any sequences that have no mapping so can't be realigned
2233      */
2234     unmapped.addAll(unaligned.getSequences());
2235
2236     List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2237
2238     for (SequenceI seq : unaligned.getSequences())
2239     {
2240       for (AlignedCodonFrame mapping : mappings)
2241       {
2242         SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2243         if (fromSeq != null)
2244         {
2245           Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2246           if (addMappedPositions(seq, fromSeq, seqMap, map))
2247           {
2248             unmapped.remove(seq);
2249           }
2250         }
2251       }
2252     }
2253     return map;
2254   }
2255
2256   /**
2257    * Helper method that adds to a map the mapped column positions of a sequence. <br>
2258    * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2259    * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2260    * sequence.
2261    * 
2262    * @param seq
2263    *          the sequence whose column positions we are recording
2264    * @param fromSeq
2265    *          a sequence that is mapped to the first sequence
2266    * @param seqMap
2267    *          the mapping from 'fromSeq' to 'seq'
2268    * @param map
2269    *          a map to add the column positions (in fromSeq) of the mapped
2270    *          positions of seq
2271    * @return
2272    */
2273   static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2274           Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2275   {
2276     if (seqMap == null)
2277     {
2278       return false;
2279     }
2280
2281     char[] fromChars = fromSeq.getSequence();
2282     int toStart = seq.getStart();
2283     char[] toChars = seq.getSequence();
2284
2285     /*
2286      * traverse [start, end, start, end...] ranges in fromSeq
2287      */
2288     for (int[] fromRange : seqMap.getMap().getFromRanges())
2289     {
2290       for (int i = 0; i < fromRange.length - 1; i += 2)
2291       {
2292         boolean forward = fromRange[i + 1] >= fromRange[i];
2293
2294         /*
2295          * find the range mapped to (sequence positions base 1)
2296          */
2297         int[] range = seqMap.locateMappedRange(fromRange[i],
2298                 fromRange[i + 1]);
2299         if (range == null)
2300         {
2301           System.err.println("Error in mapping " + seqMap + " from "
2302                   + fromSeq.getName());
2303           return false;
2304         }
2305         int fromCol = fromSeq.findIndex(fromRange[i]);
2306         int mappedCharPos = range[0];
2307
2308         /*
2309          * walk over the 'from' aligned sequence in forward or reverse
2310          * direction; when a non-gap is found, record the column position
2311          * of the next character of the mapped-to sequence; stop when all
2312          * the characters of the range have been counted
2313          */
2314         while (mappedCharPos <= range[1])
2315         {
2316           if (!Comparison.isGap(fromChars[fromCol - 1]))
2317           {
2318             /*
2319              * mapped from sequence has a character in this column
2320              * record the column position for the mapped to character
2321              */
2322             Map<SequenceI, Character> seqsMap = map.get(fromCol);
2323             if (seqsMap == null)
2324             {
2325               seqsMap = new HashMap<SequenceI, Character>();
2326               map.put(fromCol, seqsMap);
2327             }
2328             seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2329             mappedCharPos++;
2330           }
2331           fromCol += (forward ? 1 : -1);
2332         }
2333       }
2334     }
2335     return true;
2336   }
2337
2338   // strictly temporary hack until proper criteria for aligning protein to cds
2339   // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2340   public static boolean looksLikeEnsembl(AlignmentI alignment)
2341   {
2342     for (SequenceI seq : alignment.getSequences())
2343     {
2344       String name = seq.getName();
2345       if (!name.startsWith("ENSG") && !name.startsWith("ENST"))
2346       {
2347         return false;
2348       }
2349     }
2350     return true;
2351   }
2352 }