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