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