JAL-1982 defensive checks for null annotations array
[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     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
1336     if (anns != null)
1337     {
1338       for (AlignmentAnnotation aa : anns)
1339       {
1340         if (anyType || types.contains(aa.label))
1341         {
1342           if ((aa.sequenceRef != null)
1343                   && (forSequences == null || forSequences
1344                           .contains(aa.sequenceRef)))
1345           {
1346             aa.visible = doShow;
1347           }
1348         }
1349       }
1350     }
1351   }
1352
1353   /**
1354    * Returns true if either sequence has a cross-reference to the other
1355    * 
1356    * @param seq1
1357    * @param seq2
1358    * @return
1359    */
1360   public static boolean haveCrossRef(SequenceI seq1, SequenceI seq2)
1361   {
1362     // Note: moved here from class CrossRef as the latter class has dependencies
1363     // not availability to the applet's classpath
1364     return hasCrossRef(seq1, seq2) || hasCrossRef(seq2, seq1);
1365   }
1366
1367   /**
1368    * Returns true if seq1 has a cross-reference to seq2. Currently this assumes
1369    * that sequence name is structured as Source|AccessionId.
1370    * 
1371    * @param seq1
1372    * @param seq2
1373    * @return
1374    */
1375   public static boolean hasCrossRef(SequenceI seq1, SequenceI seq2)
1376   {
1377     if (seq1 == null || seq2 == null)
1378     {
1379       return false;
1380     }
1381     String name = seq2.getName();
1382     final DBRefEntry[] xrefs = seq1.getDBRefs();
1383     if (xrefs != null)
1384     {
1385       for (DBRefEntry xref : xrefs)
1386       {
1387         String xrefName = xref.getSource() + "|" + xref.getAccessionId();
1388         // case-insensitive test, consistent with DBRefEntry.equalRef()
1389         if (xrefName.equalsIgnoreCase(name))
1390         {
1391           return true;
1392         }
1393       }
1394     }
1395     return false;
1396   }
1397
1398   /**
1399    * Constructs an alignment consisting of the mapped (CDS) regions in the given
1400    * nucleotide sequences, and updates mappings to match. The CDS sequences are
1401    * added to the original alignment's dataset, which is shared by the new
1402    * alignment. Mappings from nucleotide to CDS, and from CDS to protein, are
1403    * added to the alignment dataset.
1404    * 
1405    * @param dna
1406    *          aligned dna sequences
1407    * @param mappings
1408    *          from dna to protein
1409    * @param al
1410    * @return an alignment whose sequences are the cds-only parts of the dna
1411    *         sequences (or null if no mappings are found)
1412    */
1413   public static AlignmentI makeCdsAlignment(SequenceI[] dna,
1414           List<AlignedCodonFrame> mappings, AlignmentI al)
1415   {
1416     List<SequenceI> cdsSeqs = new ArrayList<SequenceI>();
1417     
1418     for (SequenceI seq : dna)
1419     {
1420       AlignedCodonFrame cdsMappings = new AlignedCodonFrame();
1421       List<AlignedCodonFrame> seqMappings = MappingUtils
1422               .findMappingsForSequence(seq, mappings);
1423       List<AlignedCodonFrame> alignmentMappings = al.getCodonFrames();
1424       for (AlignedCodonFrame mapping : seqMappings)
1425       {
1426         for (Mapping aMapping : mapping.getMappingsFromSequence(seq))
1427         {
1428           SequenceI cdsSeq = makeCdsSequence(seq.getDatasetSequence(),
1429                   aMapping);
1430           cdsSeqs.add(cdsSeq);
1431     
1432           /*
1433            * add a mapping from CDS to the (unchanged) mapped to range
1434            */
1435           List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1436               cdsSeq.getLength() });
1437           MapList map = new MapList(cdsRange, aMapping.getMap()
1438                   .getToRanges(), aMapping.getMap().getFromRatio(),
1439                   aMapping.getMap().getToRatio());
1440           cdsMappings.addMap(cdsSeq, aMapping.getTo(), map);
1441
1442           /*
1443            * add another mapping from original 'from' range to CDS
1444            */
1445           map = new MapList(aMapping.getMap().getFromRanges(), cdsRange, 1,
1446                   1);
1447           cdsMappings.addMap(seq.getDatasetSequence(), cdsSeq, map);
1448
1449           alignmentMappings.add(cdsMappings);
1450
1451           /*
1452            * transfer any features on dna that overlap the CDS
1453            */
1454           transferFeatures(seq, cdsSeq, map, null, SequenceOntologyI.CDS);
1455         }
1456       }
1457     }
1458
1459     /*
1460      * add CDS seqs to shared dataset
1461      */
1462     Alignment dataset = al.getDataset();
1463     for (SequenceI seq : cdsSeqs)
1464     {
1465       if (!dataset.getSequences().contains(seq.getDatasetSequence()))
1466       {
1467         dataset.addSequence(seq.getDatasetSequence());
1468       }
1469     }
1470     AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1471             .size()]));
1472     cds.setDataset(dataset);
1473
1474     return cds;
1475   }
1476
1477   /**
1478    * Helper method that makes a CDS sequence as defined by the mappings from the
1479    * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1480    * forward or reverse strand).
1481    * 
1482    * @param seq
1483    * @param mapping
1484    * @return
1485    */
1486   static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1487   {
1488     char[] seqChars = seq.getSequence();
1489     List<int[]> fromRanges = mapping.getMap().getFromRanges();
1490     int cdsWidth = MappingUtils.getLength(fromRanges);
1491     char[] newSeqChars = new char[cdsWidth];
1492
1493     int newPos = 0;
1494     for (int[] range : fromRanges)
1495     {
1496       if (range[0] <= range[1])
1497       {
1498         // forward strand mapping - just copy the range
1499         int length = range[1] - range[0] + 1;
1500         System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1501                 length);
1502         newPos += length;
1503       }
1504       else
1505       {
1506         // reverse strand mapping - copy and complement one by one
1507         for (int i = range[0]; i >= range[1]; i--)
1508         {
1509           newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1510         }
1511       }
1512     }
1513
1514     SequenceI newSeq = new Sequence(seq.getName() + "|"
1515             + mapping.getTo().getName(), newSeqChars, 1, newPos);
1516     newSeq.createDatasetSequence();
1517     return newSeq;
1518   }
1519
1520   /**
1521    * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1522    * feature start/end ranges, optionally omitting specified feature types.
1523    * Returns the number of features copied.
1524    * 
1525    * @param fromSeq
1526    * @param toSeq
1527    * @param select
1528    *          if not null, only features of this type are copied (including
1529    *          subtypes in the Sequence Ontology)
1530    * @param mapping
1531    *          the mapping from 'fromSeq' to 'toSeq'
1532    * @param omitting
1533    */
1534   public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1535           MapList mapping, String select, String... omitting)
1536   {
1537     SequenceI copyTo = toSeq;
1538     while (copyTo.getDatasetSequence() != null)
1539     {
1540       copyTo = copyTo.getDatasetSequence();
1541     }
1542
1543     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1544     int count = 0;
1545     SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
1546     if (sfs != null)
1547     {
1548       for (SequenceFeature sf : sfs)
1549       {
1550         String type = sf.getType();
1551         if (select != null && !so.isA(type, select))
1552         {
1553           continue;
1554         }
1555         boolean omit = false;
1556         for (String toOmit : omitting)
1557         {
1558           if (type.equals(toOmit))
1559           {
1560             omit = true;
1561           }
1562         }
1563         if (omit)
1564         {
1565           continue;
1566         }
1567
1568         /*
1569          * locate the mapped range - null if either start or end is
1570          * not mapped (no partial overlaps are calculated)
1571          */
1572         int start = sf.getBegin();
1573         int end = sf.getEnd();
1574         int[] mappedTo = mapping.locateInTo(start, end);
1575         /*
1576          * if whole exon range doesn't map, try interpreting it
1577          * as 5' or 3' exon overlapping the CDS range
1578          */
1579         if (mappedTo == null)
1580         {
1581           mappedTo = mapping.locateInTo(end, end);
1582           if (mappedTo != null)
1583           {
1584             /*
1585              * end of exon is in CDS range - 5' overlap
1586              * to a range from the start of the peptide
1587              */
1588             mappedTo[0] = 1;
1589           }
1590         }
1591         if (mappedTo == null)
1592         {
1593           mappedTo = mapping.locateInTo(start, start);
1594           if (mappedTo != null)
1595           {
1596             /*
1597              * start of exon is in CDS range - 3' overlap
1598              * to a range up to the end of the peptide
1599              */
1600             mappedTo[1] = toSeq.getLength();
1601           }
1602         }
1603         if (mappedTo != null)
1604         {
1605           SequenceFeature copy = new SequenceFeature(sf);
1606           copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
1607           copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
1608           copyTo.addSequenceFeature(copy);
1609           count++;
1610         }
1611       }
1612     }
1613     return count;
1614   }
1615
1616   /**
1617    * Returns a mapping from dna to protein by inspecting sequence features of
1618    * type "CDS" on the dna.
1619    * 
1620    * @param dnaSeq
1621    * @param proteinSeq
1622    * @return
1623    */
1624   public static MapList mapCdsToProtein(SequenceI dnaSeq,
1625           SequenceI proteinSeq)
1626   {
1627     List<int[]> ranges = findCdsPositions(dnaSeq);
1628     int mappedDnaLength = MappingUtils.getLength(ranges);
1629
1630     int proteinLength = proteinSeq.getLength();
1631     int proteinStart = proteinSeq.getStart();
1632     int proteinEnd = proteinSeq.getEnd();
1633
1634     /*
1635      * incomplete start codon may mean X at start of peptide
1636      * we ignore both for mapping purposes
1637      */
1638     if (proteinSeq.getCharAt(0) == 'X')
1639     {
1640       // todo JAL-2022 support startPhase > 0
1641       proteinStart++;
1642       proteinLength--;
1643     }
1644     List<int[]> proteinRange = new ArrayList<int[]>();
1645
1646     /*
1647      * dna length should map to protein (or protein plus stop codon)
1648      */
1649     int codesForResidues = mappedDnaLength / 3;
1650     if (codesForResidues == (proteinLength + 1))
1651     {
1652       // assuming extra codon is for STOP and not in peptide
1653       codesForResidues--;
1654     }
1655     if (codesForResidues == proteinLength)
1656     {
1657       proteinRange.add(new int[] { proteinStart, proteinEnd });
1658       return new MapList(ranges, proteinRange, 3, 1);
1659     }
1660     return null;
1661   }
1662
1663   /**
1664    * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
1665    * start/end positions of sequence features of type "CDS" (or a sub-type of
1666    * CDS in the Sequence Ontology). The ranges are sorted into ascending start
1667    * position order, so this method is only valid for linear CDS in the same
1668    * sense as the protein product.
1669    * 
1670    * @param dnaSeq
1671    * @return
1672    */
1673   public static List<int[]> findCdsPositions(SequenceI dnaSeq)
1674   {
1675     List<int[]> result = new ArrayList<int[]>();
1676     SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
1677     if (sfs == null)
1678     {
1679       return result;
1680     }
1681
1682     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
1683     int startPhase = 0;
1684
1685     for (SequenceFeature sf : sfs)
1686     {
1687       /*
1688        * process a CDS feature (or a sub-type of CDS)
1689        */
1690       if (so.isA(sf.getType(), SequenceOntologyI.CDS))
1691       {
1692         int phase = 0;
1693         try
1694         {
1695           phase = Integer.parseInt(sf.getPhase());
1696         } catch (NumberFormatException e)
1697         {
1698           // ignore
1699         }
1700         /*
1701          * phase > 0 on first codon means 5' incomplete - skip to the start
1702          * of the next codon; example ENST00000496384
1703          */
1704         int begin = sf.getBegin();
1705         int end = sf.getEnd();
1706         if (result.isEmpty())
1707         {
1708           begin += phase;
1709           if (begin > end)
1710           {
1711             // shouldn't happen!
1712             System.err
1713                     .println("Error: start phase extends beyond start CDS in "
1714                             + dnaSeq.getName());
1715           }
1716         }
1717         result.add(new int[] { begin, end });
1718       }
1719     }
1720
1721     /*
1722      * remove 'startPhase' positions (usually 0) from the first range 
1723      * so we begin at the start of a complete codon
1724      */
1725     if (!result.isEmpty())
1726     {
1727       // TODO JAL-2022 correctly model start phase > 0
1728       result.get(0)[0] += startPhase;
1729     }
1730
1731     /*
1732      * Finally sort ranges by start position. This avoids a dependency on 
1733      * keeping features in order on the sequence (if they are in order anyway,
1734      * the sort will have almost no work to do). The implicit assumption is CDS
1735      * ranges are assembled in order. Other cases should not use this method,
1736      * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
1737      */
1738     Collections.sort(result, new Comparator<int[]>()
1739     {
1740       @Override
1741       public int compare(int[] o1, int[] o2)
1742       {
1743         return Integer.compare(o1[0], o2[0]);
1744       }
1745     });
1746     return result;
1747   }
1748
1749   /**
1750    * Maps exon features from dna to protein, and computes variants in peptide
1751    * product generated by variants in dna, and adds them as sequence_variant
1752    * features on the protein sequence. Returns the number of variant features
1753    * added.
1754    * 
1755    * @param dnaSeq
1756    * @param peptide
1757    * @param dnaToProtein
1758    */
1759   public static int computeProteinFeatures(SequenceI dnaSeq,
1760           SequenceI peptide, MapList dnaToProtein)
1761   {
1762     while (dnaSeq.getDatasetSequence() != null)
1763     {
1764       dnaSeq = dnaSeq.getDatasetSequence();
1765     }
1766     while (peptide.getDatasetSequence() != null)
1767     {
1768       peptide = peptide.getDatasetSequence();
1769     }
1770
1771     transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
1772
1773     /*
1774      * compute protein variants from dna variants and codon mappings;
1775      * NB - alternatively we could retrieve this using the REST service e.g.
1776      * http://rest.ensembl.org/overlap/translation
1777      * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
1778      * which would be a bit slower but possibly more reliable
1779      */
1780
1781     /*
1782      * build a map with codon variations for each potentially varying peptide
1783      */
1784     LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
1785             dnaSeq, dnaToProtein);
1786
1787     /*
1788      * scan codon variations, compute peptide variants and add to peptide sequence
1789      */
1790     int count = 0;
1791     for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
1792     {
1793       int peptidePos = variant.getKey();
1794       List<DnaVariant>[] codonVariants = variant.getValue();
1795       count += computePeptideVariants(peptide, peptidePos, codonVariants);
1796     }
1797
1798     /*
1799      * sort to get sequence features in start position order
1800      * - would be better to store in Sequence as a TreeSet or NCList?
1801      */
1802     Arrays.sort(peptide.getSequenceFeatures(),
1803             new Comparator<SequenceFeature>()
1804             {
1805               @Override
1806               public int compare(SequenceFeature o1, SequenceFeature o2)
1807               {
1808                 int c = Integer.compare(o1.getBegin(), o2.getBegin());
1809                 return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
1810                         : c;
1811               }
1812             });
1813     return count;
1814   }
1815
1816   /**
1817    * Computes non-synonymous peptide variants from codon variants and adds them
1818    * as sequence_variant features on the protein sequence (one feature per
1819    * allele variant). Selected attributes (variant id, clinical significance)
1820    * are copied over to the new features.
1821    * 
1822    * @param peptide
1823    *          the protein sequence
1824    * @param peptidePos
1825    *          the position to compute peptide variants for
1826    * @param codonVariants
1827    *          a list of dna variants per codon position
1828    * @return the number of features added
1829    */
1830   static int computePeptideVariants(SequenceI peptide, int peptidePos,
1831           List<DnaVariant>[] codonVariants)
1832   {
1833     String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
1834     int count = 0;
1835     String base1 = codonVariants[0].get(0).base;
1836     String base2 = codonVariants[1].get(0).base;
1837     String base3 = codonVariants[2].get(0).base;
1838
1839     /*
1840      * variants in first codon base
1841      */
1842     for (DnaVariant var : codonVariants[0])
1843     {
1844       if (var.variant != null)
1845       {
1846         String alleles = (String) var.variant.getValue("alleles");
1847         if (alleles != null)
1848         {
1849           for (String base : alleles.split(","))
1850           {
1851             String codon = base + base2 + base3;
1852             if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1853             {
1854               count++;
1855             }
1856           }
1857         }
1858       }
1859     }
1860
1861     /*
1862      * variants in second codon base
1863      */
1864     for (DnaVariant var : codonVariants[1])
1865     {
1866       if (var.variant != null)
1867       {
1868         String alleles = (String) var.variant.getValue("alleles");
1869         if (alleles != null)
1870         {
1871           for (String base : alleles.split(","))
1872           {
1873             String codon = base1 + base + base3;
1874             if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1875             {
1876               count++;
1877             }
1878           }
1879         }
1880       }
1881     }
1882
1883     /*
1884      * variants in third codon base
1885      */
1886     for (DnaVariant var : codonVariants[2])
1887     {
1888       if (var.variant != null)
1889       {
1890         String alleles = (String) var.variant.getValue("alleles");
1891         if (alleles != null)
1892         {
1893           for (String base : alleles.split(","))
1894           {
1895             String codon = base1 + base2 + base;
1896             if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
1897             {
1898               count++;
1899             }
1900           }
1901         }
1902       }
1903     }
1904
1905     return count;
1906   }
1907
1908   /**
1909    * Helper method that adds a peptide variant feature, provided the given codon
1910    * translates to a value different to the current residue (is a non-synonymous
1911    * variant). ID and clinical_significance attributes of the dna variant (if
1912    * present) are copied to the new feature.
1913    * 
1914    * @param peptide
1915    * @param peptidePos
1916    * @param residue
1917    * @param var
1918    * @param codon
1919    * @return true if a feature was added, else false
1920    */
1921   static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
1922           String residue, DnaVariant var, String codon)
1923   {
1924     /*
1925      * get peptide translation of codon e.g. GAT -> D
1926      * note that variants which are not single alleles,
1927      * e.g. multibase variants or HGMD_MUTATION etc
1928      * are currently ignored here
1929      */
1930     String trans = codon.contains("-") ? "-"
1931             : (codon.length() > 3 ? null : ResidueProperties
1932                     .codonTranslate(codon));
1933     if (trans != null && !trans.equals(residue))
1934     {
1935       String residue3Char = StringUtils
1936               .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
1937       String trans3Char = StringUtils
1938               .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
1939       String desc = "p." + residue3Char + peptidePos + trans3Char;
1940       // set score to 0f so 'graduated colour' option is offered! JAL-2060
1941       SequenceFeature sf = new SequenceFeature(
1942               SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
1943               peptidePos, 0f, "Jalview");
1944       StringBuilder attributes = new StringBuilder(32);
1945       String id = (String) var.variant.getValue(ID);
1946       if (id != null)
1947       {
1948         if (id.startsWith(SEQUENCE_VARIANT))
1949         {
1950           id = id.substring(SEQUENCE_VARIANT.length());
1951         }
1952         sf.setValue(ID, id);
1953         attributes.append(ID).append("=").append(id);
1954         // TODO handle other species variants
1955         StringBuilder link = new StringBuilder(32);
1956         try
1957         {
1958           link.append(desc).append(" ").append(id)
1959                   .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
1960                   .append(URLEncoder.encode(id, "UTF-8"));
1961           sf.addLink(link.toString());
1962         } catch (UnsupportedEncodingException e)
1963         {
1964           // as if
1965         }
1966       }
1967       String clinSig = (String) var.variant
1968               .getValue(CLINICAL_SIGNIFICANCE);
1969       if (clinSig != null)
1970       {
1971         sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
1972         attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
1973                 .append(clinSig);
1974       }
1975       peptide.addSequenceFeature(sf);
1976       if (attributes.length() > 0)
1977       {
1978         sf.setAttributes(attributes.toString());
1979       }
1980       return true;
1981     }
1982     return false;
1983   }
1984
1985   /**
1986    * Builds a map whose key is position in the protein sequence, and value is a
1987    * list of the base and all variants for each corresponding codon position
1988    * 
1989    * @param dnaSeq
1990    * @param dnaToProtein
1991    * @return
1992    */
1993   static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
1994           SequenceI dnaSeq, MapList dnaToProtein)
1995   {
1996     /*
1997      * map from peptide position to all variants of the codon which codes for it
1998      * LinkedHashMap ensures we keep the peptide features in sequence order
1999      */
2000     LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
2001     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2002
2003     SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2004     if (dnaFeatures == null)
2005     {
2006       return variants;
2007     }
2008
2009     int dnaStart = dnaSeq.getStart();
2010     int[] lastCodon = null;
2011     int lastPeptidePostion = 0;
2012
2013     /*
2014      * build a map of codon variations for peptides
2015      */
2016     for (SequenceFeature sf : dnaFeatures)
2017     {
2018       int dnaCol = sf.getBegin();
2019       if (dnaCol != sf.getEnd())
2020       {
2021         // not handling multi-locus variant features
2022         continue;
2023       }
2024       if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2025       {
2026         int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2027         if (mapsTo == null)
2028         {
2029           // feature doesn't lie within coding region
2030           continue;
2031         }
2032         int peptidePosition = mapsTo[0];
2033         List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2034         if (codonVariants == null)
2035         {
2036           codonVariants = new ArrayList[3];
2037           codonVariants[0] = new ArrayList<DnaVariant>();
2038           codonVariants[1] = new ArrayList<DnaVariant>();
2039           codonVariants[2] = new ArrayList<DnaVariant>();
2040           variants.put(peptidePosition, codonVariants);
2041         }
2042
2043         /*
2044          * extract dna variants to a string array
2045          */
2046         String alls = (String) sf.getValue("alleles");
2047         if (alls == null)
2048         {
2049           continue;
2050         }
2051         String[] alleles = alls.toUpperCase().split(",");
2052         int i = 0;
2053         for (String allele : alleles)
2054         {
2055           alleles[i++] = allele.trim(); // lose any space characters "A, G"
2056         }
2057
2058         /*
2059          * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2060          */
2061         int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2062                 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2063                         peptidePosition, peptidePosition));
2064         lastPeptidePostion = peptidePosition;
2065         lastCodon = codon;
2066
2067         /*
2068          * save nucleotide (and any variant) for each codon position
2069          */
2070         for (int codonPos = 0; codonPos < 3; codonPos++)
2071         {
2072           String nucleotide = String.valueOf(
2073                   dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2074                   .toUpperCase();
2075           List<DnaVariant> codonVariant = codonVariants[codonPos];
2076           if (codon[codonPos] == dnaCol)
2077           {
2078             if (!codonVariant.isEmpty()
2079                     && codonVariant.get(0).variant == null)
2080             {
2081               /*
2082                * already recorded base value, add this variant
2083                */
2084               codonVariant.get(0).variant = sf;
2085             }
2086             else
2087             {
2088               /*
2089                * add variant with base value
2090                */
2091               codonVariant.add(new DnaVariant(nucleotide, sf));
2092             }
2093           }
2094           else if (codonVariant.isEmpty())
2095           {
2096             /*
2097              * record (possibly non-varying) base value
2098              */
2099             codonVariant.add(new DnaVariant(nucleotide));
2100           }
2101         }
2102       }
2103     }
2104     return variants;
2105   }
2106
2107   /**
2108    * Makes an alignment with a copy of the given sequences, adding in any
2109    * non-redundant sequences which are mapped to by the cross-referenced
2110    * sequences.
2111    * 
2112    * @param seqs
2113    * @param xrefs
2114    * @return
2115    */
2116   public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2117           SequenceI[] xrefs)
2118   {
2119     AlignmentI copy = new Alignment(new Alignment(seqs));
2120
2121     /*
2122      * add mappings between sequences to the new alignment
2123      */
2124     AlignedCodonFrame mappings = new AlignedCodonFrame();
2125     copy.addCodonFrame(mappings);
2126     for (int i = 0; i < copy.getHeight(); i++)
2127     {
2128       SequenceI from = seqs[i];
2129       SequenceI to = copy.getSequenceAt(i);
2130       if (to.getDatasetSequence() != null)
2131       {
2132         to = to.getDatasetSequence();
2133       }
2134       int start = from.getStart();
2135       int end = from.getEnd();
2136       MapList map = new MapList(new int[] { start, end }, new int[] {
2137           start, end }, 1, 1);
2138       mappings.addMap(to, from, map);
2139     }
2140
2141     SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2142     if (xrefs != null)
2143     {
2144       for (SequenceI xref : xrefs)
2145       {
2146         DBRefEntry[] dbrefs = xref.getDBRefs();
2147         if (dbrefs != null)
2148         {
2149           for (DBRefEntry dbref : dbrefs)
2150           {
2151             if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2152             {
2153               continue;
2154             }
2155             SequenceI mappedTo = dbref.getMap().getTo();
2156             SequenceI match = matcher.findIdMatch(mappedTo);
2157             if (match == null)
2158             {
2159               matcher.add(mappedTo);
2160               copy.addSequence(mappedTo);
2161             }
2162           }
2163         }
2164       }
2165     }
2166     return copy;
2167   }
2168
2169   /**
2170    * Try to align sequences in 'unaligned' to match the alignment of their
2171    * mapped regions in 'aligned'. For example, could use this to align CDS
2172    * sequences which are mapped to their parent cDNA sequences.
2173    * 
2174    * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2175    * dna-to-protein or protein-to-dna use alternative methods.
2176    * 
2177    * @param unaligned
2178    *          sequences to be aligned
2179    * @param aligned
2180    *          holds aligned sequences and their mappings
2181    * @return
2182    */
2183   public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2184   {
2185     List<SequenceI> unmapped = new ArrayList<SequenceI>();
2186     Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2187             unaligned, aligned, unmapped);
2188     int width = columnMap.size();
2189     char gap = unaligned.getGapCharacter();
2190     int realignedCount = 0;
2191
2192     for (SequenceI seq : unaligned.getSequences())
2193     {
2194       if (!unmapped.contains(seq))
2195       {
2196         char[] newSeq = new char[width];
2197         Arrays.fill(newSeq, gap);
2198         int newCol = 0;
2199         int lastCol = 0;
2200
2201         /*
2202          * traverse the map to find columns populated
2203          * by our sequence
2204          */
2205         for (Integer column : columnMap.keySet())
2206         {
2207           Character c = columnMap.get(column).get(seq);
2208           if (c != null)
2209           {
2210             /*
2211              * sequence has a character at this position
2212              * 
2213              */
2214             newSeq[newCol] = c;
2215             lastCol = newCol;
2216           }
2217           newCol++;
2218         }
2219         
2220         /*
2221          * trim trailing gaps
2222          */
2223         if (lastCol < width)
2224         {
2225           char[] tmp = new char[lastCol + 1];
2226           System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2227           newSeq = tmp;
2228         }
2229         seq.setSequence(String.valueOf(newSeq));
2230         realignedCount++;
2231       }
2232     }
2233     return realignedCount;
2234   }
2235
2236   /**
2237    * Returns a map whose key is alignment column number (base 1), and whose
2238    * values are a map of sequence characters in that column.
2239    * 
2240    * @param unaligned
2241    * @param aligned
2242    * @param unmapped
2243    * @return
2244    */
2245   static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2246           AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2247   {
2248     /*
2249      * Map will hold, for each aligned column position, a map of
2250      * {unalignedSequence, sequenceCharacter} at that position.
2251      * TreeMap keeps the entries in ascending column order. 
2252      */
2253     Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2254
2255     /*
2256      * r any sequences that have no mapping so can't be realigned
2257      */
2258     unmapped.addAll(unaligned.getSequences());
2259
2260     List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2261
2262     for (SequenceI seq : unaligned.getSequences())
2263     {
2264       for (AlignedCodonFrame mapping : mappings)
2265       {
2266         SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2267         if (fromSeq != null)
2268         {
2269           Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2270           if (addMappedPositions(seq, fromSeq, seqMap, map))
2271           {
2272             unmapped.remove(seq);
2273           }
2274         }
2275       }
2276     }
2277     return map;
2278   }
2279
2280   /**
2281    * Helper method that adds to a map the mapped column positions of a sequence. <br>
2282    * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2283    * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2284    * sequence.
2285    * 
2286    * @param seq
2287    *          the sequence whose column positions we are recording
2288    * @param fromSeq
2289    *          a sequence that is mapped to the first sequence
2290    * @param seqMap
2291    *          the mapping from 'fromSeq' to 'seq'
2292    * @param map
2293    *          a map to add the column positions (in fromSeq) of the mapped
2294    *          positions of seq
2295    * @return
2296    */
2297   static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2298           Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2299   {
2300     if (seqMap == null)
2301     {
2302       return false;
2303     }
2304
2305     char[] fromChars = fromSeq.getSequence();
2306     int toStart = seq.getStart();
2307     char[] toChars = seq.getSequence();
2308
2309     /*
2310      * traverse [start, end, start, end...] ranges in fromSeq
2311      */
2312     for (int[] fromRange : seqMap.getMap().getFromRanges())
2313     {
2314       for (int i = 0; i < fromRange.length - 1; i += 2)
2315       {
2316         boolean forward = fromRange[i + 1] >= fromRange[i];
2317
2318         /*
2319          * find the range mapped to (sequence positions base 1)
2320          */
2321         int[] range = seqMap.locateMappedRange(fromRange[i],
2322                 fromRange[i + 1]);
2323         if (range == null)
2324         {
2325           System.err.println("Error in mapping " + seqMap + " from "
2326                   + fromSeq.getName());
2327           return false;
2328         }
2329         int fromCol = fromSeq.findIndex(fromRange[i]);
2330         int mappedCharPos = range[0];
2331
2332         /*
2333          * walk over the 'from' aligned sequence in forward or reverse
2334          * direction; when a non-gap is found, record the column position
2335          * of the next character of the mapped-to sequence; stop when all
2336          * the characters of the range have been counted
2337          */
2338         while (mappedCharPos <= range[1])
2339         {
2340           if (!Comparison.isGap(fromChars[fromCol - 1]))
2341           {
2342             /*
2343              * mapped from sequence has a character in this column
2344              * record the column position for the mapped to character
2345              */
2346             Map<SequenceI, Character> seqsMap = map.get(fromCol);
2347             if (seqsMap == null)
2348             {
2349               seqsMap = new HashMap<SequenceI, Character>();
2350               map.put(fromCol, seqsMap);
2351             }
2352             seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2353             mappedCharPos++;
2354           }
2355           fromCol += (forward ? 1 : -1);
2356         }
2357       }
2358     }
2359     return true;
2360   }
2361
2362   // strictly temporary hack until proper criteria for aligning protein to cds
2363   // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2364   public static boolean looksLikeEnsembl(AlignmentI alignment)
2365   {
2366     for (SequenceI seq : alignment.getSequences())
2367     {
2368       String name = seq.getName();
2369       if (!name.startsWith("ENSG") && !name.startsWith("ENST"))
2370       {
2371         return false;
2372       }
2373     }
2374     return true;
2375   }
2376 }