JAL-2230 JAL-2049 added sequence feature transfer to
[jalview.git] / test / jalview / analysis / AlignmentUtilsTests.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 org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertFalse;
25 import static org.testng.AssertJUnit.assertNotNull;
26 import static org.testng.AssertJUnit.assertNull;
27 import static org.testng.AssertJUnit.assertSame;
28 import static org.testng.AssertJUnit.assertTrue;
29
30 import jalview.analysis.AlignmentUtils.DnaVariant;
31 import jalview.datamodel.AlignedCodonFrame;
32 import jalview.datamodel.Alignment;
33 import jalview.datamodel.AlignmentAnnotation;
34 import jalview.datamodel.AlignmentI;
35 import jalview.datamodel.Annotation;
36 import jalview.datamodel.DBRefEntry;
37 import jalview.datamodel.Mapping;
38 import jalview.datamodel.SearchResults;
39 import jalview.datamodel.SearchResults.Match;
40 import jalview.datamodel.Sequence;
41 import jalview.datamodel.SequenceFeature;
42 import jalview.datamodel.SequenceI;
43 import jalview.io.AppletFormatAdapter;
44 import jalview.io.FormatAdapter;
45 import jalview.util.MapList;
46 import jalview.util.MappingUtils;
47
48 import java.io.IOException;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.LinkedHashMap;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.TreeMap;
55
56 import org.testng.annotations.Test;
57
58 public class AlignmentUtilsTests
59 {
60   public static Sequence ts = new Sequence("short",
61           "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm");
62
63   @Test(groups = { "Functional" })
64   public void testExpandContext()
65   {
66     AlignmentI al = new Alignment(new Sequence[] {});
67     for (int i = 4; i < 14; i += 2)
68     {
69       SequenceI s1 = ts.deriveSequence().getSubSequence(i, i + 7);
70       al.addSequence(s1);
71     }
72     System.out.println(new AppletFormatAdapter().formatSequences("Clustal",
73             al, true));
74     for (int flnk = -1; flnk < 25; flnk++)
75     {
76       AlignmentI exp = AlignmentUtils.expandContext(al, flnk);
77       System.out.println("\nFlank size: " + flnk);
78       System.out.println(new AppletFormatAdapter().formatSequences(
79               "Clustal", exp, true));
80       if (flnk == -1)
81       {
82         /*
83          * Full expansion to complete sequences
84          */
85         for (SequenceI sq : exp.getSequences())
86         {
87           String ung = sq.getSequenceAsString().replaceAll("-+", "");
88           final String errorMsg = "Flanking sequence not the same as original dataset sequence.\n"
89                   + ung
90                   + "\n"
91                   + sq.getDatasetSequence().getSequenceAsString();
92           assertTrue(errorMsg, ung.equalsIgnoreCase(sq.getDatasetSequence()
93                   .getSequenceAsString()));
94         }
95       }
96       else if (flnk == 24)
97       {
98         /*
99          * Last sequence is fully expanded, others have leading gaps to match
100          */
101         assertTrue(exp.getSequenceAt(4).getSequenceAsString()
102                 .startsWith("abc"));
103         assertTrue(exp.getSequenceAt(3).getSequenceAsString()
104                 .startsWith("--abc"));
105         assertTrue(exp.getSequenceAt(2).getSequenceAsString()
106                 .startsWith("----abc"));
107         assertTrue(exp.getSequenceAt(1).getSequenceAsString()
108                 .startsWith("------abc"));
109         assertTrue(exp.getSequenceAt(0).getSequenceAsString()
110                 .startsWith("--------abc"));
111       }
112     }
113   }
114
115   /**
116    * Test that annotations are correctly adjusted by expandContext
117    */
118   @Test(groups = { "Functional" })
119   public void testExpandContext_annotation()
120   {
121     AlignmentI al = new Alignment(new Sequence[] {});
122     SequenceI ds = new Sequence("Seq1", "ABCDEFGHI");
123     // subsequence DEF:
124     SequenceI seq1 = ds.deriveSequence().getSubSequence(3, 6);
125     al.addSequence(seq1);
126
127     /*
128      * Annotate DEF with 4/5/6 respectively
129      */
130     Annotation[] anns = new Annotation[] { new Annotation(4),
131         new Annotation(5), new Annotation(6) };
132     AlignmentAnnotation ann = new AlignmentAnnotation("SS",
133             "secondary structure", anns);
134     seq1.addAlignmentAnnotation(ann);
135
136     /*
137      * The annotations array should match aligned positions
138      */
139     assertEquals(3, ann.annotations.length);
140     assertEquals(4, ann.annotations[0].value, 0.001);
141     assertEquals(5, ann.annotations[1].value, 0.001);
142     assertEquals(6, ann.annotations[2].value, 0.001);
143
144     /*
145      * Check annotation to sequence position mappings before expanding the
146      * sequence; these are set up in Sequence.addAlignmentAnnotation ->
147      * Annotation.setSequenceRef -> createSequenceMappings
148      */
149     assertNull(ann.getAnnotationForPosition(1));
150     assertNull(ann.getAnnotationForPosition(2));
151     assertNull(ann.getAnnotationForPosition(3));
152     assertEquals(4, ann.getAnnotationForPosition(4).value, 0.001);
153     assertEquals(5, ann.getAnnotationForPosition(5).value, 0.001);
154     assertEquals(6, ann.getAnnotationForPosition(6).value, 0.001);
155     assertNull(ann.getAnnotationForPosition(7));
156     assertNull(ann.getAnnotationForPosition(8));
157     assertNull(ann.getAnnotationForPosition(9));
158
159     /*
160      * Expand the subsequence to the full sequence abcDEFghi
161      */
162     AlignmentI expanded = AlignmentUtils.expandContext(al, -1);
163     assertEquals("abcDEFghi", expanded.getSequenceAt(0)
164             .getSequenceAsString());
165
166     /*
167      * Confirm the alignment and sequence have the same SS annotation,
168      * referencing the expanded sequence
169      */
170     ann = expanded.getSequenceAt(0).getAnnotation()[0];
171     assertSame(ann, expanded.getAlignmentAnnotation()[0]);
172     assertSame(expanded.getSequenceAt(0), ann.sequenceRef);
173
174     /*
175      * The annotations array should have null values except for annotated
176      * positions
177      */
178     assertNull(ann.annotations[0]);
179     assertNull(ann.annotations[1]);
180     assertNull(ann.annotations[2]);
181     assertEquals(4, ann.annotations[3].value, 0.001);
182     assertEquals(5, ann.annotations[4].value, 0.001);
183     assertEquals(6, ann.annotations[5].value, 0.001);
184     assertNull(ann.annotations[6]);
185     assertNull(ann.annotations[7]);
186     assertNull(ann.annotations[8]);
187
188     /*
189      * sequence position mappings should be unchanged
190      */
191     assertNull(ann.getAnnotationForPosition(1));
192     assertNull(ann.getAnnotationForPosition(2));
193     assertNull(ann.getAnnotationForPosition(3));
194     assertEquals(4, ann.getAnnotationForPosition(4).value, 0.001);
195     assertEquals(5, ann.getAnnotationForPosition(5).value, 0.001);
196     assertEquals(6, ann.getAnnotationForPosition(6).value, 0.001);
197     assertNull(ann.getAnnotationForPosition(7));
198     assertNull(ann.getAnnotationForPosition(8));
199     assertNull(ann.getAnnotationForPosition(9));
200   }
201
202   /**
203    * Test method that returns a map of lists of sequences by sequence name.
204    * 
205    * @throws IOException
206    */
207   @Test(groups = { "Functional" })
208   public void testGetSequencesByName() throws IOException
209   {
210     final String data = ">Seq1Name\nKQYL\n" + ">Seq2Name\nRFPW\n"
211             + ">Seq1Name\nABCD\n";
212     AlignmentI al = loadAlignment(data, "FASTA");
213     Map<String, List<SequenceI>> map = AlignmentUtils
214             .getSequencesByName(al);
215     assertEquals(2, map.keySet().size());
216     assertEquals(2, map.get("Seq1Name").size());
217     assertEquals("KQYL", map.get("Seq1Name").get(0).getSequenceAsString());
218     assertEquals("ABCD", map.get("Seq1Name").get(1).getSequenceAsString());
219     assertEquals(1, map.get("Seq2Name").size());
220     assertEquals("RFPW", map.get("Seq2Name").get(0).getSequenceAsString());
221   }
222
223   /**
224    * Helper method to load an alignment and ensure dataset sequences are set up.
225    * 
226    * @param data
227    * @param format
228    *          TODO
229    * @return
230    * @throws IOException
231    */
232   protected AlignmentI loadAlignment(final String data, String format)
233           throws IOException
234   {
235     AlignmentI a = new FormatAdapter().readFile(data,
236             AppletFormatAdapter.PASTE, format);
237     a.setDataset(null);
238     return a;
239   }
240
241   /**
242    * Test mapping of protein to cDNA, for the case where we have no sequence
243    * cross-references, so mappings are made first-served 1-1 where sequences
244    * translate.
245    * 
246    * @throws IOException
247    */
248   @Test(groups = { "Functional" })
249   public void testMapProteinAlignmentToCdna_noXrefs() throws IOException
250   {
251     List<SequenceI> protseqs = new ArrayList<SequenceI>();
252     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
253     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
254     protseqs.add(new Sequence("UNIPROT|V12347", "SAR"));
255     AlignmentI protein = new Alignment(protseqs.toArray(new SequenceI[3]));
256     protein.setDataset(null);
257
258     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
259     dnaseqs.add(new Sequence("EMBL|A11111", "TCAGCACGC")); // = SAR
260     dnaseqs.add(new Sequence("EMBL|A22222", "GAGATACAA")); // = EIQ
261     dnaseqs.add(new Sequence("EMBL|A33333", "GAAATCCAG")); // = EIQ
262     dnaseqs.add(new Sequence("EMBL|A44444", "GAAATTCAG")); // = EIQ
263     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[4]));
264     cdna.setDataset(null);
265
266     assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
267
268     // 3 mappings made, each from 1 to 1 sequence
269     assertEquals(3, protein.getCodonFrames().size());
270     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
271     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
272     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(2)).size());
273
274     // V12345 mapped to A22222
275     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
276             .get(0);
277     assertEquals(1, acf.getdnaSeqs().length);
278     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
279             acf.getdnaSeqs()[0]);
280     Mapping[] protMappings = acf.getProtMappings();
281     assertEquals(1, protMappings.length);
282     MapList mapList = protMappings[0].getMap();
283     assertEquals(3, mapList.getFromRatio());
284     assertEquals(1, mapList.getToRatio());
285     assertTrue(Arrays.equals(new int[] { 1, 9 }, mapList.getFromRanges()
286             .get(0)));
287     assertEquals(1, mapList.getFromRanges().size());
288     assertTrue(Arrays.equals(new int[] { 1, 3 },
289             mapList.getToRanges().get(0)));
290     assertEquals(1, mapList.getToRanges().size());
291
292     // V12346 mapped to A33333
293     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
294     assertEquals(1, acf.getdnaSeqs().length);
295     assertEquals(cdna.getSequenceAt(2).getDatasetSequence(),
296             acf.getdnaSeqs()[0]);
297
298     // V12347 mapped to A11111
299     acf = protein.getCodonFrame(protein.getSequenceAt(2)).get(0);
300     assertEquals(1, acf.getdnaSeqs().length);
301     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
302             acf.getdnaSeqs()[0]);
303
304     // no mapping involving the 'extra' A44444
305     assertTrue(protein.getCodonFrame(cdna.getSequenceAt(3)).isEmpty());
306   }
307
308   /**
309    * Test for the alignSequenceAs method that takes two sequences and a mapping.
310    */
311   @Test(groups = { "Functional" })
312   public void testAlignSequenceAs_withMapping_noIntrons()
313   {
314     MapList map = new MapList(new int[] { 1, 6 }, new int[] { 1, 2 }, 3, 1);
315
316     /*
317      * No existing gaps in dna:
318      */
319     checkAlignSequenceAs("GGGAAA", "-A-L-", false, false, map,
320             "---GGG---AAA");
321
322     /*
323      * Now introduce gaps in dna but ignore them when realigning.
324      */
325     checkAlignSequenceAs("-G-G-G-A-A-A-", "-A-L-", false, false, map,
326             "---GGG---AAA");
327
328     /*
329      * Now include gaps in dna when realigning. First retaining 'mapped' gaps
330      * only, i.e. those within the exon region.
331      */
332     checkAlignSequenceAs("-G-G--G-A--A-A-", "-A-L-", true, false, map,
333             "---G-G--G---A--A-A");
334
335     /*
336      * Include all gaps in dna when realigning (within and without the exon
337      * region). The leading gap, and the gaps between codons, are subsumed by
338      * the protein alignment gap.
339      */
340     checkAlignSequenceAs("-G-GG--AA-A---", "-A-L-", true, true, map,
341             "---G-GG---AA-A---");
342
343     /*
344      * Include only unmapped gaps in dna when realigning (outside the exon
345      * region). The leading gap, and the gaps between codons, are subsumed by
346      * the protein alignment gap.
347      */
348     checkAlignSequenceAs("-G-GG--AA-A-", "-A-L-", false, true, map,
349             "---GGG---AAA---");
350   }
351
352   /**
353    * Test for the alignSequenceAs method that takes two sequences and a mapping.
354    */
355   @Test(groups = { "Functional" })
356   public void testAlignSequenceAs_withMapping_withIntrons()
357   {
358     /*
359      * Exons at codon 2 (AAA) and 4 (TTT)
360      */
361     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
362             new int[] { 1, 2 }, 3, 1);
363
364     /*
365      * Simple case: no gaps in dna
366      */
367     checkAlignSequenceAs("GGGAAACCCTTTGGG", "--A-L-", false, false, map,
368             "GGG---AAACCCTTTGGG");
369
370     /*
371      * Add gaps to dna - but ignore when realigning.
372      */
373     checkAlignSequenceAs("-G-G-G--A--A---AC-CC-T-TT-GG-G-", "--A-L-",
374             false, false, map, "GGG---AAACCCTTTGGG");
375
376     /*
377      * Add gaps to dna - include within exons only when realigning.
378      */
379     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
380             true, false, map, "GGG---A--A---ACCCT-TTGGG");
381
382     /*
383      * Include gaps outside exons only when realigning.
384      */
385     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
386             false, true, map, "-G-G-GAAAC-CCTTT-GG-G-");
387
388     /*
389      * Include gaps following first intron if we are 'preserving mapped gaps'
390      */
391     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
392             true, true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
393
394     /*
395      * Include all gaps in dna when realigning.
396      */
397     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
398             true, true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
399   }
400
401   /**
402    * Test for the case where not all of the protein sequence is mapped to cDNA.
403    */
404   @Test(groups = { "Functional" })
405   public void testAlignSequenceAs_withMapping_withUnmappedProtein()
406   {
407     /*
408      * Exons at codon 2 (AAA) and 4 (TTT) mapped to A and P
409      */
410     final MapList map = new MapList(new int[] { 4, 6, 10, 12 }, new int[] {
411         1, 1, 3, 3 }, 3, 1);
412
413     /*
414      * -L- 'aligns' ccc------
415      */
416     checkAlignSequenceAs("gggAAAcccTTTggg", "-A-L-P-", false, false, map,
417             "gggAAAccc------TTTggg");
418   }
419
420   /**
421    * Helper method that performs and verifies the method under test.
422    * 
423    * @param alignee
424    *          the sequence to be realigned
425    * @param alignModel
426    *          the sequence whose alignment is to be copied
427    * @param preserveMappedGaps
428    * @param preserveUnmappedGaps
429    * @param map
430    * @param expected
431    */
432   protected void checkAlignSequenceAs(final String alignee,
433           final String alignModel, final boolean preserveMappedGaps,
434           final boolean preserveUnmappedGaps, MapList map,
435           final String expected)
436   {
437     SequenceI alignMe = new Sequence("Seq1", alignee);
438     alignMe.createDatasetSequence();
439     SequenceI alignFrom = new Sequence("Seq2", alignModel);
440     alignFrom.createDatasetSequence();
441     AlignedCodonFrame acf = new AlignedCodonFrame();
442     acf.addMap(alignMe.getDatasetSequence(), alignFrom.getDatasetSequence(), map);
443
444     AlignmentUtils.alignSequenceAs(alignMe, alignFrom, acf, "---", '-',
445             preserveMappedGaps, preserveUnmappedGaps);
446     assertEquals(expected, alignMe.getSequenceAsString());
447   }
448
449   /**
450    * Test for the alignSequenceAs method where we preserve gaps in introns only.
451    */
452   @Test(groups = { "Functional" })
453   public void testAlignSequenceAs_keepIntronGapsOnly()
454   {
455
456     /*
457      * Intron GGGAAA followed by exon CCCTTT
458      */
459     MapList map = new MapList(new int[] { 7, 12 }, new int[] { 1, 2 }, 3, 1);
460
461     checkAlignSequenceAs("GG-G-AA-A-C-CC-T-TT", "AL", false, true, map,
462             "GG-G-AA-ACCCTTT");
463   }
464
465   /**
466    * Test the method that realigns protein to match mapped codon alignment.
467    */
468   @Test(groups = { "Functional" })
469   public void testAlignProteinAsDna()
470   {
471     // seq1 codons are [1,2,3] [4,5,6] [7,8,9] [10,11,12]
472     SequenceI dna1 = new Sequence("Seq1", "TGCCATTACCAG-");
473     // seq2 codons are [1,3,4] [5,6,7] [8,9,10] [11,12,13]
474     SequenceI dna2 = new Sequence("Seq2", "T-GCCATTACCAG");
475     // seq3 codons are [1,2,3] [4,5,7] [8,9,10] [11,12,13]
476     SequenceI dna3 = new Sequence("Seq3", "TGCCA-TTACCAG");
477     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2, dna3 });
478     dna.setDataset(null);
479
480     // protein alignment will be realigned like dna
481     SequenceI prot1 = new Sequence("Seq1", "CHYQ");
482     SequenceI prot2 = new Sequence("Seq2", "CHYQ");
483     SequenceI prot3 = new Sequence("Seq3", "CHYQ");
484     SequenceI prot4 = new Sequence("Seq4", "R-QSV"); // unmapped, unchanged
485     AlignmentI protein = new Alignment(new SequenceI[] { prot1, prot2,
486         prot3, prot4 });
487     protein.setDataset(null);
488
489     MapList map = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 }, 3, 1);
490     AlignedCodonFrame acf = new AlignedCodonFrame();
491     acf.addMap(dna1.getDatasetSequence(), prot1.getDatasetSequence(), map);
492     acf.addMap(dna2.getDatasetSequence(), prot2.getDatasetSequence(), map);
493     acf.addMap(dna3.getDatasetSequence(), prot3.getDatasetSequence(), map);
494     ArrayList<AlignedCodonFrame> acfs = new ArrayList<AlignedCodonFrame>();
495     acfs.add(acf);
496     protein.setCodonFrames(acfs);
497
498     /*
499      * Translated codon order is [1,2,3] [1,3,4] [4,5,6] [4,5,7] [5,6,7] [7,8,9]
500      * [8,9,10] [10,11,12] [11,12,13]
501      */
502     AlignmentUtils.alignProteinAsDna(protein, dna);
503     assertEquals("C-H--Y-Q-", prot1.getSequenceAsString());
504     assertEquals("-C--H-Y-Q", prot2.getSequenceAsString());
505     assertEquals("C--H--Y-Q", prot3.getSequenceAsString());
506     assertEquals("R-QSV", prot4.getSequenceAsString());
507   }
508
509   /**
510    * Test the method that tests whether a CDNA sequence translates to a protein
511    * sequence
512    */
513   @Test(groups = { "Functional" })
514   public void testTranslatesAs()
515   {
516     // null arguments check
517     assertFalse(AlignmentUtils.translatesAs(null, 0, null));
518     assertFalse(AlignmentUtils.translatesAs(new char[] { 't' }, 0, null));
519     assertFalse(AlignmentUtils.translatesAs(null, 0, new char[] { 'a' }));
520
521     // straight translation
522     assertTrue(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(), 0,
523             "FPKG".toCharArray()));
524     // with extra start codon (not in protein)
525     assertTrue(AlignmentUtils.translatesAs("atgtttcccaaaggg".toCharArray(),
526             3, "FPKG".toCharArray()));
527     // with stop codon1 (not in protein)
528     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtaa".toCharArray(),
529             0, "FPKG".toCharArray()));
530     // with stop codon1 (in protein as *)
531     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtaa".toCharArray(),
532             0, "FPKG*".toCharArray()));
533     // with stop codon2 (not in protein)
534     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtag".toCharArray(),
535             0, "FPKG".toCharArray()));
536     // with stop codon3 (not in protein)
537     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtga".toCharArray(),
538             0, "FPKG".toCharArray()));
539     // with start and stop codon1
540     assertTrue(AlignmentUtils.translatesAs(
541             "atgtttcccaaagggtaa".toCharArray(), 3, "FPKG".toCharArray()));
542     // with start and stop codon1 (in protein as *)
543     assertTrue(AlignmentUtils.translatesAs(
544             "atgtttcccaaagggtaa".toCharArray(), 3, "FPKG*".toCharArray()));
545     // with start and stop codon2
546     assertTrue(AlignmentUtils.translatesAs(
547             "atgtttcccaaagggtag".toCharArray(), 3, "FPKG".toCharArray()));
548     // with start and stop codon3
549     assertTrue(AlignmentUtils.translatesAs(
550             "atgtttcccaaagggtga".toCharArray(), 3, "FPKG".toCharArray()));
551
552     // with embedded stop codons
553     assertTrue(AlignmentUtils.translatesAs(
554             "atgtttTAGcccaaaTAAgggtga".toCharArray(), 3,
555             "F*PK*G".toCharArray()));
556
557     // wrong protein
558     assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
559             0, "FPMG".toCharArray()));
560
561     // truncated dna
562     assertFalse(AlignmentUtils.translatesAs("tttcccaaagg".toCharArray(), 0,
563             "FPKG".toCharArray()));
564
565     // truncated protein
566     assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
567             0, "FPK".toCharArray()));
568
569     // overlong dna (doesn't end in stop codon)
570     assertFalse(AlignmentUtils.translatesAs(
571             "tttcccaaagggttt".toCharArray(), 0, "FPKG".toCharArray()));
572
573     // dna + stop codon + more
574     assertFalse(AlignmentUtils.translatesAs(
575             "tttcccaaagggttaga".toCharArray(), 0, "FPKG".toCharArray()));
576
577     // overlong protein
578     assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
579             0, "FPKGQ".toCharArray()));
580   }
581
582   /**
583    * Test mapping of protein to cDNA, for cases where the cDNA has start and/or
584    * stop codons in addition to the protein coding sequence.
585    * 
586    * @throws IOException
587    */
588   @Test(groups = { "Functional" })
589   public void testMapProteinAlignmentToCdna_withStartAndStopCodons()
590           throws IOException
591   {
592     List<SequenceI> protseqs = new ArrayList<SequenceI>();
593     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
594     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
595     protseqs.add(new Sequence("UNIPROT|V12347", "SAR"));
596     AlignmentI protein = new Alignment(protseqs.toArray(new SequenceI[3]));
597     protein.setDataset(null);
598
599     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
600     // start + SAR:
601     dnaseqs.add(new Sequence("EMBL|A11111", "ATGTCAGCACGC"));
602     // = EIQ + stop
603     dnaseqs.add(new Sequence("EMBL|A22222", "GAGATACAATAA"));
604     // = start +EIQ + stop
605     dnaseqs.add(new Sequence("EMBL|A33333", "ATGGAAATCCAGTAG"));
606     dnaseqs.add(new Sequence("EMBL|A44444", "GAAATTCAG"));
607     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[4]));
608     cdna.setDataset(null);
609
610     assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
611
612     // 3 mappings made, each from 1 to 1 sequence
613     assertEquals(3, protein.getCodonFrames().size());
614     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
615     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
616     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(2)).size());
617
618     // V12345 mapped from A22222
619     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
620             .get(0);
621     assertEquals(1, acf.getdnaSeqs().length);
622     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
623             acf.getdnaSeqs()[0]);
624     Mapping[] protMappings = acf.getProtMappings();
625     assertEquals(1, protMappings.length);
626     MapList mapList = protMappings[0].getMap();
627     assertEquals(3, mapList.getFromRatio());
628     assertEquals(1, mapList.getToRatio());
629     assertTrue(Arrays.equals(new int[] { 1, 9 }, mapList.getFromRanges()
630             .get(0)));
631     assertEquals(1, mapList.getFromRanges().size());
632     assertTrue(Arrays.equals(new int[] { 1, 3 },
633             mapList.getToRanges().get(0)));
634     assertEquals(1, mapList.getToRanges().size());
635
636     // V12346 mapped from A33333 starting position 4
637     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
638     assertEquals(1, acf.getdnaSeqs().length);
639     assertEquals(cdna.getSequenceAt(2).getDatasetSequence(),
640             acf.getdnaSeqs()[0]);
641     protMappings = acf.getProtMappings();
642     assertEquals(1, protMappings.length);
643     mapList = protMappings[0].getMap();
644     assertEquals(3, mapList.getFromRatio());
645     assertEquals(1, mapList.getToRatio());
646     assertTrue(Arrays.equals(new int[] { 4, 12 }, mapList.getFromRanges()
647             .get(0)));
648     assertEquals(1, mapList.getFromRanges().size());
649     assertTrue(Arrays.equals(new int[] { 1, 3 },
650             mapList.getToRanges().get(0)));
651     assertEquals(1, mapList.getToRanges().size());
652
653     // V12347 mapped to A11111 starting position 4
654     acf = protein.getCodonFrame(protein.getSequenceAt(2)).get(0);
655     assertEquals(1, acf.getdnaSeqs().length);
656     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
657             acf.getdnaSeqs()[0]);
658     protMappings = acf.getProtMappings();
659     assertEquals(1, protMappings.length);
660     mapList = protMappings[0].getMap();
661     assertEquals(3, mapList.getFromRatio());
662     assertEquals(1, mapList.getToRatio());
663     assertTrue(Arrays.equals(new int[] { 4, 12 }, mapList.getFromRanges()
664             .get(0)));
665     assertEquals(1, mapList.getFromRanges().size());
666     assertTrue(Arrays.equals(new int[] { 1, 3 },
667             mapList.getToRanges().get(0)));
668     assertEquals(1, mapList.getToRanges().size());
669
670     // no mapping involving the 'extra' A44444
671     assertTrue(protein.getCodonFrame(cdna.getSequenceAt(3)).isEmpty());
672   }
673
674   /**
675    * Test mapping of protein to cDNA, for the case where we have some sequence
676    * cross-references. Verify that 1-to-many mappings are made where
677    * cross-references exist and sequences are mappable.
678    * 
679    * @throws IOException
680    */
681   @Test(groups = { "Functional" })
682   public void testMapProteinAlignmentToCdna_withXrefs() throws IOException
683   {
684     List<SequenceI> protseqs = new ArrayList<SequenceI>();
685     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
686     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
687     protseqs.add(new Sequence("UNIPROT|V12347", "SAR"));
688     AlignmentI protein = new Alignment(protseqs.toArray(new SequenceI[3]));
689     protein.setDataset(null);
690
691     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
692     dnaseqs.add(new Sequence("EMBL|A11111", "TCAGCACGC")); // = SAR
693     dnaseqs.add(new Sequence("EMBL|A22222", "ATGGAGATACAA")); // = start + EIQ
694     dnaseqs.add(new Sequence("EMBL|A33333", "GAAATCCAG")); // = EIQ
695     dnaseqs.add(new Sequence("EMBL|A44444", "GAAATTCAG")); // = EIQ
696     dnaseqs.add(new Sequence("EMBL|A55555", "GAGATTCAG")); // = EIQ
697     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[5]));
698     cdna.setDataset(null);
699
700     // Xref A22222 to V12345 (should get mapped)
701     dnaseqs.get(1).addDBRef(new DBRefEntry("UNIPROT", "1", "V12345"));
702     // Xref V12345 to A44444 (should get mapped)
703     protseqs.get(0).addDBRef(new DBRefEntry("EMBL", "1", "A44444"));
704     // Xref A33333 to V12347 (sequence mismatch - should not get mapped)
705     dnaseqs.get(2).addDBRef(new DBRefEntry("UNIPROT", "1", "V12347"));
706     // as V12345 is mapped to A22222 and A44444, this leaves V12346 unmapped.
707     // it should get paired up with the unmapped A33333
708     // A11111 should be mapped to V12347
709     // A55555 is spare and has no xref so is not mapped
710
711     assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
712
713     // 4 protein mappings made for 3 proteins, 2 to V12345, 1 each to V12346/7
714     assertEquals(3, protein.getCodonFrames().size());
715     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
716     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
717     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(2)).size());
718
719     // one mapping for each of the first 4 cDNA sequences
720     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(0)).size());
721     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(1)).size());
722     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(2)).size());
723     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(3)).size());
724
725     // V12345 mapped to A22222 and A44444
726     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
727             .get(0);
728     assertEquals(2, acf.getdnaSeqs().length);
729     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
730             acf.getdnaSeqs()[0]);
731     assertEquals(cdna.getSequenceAt(3).getDatasetSequence(),
732             acf.getdnaSeqs()[1]);
733
734     // V12346 mapped to A33333
735     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
736     assertEquals(1, acf.getdnaSeqs().length);
737     assertEquals(cdna.getSequenceAt(2).getDatasetSequence(),
738             acf.getdnaSeqs()[0]);
739
740     // V12347 mapped to A11111
741     acf = protein.getCodonFrame(protein.getSequenceAt(2)).get(0);
742     assertEquals(1, acf.getdnaSeqs().length);
743     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
744             acf.getdnaSeqs()[0]);
745
746     // no mapping involving the 'extra' A55555
747     assertTrue(protein.getCodonFrame(cdna.getSequenceAt(4)).isEmpty());
748   }
749
750   /**
751    * Test mapping of protein to cDNA, for the case where we have some sequence
752    * cross-references. Verify that once we have made an xref mapping we don't
753    * also map un-xrefd sequeces.
754    * 
755    * @throws IOException
756    */
757   @Test(groups = { "Functional" })
758   public void testMapProteinAlignmentToCdna_prioritiseXrefs()
759           throws IOException
760   {
761     List<SequenceI> protseqs = new ArrayList<SequenceI>();
762     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
763     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
764     AlignmentI protein = new Alignment(
765             protseqs.toArray(new SequenceI[protseqs.size()]));
766     protein.setDataset(null);
767
768     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
769     dnaseqs.add(new Sequence("EMBL|A11111", "GAAATCCAG")); // = EIQ
770     dnaseqs.add(new Sequence("EMBL|A22222", "GAAATTCAG")); // = EIQ
771     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[dnaseqs
772             .size()]));
773     cdna.setDataset(null);
774
775     // Xref A22222 to V12345 (should get mapped)
776     // A11111 should then be mapped to the unmapped V12346
777     dnaseqs.get(1).addDBRef(new DBRefEntry("UNIPROT", "1", "V12345"));
778
779     assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
780
781     // 2 protein mappings made
782     assertEquals(2, protein.getCodonFrames().size());
783     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
784     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
785
786     // one mapping for each of the cDNA sequences
787     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(0)).size());
788     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(1)).size());
789
790     // V12345 mapped to A22222
791     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
792             .get(0);
793     assertEquals(1, acf.getdnaSeqs().length);
794     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
795             acf.getdnaSeqs()[0]);
796
797     // V12346 mapped to A11111
798     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
799     assertEquals(1, acf.getdnaSeqs().length);
800     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
801             acf.getdnaSeqs()[0]);
802   }
803
804   /**
805    * Test the method that shows or hides sequence annotations by type(s) and
806    * selection group.
807    */
808   @Test(groups = { "Functional" })
809   public void testShowOrHideSequenceAnnotations()
810   {
811     SequenceI seq1 = new Sequence("Seq1", "AAA");
812     SequenceI seq2 = new Sequence("Seq2", "BBB");
813     SequenceI seq3 = new Sequence("Seq3", "CCC");
814     Annotation[] anns = new Annotation[] { new Annotation(2f) };
815     AlignmentAnnotation ann1 = new AlignmentAnnotation("Structure", "ann1",
816             anns);
817     ann1.setSequenceRef(seq1);
818     AlignmentAnnotation ann2 = new AlignmentAnnotation("Structure", "ann2",
819             anns);
820     ann2.setSequenceRef(seq2);
821     AlignmentAnnotation ann3 = new AlignmentAnnotation("Structure", "ann3",
822             anns);
823     AlignmentAnnotation ann4 = new AlignmentAnnotation("Temp", "ann4", anns);
824     ann4.setSequenceRef(seq1);
825     AlignmentAnnotation ann5 = new AlignmentAnnotation("Temp", "ann5", anns);
826     ann5.setSequenceRef(seq2);
827     AlignmentAnnotation ann6 = new AlignmentAnnotation("Temp", "ann6", anns);
828     AlignmentI al = new Alignment(new SequenceI[] { seq1, seq2, seq3 });
829     al.addAnnotation(ann1); // Structure for Seq1
830     al.addAnnotation(ann2); // Structure for Seq2
831     al.addAnnotation(ann3); // Structure for no sequence
832     al.addAnnotation(ann4); // Temp for seq1
833     al.addAnnotation(ann5); // Temp for seq2
834     al.addAnnotation(ann6); // Temp for no sequence
835     List<String> types = new ArrayList<String>();
836     List<SequenceI> scope = new ArrayList<SequenceI>();
837
838     /*
839      * Set all sequence related Structure to hidden (ann1, ann2)
840      */
841     types.add("Structure");
842     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, false,
843             false);
844     assertFalse(ann1.visible);
845     assertFalse(ann2.visible);
846     assertTrue(ann3.visible); // not sequence-related, not affected
847     assertTrue(ann4.visible); // not Structure, not affected
848     assertTrue(ann5.visible); // "
849     assertTrue(ann6.visible); // not sequence-related, not affected
850
851     /*
852      * Set Temp in {seq1, seq3} to hidden
853      */
854     types.clear();
855     types.add("Temp");
856     scope.add(seq1);
857     scope.add(seq3);
858     AlignmentUtils.showOrHideSequenceAnnotations(al, types, scope, false,
859             false);
860     assertFalse(ann1.visible); // unchanged
861     assertFalse(ann2.visible); // unchanged
862     assertTrue(ann3.visible); // not sequence-related, not affected
863     assertFalse(ann4.visible); // Temp for seq1 hidden
864     assertTrue(ann5.visible); // not in scope, not affected
865     assertTrue(ann6.visible); // not sequence-related, not affected
866
867     /*
868      * Set Temp in all sequences to hidden
869      */
870     types.clear();
871     types.add("Temp");
872     scope.add(seq1);
873     scope.add(seq3);
874     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, false,
875             false);
876     assertFalse(ann1.visible); // unchanged
877     assertFalse(ann2.visible); // unchanged
878     assertTrue(ann3.visible); // not sequence-related, not affected
879     assertFalse(ann4.visible); // Temp for seq1 hidden
880     assertFalse(ann5.visible); // Temp for seq2 hidden
881     assertTrue(ann6.visible); // not sequence-related, not affected
882
883     /*
884      * Set all types in {seq1, seq3} to visible
885      */
886     types.clear();
887     scope.clear();
888     scope.add(seq1);
889     scope.add(seq3);
890     AlignmentUtils.showOrHideSequenceAnnotations(al, types, scope, true,
891             true);
892     assertTrue(ann1.visible); // Structure for seq1 set visible
893     assertFalse(ann2.visible); // not in scope, unchanged
894     assertTrue(ann3.visible); // not sequence-related, not affected
895     assertTrue(ann4.visible); // Temp for seq1 set visible
896     assertFalse(ann5.visible); // not in scope, unchanged
897     assertTrue(ann6.visible); // not sequence-related, not affected
898
899     /*
900      * Set all types in all scope to hidden
901      */
902     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, true,
903             false);
904     assertFalse(ann1.visible);
905     assertFalse(ann2.visible);
906     assertTrue(ann3.visible); // not sequence-related, not affected
907     assertFalse(ann4.visible);
908     assertFalse(ann5.visible);
909     assertTrue(ann6.visible); // not sequence-related, not affected
910   }
911
912   /**
913    * Tests for the method that checks if one sequence cross-references another
914    */
915   @Test(groups = { "Functional" })
916   public void testHasCrossRef()
917   {
918     assertFalse(AlignmentUtils.hasCrossRef(null, null));
919     SequenceI seq1 = new Sequence("EMBL|A12345", "ABCDEF");
920     assertFalse(AlignmentUtils.hasCrossRef(seq1, null));
921     assertFalse(AlignmentUtils.hasCrossRef(null, seq1));
922     SequenceI seq2 = new Sequence("UNIPROT|V20192", "ABCDEF");
923     assertFalse(AlignmentUtils.hasCrossRef(seq1, seq2));
924
925     // different ref
926     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "v20193"));
927     assertFalse(AlignmentUtils.hasCrossRef(seq1, seq2));
928
929     // case-insensitive; version number is ignored
930     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "v20192"));
931     assertTrue(AlignmentUtils.hasCrossRef(seq1, seq2));
932
933     // right case!
934     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
935     assertTrue(AlignmentUtils.hasCrossRef(seq1, seq2));
936     // test is one-way only
937     assertFalse(AlignmentUtils.hasCrossRef(seq2, seq1));
938   }
939
940   /**
941    * Tests for the method that checks if either sequence cross-references the
942    * other
943    */
944   @Test(groups = { "Functional" })
945   public void testHaveCrossRef()
946   {
947     assertFalse(AlignmentUtils.hasCrossRef(null, null));
948     SequenceI seq1 = new Sequence("EMBL|A12345", "ABCDEF");
949     assertFalse(AlignmentUtils.haveCrossRef(seq1, null));
950     assertFalse(AlignmentUtils.haveCrossRef(null, seq1));
951     SequenceI seq2 = new Sequence("UNIPROT|V20192", "ABCDEF");
952     assertFalse(AlignmentUtils.haveCrossRef(seq1, seq2));
953
954     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
955     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
956     // next is true for haveCrossRef, false for hasCrossRef
957     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
958
959     // now the other way round
960     seq1.setDBRefs(null);
961     seq2.addDBRef(new DBRefEntry("EMBL", "1", "A12345"));
962     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
963     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
964
965     // now both ways
966     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
967     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
968     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
969   }
970
971   /**
972    * Test the method that extracts the cds-only part of a dna alignment.
973    */
974   @Test(groups = { "Functional" })
975   public void testMakeCdsAlignment()
976   {
977     /*
978      * scenario:
979      *     dna1 --> [4, 6] [10,12]        --> pep1 
980      *     dna2 --> [1, 3] [7, 9] [13,15] --> pep2
981      */
982     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
983     SequenceI dna2 = new Sequence("dna2", "GGGcccTTTaaaCCC");
984     SequenceI pep1 = new Sequence("pep1", "GF");
985     SequenceI pep2 = new Sequence("pep2", "GFP");
986     pep1.addDBRef(new DBRefEntry("UNIPROT", "0", "pep1"));
987     pep2.addDBRef(new DBRefEntry("UNIPROT", "0", "pep2"));
988     dna1.createDatasetSequence();
989     dna2.createDatasetSequence();
990     pep1.createDatasetSequence();
991     pep2.createDatasetSequence();
992     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2 });
993     dna.setDataset(null);
994
995     /*
996      * put a variant feature on dna2 base 8
997      * - should transfer to cds2 base 5
998      */
999     dna2.addSequenceFeature(new SequenceFeature("variant", "hgmd", 8, 8,
1000             0f, null));
1001
1002     /*
1003      * need a sourceDbRef if we are to construct dbrefs to the CDS
1004      * sequence from the dna contig sequences
1005      */
1006     DBRefEntry dbref = new DBRefEntry("ENSEMBL", "0", "dna1");
1007     dna1.getDatasetSequence().addDBRef(dbref);
1008     org.testng.Assert.assertEquals(dbref, dna1.getPrimaryDBRefs().get(0));
1009     dbref = new DBRefEntry("ENSEMBL", "0", "dna2");
1010     dna2.getDatasetSequence().addDBRef(dbref);
1011     org.testng.Assert.assertEquals(dbref, dna2.getPrimaryDBRefs().get(0));
1012
1013     /*
1014      * CDS sequences are 'discovered' from dna-to-protein mappings on the alignment
1015      * dataset (e.g. added from dbrefs by CrossRef.findXrefSequences)
1016      */
1017     MapList mapfordna1 = new MapList(new int[] { 4, 6, 10, 12 },
1018             new int[] { 1, 2 }, 3, 1);
1019     AlignedCodonFrame acf = new AlignedCodonFrame();
1020     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(),
1021             mapfordna1);
1022     dna.addCodonFrame(acf);
1023     MapList mapfordna2 = new MapList(new int[] { 1, 3, 7, 9, 13, 15 },
1024             new int[] { 1, 3 },
1025             3, 1);
1026     acf = new AlignedCodonFrame();
1027     acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(),
1028             mapfordna2);
1029     dna.addCodonFrame(acf);
1030
1031     /*
1032      * In this case, mappings originally came from matching Uniprot accessions - so need an xref on dna involving those regions. These are normally constructed from CDS annotation
1033      */
1034     DBRefEntry dna1xref = new DBRefEntry("UNIPROT", "ENSEMBL", "pep1",
1035             new Mapping(mapfordna1));
1036     dna1.getDatasetSequence().addDBRef(dna1xref);
1037     DBRefEntry dna2xref = new DBRefEntry("UNIPROT", "ENSEMBL", "pep2",
1038             new Mapping(mapfordna2));
1039     dna2.getDatasetSequence().addDBRef(dna2xref);
1040
1041     /*
1042      * execute method under test:
1043      */
1044     AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
1045         dna1, dna2 }, dna.getDataset(), null);
1046
1047     /*
1048      * verify cds sequences
1049      */
1050     assertEquals(2, cds.getSequences().size());
1051     assertEquals("GGGTTT", cds.getSequenceAt(0).getSequenceAsString());
1052     assertEquals("GGGTTTCCC", cds.getSequenceAt(1).getSequenceAsString());
1053
1054     /*
1055      * verify shared, extended alignment dataset
1056      */
1057     assertSame(dna.getDataset(), cds.getDataset());
1058     SequenceI cds1Dss = cds.getSequenceAt(0).getDatasetSequence();
1059     SequenceI cds2Dss = cds.getSequenceAt(1).getDatasetSequence();
1060     assertTrue(dna.getDataset().getSequences().contains(cds1Dss));
1061     assertTrue(dna.getDataset().getSequences().contains(cds2Dss));
1062
1063     /*
1064      * verify CDS has a dbref with mapping to peptide
1065      */
1066     assertNotNull(cds1Dss.getDBRefs());
1067     assertEquals(2, cds1Dss.getDBRefs().length);
1068     dbref = cds1Dss.getDBRefs()[0];
1069     assertEquals(dna1xref.getSource(), dbref.getSource());
1070     // version is via ensembl's primary ref
1071     assertEquals(dna1xref.getVersion(), dbref.getVersion());
1072     assertEquals(dna1xref.getAccessionId(), dbref.getAccessionId());
1073     assertNotNull(dbref.getMap());
1074     assertSame(pep1.getDatasetSequence(), dbref.getMap().getTo());
1075     MapList cdsMapping = new MapList(new int[] { 1, 6 },
1076             new int[] { 1, 2 }, 3, 1);
1077     assertEquals(cdsMapping, dbref.getMap().getMap());
1078
1079     /*
1080      * verify peptide has added a dbref with reverse mapping to CDS
1081      */
1082     assertNotNull(pep1.getDBRefs());
1083     // FIXME pep1.getDBRefs() is 1 - is that the correct behaviour ?
1084     assertEquals(2, pep1.getDBRefs().length);
1085     dbref = pep1.getDBRefs()[1];
1086     assertEquals("ENSEMBL", dbref.getSource());
1087     assertEquals("0", dbref.getVersion());
1088     assertEquals("CDS|dna1", dbref.getAccessionId());
1089     assertNotNull(dbref.getMap());
1090     assertSame(cds1Dss, dbref.getMap().getTo());
1091     assertEquals(cdsMapping.getInverse(), dbref.getMap().getMap());
1092
1093     /*
1094      * Verify mappings from CDS to peptide, cDNA to CDS, and cDNA to peptide
1095      * the mappings are on the shared alignment dataset
1096      * 6 mappings, 2*(DNA->CDS), 2*(DNA->Pep), 2*(CDS->Pep) 
1097      */
1098     List<AlignedCodonFrame> cdsMappings = cds.getDataset().getCodonFrames();
1099     assertEquals(6, cdsMappings.size());
1100
1101     /*
1102      * verify that mapping sets for dna and cds alignments are different
1103      * [not current behaviour - all mappings are on the alignment dataset]  
1104      */
1105     // select -> subselect type to test.
1106     // Assert.assertNotSame(dna.getCodonFrames(), cds.getCodonFrames());
1107     // assertEquals(4, dna.getCodonFrames().size());
1108     // assertEquals(4, cds.getCodonFrames().size());
1109
1110     /*
1111      * Two mappings involve pep1 (dna to pep1, cds to pep1)
1112      * Mapping from pep1 to GGGTTT in first new exon sequence
1113      */
1114     List<AlignedCodonFrame> pep1Mappings = MappingUtils
1115             .findMappingsForSequence(pep1, cdsMappings);
1116     assertEquals(2, pep1Mappings.size());
1117     List<AlignedCodonFrame> mappings = MappingUtils
1118             .findMappingsForSequence(cds.getSequenceAt(0), pep1Mappings);
1119     assertEquals(1, mappings.size());
1120
1121     // map G to GGG
1122     SearchResults sr = MappingUtils.buildSearchResults(pep1, 1, mappings);
1123     assertEquals(1, sr.getResults().size());
1124     Match m = sr.getResults().get(0);
1125     assertSame(cds1Dss, m.getSequence());
1126     assertEquals(1, m.getStart());
1127     assertEquals(3, m.getEnd());
1128     // map F to TTT
1129     sr = MappingUtils.buildSearchResults(pep1, 2, mappings);
1130     m = sr.getResults().get(0);
1131     assertSame(cds1Dss, m.getSequence());
1132     assertEquals(4, m.getStart());
1133     assertEquals(6, m.getEnd());
1134
1135     /*
1136      * Two mappings involve pep2 (dna to pep2, cds to pep2)
1137      * Verify mapping from pep2 to GGGTTTCCC in second new exon sequence
1138      */
1139     List<AlignedCodonFrame> pep2Mappings = MappingUtils
1140             .findMappingsForSequence(pep2, cdsMappings);
1141     assertEquals(2, pep2Mappings.size());
1142     mappings = MappingUtils.findMappingsForSequence(cds.getSequenceAt(1),
1143             pep2Mappings);
1144     assertEquals(1, mappings.size());
1145     // map G to GGG
1146     sr = MappingUtils.buildSearchResults(pep2, 1, mappings);
1147     assertEquals(1, sr.getResults().size());
1148     m = sr.getResults().get(0);
1149     assertSame(cds2Dss, m.getSequence());
1150     assertEquals(1, m.getStart());
1151     assertEquals(3, m.getEnd());
1152     // map F to TTT
1153     sr = MappingUtils.buildSearchResults(pep2, 2, mappings);
1154     m = sr.getResults().get(0);
1155     assertSame(cds2Dss, m.getSequence());
1156     assertEquals(4, m.getStart());
1157     assertEquals(6, m.getEnd());
1158     // map P to CCC
1159     sr = MappingUtils.buildSearchResults(pep2, 3, mappings);
1160     m = sr.getResults().get(0);
1161     assertSame(cds2Dss, m.getSequence());
1162     assertEquals(7, m.getStart());
1163     assertEquals(9, m.getEnd());
1164
1165     /*
1166      * check cds2 acquired a variant feature in position 5
1167      */
1168     SequenceFeature[] sfs = cds2Dss.getSequenceFeatures();
1169     assertNotNull(sfs);
1170     assertEquals(1, sfs.length);
1171     assertEquals("variant", sfs[0].type);
1172     assertEquals(5, sfs[0].begin);
1173     assertEquals(5, sfs[0].end);
1174   }
1175
1176   /**
1177    * Test the method that makes a cds-only alignment from a DNA sequence and its
1178    * product mappings, for the case where there are multiple exon mappings to
1179    * different protein products.
1180    */
1181   @Test(groups = { "Functional" })
1182   public void testMakeCdsAlignment_multipleProteins()
1183   {
1184     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
1185     SequenceI pep1 = new Sequence("pep1", "GF"); // GGGTTT
1186     SequenceI pep2 = new Sequence("pep2", "KP"); // aaaccc
1187     SequenceI pep3 = new Sequence("pep3", "KF"); // aaaTTT
1188     dna1.createDatasetSequence();
1189     pep1.createDatasetSequence();
1190     pep2.createDatasetSequence();
1191     pep3.createDatasetSequence();
1192     pep1.getDatasetSequence().addDBRef(
1193             new DBRefEntry("EMBLCDS", "2", "A12345"));
1194     pep2.getDatasetSequence().addDBRef(
1195             new DBRefEntry("EMBLCDS", "3", "A12346"));
1196     pep3.getDatasetSequence().addDBRef(
1197             new DBRefEntry("EMBLCDS", "4", "A12347"));
1198
1199     /*
1200      * Create the CDS alignment
1201      */
1202     AlignmentI dna = new Alignment(new SequenceI[] { dna1 });
1203     dna.setDataset(null);
1204
1205     /*
1206      * Make the mappings from dna to protein
1207      */
1208     // map ...GGG...TTT to GF
1209     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1210             new int[] { 1, 2 }, 3, 1);
1211     AlignedCodonFrame acf = new AlignedCodonFrame();
1212     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
1213     dna.addCodonFrame(acf);
1214
1215     // map aaa...ccc to KP
1216     map = new MapList(new int[] { 1, 3, 7, 9 }, new int[] { 1, 2 }, 3, 1);
1217     acf = new AlignedCodonFrame();
1218     acf.addMap(dna1.getDatasetSequence(), pep2.getDatasetSequence(), map);
1219     dna.addCodonFrame(acf);
1220
1221     // map aaa......TTT to KF
1222     map = new MapList(new int[] { 1, 3, 10, 12 }, new int[] { 1, 2 }, 3, 1);
1223     acf = new AlignedCodonFrame();
1224     acf.addMap(dna1.getDatasetSequence(), pep3.getDatasetSequence(), map);
1225     dna.addCodonFrame(acf);
1226
1227     /*
1228      * execute method under test
1229      */
1230     AlignmentI cdsal = AlignmentUtils.makeCdsAlignment(
1231             new SequenceI[] { dna1 }, dna.getDataset(), null);
1232
1233     /*
1234      * Verify we have 3 cds sequences, mapped to pep1/2/3 respectively
1235      */
1236     List<SequenceI> cds = cdsal.getSequences();
1237     assertEquals(3, cds.size());
1238
1239     /*
1240      * verify shared, extended alignment dataset
1241      */
1242     assertSame(cdsal.getDataset(), dna.getDataset());
1243     assertTrue(dna.getDataset().getSequences()
1244             .contains(cds.get(0).getDatasetSequence()));
1245     assertTrue(dna.getDataset().getSequences()
1246             .contains(cds.get(1).getDatasetSequence()));
1247     assertTrue(dna.getDataset().getSequences()
1248             .contains(cds.get(2).getDatasetSequence()));
1249
1250     /*
1251      * verify aligned cds sequences and their xrefs
1252      */
1253     SequenceI cdsSeq = cds.get(0);
1254     assertEquals("GGGTTT", cdsSeq.getSequenceAsString());
1255     // assertEquals("dna1|A12345", cdsSeq.getName());
1256     assertEquals("CDS|dna1", cdsSeq.getName());
1257     // assertEquals(1, cdsSeq.getDBRefs().length);
1258     // DBRefEntry cdsRef = cdsSeq.getDBRefs()[0];
1259     // assertEquals("EMBLCDS", cdsRef.getSource());
1260     // assertEquals("2", cdsRef.getVersion());
1261     // assertEquals("A12345", cdsRef.getAccessionId());
1262
1263     cdsSeq = cds.get(1);
1264     assertEquals("aaaccc", cdsSeq.getSequenceAsString());
1265     // assertEquals("dna1|A12346", cdsSeq.getName());
1266     assertEquals("CDS|dna1", cdsSeq.getName());
1267     // assertEquals(1, cdsSeq.getDBRefs().length);
1268     // cdsRef = cdsSeq.getDBRefs()[0];
1269     // assertEquals("EMBLCDS", cdsRef.getSource());
1270     // assertEquals("3", cdsRef.getVersion());
1271     // assertEquals("A12346", cdsRef.getAccessionId());
1272
1273     cdsSeq = cds.get(2);
1274     assertEquals("aaaTTT", cdsSeq.getSequenceAsString());
1275     // assertEquals("dna1|A12347", cdsSeq.getName());
1276     assertEquals("CDS|dna1", cdsSeq.getName());
1277     // assertEquals(1, cdsSeq.getDBRefs().length);
1278     // cdsRef = cdsSeq.getDBRefs()[0];
1279     // assertEquals("EMBLCDS", cdsRef.getSource());
1280     // assertEquals("4", cdsRef.getVersion());
1281     // assertEquals("A12347", cdsRef.getAccessionId());
1282
1283     /*
1284      * Verify there are mappings from each cds sequence to its protein product
1285      * and also to its dna source
1286      */
1287     List<AlignedCodonFrame> newMappings = cdsal.getCodonFrames();
1288
1289     /*
1290      * 6 mappings involve dna1 (to pep1/2/3, cds1/2/3) 
1291      */
1292     List<AlignedCodonFrame> dnaMappings = MappingUtils
1293             .findMappingsForSequence(dna1, newMappings);
1294     assertEquals(6, dnaMappings.size());
1295
1296     /*
1297      * dna1 to pep1
1298      */
1299     List<AlignedCodonFrame> mappings = MappingUtils
1300             .findMappingsForSequence(pep1, dnaMappings);
1301     assertEquals(1, mappings.size());
1302     assertEquals(1, mappings.get(0).getMappings().size());
1303     assertSame(pep1.getDatasetSequence(), mappings.get(0).getMappings()
1304             .get(0).getMapping().getTo());
1305
1306     /*
1307      * dna1 to cds1
1308      */
1309     List<AlignedCodonFrame> dnaToCds1Mappings = MappingUtils
1310             .findMappingsForSequence(cds.get(0), dnaMappings);
1311     Mapping mapping = dnaToCds1Mappings.get(0).getMappings().get(0)
1312             .getMapping();
1313     assertSame(cds.get(0).getDatasetSequence(), mapping
1314             .getTo());
1315     assertEquals("G(1) in CDS should map to G(4) in DNA", 4, mapping
1316             .getMap().getToPosition(1));
1317
1318     /*
1319      * dna1 to pep2
1320      */
1321     mappings = MappingUtils.findMappingsForSequence(pep2, dnaMappings);
1322     assertEquals(1, mappings.size());
1323     assertEquals(1, mappings.get(0).getMappings().size());
1324     assertSame(pep2.getDatasetSequence(), mappings.get(0).getMappings()
1325             .get(0).getMapping().getTo());
1326
1327     /*
1328      * dna1 to cds2
1329      */
1330     List<AlignedCodonFrame> dnaToCds2Mappings = MappingUtils
1331             .findMappingsForSequence(cds.get(1), dnaMappings);
1332     mapping = dnaToCds2Mappings.get(0).getMappings().get(0).getMapping();
1333     assertSame(cds.get(1).getDatasetSequence(), mapping.getTo());
1334     assertEquals("c(4) in CDS should map to c(7) in DNA", 7, mapping
1335             .getMap().getToPosition(4));
1336
1337     /*
1338      * dna1 to pep3
1339      */
1340     mappings = MappingUtils.findMappingsForSequence(pep3, dnaMappings);
1341     assertEquals(1, mappings.size());
1342     assertEquals(1, mappings.get(0).getMappings().size());
1343     assertSame(pep3.getDatasetSequence(), mappings.get(0).getMappings()
1344             .get(0).getMapping().getTo());
1345
1346     /*
1347      * dna1 to cds3
1348      */
1349     List<AlignedCodonFrame> dnaToCds3Mappings = MappingUtils
1350             .findMappingsForSequence(cds.get(2), dnaMappings);
1351     mapping = dnaToCds3Mappings.get(0).getMappings().get(0).getMapping();
1352     assertSame(cds.get(2).getDatasetSequence(), mapping.getTo());
1353     assertEquals("T(4) in CDS should map to T(10) in DNA", 10, mapping
1354             .getMap().getToPosition(4));
1355   }
1356
1357   @Test(groups = { "Functional" })
1358   public void testIsMappable()
1359   {
1360     SequenceI dna1 = new Sequence("dna1", "cgCAGtgGT");
1361     SequenceI aa1 = new Sequence("aa1", "RSG");
1362     AlignmentI al1 = new Alignment(new SequenceI[] { dna1 });
1363     AlignmentI al2 = new Alignment(new SequenceI[] { aa1 });
1364
1365     assertFalse(AlignmentUtils.isMappable(null, null));
1366     assertFalse(AlignmentUtils.isMappable(al1, null));
1367     assertFalse(AlignmentUtils.isMappable(null, al1));
1368     assertFalse(AlignmentUtils.isMappable(al1, al1));
1369     assertFalse(AlignmentUtils.isMappable(al2, al2));
1370
1371     assertTrue(AlignmentUtils.isMappable(al1, al2));
1372     assertTrue(AlignmentUtils.isMappable(al2, al1));
1373   }
1374
1375   /**
1376    * Test creating a mapping when the sequences involved do not start at residue
1377    * 1
1378    * 
1379    * @throws IOException
1380    */
1381   @Test(groups = { "Functional" })
1382   public void testMapCdnaToProtein_forSubsequence()
1383           throws IOException
1384   {
1385     SequenceI prot = new Sequence("UNIPROT|V12345", "E-I--Q", 10, 12);
1386     prot.createDatasetSequence();
1387
1388     SequenceI dna = new Sequence("EMBL|A33333", "GAA--AT-C-CAG", 40, 48);
1389     dna.createDatasetSequence();
1390
1391     MapList map = AlignmentUtils.mapCdnaToProtein(prot, dna);
1392     assertEquals(10, map.getToLowest());
1393     assertEquals(12, map.getToHighest());
1394     assertEquals(40, map.getFromLowest());
1395     assertEquals(48, map.getFromHighest());
1396   }
1397
1398   /**
1399    * Test for the alignSequenceAs method where we have protein mapped to protein
1400    */
1401   @Test(groups = { "Functional" })
1402   public void testAlignSequenceAs_mappedProteinProtein()
1403   {
1404   
1405     SequenceI alignMe = new Sequence("Match", "MGAASEV");
1406     alignMe.createDatasetSequence();
1407     SequenceI alignFrom = new Sequence("Query", "LQTGYMGAASEVMFSPTRR");
1408     alignFrom.createDatasetSequence();
1409
1410     AlignedCodonFrame acf = new AlignedCodonFrame();
1411     // this is like a domain or motif match of part of a peptide sequence
1412     MapList map = new MapList(new int[] { 6, 12 }, new int[] { 1, 7 }, 1, 1);
1413     acf.addMap(alignFrom.getDatasetSequence(),
1414             alignMe.getDatasetSequence(), map);
1415     
1416     AlignmentUtils.alignSequenceAs(alignMe, alignFrom, acf, "-", '-', true,
1417             true);
1418     assertEquals("-----MGAASEV-------", alignMe.getSequenceAsString());
1419   }
1420
1421   /**
1422    * Test for the alignSequenceAs method where there are trailing unmapped
1423    * residues in the model sequence
1424    */
1425   @Test(groups = { "Functional" })
1426   public void testAlignSequenceAs_withTrailingPeptide()
1427   {
1428     // map first 3 codons to KPF; G is a trailing unmapped residue
1429     MapList map = new MapList(new int[] { 1, 9 }, new int[] { 1, 3 }, 3, 1);
1430   
1431     checkAlignSequenceAs("AAACCCTTT", "K-PFG", true, true, map,
1432             "AAA---CCCTTT---");
1433   }
1434
1435   /**
1436    * Tests for transferring features between mapped sequences
1437    */
1438   @Test(groups = { "Functional" })
1439   public void testTransferFeatures()
1440   {
1441     SequenceI dna = new Sequence("dna/20-34", "acgTAGcaaGCCcgt");
1442     SequenceI cds = new Sequence("cds/10-15", "TAGGCC");
1443
1444     // no overlap
1445     dna.addSequenceFeature(new SequenceFeature("type1", "desc1", 1, 2, 1f,
1446             null));
1447     // partial overlap - to [1, 1]
1448     dna.addSequenceFeature(new SequenceFeature("type2", "desc2", 3, 4, 2f,
1449             null));
1450     // exact overlap - to [1, 3]
1451     dna.addSequenceFeature(new SequenceFeature("type3", "desc3", 4, 6, 3f,
1452             null));
1453     // spanning overlap - to [2, 5]
1454     dna.addSequenceFeature(new SequenceFeature("type4", "desc4", 5, 11, 4f,
1455             null));
1456     // exactly overlaps whole mapped range [1, 6]
1457     dna.addSequenceFeature(new SequenceFeature("type5", "desc5", 4, 12, 5f,
1458             null));
1459     // no overlap (internal)
1460     dna.addSequenceFeature(new SequenceFeature("type6", "desc6", 7, 9, 6f,
1461             null));
1462     // no overlap (3' end)
1463     dna.addSequenceFeature(new SequenceFeature("type7", "desc7", 13, 15,
1464             7f, null));
1465     // overlap (3' end) - to [6, 6]
1466     dna.addSequenceFeature(new SequenceFeature("type8", "desc8", 12, 12,
1467             8f, null));
1468     // extended overlap - to [6, +]
1469     dna.addSequenceFeature(new SequenceFeature("type9", "desc9", 12, 13,
1470             9f, null));
1471
1472     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1473             new int[] { 1, 6 }, 1, 1);
1474
1475     /*
1476      * transferFeatures() will build 'partial overlap' for regions
1477      * that partially overlap 5' or 3' (start or end) of target sequence
1478      */
1479     AlignmentUtils.transferFeatures(dna, cds, map, null);
1480     SequenceFeature[] sfs = cds.getSequenceFeatures();
1481     assertEquals(6, sfs.length);
1482
1483     SequenceFeature sf = sfs[0];
1484     assertEquals("type2", sf.getType());
1485     assertEquals("desc2", sf.getDescription());
1486     assertEquals(2f, sf.getScore());
1487     assertEquals(1, sf.getBegin());
1488     assertEquals(1, sf.getEnd());
1489
1490     sf = sfs[1];
1491     assertEquals("type3", sf.getType());
1492     assertEquals("desc3", sf.getDescription());
1493     assertEquals(3f, sf.getScore());
1494     assertEquals(1, sf.getBegin());
1495     assertEquals(3, sf.getEnd());
1496
1497     sf = sfs[2];
1498     assertEquals("type4", sf.getType());
1499     assertEquals(2, sf.getBegin());
1500     assertEquals(5, sf.getEnd());
1501
1502     sf = sfs[3];
1503     assertEquals("type5", sf.getType());
1504     assertEquals(1, sf.getBegin());
1505     assertEquals(6, sf.getEnd());
1506
1507     sf = sfs[4];
1508     assertEquals("type8", sf.getType());
1509     assertEquals(6, sf.getBegin());
1510     assertEquals(6, sf.getEnd());
1511
1512     sf = sfs[5];
1513     assertEquals("type9", sf.getType());
1514     assertEquals(6, sf.getBegin());
1515     assertEquals(6, sf.getEnd());
1516   }
1517
1518   /**
1519    * Tests for transferring features between mapped sequences
1520    */
1521   @Test(groups = { "Functional" })
1522   public void testTransferFeatures_withOmit()
1523   {
1524     SequenceI dna = new Sequence("dna/20-34", "acgTAGcaaGCCcgt");
1525     SequenceI cds = new Sequence("cds/10-15", "TAGGCC");
1526
1527     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1528             new int[] { 1, 6 }, 1, 1);
1529   
1530     // [5, 11] maps to [2, 5]
1531     dna.addSequenceFeature(new SequenceFeature("type4", "desc4", 5, 11, 4f,
1532             null));
1533     // [4, 12] maps to [1, 6]
1534     dna.addSequenceFeature(new SequenceFeature("type5", "desc5", 4, 12, 5f,
1535             null));
1536     // [12, 12] maps to [6, 6]
1537     dna.addSequenceFeature(new SequenceFeature("type8", "desc8", 12, 12,
1538             8f, null));
1539   
1540     // desc4 and desc8 are the 'omit these' varargs
1541     AlignmentUtils.transferFeatures(dna, cds, map, null, "type4", "type8");
1542     SequenceFeature[] sfs = cds.getSequenceFeatures();
1543     assertEquals(1, sfs.length);
1544   
1545     SequenceFeature sf = sfs[0];
1546     assertEquals("type5", sf.getType());
1547     assertEquals(1, sf.getBegin());
1548     assertEquals(6, sf.getEnd());
1549   }
1550
1551   /**
1552    * Tests for transferring features between mapped sequences
1553    */
1554   @Test(groups = { "Functional" })
1555   public void testTransferFeatures_withSelect()
1556   {
1557     SequenceI dna = new Sequence("dna/20-34", "acgTAGcaaGCCcgt");
1558     SequenceI cds = new Sequence("cds/10-15", "TAGGCC");
1559   
1560     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1561             new int[] { 1, 6 }, 1, 1);
1562   
1563     // [5, 11] maps to [2, 5]
1564     dna.addSequenceFeature(new SequenceFeature("type4", "desc4", 5, 11, 4f,
1565             null));
1566     // [4, 12] maps to [1, 6]
1567     dna.addSequenceFeature(new SequenceFeature("type5", "desc5", 4, 12, 5f,
1568             null));
1569     // [12, 12] maps to [6, 6]
1570     dna.addSequenceFeature(new SequenceFeature("type8", "desc8", 12, 12,
1571             8f, null));
1572   
1573     // "type5" is the 'select this type' argument
1574     AlignmentUtils.transferFeatures(dna, cds, map, "type5");
1575     SequenceFeature[] sfs = cds.getSequenceFeatures();
1576     assertEquals(1, sfs.length);
1577   
1578     SequenceFeature sf = sfs[0];
1579     assertEquals("type5", sf.getType());
1580     assertEquals(1, sf.getBegin());
1581     assertEquals(6, sf.getEnd());
1582   }
1583
1584   /**
1585    * Test the method that extracts the cds-only part of a dna alignment, for the
1586    * case where the cds should be aligned to match its nucleotide sequence.
1587    */
1588   @Test(groups = { "Functional" })
1589   public void testMakeCdsAlignment_alternativeTranscripts()
1590   {
1591     SequenceI dna1 = new Sequence("dna1", "aaaGGGCC-----CTTTaaaGGG");
1592     // alternative transcript of same dna skips CCC codon
1593     SequenceI dna2 = new Sequence("dna2", "aaaGGGCC-----cttTaaaGGG");
1594     // dna3 has no mapping (protein product) so should be ignored here
1595     SequenceI dna3 = new Sequence("dna3", "aaaGGGCCCCCGGGcttTaaaGGG");
1596     SequenceI pep1 = new Sequence("pep1", "GPFG");
1597     SequenceI pep2 = new Sequence("pep2", "GPG");
1598     dna1.createDatasetSequence();
1599     dna2.createDatasetSequence();
1600     dna3.createDatasetSequence();
1601     pep1.createDatasetSequence();
1602     pep2.createDatasetSequence();
1603
1604     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2, dna3 });
1605     dna.setDataset(null);
1606   
1607     MapList map = new MapList(new int[] { 4, 12, 16, 18 },
1608             new int[] { 1, 4 }, 3, 1);
1609     AlignedCodonFrame acf = new AlignedCodonFrame();
1610     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
1611     dna.addCodonFrame(acf);
1612     map = new MapList(new int[] { 4, 8, 12, 12, 16, 18 },
1613             new int[] { 1, 3 },
1614             3, 1);
1615     acf = new AlignedCodonFrame();
1616     acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
1617     dna.addCodonFrame(acf);
1618   
1619     AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
1620         dna1, dna2, dna3 }, dna.getDataset(), null);
1621     List<SequenceI> cdsSeqs = cds.getSequences();
1622     assertEquals(2, cdsSeqs.size());
1623     assertEquals("GGGCCCTTTGGG", cdsSeqs.get(0).getSequenceAsString());
1624     assertEquals("GGGCCTGGG", cdsSeqs.get(1).getSequenceAsString());
1625   
1626     /*
1627      * verify shared, extended alignment dataset
1628      */
1629     assertSame(dna.getDataset(), cds.getDataset());
1630     assertTrue(dna.getDataset().getSequences()
1631             .contains(cdsSeqs.get(0).getDatasetSequence()));
1632     assertTrue(dna.getDataset().getSequences()
1633             .contains(cdsSeqs.get(1).getDatasetSequence()));
1634
1635     /*
1636      * Verify 6 mappings: dna1 to cds1, cds1 to pep1, dna1 to pep1
1637      * and the same for dna2/cds2/pep2
1638      */
1639     List<AlignedCodonFrame> mappings = cds.getCodonFrames();
1640     assertEquals(6, mappings.size());
1641   
1642     /*
1643      * 2 mappings involve pep1
1644      */
1645     List<AlignedCodonFrame> pep1Mappings = MappingUtils
1646             .findMappingsForSequence(pep1, mappings);
1647     assertEquals(2, pep1Mappings.size());
1648
1649     /*
1650      * Get mapping of pep1 to cds1 and verify it
1651      * maps GPFG to 1-3,4-6,7-9,10-12
1652      */
1653     List<AlignedCodonFrame> pep1CdsMappings = MappingUtils
1654             .findMappingsForSequence(cds.getSequenceAt(0), pep1Mappings);
1655     assertEquals(1, pep1CdsMappings.size());
1656     SearchResults sr = MappingUtils.buildSearchResults(pep1, 1,
1657             pep1CdsMappings);
1658     assertEquals(1, sr.getResults().size());
1659     Match m = sr.getResults().get(0);
1660     assertEquals(cds.getSequenceAt(0).getDatasetSequence(),
1661             m.getSequence());
1662     assertEquals(1, m.getStart());
1663     assertEquals(3, m.getEnd());
1664     sr = MappingUtils.buildSearchResults(pep1, 2, pep1CdsMappings);
1665     m = sr.getResults().get(0);
1666     assertEquals(4, m.getStart());
1667     assertEquals(6, m.getEnd());
1668     sr = MappingUtils.buildSearchResults(pep1, 3, pep1CdsMappings);
1669     m = sr.getResults().get(0);
1670     assertEquals(7, m.getStart());
1671     assertEquals(9, m.getEnd());
1672     sr = MappingUtils.buildSearchResults(pep1, 4, pep1CdsMappings);
1673     m = sr.getResults().get(0);
1674     assertEquals(10, m.getStart());
1675     assertEquals(12, m.getEnd());
1676   
1677     /*
1678      * Get mapping of pep2 to cds2 and verify it
1679      * maps GPG in pep2 to 1-3,4-6,7-9 in second CDS sequence
1680      */
1681     List<AlignedCodonFrame> pep2Mappings = MappingUtils
1682             .findMappingsForSequence(pep2, mappings);
1683     assertEquals(2, pep2Mappings.size());
1684     List<AlignedCodonFrame> pep2CdsMappings = MappingUtils
1685             .findMappingsForSequence(cds.getSequenceAt(1), pep2Mappings);
1686     assertEquals(1, pep2CdsMappings.size());
1687     sr = MappingUtils.buildSearchResults(pep2, 1, pep2CdsMappings);
1688     assertEquals(1, sr.getResults().size());
1689     m = sr.getResults().get(0);
1690     assertEquals(cds.getSequenceAt(1).getDatasetSequence(),
1691             m.getSequence());
1692     assertEquals(1, m.getStart());
1693     assertEquals(3, m.getEnd());
1694     sr = MappingUtils.buildSearchResults(pep2, 2, pep2CdsMappings);
1695     m = sr.getResults().get(0);
1696     assertEquals(4, m.getStart());
1697     assertEquals(6, m.getEnd());
1698     sr = MappingUtils.buildSearchResults(pep2, 3, pep2CdsMappings);
1699     m = sr.getResults().get(0);
1700     assertEquals(7, m.getStart());
1701     assertEquals(9, m.getEnd());
1702   }
1703
1704   /**
1705    * Test the method that realigns protein to match mapped codon alignment.
1706    */
1707   @Test(groups = { "Functional" })
1708   public void testAlignProteinAsDna_incompleteStartCodon()
1709   {
1710     // seq1: incomplete start codon (not mapped), then [3, 11]
1711     SequenceI dna1 = new Sequence("Seq1", "ccAAA-TTT-GGG-");
1712     // seq2 codons are [4, 5], [8, 11]
1713     SequenceI dna2 = new Sequence("Seq2", "ccaAA-ttT-GGG-");
1714     // seq3 incomplete start codon at 'tt'
1715     SequenceI dna3 = new Sequence("Seq3", "ccaaa-ttt-GGG-");
1716     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2, dna3 });
1717     dna.setDataset(null);
1718   
1719     // prot1 has 'X' for incomplete start codon (not mapped)
1720     SequenceI prot1 = new Sequence("Seq1", "XKFG"); // X for incomplete start
1721     SequenceI prot2 = new Sequence("Seq2", "NG");
1722     SequenceI prot3 = new Sequence("Seq3", "XG"); // X for incomplete start
1723     AlignmentI protein = new Alignment(new SequenceI[] { prot1, prot2,
1724         prot3 });
1725     protein.setDataset(null);
1726   
1727     // map dna1 [3, 11] to prot1 [2, 4] KFG
1728     MapList map = new MapList(new int[] { 3, 11 }, new int[] { 2, 4 }, 3, 1);
1729     AlignedCodonFrame acf = new AlignedCodonFrame();
1730     acf.addMap(dna1.getDatasetSequence(), prot1.getDatasetSequence(), map);
1731
1732     // map dna2 [4, 5] [8, 11] to prot2 [1, 2] NG
1733     map = new MapList(new int[] { 4, 5, 8, 11 }, new int[] { 1, 2 }, 3, 1);
1734     acf.addMap(dna2.getDatasetSequence(), prot2.getDatasetSequence(), map);
1735
1736     // map dna3 [9, 11] to prot3 [2, 2] G
1737     map = new MapList(new int[] { 9, 11 }, new int[] { 2, 2 }, 3, 1);
1738     acf.addMap(dna3.getDatasetSequence(), prot3.getDatasetSequence(), map);
1739
1740     ArrayList<AlignedCodonFrame> acfs = new ArrayList<AlignedCodonFrame>();
1741     acfs.add(acf);
1742     protein.setCodonFrames(acfs);
1743
1744     /*
1745      * verify X is included in the aligned proteins, and placed just
1746      * before the first mapped residue 
1747      * CCT is between CCC and TTT
1748      */
1749     AlignmentUtils.alignProteinAsDna(protein, dna);
1750     assertEquals("XK-FG", prot1.getSequenceAsString());
1751     assertEquals("--N-G", prot2.getSequenceAsString());
1752     assertEquals("---XG", prot3.getSequenceAsString());
1753   }
1754
1755   /**
1756    * Tests for the method that maps the subset of a dna sequence that has CDS
1757    * (or subtype) feature - case where the start codon is incomplete.
1758    */
1759   @Test(groups = "Functional")
1760   public void testFindCdsPositions_fivePrimeIncomplete()
1761   {
1762     SequenceI dnaSeq = new Sequence("dna", "aaagGGCCCaaaTTTttt");
1763     dnaSeq.createDatasetSequence();
1764     SequenceI ds = dnaSeq.getDatasetSequence();
1765   
1766     // CDS for dna 5-6 (incomplete codon), 7-9
1767     SequenceFeature sf = new SequenceFeature("CDS", "", 5, 9, 0f, null);
1768     sf.setPhase("2"); // skip 2 bases to start of next codon
1769     ds.addSequenceFeature(sf);
1770     // CDS for dna 13-15
1771     sf = new SequenceFeature("CDS_predicted", "", 13, 15, 0f, null);
1772     ds.addSequenceFeature(sf);
1773   
1774     List<int[]> ranges = AlignmentUtils.findCdsPositions(dnaSeq);
1775   
1776     /*
1777      * check the mapping starts with the first complete codon
1778      */
1779     assertEquals(6, MappingUtils.getLength(ranges));
1780     assertEquals(2, ranges.size());
1781     assertEquals(7, ranges.get(0)[0]);
1782     assertEquals(9, ranges.get(0)[1]);
1783     assertEquals(13, ranges.get(1)[0]);
1784     assertEquals(15, ranges.get(1)[1]);
1785   }
1786
1787   /**
1788    * Tests for the method that maps the subset of a dna sequence that has CDS
1789    * (or subtype) feature.
1790    */
1791   @Test(groups = "Functional")
1792   public void testFindCdsPositions()
1793   {
1794     SequenceI dnaSeq = new Sequence("dna", "aaaGGGcccAAATTTttt");
1795     dnaSeq.createDatasetSequence();
1796     SequenceI ds = dnaSeq.getDatasetSequence();
1797   
1798     // CDS for dna 10-12
1799     SequenceFeature sf = new SequenceFeature("CDS_predicted", "", 10, 12,
1800             0f, null);
1801     sf.setStrand("+");
1802     ds.addSequenceFeature(sf);
1803     // CDS for dna 4-6
1804     sf = new SequenceFeature("CDS", "", 4, 6, 0f, null);
1805     sf.setStrand("+");
1806     ds.addSequenceFeature(sf);
1807     // exon feature should be ignored here
1808     sf = new SequenceFeature("exon", "", 7, 9, 0f, null);
1809     ds.addSequenceFeature(sf);
1810   
1811     List<int[]> ranges = AlignmentUtils.findCdsPositions(dnaSeq);
1812     /*
1813      * verify ranges { [4-6], [12-10] }
1814      * note CDS ranges are ordered ascending even if the CDS
1815      * features are not
1816      */
1817     assertEquals(6, MappingUtils.getLength(ranges));
1818     assertEquals(2, ranges.size());
1819     assertEquals(4, ranges.get(0)[0]);
1820     assertEquals(6, ranges.get(0)[1]);
1821     assertEquals(10, ranges.get(1)[0]);
1822     assertEquals(12, ranges.get(1)[1]);
1823   }
1824
1825   /**
1826    * Test the method that computes a map of codon variants for each protein
1827    * position from "sequence_variant" features on dna
1828    */
1829   @Test(groups = "Functional")
1830   public void testBuildDnaVariantsMap()
1831   {
1832     SequenceI dna = new Sequence("dna", "atgAAATTTGGGCCCtag");
1833     MapList map = new MapList(new int[] { 1, 18 }, new int[] { 1, 5 }, 3, 1);
1834
1835     /*
1836      * first with no variants on dna
1837      */
1838     LinkedHashMap<Integer, List<DnaVariant>[]> variantsMap = AlignmentUtils
1839             .buildDnaVariantsMap(dna, map);
1840     assertTrue(variantsMap.isEmpty());
1841
1842     /*
1843      * single allele codon 1, on base 1
1844      */
1845     SequenceFeature sf1 = new SequenceFeature("sequence_variant", "", 1, 1,
1846             0f, null);
1847     sf1.setValue("alleles", "T");
1848     sf1.setValue("ID", "sequence_variant:rs758803211");
1849     dna.addSequenceFeature(sf1);
1850
1851     /*
1852      * two alleles codon 2, on bases 2 and 3 (distinct variants)
1853      */
1854     SequenceFeature sf2 = new SequenceFeature("sequence_variant", "", 5, 5,
1855             0f, null);
1856     sf2.setValue("alleles", "T");
1857     sf2.setValue("ID", "sequence_variant:rs758803212");
1858     dna.addSequenceFeature(sf2);
1859     SequenceFeature sf3 = new SequenceFeature("sequence_variant", "", 6, 6,
1860             0f, null);
1861     sf3.setValue("alleles", "G");
1862     sf3.setValue("ID", "sequence_variant:rs758803213");
1863     dna.addSequenceFeature(sf3);
1864
1865     /*
1866      * two alleles codon 3, both on base 2 (one variant)
1867      */
1868     SequenceFeature sf4 = new SequenceFeature("sequence_variant", "", 8, 8,
1869             0f, null);
1870     sf4.setValue("alleles", "C, G");
1871     sf4.setValue("ID", "sequence_variant:rs758803214");
1872     dna.addSequenceFeature(sf4);
1873
1874     // no alleles on codon 4
1875
1876     /*
1877      * alleles on codon 5 on all 3 bases (distinct variants)
1878      */
1879     SequenceFeature sf5 = new SequenceFeature("sequence_variant", "", 13,
1880             13, 0f, null);
1881     sf5.setValue("alleles", "C, G"); // (C duplicates given base value)
1882     sf5.setValue("ID", "sequence_variant:rs758803215");
1883     dna.addSequenceFeature(sf5);
1884     SequenceFeature sf6 = new SequenceFeature("sequence_variant", "", 14,
1885             14, 0f, null);
1886     sf6.setValue("alleles", "g, a"); // should force to upper-case
1887     sf6.setValue("ID", "sequence_variant:rs758803216");
1888     dna.addSequenceFeature(sf6);
1889     SequenceFeature sf7 = new SequenceFeature("sequence_variant", "", 15,
1890             15, 0f, null);
1891     sf7.setValue("alleles", "A, T");
1892     sf7.setValue("ID", "sequence_variant:rs758803217");
1893     dna.addSequenceFeature(sf7);
1894
1895     /*
1896      * build map - expect variants on positions 1, 2, 3, 5
1897      */
1898     variantsMap = AlignmentUtils.buildDnaVariantsMap(dna, map);
1899     assertEquals(4, variantsMap.size());
1900
1901     /*
1902      * protein residue 1: variant on codon (ATG) base 1, not on 2 or 3
1903      */
1904     List<DnaVariant>[] pep1Variants = variantsMap.get(1);
1905     assertEquals(3, pep1Variants.length);
1906     assertEquals(1, pep1Variants[0].size());
1907     assertEquals("A", pep1Variants[0].get(0).base); // codon[1] base
1908     assertSame(sf1, pep1Variants[0].get(0).variant); // codon[1] variant
1909     assertEquals(1, pep1Variants[1].size());
1910     assertEquals("T", pep1Variants[1].get(0).base); // codon[2] base
1911     assertNull(pep1Variants[1].get(0).variant); // no variant here
1912     assertEquals(1, pep1Variants[2].size());
1913     assertEquals("G", pep1Variants[2].get(0).base); // codon[3] base
1914     assertNull(pep1Variants[2].get(0).variant); // no variant here
1915
1916     /*
1917      * protein residue 2: variants on codon (AAA) bases 2 and 3
1918      */
1919     List<DnaVariant>[] pep2Variants = variantsMap.get(2);
1920     assertEquals(3, pep2Variants.length);
1921     assertEquals(1, pep2Variants[0].size());
1922     // codon[1] base recorded while processing variant on codon[2]
1923     assertEquals("A", pep2Variants[0].get(0).base);
1924     assertNull(pep2Variants[0].get(0).variant); // no variant here
1925     // codon[2] base and variant:
1926     assertEquals(1, pep2Variants[1].size());
1927     assertEquals("A", pep2Variants[1].get(0).base);
1928     assertSame(sf2, pep2Variants[1].get(0).variant);
1929     // codon[3] base was recorded when processing codon[2] variant
1930     // and then the variant for codon[3] added to it
1931     assertEquals(1, pep2Variants[2].size());
1932     assertEquals("A", pep2Variants[2].get(0).base);
1933     assertSame(sf3, pep2Variants[2].get(0).variant);
1934
1935     /*
1936      * protein residue 3: variants on codon (TTT) base 2 only
1937      */
1938     List<DnaVariant>[] pep3Variants = variantsMap.get(3);
1939     assertEquals(3, pep3Variants.length);
1940     assertEquals(1, pep3Variants[0].size());
1941     assertEquals("T", pep3Variants[0].get(0).base); // codon[1] base
1942     assertNull(pep3Variants[0].get(0).variant); // no variant here
1943     assertEquals(1, pep3Variants[1].size());
1944     assertEquals("T", pep3Variants[1].get(0).base); // codon[2] base
1945     assertSame(sf4, pep3Variants[1].get(0).variant); // codon[2] variant
1946     assertEquals(1, pep3Variants[2].size());
1947     assertEquals("T", pep3Variants[2].get(0).base); // codon[3] base
1948     assertNull(pep3Variants[2].get(0).variant); // no variant here
1949
1950     /*
1951      * three variants on protein position 5
1952      */
1953     List<DnaVariant>[] pep5Variants = variantsMap.get(5);
1954     assertEquals(3, pep5Variants.length);
1955     assertEquals(1, pep5Variants[0].size());
1956     assertEquals("C", pep5Variants[0].get(0).base); // codon[1] base
1957     assertSame(sf5, pep5Variants[0].get(0).variant); // codon[1] variant
1958     assertEquals(1, pep5Variants[1].size());
1959     assertEquals("C", pep5Variants[1].get(0).base); // codon[2] base
1960     assertSame(sf6, pep5Variants[1].get(0).variant); // codon[2] variant
1961     assertEquals(1, pep5Variants[2].size());
1962     assertEquals("C", pep5Variants[2].get(0).base); // codon[3] base
1963     assertSame(sf7, pep5Variants[2].get(0).variant); // codon[3] variant
1964   }
1965
1966   /**
1967    * Tests for the method that computes all peptide variants given codon
1968    * variants
1969    */
1970   @Test(groups = "Functional")
1971   public void testComputePeptideVariants()
1972   {
1973     /*
1974      * scenario: AAATTTCCC codes for KFP
1975      * variants:
1976      *           GAA -> E             source: Ensembl
1977      *           CAA -> Q             source: dbSNP
1978      *           AAG synonymous       source: COSMIC
1979      *           AAT -> N             source: Ensembl
1980      *           ...TTC synonymous    source: dbSNP
1981      *           ......CAC,CGC -> H,R source: COSMIC
1982      *                 (one variant with two alleles)
1983      */
1984     SequenceI peptide = new Sequence("pep/10-12", "KFP");
1985
1986     /*
1987      * two distinct variants for codon 1 position 1
1988      * second one has clinical significance
1989      */
1990     String ensembl = "Ensembl";
1991     String dbSnp = "dbSNP";
1992     String cosmic = "COSMIC";
1993     SequenceFeature sf1 = new SequenceFeature("sequence_variant", "", 1, 1,
1994             0f, ensembl);
1995     sf1.setValue("alleles", "A,G"); // GAA -> E
1996     sf1.setValue("ID", "var1.125A>G");
1997     SequenceFeature sf2 = new SequenceFeature("sequence_variant", "", 1, 1,
1998             0f, dbSnp);
1999     sf2.setValue("alleles", "A,C"); // CAA -> Q
2000     sf2.setValue("ID", "var2");
2001     sf2.setValue("clinical_significance", "Dodgy");
2002     SequenceFeature sf3 = new SequenceFeature("sequence_variant", "", 3, 3,
2003             0f, cosmic);
2004     sf3.setValue("alleles", "A,G"); // synonymous
2005     sf3.setValue("ID", "var3");
2006     sf3.setValue("clinical_significance", "None");
2007     SequenceFeature sf4 = new SequenceFeature("sequence_variant", "", 3, 3,
2008             0f, ensembl);
2009     sf4.setValue("alleles", "A,T"); // AAT -> N
2010     sf4.setValue("ID", "sequence_variant:var4"); // prefix gets stripped off
2011     sf4.setValue("clinical_significance", "Benign");
2012     SequenceFeature sf5 = new SequenceFeature("sequence_variant", "", 6, 6,
2013             0f, dbSnp);
2014     sf5.setValue("alleles", "T,C"); // synonymous
2015     sf5.setValue("ID", "var5");
2016     sf5.setValue("clinical_significance", "Bad");
2017     SequenceFeature sf6 = new SequenceFeature("sequence_variant", "", 8, 8,
2018             0f, cosmic);
2019     sf6.setValue("alleles", "C,A,G"); // CAC,CGC -> H,R
2020     sf6.setValue("ID", "var6");
2021     sf6.setValue("clinical_significance", "Good");
2022
2023     List<DnaVariant> codon1Variants = new ArrayList<DnaVariant>();
2024     List<DnaVariant> codon2Variants = new ArrayList<DnaVariant>();
2025     List<DnaVariant> codon3Variants = new ArrayList<DnaVariant>();
2026     List<DnaVariant> codonVariants[] = new ArrayList[3];
2027     codonVariants[0] = codon1Variants;
2028     codonVariants[1] = codon2Variants;
2029     codonVariants[2] = codon3Variants;
2030
2031     /*
2032      * compute variants for protein position 1
2033      */
2034     codon1Variants.add(new DnaVariant("A", sf1));
2035     codon1Variants.add(new DnaVariant("A", sf2));
2036     codon2Variants.add(new DnaVariant("A"));
2037     codon2Variants.add(new DnaVariant("A"));
2038     codon3Variants.add(new DnaVariant("A", sf3));
2039     codon3Variants.add(new DnaVariant("A", sf4));
2040     AlignmentUtils.computePeptideVariants(peptide, 1, codonVariants);
2041
2042     /*
2043      * compute variants for protein position 2
2044      */
2045     codon1Variants.clear();
2046     codon2Variants.clear();
2047     codon3Variants.clear();
2048     codon1Variants.add(new DnaVariant("T"));
2049     codon2Variants.add(new DnaVariant("T"));
2050     codon3Variants.add(new DnaVariant("T", sf5));
2051     AlignmentUtils.computePeptideVariants(peptide, 2, codonVariants);
2052
2053     /*
2054      * compute variants for protein position 3
2055      */
2056     codon1Variants.clear();
2057     codon2Variants.clear();
2058     codon3Variants.clear();
2059     codon1Variants.add(new DnaVariant("C"));
2060     codon2Variants.add(new DnaVariant("C", sf6));
2061     codon3Variants.add(new DnaVariant("C"));
2062     AlignmentUtils.computePeptideVariants(peptide, 3, codonVariants);
2063
2064     /*
2065      * verify added sequence features for
2066      * var1 K -> E Ensembl
2067      * var2 K -> Q dbSNP
2068      * var4 K -> N Ensembl
2069      * var6 P -> H COSMIC
2070      * var6 P -> R COSMIC
2071      */
2072     SequenceFeature[] sfs = peptide.getSequenceFeatures();
2073     assertEquals(5, sfs.length);
2074
2075     SequenceFeature sf = sfs[0];
2076     assertEquals(1, sf.getBegin());
2077     assertEquals(1, sf.getEnd());
2078     assertEquals("p.Lys1Glu", sf.getDescription());
2079     assertEquals("var1.125A>G", sf.getValue("ID"));
2080     assertNull(sf.getValue("clinical_significance"));
2081     assertEquals("ID=var1.125A>G", sf.getAttributes());
2082     assertEquals(1, sf.links.size());
2083     // link to variation is urlencoded
2084     assertEquals(
2085             "p.Lys1Glu var1.125A>G|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var1.125A%3EG",
2086             sf.links.get(0));
2087     assertEquals(ensembl, sf.getFeatureGroup());
2088
2089     sf = sfs[1];
2090     assertEquals(1, sf.getBegin());
2091     assertEquals(1, sf.getEnd());
2092     assertEquals("p.Lys1Gln", sf.getDescription());
2093     assertEquals("var2", sf.getValue("ID"));
2094     assertEquals("Dodgy", sf.getValue("clinical_significance"));
2095     assertEquals("ID=var2;clinical_significance=Dodgy", sf.getAttributes());
2096     assertEquals(1, sf.links.size());
2097     assertEquals(
2098             "p.Lys1Gln var2|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var2",
2099             sf.links.get(0));
2100     assertEquals(dbSnp, sf.getFeatureGroup());
2101
2102     sf = sfs[2];
2103     assertEquals(1, sf.getBegin());
2104     assertEquals(1, sf.getEnd());
2105     assertEquals("p.Lys1Asn", sf.getDescription());
2106     assertEquals("var4", sf.getValue("ID"));
2107     assertEquals("Benign", sf.getValue("clinical_significance"));
2108     assertEquals("ID=var4;clinical_significance=Benign", sf.getAttributes());
2109     assertEquals(1, sf.links.size());
2110     assertEquals(
2111             "p.Lys1Asn var4|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var4",
2112             sf.links.get(0));
2113     assertEquals(ensembl, sf.getFeatureGroup());
2114
2115     // var5 generates two distinct protein variant features
2116     sf = sfs[3];
2117     assertEquals(3, sf.getBegin());
2118     assertEquals(3, sf.getEnd());
2119     assertEquals("p.Pro3His", sf.getDescription());
2120     assertEquals("var6", sf.getValue("ID"));
2121     assertEquals("Good", sf.getValue("clinical_significance"));
2122     assertEquals("ID=var6;clinical_significance=Good", sf.getAttributes());
2123     assertEquals(1, sf.links.size());
2124     assertEquals(
2125             "p.Pro3His var6|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var6",
2126             sf.links.get(0));
2127     assertEquals(cosmic, sf.getFeatureGroup());
2128
2129     sf = sfs[4];
2130     assertEquals(3, sf.getBegin());
2131     assertEquals(3, sf.getEnd());
2132     assertEquals("p.Pro3Arg", sf.getDescription());
2133     assertEquals("var6", sf.getValue("ID"));
2134     assertEquals("Good", sf.getValue("clinical_significance"));
2135     assertEquals("ID=var6;clinical_significance=Good", sf.getAttributes());
2136     assertEquals(1, sf.links.size());
2137     assertEquals(
2138             "p.Pro3Arg var6|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var6",
2139             sf.links.get(0));
2140     assertEquals(cosmic, sf.getFeatureGroup());
2141   }
2142
2143   /**
2144    * Tests for the method that maps the subset of a dna sequence that has CDS
2145    * (or subtype) feature, with CDS strand = '-' (reverse)
2146    */
2147   // test turned off as currently findCdsPositions is not strand-dependent
2148   // left in case it comes around again...
2149   @Test(groups = "Functional", enabled = false)
2150   public void testFindCdsPositions_reverseStrand()
2151   {
2152     SequenceI dnaSeq = new Sequence("dna", "aaaGGGcccAAATTTttt");
2153     dnaSeq.createDatasetSequence();
2154     SequenceI ds = dnaSeq.getDatasetSequence();
2155   
2156     // CDS for dna 4-6
2157     SequenceFeature sf = new SequenceFeature("CDS", "", 4, 6, 0f, null);
2158     sf.setStrand("-");
2159     ds.addSequenceFeature(sf);
2160     // exon feature should be ignored here
2161     sf = new SequenceFeature("exon", "", 7, 9, 0f, null);
2162     ds.addSequenceFeature(sf);
2163     // CDS for dna 10-12
2164     sf = new SequenceFeature("CDS_predicted", "", 10, 12, 0f, null);
2165     sf.setStrand("-");
2166     ds.addSequenceFeature(sf);
2167   
2168     List<int[]> ranges = AlignmentUtils.findCdsPositions(dnaSeq);
2169     /*
2170      * verify ranges { [12-10], [6-4] }
2171      */
2172     assertEquals(6, MappingUtils.getLength(ranges));
2173     assertEquals(2, ranges.size());
2174     assertEquals(12, ranges.get(0)[0]);
2175     assertEquals(10, ranges.get(0)[1]);
2176     assertEquals(6, ranges.get(1)[0]);
2177     assertEquals(4, ranges.get(1)[1]);
2178   }
2179
2180   /**
2181    * Tests for the method that maps the subset of a dna sequence that has CDS
2182    * (or subtype) feature - reverse strand case where the start codon is
2183    * incomplete.
2184    */
2185   @Test(groups = "Functional", enabled = false)
2186   // test turned off as currently findCdsPositions is not strand-dependent
2187   // left in case it comes around again...
2188   public void testFindCdsPositions_reverseStrandThreePrimeIncomplete()
2189   {
2190     SequenceI dnaSeq = new Sequence("dna", "aaagGGCCCaaaTTTttt");
2191     dnaSeq.createDatasetSequence();
2192     SequenceI ds = dnaSeq.getDatasetSequence();
2193   
2194     // CDS for dna 5-9
2195     SequenceFeature sf = new SequenceFeature("CDS", "", 5, 9, 0f, null);
2196     sf.setStrand("-");
2197     ds.addSequenceFeature(sf);
2198     // CDS for dna 13-15
2199     sf = new SequenceFeature("CDS_predicted", "", 13, 15, 0f, null);
2200     sf.setStrand("-");
2201     sf.setPhase("2"); // skip 2 bases to start of next codon
2202     ds.addSequenceFeature(sf);
2203   
2204     List<int[]> ranges = AlignmentUtils.findCdsPositions(dnaSeq);
2205   
2206     /*
2207      * check the mapping starts with the first complete codon
2208      * expect ranges [13, 13], [9, 5]
2209      */
2210     assertEquals(6, MappingUtils.getLength(ranges));
2211     assertEquals(2, ranges.size());
2212     assertEquals(13, ranges.get(0)[0]);
2213     assertEquals(13, ranges.get(0)[1]);
2214     assertEquals(9, ranges.get(1)[0]);
2215     assertEquals(5, ranges.get(1)[1]);
2216   }
2217
2218   @Test(groups = "Functional")
2219   public void testAlignAs_alternateTranscriptsUngapped()
2220   {
2221     SequenceI dna1 = new Sequence("dna1", "cccGGGTTTaaa");
2222     SequenceI dna2 = new Sequence("dna2", "CCCgggtttAAA");
2223     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2 });
2224     ((Alignment) dna).createDatasetAlignment();
2225     SequenceI cds1 = new Sequence("cds1", "GGGTTT");
2226     SequenceI cds2 = new Sequence("cds2", "CCCAAA");
2227     AlignmentI cds = new Alignment(new SequenceI[] { cds1, cds2 });
2228     ((Alignment) cds).createDatasetAlignment();
2229
2230     AlignedCodonFrame acf = new AlignedCodonFrame();
2231     MapList map = new MapList(new int[] { 4, 9 }, new int[] { 1, 6 }, 1, 1);
2232     acf.addMap(dna1.getDatasetSequence(), cds1.getDatasetSequence(), map);
2233     map = new MapList(new int[] { 1, 3, 10, 12 }, new int[] { 1, 6 }, 1, 1);
2234     acf.addMap(dna2.getDatasetSequence(), cds2.getDatasetSequence(), map);
2235
2236     /*
2237      * verify CDS alignment is as:
2238      *   cccGGGTTTaaa (cdna)
2239      *   CCCgggtttAAA (cdna)
2240      *   
2241      *   ---GGGTTT--- (cds)
2242      *   CCC------AAA (cds)
2243      */
2244     dna.addCodonFrame(acf);
2245     AlignmentUtils.alignAs(cds, dna);
2246     assertEquals("---GGGTTT", cds.getSequenceAt(0).getSequenceAsString());
2247     assertEquals("CCC------AAA", cds.getSequenceAt(1).getSequenceAsString());
2248   }
2249
2250   @Test(groups = { "Functional" })
2251   public void testAddMappedPositions()
2252   {
2253     SequenceI from = new Sequence("dna", "ggAA-ATcc-TT-g");
2254     SequenceI seq1 = new Sequence("cds", "AAATTT");
2255     from.createDatasetSequence();
2256     seq1.createDatasetSequence();
2257     Mapping mapping = new Mapping(seq1, new MapList(
2258             new int[] { 3, 6, 9, 10 },
2259             new int[] { 1, 6 }, 1, 1));
2260     Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2261     AlignmentUtils.addMappedPositions(seq1, from, mapping, map);
2262
2263     /*
2264      * verify map has seq1 residues in columns 3,4,6,7,11,12
2265      */
2266     assertEquals(6, map.size());
2267     assertEquals('A', map.get(3).get(seq1).charValue());
2268     assertEquals('A', map.get(4).get(seq1).charValue());
2269     assertEquals('A', map.get(6).get(seq1).charValue());
2270     assertEquals('T', map.get(7).get(seq1).charValue());
2271     assertEquals('T', map.get(11).get(seq1).charValue());
2272     assertEquals('T', map.get(12).get(seq1).charValue());
2273
2274     /*
2275      * 
2276      */
2277   }
2278
2279   /**
2280    * Test case where the mapping 'from' range includes a stop codon which is
2281    * absent in the 'to' range
2282    */
2283   @Test(groups = { "Functional" })
2284   public void testAddMappedPositions_withStopCodon()
2285   {
2286     SequenceI from = new Sequence("dna", "ggAA-ATcc-TT-g");
2287     SequenceI seq1 = new Sequence("cds", "AAATTT");
2288     from.createDatasetSequence();
2289     seq1.createDatasetSequence();
2290     Mapping mapping = new Mapping(seq1, new MapList(
2291             new int[] { 3, 6, 9, 10 },
2292             new int[] { 1, 6 }, 1, 1));
2293     Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2294     AlignmentUtils.addMappedPositions(seq1, from, mapping, map);
2295   
2296     /*
2297      * verify map has seq1 residues in columns 3,4,6,7,11,12
2298      */
2299     assertEquals(6, map.size());
2300     assertEquals('A', map.get(3).get(seq1).charValue());
2301     assertEquals('A', map.get(4).get(seq1).charValue());
2302     assertEquals('A', map.get(6).get(seq1).charValue());
2303     assertEquals('T', map.get(7).get(seq1).charValue());
2304     assertEquals('T', map.get(11).get(seq1).charValue());
2305     assertEquals('T', map.get(12).get(seq1).charValue());
2306   }
2307
2308   /**
2309    * Test for the case where the products for which we want CDS are specified.
2310    * This is to represent the case where EMBL has CDS mappings to both Uniprot
2311    * and EMBLCDSPROTEIN. makeCdsAlignment() should only return the mappings for
2312    * the protein sequences specified.
2313    */
2314   @Test(groups = { "Functional" })
2315   public void testMakeCdsAlignment_filterProducts()
2316   {
2317     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
2318     SequenceI dna2 = new Sequence("dna2", "GGGcccTTTaaaCCC");
2319     SequenceI pep1 = new Sequence("Uniprot|pep1", "GF");
2320     SequenceI pep2 = new Sequence("Uniprot|pep2", "GFP");
2321     SequenceI pep3 = new Sequence("EMBL|pep3", "GF");
2322     SequenceI pep4 = new Sequence("EMBL|pep4", "GFP");
2323     dna1.createDatasetSequence();
2324     dna2.createDatasetSequence();
2325     pep1.createDatasetSequence();
2326     pep2.createDatasetSequence();
2327     pep3.createDatasetSequence();
2328     pep4.createDatasetSequence();
2329     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2 });
2330     dna.setDataset(null);
2331     AlignmentI emblPeptides = new Alignment(new SequenceI[] { pep3, pep4 });
2332     emblPeptides.setDataset(null);
2333   
2334     AlignedCodonFrame acf = new AlignedCodonFrame();
2335     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
2336             new int[] { 1, 2 }, 3, 1);
2337     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
2338     acf.addMap(dna1.getDatasetSequence(), pep3.getDatasetSequence(), map);
2339     dna.addCodonFrame(acf);
2340
2341     acf = new AlignedCodonFrame();
2342     map = new MapList(new int[] { 1, 3, 7, 9, 13, 15 }, new int[] { 1, 3 },
2343             3, 1);
2344     acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
2345     acf.addMap(dna2.getDatasetSequence(), pep4.getDatasetSequence(), map);
2346     dna.addCodonFrame(acf);
2347   
2348     /*
2349      * execute method under test to find CDS for EMBL peptides only
2350      */
2351     AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
2352         dna1, dna2 }, dna.getDataset(), emblPeptides.getSequencesArray());
2353   
2354     assertEquals(2, cds.getSequences().size());
2355     assertEquals("GGGTTT", cds.getSequenceAt(0).getSequenceAsString());
2356     assertEquals("GGGTTTCCC", cds.getSequenceAt(1).getSequenceAsString());
2357   
2358     /*
2359      * verify shared, extended alignment dataset
2360      */
2361     assertSame(dna.getDataset(), cds.getDataset());
2362     assertTrue(dna.getDataset().getSequences()
2363             .contains(cds.getSequenceAt(0).getDatasetSequence()));
2364     assertTrue(dna.getDataset().getSequences()
2365             .contains(cds.getSequenceAt(1).getDatasetSequence()));
2366   
2367     /*
2368      * Verify mappings from CDS to peptide, cDNA to CDS, and cDNA to peptide
2369      * the mappings are on the shared alignment dataset
2370      */
2371     List<AlignedCodonFrame> cdsMappings = cds.getDataset().getCodonFrames();
2372     /*
2373      * 6 mappings, 2*(DNA->CDS), 2*(DNA->Pep), 2*(CDS->Pep) 
2374      */
2375     assertEquals(6, cdsMappings.size());
2376   
2377     /*
2378      * verify that mapping sets for dna and cds alignments are different
2379      * [not current behaviour - all mappings are on the alignment dataset]  
2380      */
2381     // select -> subselect type to test.
2382     // Assert.assertNotSame(dna.getCodonFrames(), cds.getCodonFrames());
2383     // assertEquals(4, dna.getCodonFrames().size());
2384     // assertEquals(4, cds.getCodonFrames().size());
2385   
2386     /*
2387      * Two mappings involve pep3 (dna to pep3, cds to pep3)
2388      * Mapping from pep3 to GGGTTT in first new exon sequence
2389      */
2390     List<AlignedCodonFrame> pep3Mappings = MappingUtils
2391             .findMappingsForSequence(pep3, cdsMappings);
2392     assertEquals(2, pep3Mappings.size());
2393     List<AlignedCodonFrame> mappings = MappingUtils
2394             .findMappingsForSequence(cds.getSequenceAt(0), pep3Mappings);
2395     assertEquals(1, mappings.size());
2396   
2397     // map G to GGG
2398     SearchResults sr = MappingUtils.buildSearchResults(pep3, 1, mappings);
2399     assertEquals(1, sr.getResults().size());
2400     Match m = sr.getResults().get(0);
2401     assertSame(cds.getSequenceAt(0).getDatasetSequence(), m.getSequence());
2402     assertEquals(1, m.getStart());
2403     assertEquals(3, m.getEnd());
2404     // map F to TTT
2405     sr = MappingUtils.buildSearchResults(pep3, 2, mappings);
2406     m = sr.getResults().get(0);
2407     assertSame(cds.getSequenceAt(0).getDatasetSequence(), m.getSequence());
2408     assertEquals(4, m.getStart());
2409     assertEquals(6, m.getEnd());
2410   
2411     /*
2412      * Two mappings involve pep4 (dna to pep4, cds to pep4)
2413      * Verify mapping from pep4 to GGGTTTCCC in second new exon sequence
2414      */
2415     List<AlignedCodonFrame> pep4Mappings = MappingUtils
2416             .findMappingsForSequence(pep4, cdsMappings);
2417     assertEquals(2, pep4Mappings.size());
2418     mappings = MappingUtils.findMappingsForSequence(cds.getSequenceAt(1),
2419             pep4Mappings);
2420     assertEquals(1, mappings.size());
2421     // map G to GGG
2422     sr = MappingUtils.buildSearchResults(pep4, 1, mappings);
2423     assertEquals(1, sr.getResults().size());
2424     m = sr.getResults().get(0);
2425     assertSame(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
2426     assertEquals(1, m.getStart());
2427     assertEquals(3, m.getEnd());
2428     // map F to TTT
2429     sr = MappingUtils.buildSearchResults(pep4, 2, mappings);
2430     m = sr.getResults().get(0);
2431     assertSame(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
2432     assertEquals(4, m.getStart());
2433     assertEquals(6, m.getEnd());
2434     // map P to CCC
2435     sr = MappingUtils.buildSearchResults(pep4, 3, mappings);
2436     m = sr.getResults().get(0);
2437     assertSame(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
2438     assertEquals(7, m.getStart());
2439     assertEquals(9, m.getEnd());
2440   }
2441
2442   /**
2443    * Test the method that just copies aligned sequences, provided all sequences
2444    * to be aligned share the aligned sequence's dataset
2445    */
2446   @Test(groups = "Functional")
2447   public void testAlignAsSameSequences()
2448   {
2449     SequenceI dna1 = new Sequence("dna1", "cccGGGTTTaaa");
2450     SequenceI dna2 = new Sequence("dna2", "CCCgggtttAAA");
2451     AlignmentI al1 = new Alignment(new SequenceI[] { dna1, dna2 });
2452     ((Alignment) al1).createDatasetAlignment();
2453
2454     SequenceI dna3 = new Sequence(dna1);
2455     SequenceI dna4 = new Sequence(dna2);
2456     assertSame(dna3.getDatasetSequence(), dna1.getDatasetSequence());
2457     assertSame(dna4.getDatasetSequence(), dna2.getDatasetSequence());
2458     String seq1 = "-cc-GG-GT-TT--aaa";
2459     dna3.setSequence(seq1);
2460     String seq2 = "C--C-Cgg--gtt-tAA-A-";
2461     dna4.setSequence(seq2);
2462     AlignmentI al2 = new Alignment(new SequenceI[] { dna3, dna4 });
2463     ((Alignment) al2).createDatasetAlignment();
2464     
2465     assertTrue(AlignmentUtils.alignAsSameSequences(al1, al2));
2466     assertEquals(seq1, al1.getSequenceAt(0).getSequenceAsString());
2467     assertEquals(seq2, al1.getSequenceAt(1).getSequenceAsString());
2468
2469     /*
2470      * add another sequence to 'aligned' - should still succeed, since
2471      * unaligned sequences still share a dataset with aligned sequences
2472      */
2473     SequenceI dna5 = new Sequence("dna5", "CCCgggtttAAA");
2474     dna5.createDatasetSequence();
2475     al2.addSequence(dna5);
2476     assertTrue(AlignmentUtils.alignAsSameSequences(al1, al2));
2477     assertEquals(seq1, al1.getSequenceAt(0).getSequenceAsString());
2478     assertEquals(seq2, al1.getSequenceAt(1).getSequenceAsString());
2479
2480     /*
2481      * add another sequence to 'unaligned' - should fail, since now not
2482      * all unaligned sequences share a dataset with aligned sequences
2483      */
2484     SequenceI dna6 = new Sequence("dna6", "CCCgggtttAAA");
2485     dna6.createDatasetSequence();
2486     al1.addSequence(dna6);
2487     // JAL-2110 JBP Comment: what's the use case for this behaviour ?
2488     assertFalse(AlignmentUtils.alignAsSameSequences(al1, al2));
2489   }
2490
2491   @Test(groups = "Functional")
2492   public void testAlignAsSameSequencesMultipleSubSeq()
2493   {
2494     SequenceI dna1 = new Sequence("dna1", "cccGGGTTTaaa");
2495     SequenceI dna2 = new Sequence("dna2", "CCCgggtttAAA");
2496     SequenceI as1 = dna1.deriveSequence();
2497     SequenceI as2 = dna1.deriveSequence().getSubSequence(3, 7);
2498     SequenceI as3 = dna2.deriveSequence();
2499     as1.insertCharAt(6, 5, '-');
2500     String s_as1 = as1.getSequenceAsString();
2501     as2.insertCharAt(6, 5, '-');
2502     String s_as2 = as2.getSequenceAsString();
2503     as3.insertCharAt(6, 5, '-');
2504     String s_as3 = as3.getSequenceAsString();
2505     AlignmentI aligned = new Alignment(new SequenceI[] { as1, as2, as3 });
2506
2507     // why do we need to cast this still ?
2508     ((Alignment) aligned).createDatasetAlignment();
2509     SequenceI uas1 = dna1.deriveSequence();
2510     SequenceI uas2 = dna1.deriveSequence().getSubSequence(3, 7);
2511     SequenceI uas3 = dna2.deriveSequence();
2512     AlignmentI tobealigned = new Alignment(new SequenceI[] { uas1, uas2,
2513         uas3 });
2514     ((Alignment) tobealigned).createDatasetAlignment();
2515
2516     assertTrue(AlignmentUtils.alignAsSameSequences(tobealigned, aligned));
2517     assertEquals(s_as1, uas1.getSequenceAsString());
2518     assertEquals(s_as2, uas2.getSequenceAsString());
2519     assertEquals(s_as3, uas3.getSequenceAsString());
2520   }
2521     
2522 }