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