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