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