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