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