Merge branch 'trailm' into trial_fixMakeCDSDBRefPropagation
[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           // cdsSeq has a name constructed as CDS|<dbref>
1685           // <dbref> will be either the accession for the coding sequence,
1686           // marked in the /via/ dbref to the protein product accession
1687           // or it will be the original nucleotide accession.
1688           SequenceI cdsSeqDss = cdsSeq.createDatasetSequence();
1689           cdsSeqs.add(cdsSeq);
1690           if (!dataset.getSequences().contains(cdsSeqDss))
1691           {
1692             dataset.addSequence(cdsSeqDss);
1693           }
1694
1695           /*
1696            * add a mapping from CDS to the (unchanged) mapped to range
1697            */
1698           List<int[]> cdsRange = Collections.singletonList(new int[] { 1,
1699               cdsSeq.getLength() });
1700           MapList cdsToProteinMap = new MapList(cdsRange, mapList.getToRanges(),
1701                   mapList.getFromRatio(), mapList.getToRatio());
1702           AlignedCodonFrame cdsToProteinMapping = new AlignedCodonFrame();
1703           cdsToProteinMapping.addMap(cdsSeqDss, proteinProduct,
1704                   cdsToProteinMap);
1705
1706           /*
1707            * guard against duplicating the mapping if repeating this action
1708            */
1709           if (!mappings.contains(cdsToProteinMapping))
1710           {
1711             mappings.add(cdsToProteinMapping);
1712           }
1713
1714           propagateDBRefsToCDS(cdsSeqDss, dnaSeq.getDatasetSequence(),
1715                   proteinProduct, aMapping);
1716           /*
1717            * add another mapping from original 'from' range to CDS
1718            */
1719           AlignedCodonFrame dnaToCdsMapping = new AlignedCodonFrame();
1720           MapList dnaToCdsMap = new MapList(mapList.getFromRanges(),
1721                   cdsRange, 1,
1722                   1);
1723           dnaToCdsMapping.addMap(dnaSeq.getDatasetSequence(), cdsSeqDss,
1724                   dnaToCdsMap);
1725           if (!mappings.contains(dnaToCdsMapping))
1726           {
1727             mappings.add(dnaToCdsMapping);
1728           }
1729
1730           /*
1731            * add DBRef with mapping from protein to CDS
1732            * (this enables Get Cross-References from protein alignment)
1733            * This is tricky because we can't have two DBRefs with the
1734            * same source and accession, so need a different accession for
1735            * the CDS from the dna sequence
1736            */
1737           // specific use case:
1738           // Genomic contig ENSCHR:1, contains coding regions for ENSG01,
1739           // ENSG02, ENSG03, with transcripts and products similarly named.
1740           // cannot add distinct dbrefs mapping location on ENSCHR:1 to ENSG01
1741           // JBPNote: ?? can't actually create an example that demonstrates we
1742           // need to
1743           // synthesize an xref.
1744           // TODO: merge conflicts from JAL-2154 branch and use PrimaryDBRefs()
1745           // for (DBRefEntry primRef:dnaDss.getPrimaryDBRefs())
1746           // {
1747           // creates a complementary cross-reference to the source sequence's
1748           // primary reference.
1749
1750           // // problem here is that the cross-reference is synthesized -
1751           // cdsSeq.getName() may be like 'CDS|dnaaccession' or 'CDS|emblcdsacc'
1752           // // assuming cds version same as dna ?!?
1753           // DBRefEntry proteinToCdsRef = new DBRefEntry(dnaRef.getSource(),
1754           // dnaRef.getVersion(), cdsSeq.getName());
1755           // proteinToCdsRef.setMap(new Mapping(cdsSeqDss, cdsToProteinMap
1756           // .getInverse()));
1757           // proteinProduct.addDBRef(proteinToCdsRef);
1758           // }
1759
1760           /*
1761            * transfer any features on dna that overlap the CDS
1762            */
1763           transferFeatures(dnaSeq, cdsSeq, cdsToProteinMap, null,
1764                   SequenceOntologyI.CDS);
1765         }
1766       }
1767     }
1768
1769     AlignmentI cds = new Alignment(cdsSeqs.toArray(new SequenceI[cdsSeqs
1770             .size()]));
1771     cds.setDataset(dataset);
1772
1773     return cds;
1774   }
1775
1776   /**
1777    * A helper method that finds a CDS sequence in the alignment dataset that is
1778    * mapped to the given protein sequence, and either is, or has a mapping from,
1779    * the given dna sequence.
1780    * 
1781    * @param mappings
1782    *          set of all mappings on the dataset
1783    * @param dnaSeq
1784    *          a dna (or cds) sequence we are searching from
1785    * @param seqMappings
1786    *          the set of mappings involving dnaSeq
1787    * @param aMapping
1788    *          an initial candidate from seqMappings
1789    * @return
1790    */
1791   static SequenceI findCdsForProtein(List<AlignedCodonFrame> mappings,
1792           SequenceI dnaSeq, List<AlignedCodonFrame> seqMappings,
1793           Mapping aMapping)
1794   {
1795     /*
1796      * TODO a better dna-cds-protein mapping data representation to allow easy
1797      * navigation; until then this clunky looping around lists of mappings
1798      */
1799     SequenceI seqDss = dnaSeq.getDatasetSequence() == null ? dnaSeq
1800             : dnaSeq.getDatasetSequence();
1801     SequenceI proteinProduct = aMapping.getTo();
1802
1803     /*
1804      * is this mapping from the whole dna sequence (i.e. CDS)?
1805      * allowing for possible stop codon on dna but not peptide
1806      */
1807     int mappedFromLength = MappingUtils.getLength(aMapping.getMap()
1808             .getFromRanges());
1809     int dnaLength = seqDss.getLength();
1810     if (mappedFromLength == dnaLength || mappedFromLength == dnaLength - 3)
1811     {
1812       return seqDss;
1813     }
1814
1815     /*
1816      * looks like we found the dna-to-protein mapping; search for the
1817      * corresponding cds-to-protein mapping
1818      */
1819     List<AlignedCodonFrame> mappingsToPeptide = MappingUtils
1820             .findMappingsForSequence(proteinProduct, mappings);
1821     for (AlignedCodonFrame acf : mappingsToPeptide)
1822     {
1823       for (SequenceToSequenceMapping map : acf.getMappings())
1824       {
1825         Mapping mapping = map.getMapping();
1826         if (mapping != aMapping && mapping.getMap().getFromRatio() == 3
1827                 && proteinProduct == mapping.getTo()
1828                 && seqDss != map.getFromSeq())
1829         {
1830           mappedFromLength = MappingUtils.getLength(mapping.getMap()
1831                   .getFromRanges());
1832           if (mappedFromLength == map.getFromSeq().getLength())
1833           {
1834             /*
1835             * found a 3:1 mapping to the protein product which covers
1836             * the whole dna sequence i.e. is from CDS; finally check it
1837             * is from the dna start sequence
1838             */
1839             SequenceI cdsSeq = map.getFromSeq();
1840             List<AlignedCodonFrame> dnaToCdsMaps = MappingUtils
1841                     .findMappingsForSequence(cdsSeq, seqMappings);
1842             if (!dnaToCdsMaps.isEmpty())
1843             {
1844               return cdsSeq;
1845             }
1846           }
1847         }
1848       }
1849     }
1850     return null;
1851   }
1852
1853   /**
1854    * Helper method that makes a CDS sequence as defined by the mappings from the
1855    * given sequence i.e. extracts the 'mapped from' ranges (which may be on
1856    * forward or reverse strand).
1857    * 
1858    * @param seq
1859    * @param mapping
1860    * @return CDS sequence (as a dataset sequence)
1861    */
1862   static SequenceI makeCdsSequence(SequenceI seq, Mapping mapping)
1863   {
1864     char[] seqChars = seq.getSequence();
1865     List<int[]> fromRanges = mapping.getMap().getFromRanges();
1866     int cdsWidth = MappingUtils.getLength(fromRanges);
1867     char[] newSeqChars = new char[cdsWidth];
1868
1869     int newPos = 0;
1870     for (int[] range : fromRanges)
1871     {
1872       if (range[0] <= range[1])
1873       {
1874         // forward strand mapping - just copy the range
1875         int length = range[1] - range[0] + 1;
1876         System.arraycopy(seqChars, range[0] - 1, newSeqChars, newPos,
1877                 length);
1878         newPos += length;
1879       }
1880       else
1881       {
1882         // reverse strand mapping - copy and complement one by one
1883         for (int i = range[0]; i >= range[1]; i--)
1884         {
1885           newSeqChars[newPos++] = Dna.getComplement(seqChars[i - 1]);
1886         }
1887       }
1888     }
1889     
1890     /*
1891      * assign 'from id' held in the mapping if set (e.g. EMBL protein_id),
1892      * else generate a sequence name
1893      */
1894     String mapFromId = mapping.getMappedFromId();
1895     String seqId = "CDS|" + (mapFromId != null ? mapFromId : seq.getName());
1896     SequenceI newSeq = new Sequence(seqId, newSeqChars, 1, newPos);
1897     // newSeq.setDescription(mapFromId);
1898
1899     return newSeq;
1900   }
1901
1902   /**
1903    * add any DBRefEntrys to cdsSeq from contig that have a Mapping congruent to
1904    * the given mapping.
1905    * 
1906    * @param cdsSeq
1907    * @param contig
1908    * @param mapping
1909    * @return list of DBRefEntrys added.
1910    */
1911   public static List<DBRefEntry> propagateDBRefsToCDS(SequenceI cdsSeq,
1912           SequenceI contig, SequenceI proteinProduct, Mapping mapping)
1913   {
1914
1915     // gather direct refs from contig congrent with mapping
1916     List<DBRefEntry> direct = new ArrayList<DBRefEntry>();
1917     HashSet<String> directSources = new HashSet<String>();
1918     if (contig.getDBRefs() != null)
1919     {
1920       for (DBRefEntry dbr : contig.getDBRefs())
1921       {
1922         if (dbr.hasMap() && dbr.getMap().getMap().isTripletMap())
1923         {
1924           MapList map = dbr.getMap().getMap();
1925           // check if map is the CDS mapping
1926           if (mapping.getMap().equals(map))
1927           {
1928             direct.add(dbr);
1929             directSources.add(dbr.getSource());
1930           }
1931         }
1932       }
1933     }
1934     DBRefEntry[] onSource = DBRefUtils.selectRefs(
1935             proteinProduct.getDBRefs(),
1936             directSources.toArray(new String[0]));
1937     List<DBRefEntry> propagated = new ArrayList<DBRefEntry>();
1938
1939     // and generate appropriate mappings
1940     for (DBRefEntry cdsref : direct)
1941     {
1942       // clone maplist and mapping
1943       MapList cdsposmap = new MapList(Arrays.asList(new int[][] { new int[]
1944       { cdsSeq.getStart(), cdsSeq.getEnd() } }), cdsref.getMap().getMap()
1945               .getToRanges(), 3, 1);
1946       Mapping cdsmap = new Mapping(cdsref.getMap().getTo(), cdsref.getMap()
1947               .getMap());
1948
1949       // create dbref
1950       DBRefEntry newref = new DBRefEntry(cdsref.getSource(),
1951               cdsref.getVersion(), cdsref.getAccessionId(), new Mapping(
1952                       cdsmap.getTo(), cdsposmap));
1953
1954       // and see if we can map to the protein product for this mapping.
1955       // onSource is the filtered set of accessions on protein that we are
1956       // tranferring, so we assume accession is the same.
1957       if (cdsmap.getTo() == null && onSource != null)
1958       {
1959         List<DBRefEntry> sourceRefs = DBRefUtils.searchRefs(onSource,
1960                 cdsref.getAccessionId());
1961         if (sourceRefs != null)
1962         {
1963           for (DBRefEntry srcref : sourceRefs)
1964           {
1965             if (srcref.getSource().equalsIgnoreCase(cdsref.getSource()))
1966             {
1967               // we have found a complementary dbref on the protein product, so
1968               // update mapping's getTo
1969               newref.getMap().setTo(proteinProduct);
1970             }
1971           }
1972         }
1973       }
1974       cdsSeq.addDBRef(newref);
1975       propagated.add(newref);
1976     }
1977     return propagated;
1978   }
1979
1980   /**
1981    * Transfers co-located features on 'fromSeq' to 'toSeq', adjusting the
1982    * feature start/end ranges, optionally omitting specified feature types.
1983    * Returns the number of features copied.
1984    * 
1985    * @param fromSeq
1986    * @param toSeq
1987    * @param select
1988    *          if not null, only features of this type are copied (including
1989    *          subtypes in the Sequence Ontology)
1990    * @param mapping
1991    *          the mapping from 'fromSeq' to 'toSeq'
1992    * @param omitting
1993    */
1994   public static int transferFeatures(SequenceI fromSeq, SequenceI toSeq,
1995           MapList mapping, String select, String... omitting)
1996   {
1997     SequenceI copyTo = toSeq;
1998     while (copyTo.getDatasetSequence() != null)
1999     {
2000       copyTo = copyTo.getDatasetSequence();
2001     }
2002
2003     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2004     int count = 0;
2005     SequenceFeature[] sfs = fromSeq.getSequenceFeatures();
2006     if (sfs != null)
2007     {
2008       for (SequenceFeature sf : sfs)
2009       {
2010         String type = sf.getType();
2011         if (select != null && !so.isA(type, select))
2012         {
2013           continue;
2014         }
2015         boolean omit = false;
2016         for (String toOmit : omitting)
2017         {
2018           if (type.equals(toOmit))
2019           {
2020             omit = true;
2021           }
2022         }
2023         if (omit)
2024         {
2025           continue;
2026         }
2027
2028         /*
2029          * locate the mapped range - null if either start or end is
2030          * not mapped (no partial overlaps are calculated)
2031          */
2032         int start = sf.getBegin();
2033         int end = sf.getEnd();
2034         int[] mappedTo = mapping.locateInTo(start, end);
2035         /*
2036          * if whole exon range doesn't map, try interpreting it
2037          * as 5' or 3' exon overlapping the CDS range
2038          */
2039         if (mappedTo == null)
2040         {
2041           mappedTo = mapping.locateInTo(end, end);
2042           if (mappedTo != null)
2043           {
2044             /*
2045              * end of exon is in CDS range - 5' overlap
2046              * to a range from the start of the peptide
2047              */
2048             mappedTo[0] = 1;
2049           }
2050         }
2051         if (mappedTo == null)
2052         {
2053           mappedTo = mapping.locateInTo(start, start);
2054           if (mappedTo != null)
2055           {
2056             /*
2057              * start of exon is in CDS range - 3' overlap
2058              * to a range up to the end of the peptide
2059              */
2060             mappedTo[1] = toSeq.getLength();
2061           }
2062         }
2063         if (mappedTo != null)
2064         {
2065           SequenceFeature copy = new SequenceFeature(sf);
2066           copy.setBegin(Math.min(mappedTo[0], mappedTo[1]));
2067           copy.setEnd(Math.max(mappedTo[0], mappedTo[1]));
2068           copyTo.addSequenceFeature(copy);
2069           count++;
2070         }
2071       }
2072     }
2073     return count;
2074   }
2075
2076   /**
2077    * Returns a mapping from dna to protein by inspecting sequence features of
2078    * type "CDS" on the dna.
2079    * 
2080    * @param dnaSeq
2081    * @param proteinSeq
2082    * @return
2083    */
2084   public static MapList mapCdsToProtein(SequenceI dnaSeq,
2085           SequenceI proteinSeq)
2086   {
2087     List<int[]> ranges = findCdsPositions(dnaSeq);
2088     int mappedDnaLength = MappingUtils.getLength(ranges);
2089
2090     int proteinLength = proteinSeq.getLength();
2091     int proteinStart = proteinSeq.getStart();
2092     int proteinEnd = proteinSeq.getEnd();
2093
2094     /*
2095      * incomplete start codon may mean X at start of peptide
2096      * we ignore both for mapping purposes
2097      */
2098     if (proteinSeq.getCharAt(0) == 'X')
2099     {
2100       // todo JAL-2022 support startPhase > 0
2101       proteinStart++;
2102       proteinLength--;
2103     }
2104     List<int[]> proteinRange = new ArrayList<int[]>();
2105
2106     /*
2107      * dna length should map to protein (or protein plus stop codon)
2108      */
2109     int codesForResidues = mappedDnaLength / 3;
2110     if (codesForResidues == (proteinLength + 1))
2111     {
2112       // assuming extra codon is for STOP and not in peptide
2113       codesForResidues--;
2114     }
2115     if (codesForResidues == proteinLength)
2116     {
2117       proteinRange.add(new int[] { proteinStart, proteinEnd });
2118       return new MapList(ranges, proteinRange, 3, 1);
2119     }
2120     return null;
2121   }
2122
2123   /**
2124    * Returns a list of CDS ranges found (as sequence positions base 1), i.e. of
2125    * start/end positions of sequence features of type "CDS" (or a sub-type of
2126    * CDS in the Sequence Ontology). The ranges are sorted into ascending start
2127    * position order, so this method is only valid for linear CDS in the same
2128    * sense as the protein product.
2129    * 
2130    * @param dnaSeq
2131    * @return
2132    */
2133   public static List<int[]> findCdsPositions(SequenceI dnaSeq)
2134   {
2135     List<int[]> result = new ArrayList<int[]>();
2136     SequenceFeature[] sfs = dnaSeq.getSequenceFeatures();
2137     if (sfs == null)
2138     {
2139       return result;
2140     }
2141
2142     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2143     int startPhase = 0;
2144
2145     for (SequenceFeature sf : sfs)
2146     {
2147       /*
2148        * process a CDS feature (or a sub-type of CDS)
2149        */
2150       if (so.isA(sf.getType(), SequenceOntologyI.CDS))
2151       {
2152         int phase = 0;
2153         try
2154         {
2155           phase = Integer.parseInt(sf.getPhase());
2156         } catch (NumberFormatException e)
2157         {
2158           // ignore
2159         }
2160         /*
2161          * phase > 0 on first codon means 5' incomplete - skip to the start
2162          * of the next codon; example ENST00000496384
2163          */
2164         int begin = sf.getBegin();
2165         int end = sf.getEnd();
2166         if (result.isEmpty())
2167         {
2168           begin += phase;
2169           if (begin > end)
2170           {
2171             // shouldn't happen!
2172             System.err
2173                     .println("Error: start phase extends beyond start CDS in "
2174                             + dnaSeq.getName());
2175           }
2176         }
2177         result.add(new int[] { begin, end });
2178       }
2179     }
2180
2181     /*
2182      * remove 'startPhase' positions (usually 0) from the first range 
2183      * so we begin at the start of a complete codon
2184      */
2185     if (!result.isEmpty())
2186     {
2187       // TODO JAL-2022 correctly model start phase > 0
2188       result.get(0)[0] += startPhase;
2189     }
2190
2191     /*
2192      * Finally sort ranges by start position. This avoids a dependency on 
2193      * keeping features in order on the sequence (if they are in order anyway,
2194      * the sort will have almost no work to do). The implicit assumption is CDS
2195      * ranges are assembled in order. Other cases should not use this method,
2196      * but instead construct an explicit mapping for CDS (e.g. EMBL parsing).
2197      */
2198     Collections.sort(result, new Comparator<int[]>()
2199     {
2200       @Override
2201       public int compare(int[] o1, int[] o2)
2202       {
2203         return Integer.compare(o1[0], o2[0]);
2204       }
2205     });
2206     return result;
2207   }
2208
2209   /**
2210    * Maps exon features from dna to protein, and computes variants in peptide
2211    * product generated by variants in dna, and adds them as sequence_variant
2212    * features on the protein sequence. Returns the number of variant features
2213    * added.
2214    * 
2215    * @param dnaSeq
2216    * @param peptide
2217    * @param dnaToProtein
2218    */
2219   public static int computeProteinFeatures(SequenceI dnaSeq,
2220           SequenceI peptide, MapList dnaToProtein)
2221   {
2222     while (dnaSeq.getDatasetSequence() != null)
2223     {
2224       dnaSeq = dnaSeq.getDatasetSequence();
2225     }
2226     while (peptide.getDatasetSequence() != null)
2227     {
2228       peptide = peptide.getDatasetSequence();
2229     }
2230
2231     transferFeatures(dnaSeq, peptide, dnaToProtein, SequenceOntologyI.EXON);
2232
2233     /*
2234      * compute protein variants from dna variants and codon mappings;
2235      * NB - alternatively we could retrieve this using the REST service e.g.
2236      * http://rest.ensembl.org/overlap/translation
2237      * /ENSP00000288602?feature=transcript_variation;content-type=text/xml
2238      * which would be a bit slower but possibly more reliable
2239      */
2240
2241     /*
2242      * build a map with codon variations for each potentially varying peptide
2243      */
2244     LinkedHashMap<Integer, List<DnaVariant>[]> variants = buildDnaVariantsMap(
2245             dnaSeq, dnaToProtein);
2246
2247     /*
2248      * scan codon variations, compute peptide variants and add to peptide sequence
2249      */
2250     int count = 0;
2251     for (Entry<Integer, List<DnaVariant>[]> variant : variants.entrySet())
2252     {
2253       int peptidePos = variant.getKey();
2254       List<DnaVariant>[] codonVariants = variant.getValue();
2255       count += computePeptideVariants(peptide, peptidePos, codonVariants);
2256     }
2257
2258     /*
2259      * sort to get sequence features in start position order
2260      * - would be better to store in Sequence as a TreeSet or NCList?
2261      */
2262     if (peptide.getSequenceFeatures() != null)
2263     {
2264       Arrays.sort(peptide.getSequenceFeatures(),
2265               new Comparator<SequenceFeature>()
2266               {
2267                 @Override
2268                 public int compare(SequenceFeature o1, SequenceFeature o2)
2269                 {
2270                   int c = Integer.compare(o1.getBegin(), o2.getBegin());
2271                   return c == 0 ? Integer.compare(o1.getEnd(), o2.getEnd())
2272                           : c;
2273                 }
2274               });
2275     }
2276     return count;
2277   }
2278
2279   /**
2280    * Computes non-synonymous peptide variants from codon variants and adds them
2281    * as sequence_variant features on the protein sequence (one feature per
2282    * allele variant). Selected attributes (variant id, clinical significance)
2283    * are copied over to the new features.
2284    * 
2285    * @param peptide
2286    *          the protein sequence
2287    * @param peptidePos
2288    *          the position to compute peptide variants for
2289    * @param codonVariants
2290    *          a list of dna variants per codon position
2291    * @return the number of features added
2292    */
2293   static int computePeptideVariants(SequenceI peptide, int peptidePos,
2294           List<DnaVariant>[] codonVariants)
2295   {
2296     String residue = String.valueOf(peptide.getCharAt(peptidePos - 1));
2297     int count = 0;
2298     String base1 = codonVariants[0].get(0).base;
2299     String base2 = codonVariants[1].get(0).base;
2300     String base3 = codonVariants[2].get(0).base;
2301
2302     /*
2303      * variants in first codon base
2304      */
2305     for (DnaVariant var : codonVariants[0])
2306     {
2307       if (var.variant != null)
2308       {
2309         String alleles = (String) var.variant.getValue("alleles");
2310         if (alleles != null)
2311         {
2312           for (String base : alleles.split(","))
2313           {
2314             String codon = base + base2 + base3;
2315             if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2316             {
2317               count++;
2318             }
2319           }
2320         }
2321       }
2322     }
2323
2324     /*
2325      * variants in second codon base
2326      */
2327     for (DnaVariant var : codonVariants[1])
2328     {
2329       if (var.variant != null)
2330       {
2331         String alleles = (String) var.variant.getValue("alleles");
2332         if (alleles != null)
2333         {
2334           for (String base : alleles.split(","))
2335           {
2336             String codon = base1 + base + base3;
2337             if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2338             {
2339               count++;
2340             }
2341           }
2342         }
2343       }
2344     }
2345
2346     /*
2347      * variants in third codon base
2348      */
2349     for (DnaVariant var : codonVariants[2])
2350     {
2351       if (var.variant != null)
2352       {
2353         String alleles = (String) var.variant.getValue("alleles");
2354         if (alleles != null)
2355         {
2356           for (String base : alleles.split(","))
2357           {
2358             String codon = base1 + base2 + base;
2359             if (addPeptideVariant(peptide, peptidePos, residue, var, codon))
2360             {
2361               count++;
2362             }
2363           }
2364         }
2365       }
2366     }
2367
2368     return count;
2369   }
2370
2371   /**
2372    * Helper method that adds a peptide variant feature, provided the given codon
2373    * translates to a value different to the current residue (is a non-synonymous
2374    * variant). ID and clinical_significance attributes of the dna variant (if
2375    * present) are copied to the new feature.
2376    * 
2377    * @param peptide
2378    * @param peptidePos
2379    * @param residue
2380    * @param var
2381    * @param codon
2382    * @return true if a feature was added, else false
2383    */
2384   static boolean addPeptideVariant(SequenceI peptide, int peptidePos,
2385           String residue, DnaVariant var, String codon)
2386   {
2387     /*
2388      * get peptide translation of codon e.g. GAT -> D
2389      * note that variants which are not single alleles,
2390      * e.g. multibase variants or HGMD_MUTATION etc
2391      * are currently ignored here
2392      */
2393     String trans = codon.contains("-") ? "-"
2394             : (codon.length() > 3 ? null : ResidueProperties
2395                     .codonTranslate(codon));
2396     if (trans != null && !trans.equals(residue))
2397     {
2398       String residue3Char = StringUtils
2399               .toSentenceCase(ResidueProperties.aa2Triplet.get(residue));
2400       String trans3Char = StringUtils
2401               .toSentenceCase(ResidueProperties.aa2Triplet.get(trans));
2402       String desc = "p." + residue3Char + peptidePos + trans3Char;
2403       // set score to 0f so 'graduated colour' option is offered! JAL-2060
2404       SequenceFeature sf = new SequenceFeature(
2405               SequenceOntologyI.SEQUENCE_VARIANT, desc, peptidePos,
2406               peptidePos, 0f, "Jalview");
2407       StringBuilder attributes = new StringBuilder(32);
2408       String id = (String) var.variant.getValue(ID);
2409       if (id != null)
2410       {
2411         if (id.startsWith(SEQUENCE_VARIANT))
2412         {
2413           id = id.substring(SEQUENCE_VARIANT.length());
2414         }
2415         sf.setValue(ID, id);
2416         attributes.append(ID).append("=").append(id);
2417         // TODO handle other species variants
2418         StringBuilder link = new StringBuilder(32);
2419         try
2420         {
2421           link.append(desc).append(" ").append(id)
2422                   .append("|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=")
2423                   .append(URLEncoder.encode(id, "UTF-8"));
2424           sf.addLink(link.toString());
2425         } catch (UnsupportedEncodingException e)
2426         {
2427           // as if
2428         }
2429       }
2430       String clinSig = (String) var.variant
2431               .getValue(CLINICAL_SIGNIFICANCE);
2432       if (clinSig != null)
2433       {
2434         sf.setValue(CLINICAL_SIGNIFICANCE, clinSig);
2435         attributes.append(";").append(CLINICAL_SIGNIFICANCE).append("=")
2436                 .append(clinSig);
2437       }
2438       peptide.addSequenceFeature(sf);
2439       if (attributes.length() > 0)
2440       {
2441         sf.setAttributes(attributes.toString());
2442       }
2443       return true;
2444     }
2445     return false;
2446   }
2447
2448   /**
2449    * Builds a map whose key is position in the protein sequence, and value is a
2450    * list of the base and all variants for each corresponding codon position
2451    * 
2452    * @param dnaSeq
2453    * @param dnaToProtein
2454    * @return
2455    */
2456   static LinkedHashMap<Integer, List<DnaVariant>[]> buildDnaVariantsMap(
2457           SequenceI dnaSeq, MapList dnaToProtein)
2458   {
2459     /*
2460      * map from peptide position to all variants of the codon which codes for it
2461      * LinkedHashMap ensures we keep the peptide features in sequence order
2462      */
2463     LinkedHashMap<Integer, List<DnaVariant>[]> variants = new LinkedHashMap<Integer, List<DnaVariant>[]>();
2464     SequenceOntologyI so = SequenceOntologyFactory.getInstance();
2465
2466     SequenceFeature[] dnaFeatures = dnaSeq.getSequenceFeatures();
2467     if (dnaFeatures == null)
2468     {
2469       return variants;
2470     }
2471
2472     int dnaStart = dnaSeq.getStart();
2473     int[] lastCodon = null;
2474     int lastPeptidePostion = 0;
2475
2476     /*
2477      * build a map of codon variations for peptides
2478      */
2479     for (SequenceFeature sf : dnaFeatures)
2480     {
2481       int dnaCol = sf.getBegin();
2482       if (dnaCol != sf.getEnd())
2483       {
2484         // not handling multi-locus variant features
2485         continue;
2486       }
2487       if (so.isA(sf.getType(), SequenceOntologyI.SEQUENCE_VARIANT))
2488       {
2489         int[] mapsTo = dnaToProtein.locateInTo(dnaCol, dnaCol);
2490         if (mapsTo == null)
2491         {
2492           // feature doesn't lie within coding region
2493           continue;
2494         }
2495         int peptidePosition = mapsTo[0];
2496         List<DnaVariant>[] codonVariants = variants.get(peptidePosition);
2497         if (codonVariants == null)
2498         {
2499           codonVariants = new ArrayList[3];
2500           codonVariants[0] = new ArrayList<DnaVariant>();
2501           codonVariants[1] = new ArrayList<DnaVariant>();
2502           codonVariants[2] = new ArrayList<DnaVariant>();
2503           variants.put(peptidePosition, codonVariants);
2504         }
2505
2506         /*
2507          * extract dna variants to a string array
2508          */
2509         String alls = (String) sf.getValue("alleles");
2510         if (alls == null)
2511         {
2512           continue;
2513         }
2514         String[] alleles = alls.toUpperCase().split(",");
2515         int i = 0;
2516         for (String allele : alleles)
2517         {
2518           alleles[i++] = allele.trim(); // lose any space characters "A, G"
2519         }
2520
2521         /*
2522          * get this peptide's codon positions e.g. [3, 4, 5] or [4, 7, 10]
2523          */
2524         int[] codon = peptidePosition == lastPeptidePostion ? lastCodon
2525                 : MappingUtils.flattenRanges(dnaToProtein.locateInFrom(
2526                         peptidePosition, peptidePosition));
2527         lastPeptidePostion = peptidePosition;
2528         lastCodon = codon;
2529
2530         /*
2531          * save nucleotide (and any variant) for each codon position
2532          */
2533         for (int codonPos = 0; codonPos < 3; codonPos++)
2534         {
2535           String nucleotide = String.valueOf(
2536                   dnaSeq.getCharAt(codon[codonPos] - dnaStart))
2537                   .toUpperCase();
2538           List<DnaVariant> codonVariant = codonVariants[codonPos];
2539           if (codon[codonPos] == dnaCol)
2540           {
2541             if (!codonVariant.isEmpty()
2542                     && codonVariant.get(0).variant == null)
2543             {
2544               /*
2545                * already recorded base value, add this variant
2546                */
2547               codonVariant.get(0).variant = sf;
2548             }
2549             else
2550             {
2551               /*
2552                * add variant with base value
2553                */
2554               codonVariant.add(new DnaVariant(nucleotide, sf));
2555             }
2556           }
2557           else if (codonVariant.isEmpty())
2558           {
2559             /*
2560              * record (possibly non-varying) base value
2561              */
2562             codonVariant.add(new DnaVariant(nucleotide));
2563           }
2564         }
2565       }
2566     }
2567     return variants;
2568   }
2569
2570   /**
2571    * Makes an alignment with a copy of the given sequences, adding in any
2572    * non-redundant sequences which are mapped to by the cross-referenced
2573    * sequences.
2574    * 
2575    * @param seqs
2576    * @param xrefs
2577    * @param dataset
2578    *          the alignment dataset shared by the new copy
2579    * @return
2580    */
2581   public static AlignmentI makeCopyAlignment(SequenceI[] seqs,
2582           SequenceI[] xrefs, AlignmentI dataset)
2583   {
2584     AlignmentI copy = new Alignment(new Alignment(seqs));
2585     copy.setDataset(dataset);
2586
2587     SequenceIdMatcher matcher = new SequenceIdMatcher(seqs);
2588     if (xrefs != null)
2589     {
2590       for (SequenceI xref : xrefs)
2591       {
2592         DBRefEntry[] dbrefs = xref.getDBRefs();
2593         if (dbrefs != null)
2594         {
2595           for (DBRefEntry dbref : dbrefs)
2596           {
2597             if (dbref.getMap() == null || dbref.getMap().getTo() == null)
2598             {
2599               continue;
2600             }
2601             SequenceI mappedTo = dbref.getMap().getTo();
2602             SequenceI match = matcher.findIdMatch(mappedTo);
2603             if (match == null)
2604             {
2605               matcher.add(mappedTo);
2606               copy.addSequence(mappedTo);
2607             }
2608           }
2609         }
2610       }
2611     }
2612     return copy;
2613   }
2614
2615   /**
2616    * Try to align sequences in 'unaligned' to match the alignment of their
2617    * mapped regions in 'aligned'. For example, could use this to align CDS
2618    * sequences which are mapped to their parent cDNA sequences.
2619    * 
2620    * This method handles 1:1 mappings (dna-to-dna or protein-to-protein). For
2621    * dna-to-protein or protein-to-dna use alternative methods.
2622    * 
2623    * @param unaligned
2624    *          sequences to be aligned
2625    * @param aligned
2626    *          holds aligned sequences and their mappings
2627    * @return
2628    */
2629   public static int alignAs(AlignmentI unaligned, AlignmentI aligned)
2630   {
2631     /*
2632      * easy case - aligning a copy of aligned sequences
2633      */
2634     if (alignAsSameSequences(unaligned, aligned))
2635     {
2636       return unaligned.getHeight();
2637     }
2638
2639     /*
2640      * fancy case - aligning via mappings between sequences
2641      */
2642     List<SequenceI> unmapped = new ArrayList<SequenceI>();
2643     Map<Integer, Map<SequenceI, Character>> columnMap = buildMappedColumnsMap(
2644             unaligned, aligned, unmapped);
2645     int width = columnMap.size();
2646     char gap = unaligned.getGapCharacter();
2647     int realignedCount = 0;
2648     // TODO: verify this loop scales sensibly for very wide/high alignments
2649
2650     for (SequenceI seq : unaligned.getSequences())
2651     {
2652       if (!unmapped.contains(seq))
2653       {
2654         char[] newSeq = new char[width];
2655         Arrays.fill(newSeq, gap); // JBPComment - doubt this is faster than the
2656                                   // Integer iteration below
2657         int newCol = 0;
2658         int lastCol = 0;
2659
2660         /*
2661          * traverse the map to find columns populated
2662          * by our sequence
2663          */
2664         for (Integer column : columnMap.keySet())
2665         {
2666           Character c = columnMap.get(column).get(seq);
2667           if (c != null)
2668           {
2669             /*
2670              * sequence has a character at this position
2671              * 
2672              */
2673             newSeq[newCol] = c;
2674             lastCol = newCol;
2675           }
2676           newCol++;
2677         }
2678         
2679         /*
2680          * trim trailing gaps
2681          */
2682         if (lastCol < width)
2683         {
2684           char[] tmp = new char[lastCol + 1];
2685           System.arraycopy(newSeq, 0, tmp, 0, lastCol + 1);
2686           newSeq = tmp;
2687         }
2688         // TODO: optimise SequenceI to avoid char[]->String->char[]
2689         seq.setSequence(String.valueOf(newSeq));
2690         realignedCount++;
2691       }
2692     }
2693     return realignedCount;
2694   }
2695
2696   /**
2697    * If unaligned and aligned sequences share the same dataset sequences, then
2698    * simply copies the aligned sequences to the unaligned sequences and returns
2699    * true; else returns false
2700    * 
2701    * @param unaligned
2702    *          - sequences to be aligned based on aligned
2703    * @param aligned
2704    *          - 'guide' alignment containing sequences derived from same dataset
2705    *          as unaligned
2706    * @return
2707    */
2708   static boolean alignAsSameSequences(AlignmentI unaligned,
2709           AlignmentI aligned)
2710   {
2711     if (aligned.getDataset() == null || unaligned.getDataset() == null)
2712     {
2713       return false; // should only pass alignments with datasets here
2714     }
2715
2716     // map from dataset sequence to alignment sequence(s)
2717     Map<SequenceI, List<SequenceI>> alignedDatasets = new HashMap<SequenceI, List<SequenceI>>();
2718     for (SequenceI seq : aligned.getSequences())
2719     {
2720       SequenceI ds = seq.getDatasetSequence();
2721       if (alignedDatasets.get(ds) == null)
2722       {
2723         alignedDatasets.put(ds, new ArrayList<SequenceI>());
2724       }
2725       alignedDatasets.get(ds).add(seq);
2726     }
2727
2728     /*
2729      * first pass - check whether all sequences to be aligned share a dataset
2730      * sequence with an aligned sequence
2731      */
2732     for (SequenceI seq : unaligned.getSequences())
2733     {
2734       if (!alignedDatasets.containsKey(seq.getDatasetSequence()))
2735       {
2736         return false;
2737       }
2738     }
2739
2740     /*
2741      * second pass - copy aligned sequences;
2742      * heuristic rule: pair off sequences in order for the case where 
2743      * more than one shares the same dataset sequence 
2744      */
2745     for (SequenceI seq : unaligned.getSequences())
2746     {
2747       List<SequenceI> alignedSequences = alignedDatasets.get(seq
2748               .getDatasetSequence());
2749       // TODO: getSequenceAsString() will be deprecated in the future
2750       // TODO: need to leave to SequenceI implementor to update gaps
2751       seq.setSequence(alignedSequences.get(0).getSequenceAsString());
2752       if (alignedSequences.size() > 0)
2753       {
2754         // pop off aligned sequences (except the last one)
2755         alignedSequences.remove(0);
2756       }
2757     }
2758
2759     return true;
2760   }
2761
2762   /**
2763    * Returns a map whose key is alignment column number (base 1), and whose
2764    * values are a map of sequence characters in that column.
2765    * 
2766    * @param unaligned
2767    * @param aligned
2768    * @param unmapped
2769    * @return
2770    */
2771   static Map<Integer, Map<SequenceI, Character>> buildMappedColumnsMap(
2772           AlignmentI unaligned, AlignmentI aligned, List<SequenceI> unmapped)
2773   {
2774     /*
2775      * Map will hold, for each aligned column position, a map of
2776      * {unalignedSequence, characterPerSequence} at that position.
2777      * TreeMap keeps the entries in ascending column order. 
2778      */
2779     Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2780
2781     /*
2782      * record any sequences that have no mapping so can't be realigned
2783      */
2784     unmapped.addAll(unaligned.getSequences());
2785
2786     List<AlignedCodonFrame> mappings = aligned.getCodonFrames();
2787
2788     for (SequenceI seq : unaligned.getSequences())
2789     {
2790       for (AlignedCodonFrame mapping : mappings)
2791       {
2792         SequenceI fromSeq = mapping.findAlignedSequence(seq, aligned);
2793         if (fromSeq != null)
2794         {
2795           Mapping seqMap = mapping.getMappingBetween(fromSeq, seq);
2796           if (addMappedPositions(seq, fromSeq, seqMap, map))
2797           {
2798             unmapped.remove(seq);
2799           }
2800         }
2801       }
2802     }
2803     return map;
2804   }
2805
2806   /**
2807    * Helper method that adds to a map the mapped column positions of a sequence. <br>
2808    * For example if aaTT-Tg-gAAA is mapped to TTTAAA then the map should record
2809    * that columns 3,4,6,10,11,12 map to characters T,T,T,A,A,A of the mapped to
2810    * sequence.
2811    * 
2812    * @param seq
2813    *          the sequence whose column positions we are recording
2814    * @param fromSeq
2815    *          a sequence that is mapped to the first sequence
2816    * @param seqMap
2817    *          the mapping from 'fromSeq' to 'seq'
2818    * @param map
2819    *          a map to add the column positions (in fromSeq) of the mapped
2820    *          positions of seq
2821    * @return
2822    */
2823   static boolean addMappedPositions(SequenceI seq, SequenceI fromSeq,
2824           Mapping seqMap, Map<Integer, Map<SequenceI, Character>> map)
2825   {
2826     if (seqMap == null)
2827     {
2828       return false;
2829     }
2830
2831     /*
2832      * invert mapping if it is from unaligned to aligned sequence
2833      */
2834     if (seqMap.getTo() == fromSeq.getDatasetSequence())
2835     {
2836       seqMap = new Mapping(seq.getDatasetSequence(), seqMap.getMap()
2837               .getInverse());
2838     }
2839
2840     char[] fromChars = fromSeq.getSequence();
2841     int toStart = seq.getStart();
2842     char[] toChars = seq.getSequence();
2843
2844     /*
2845      * traverse [start, end, start, end...] ranges in fromSeq
2846      */
2847     for (int[] fromRange : seqMap.getMap().getFromRanges())
2848     {
2849       for (int i = 0; i < fromRange.length - 1; i += 2)
2850       {
2851         boolean forward = fromRange[i + 1] >= fromRange[i];
2852
2853         /*
2854          * find the range mapped to (sequence positions base 1)
2855          */
2856         int[] range = seqMap.locateMappedRange(fromRange[i],
2857                 fromRange[i + 1]);
2858         if (range == null)
2859         {
2860           System.err.println("Error in mapping " + seqMap + " from "
2861                   + fromSeq.getName());
2862           return false;
2863         }
2864         int fromCol = fromSeq.findIndex(fromRange[i]);
2865         int mappedCharPos = range[0];
2866
2867         /*
2868          * walk over the 'from' aligned sequence in forward or reverse
2869          * direction; when a non-gap is found, record the column position
2870          * of the next character of the mapped-to sequence; stop when all
2871          * the characters of the range have been counted
2872          */
2873         while (mappedCharPos <= range[1] && fromCol <= fromChars.length
2874                 && fromCol >= 0)
2875         {
2876           if (!Comparison.isGap(fromChars[fromCol - 1]))
2877           {
2878             /*
2879              * mapped from sequence has a character in this column
2880              * record the column position for the mapped to character
2881              */
2882             Map<SequenceI, Character> seqsMap = map.get(fromCol);
2883             if (seqsMap == null)
2884             {
2885               seqsMap = new HashMap<SequenceI, Character>();
2886               map.put(fromCol, seqsMap);
2887             }
2888             seqsMap.put(seq, toChars[mappedCharPos - toStart]);
2889             mappedCharPos++;
2890           }
2891           fromCol += (forward ? 1 : -1);
2892         }
2893       }
2894     }
2895     return true;
2896   }
2897
2898   // strictly temporary hack until proper criteria for aligning protein to cds
2899   // are in place; this is so Ensembl -> fetch xrefs Uniprot aligns the Uniprot
2900   public static boolean looksLikeEnsembl(AlignmentI alignment)
2901   {
2902     for (SequenceI seq : alignment.getSequences())
2903     {
2904       String name = seq.getName();
2905       if (!name.startsWith("ENSG") && !name.startsWith("ENST"))
2906       {
2907         return false;
2908       }
2909     }
2910     return true;
2911   }
2912 }