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