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