JAL-2089 patch broken merge to master for Release 2.10.0b1
[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(),
443             alignFrom.getDatasetSequence(), map);
444
445     AlignmentUtils.alignSequenceAs(alignMe, alignFrom, acf, "---", '-',
446             preserveMappedGaps, preserveUnmappedGaps);
447     assertEquals(expected, alignMe.getSequenceAsString());
448   }
449
450   /**
451    * Test for the alignSequenceAs method where we preserve gaps in introns only.
452    */
453   @Test(groups = { "Functional" })
454   public void testAlignSequenceAs_keepIntronGapsOnly()
455   {
456
457     /*
458      * Intron GGGAAA followed by exon CCCTTT
459      */
460     MapList map = new MapList(new int[] { 7, 12 }, new int[] { 1, 2 }, 3, 1);
461
462     checkAlignSequenceAs("GG-G-AA-A-C-CC-T-TT", "AL", false, true, map,
463             "GG-G-AA-ACCCTTT");
464   }
465
466   /**
467    * Test the method that realigns protein to match mapped codon alignment.
468    */
469   @Test(groups = { "Functional" })
470   public void testAlignProteinAsDna()
471   {
472     // seq1 codons are [1,2,3] [4,5,6] [7,8,9] [10,11,12]
473     SequenceI dna1 = new Sequence("Seq1", "TGCCATTACCAG-");
474     // seq2 codons are [1,3,4] [5,6,7] [8,9,10] [11,12,13]
475     SequenceI dna2 = new Sequence("Seq2", "T-GCCATTACCAG");
476     // seq3 codons are [1,2,3] [4,5,7] [8,9,10] [11,12,13]
477     SequenceI dna3 = new Sequence("Seq3", "TGCCA-TTACCAG");
478     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2, dna3 });
479     dna.setDataset(null);
480
481     // protein alignment will be realigned like dna
482     SequenceI prot1 = new Sequence("Seq1", "CHYQ");
483     SequenceI prot2 = new Sequence("Seq2", "CHYQ");
484     SequenceI prot3 = new Sequence("Seq3", "CHYQ");
485     SequenceI prot4 = new Sequence("Seq4", "R-QSV"); // unmapped, unchanged
486     AlignmentI protein = new Alignment(new SequenceI[] { prot1, prot2,
487         prot3, prot4 });
488     protein.setDataset(null);
489
490     MapList map = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 }, 3, 1);
491     AlignedCodonFrame acf = new AlignedCodonFrame();
492     acf.addMap(dna1.getDatasetSequence(), prot1.getDatasetSequence(), map);
493     acf.addMap(dna2.getDatasetSequence(), prot2.getDatasetSequence(), map);
494     acf.addMap(dna3.getDatasetSequence(), prot3.getDatasetSequence(), map);
495     ArrayList<AlignedCodonFrame> acfs = new ArrayList<AlignedCodonFrame>();
496     acfs.add(acf);
497     protein.setCodonFrames(acfs);
498
499     /*
500      * Translated codon order is [1,2,3] [1,3,4] [4,5,6] [4,5,7] [5,6,7] [7,8,9]
501      * [8,9,10] [10,11,12] [11,12,13]
502      */
503     AlignmentUtils.alignProteinAsDna(protein, dna);
504     assertEquals("C-H--Y-Q-", prot1.getSequenceAsString());
505     assertEquals("-C--H-Y-Q", prot2.getSequenceAsString());
506     assertEquals("C--H--Y-Q", prot3.getSequenceAsString());
507     assertEquals("R-QSV", prot4.getSequenceAsString());
508   }
509
510   /**
511    * Test the method that tests whether a CDNA sequence translates to a protein
512    * sequence
513    */
514   @Test(groups = { "Functional" })
515   public void testTranslatesAs()
516   {
517     // null arguments check
518     assertFalse(AlignmentUtils.translatesAs(null, 0, null));
519     assertFalse(AlignmentUtils.translatesAs(new char[] { 't' }, 0, null));
520     assertFalse(AlignmentUtils.translatesAs(null, 0, new char[] { 'a' }));
521
522     // straight translation
523     assertTrue(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(), 0,
524             "FPKG".toCharArray()));
525     // with extra start codon (not in protein)
526     assertTrue(AlignmentUtils.translatesAs("atgtttcccaaaggg".toCharArray(),
527             3, "FPKG".toCharArray()));
528     // with stop codon1 (not in protein)
529     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtaa".toCharArray(),
530             0, "FPKG".toCharArray()));
531     // with stop codon1 (in protein as *)
532     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtaa".toCharArray(),
533             0, "FPKG*".toCharArray()));
534     // with stop codon2 (not in protein)
535     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtag".toCharArray(),
536             0, "FPKG".toCharArray()));
537     // with stop codon3 (not in protein)
538     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtga".toCharArray(),
539             0, "FPKG".toCharArray()));
540     // with start and stop codon1
541     assertTrue(AlignmentUtils.translatesAs(
542             "atgtttcccaaagggtaa".toCharArray(), 3, "FPKG".toCharArray()));
543     // with start and stop codon1 (in protein as *)
544     assertTrue(AlignmentUtils.translatesAs(
545             "atgtttcccaaagggtaa".toCharArray(), 3, "FPKG*".toCharArray()));
546     // with start and stop codon2
547     assertTrue(AlignmentUtils.translatesAs(
548             "atgtttcccaaagggtag".toCharArray(), 3, "FPKG".toCharArray()));
549     // with start and stop codon3
550     assertTrue(AlignmentUtils.translatesAs(
551             "atgtttcccaaagggtga".toCharArray(), 3, "FPKG".toCharArray()));
552
553     // with embedded stop codons
554     assertTrue(AlignmentUtils.translatesAs(
555             "atgtttTAGcccaaaTAAgggtga".toCharArray(), 3,
556             "F*PK*G".toCharArray()));
557
558     // wrong protein
559     assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
560             0, "FPMG".toCharArray()));
561
562     // truncated dna
563     assertFalse(AlignmentUtils.translatesAs("tttcccaaagg".toCharArray(), 0,
564             "FPKG".toCharArray()));
565
566     // truncated protein
567     assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
568             0, "FPK".toCharArray()));
569
570     // overlong dna (doesn't end in stop codon)
571     assertFalse(AlignmentUtils.translatesAs(
572             "tttcccaaagggttt".toCharArray(), 0, "FPKG".toCharArray()));
573
574     // dna + stop codon + more
575     assertFalse(AlignmentUtils.translatesAs(
576             "tttcccaaagggttaga".toCharArray(), 0, "FPKG".toCharArray()));
577
578     // overlong protein
579     assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
580             0, "FPKGQ".toCharArray()));
581   }
582
583   /**
584    * Test mapping of protein to cDNA, for cases where the cDNA has start and/or
585    * stop codons in addition to the protein coding sequence.
586    * 
587    * @throws IOException
588    */
589   @Test(groups = { "Functional" })
590   public void testMapProteinAlignmentToCdna_withStartAndStopCodons()
591           throws IOException
592   {
593     List<SequenceI> protseqs = new ArrayList<SequenceI>();
594     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
595     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
596     protseqs.add(new Sequence("UNIPROT|V12347", "SAR"));
597     AlignmentI protein = new Alignment(protseqs.toArray(new SequenceI[3]));
598     protein.setDataset(null);
599
600     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
601     // start + SAR:
602     dnaseqs.add(new Sequence("EMBL|A11111", "ATGTCAGCACGC"));
603     // = EIQ + stop
604     dnaseqs.add(new Sequence("EMBL|A22222", "GAGATACAATAA"));
605     // = start +EIQ + stop
606     dnaseqs.add(new Sequence("EMBL|A33333", "ATGGAAATCCAGTAG"));
607     dnaseqs.add(new Sequence("EMBL|A44444", "GAAATTCAG"));
608     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[4]));
609     cdna.setDataset(null);
610
611     assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
612
613     // 3 mappings made, each from 1 to 1 sequence
614     assertEquals(3, protein.getCodonFrames().size());
615     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
616     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
617     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(2)).size());
618
619     // V12345 mapped from A22222
620     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
621             .get(0);
622     assertEquals(1, acf.getdnaSeqs().length);
623     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
624             acf.getdnaSeqs()[0]);
625     Mapping[] protMappings = acf.getProtMappings();
626     assertEquals(1, protMappings.length);
627     MapList mapList = protMappings[0].getMap();
628     assertEquals(3, mapList.getFromRatio());
629     assertEquals(1, mapList.getToRatio());
630     assertTrue(Arrays.equals(new int[] { 1, 9 }, mapList.getFromRanges()
631             .get(0)));
632     assertEquals(1, mapList.getFromRanges().size());
633     assertTrue(Arrays.equals(new int[] { 1, 3 },
634             mapList.getToRanges().get(0)));
635     assertEquals(1, mapList.getToRanges().size());
636
637     // V12346 mapped from A33333 starting position 4
638     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
639     assertEquals(1, acf.getdnaSeqs().length);
640     assertEquals(cdna.getSequenceAt(2).getDatasetSequence(),
641             acf.getdnaSeqs()[0]);
642     protMappings = acf.getProtMappings();
643     assertEquals(1, protMappings.length);
644     mapList = protMappings[0].getMap();
645     assertEquals(3, mapList.getFromRatio());
646     assertEquals(1, mapList.getToRatio());
647     assertTrue(Arrays.equals(new int[] { 4, 12 }, mapList.getFromRanges()
648             .get(0)));
649     assertEquals(1, mapList.getFromRanges().size());
650     assertTrue(Arrays.equals(new int[] { 1, 3 },
651             mapList.getToRanges().get(0)));
652     assertEquals(1, mapList.getToRanges().size());
653
654     // V12347 mapped to A11111 starting position 4
655     acf = protein.getCodonFrame(protein.getSequenceAt(2)).get(0);
656     assertEquals(1, acf.getdnaSeqs().length);
657     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
658             acf.getdnaSeqs()[0]);
659     protMappings = acf.getProtMappings();
660     assertEquals(1, protMappings.length);
661     mapList = protMappings[0].getMap();
662     assertEquals(3, mapList.getFromRatio());
663     assertEquals(1, mapList.getToRatio());
664     assertTrue(Arrays.equals(new int[] { 4, 12 }, mapList.getFromRanges()
665             .get(0)));
666     assertEquals(1, mapList.getFromRanges().size());
667     assertTrue(Arrays.equals(new int[] { 1, 3 },
668             mapList.getToRanges().get(0)));
669     assertEquals(1, mapList.getToRanges().size());
670
671     // no mapping involving the 'extra' A44444
672     assertTrue(protein.getCodonFrame(cdna.getSequenceAt(3)).isEmpty());
673   }
674
675   /**
676    * Test mapping of protein to cDNA, for the case where we have some sequence
677    * cross-references. Verify that 1-to-many mappings are made where
678    * cross-references exist and sequences are mappable.
679    * 
680    * @throws IOException
681    */
682   @Test(groups = { "Functional" })
683   public void testMapProteinAlignmentToCdna_withXrefs() throws IOException
684   {
685     List<SequenceI> protseqs = new ArrayList<SequenceI>();
686     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
687     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
688     protseqs.add(new Sequence("UNIPROT|V12347", "SAR"));
689     AlignmentI protein = new Alignment(protseqs.toArray(new SequenceI[3]));
690     protein.setDataset(null);
691
692     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
693     dnaseqs.add(new Sequence("EMBL|A11111", "TCAGCACGC")); // = SAR
694     dnaseqs.add(new Sequence("EMBL|A22222", "ATGGAGATACAA")); // = start + EIQ
695     dnaseqs.add(new Sequence("EMBL|A33333", "GAAATCCAG")); // = EIQ
696     dnaseqs.add(new Sequence("EMBL|A44444", "GAAATTCAG")); // = EIQ
697     dnaseqs.add(new Sequence("EMBL|A55555", "GAGATTCAG")); // = EIQ
698     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[5]));
699     cdna.setDataset(null);
700
701     // Xref A22222 to V12345 (should get mapped)
702     dnaseqs.get(1).addDBRef(new DBRefEntry("UNIPROT", "1", "V12345"));
703     // Xref V12345 to A44444 (should get mapped)
704     protseqs.get(0).addDBRef(new DBRefEntry("EMBL", "1", "A44444"));
705     // Xref A33333 to V12347 (sequence mismatch - should not get mapped)
706     dnaseqs.get(2).addDBRef(new DBRefEntry("UNIPROT", "1", "V12347"));
707     // as V12345 is mapped to A22222 and A44444, this leaves V12346 unmapped.
708     // it should get paired up with the unmapped A33333
709     // A11111 should be mapped to V12347
710     // A55555 is spare and has no xref so is not mapped
711
712     assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
713
714     // 4 protein mappings made for 3 proteins, 2 to V12345, 1 each to V12346/7
715     assertEquals(3, protein.getCodonFrames().size());
716     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
717     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
718     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(2)).size());
719
720     // one mapping for each of the first 4 cDNA sequences
721     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(0)).size());
722     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(1)).size());
723     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(2)).size());
724     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(3)).size());
725
726     // V12345 mapped to A22222 and A44444
727     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
728             .get(0);
729     assertEquals(2, acf.getdnaSeqs().length);
730     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
731             acf.getdnaSeqs()[0]);
732     assertEquals(cdna.getSequenceAt(3).getDatasetSequence(),
733             acf.getdnaSeqs()[1]);
734
735     // V12346 mapped to A33333
736     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
737     assertEquals(1, acf.getdnaSeqs().length);
738     assertEquals(cdna.getSequenceAt(2).getDatasetSequence(),
739             acf.getdnaSeqs()[0]);
740
741     // V12347 mapped to A11111
742     acf = protein.getCodonFrame(protein.getSequenceAt(2)).get(0);
743     assertEquals(1, acf.getdnaSeqs().length);
744     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
745             acf.getdnaSeqs()[0]);
746
747     // no mapping involving the 'extra' A55555
748     assertTrue(protein.getCodonFrame(cdna.getSequenceAt(4)).isEmpty());
749   }
750
751   /**
752    * Test mapping of protein to cDNA, for the case where we have some sequence
753    * cross-references. Verify that once we have made an xref mapping we don't
754    * also map un-xrefd sequeces.
755    * 
756    * @throws IOException
757    */
758   @Test(groups = { "Functional" })
759   public void testMapProteinAlignmentToCdna_prioritiseXrefs()
760           throws IOException
761   {
762     List<SequenceI> protseqs = new ArrayList<SequenceI>();
763     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
764     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
765     AlignmentI protein = new Alignment(
766             protseqs.toArray(new SequenceI[protseqs.size()]));
767     protein.setDataset(null);
768
769     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
770     dnaseqs.add(new Sequence("EMBL|A11111", "GAAATCCAG")); // = EIQ
771     dnaseqs.add(new Sequence("EMBL|A22222", "GAAATTCAG")); // = EIQ
772     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[dnaseqs
773             .size()]));
774     cdna.setDataset(null);
775
776     // Xref A22222 to V12345 (should get mapped)
777     // A11111 should then be mapped to the unmapped V12346
778     dnaseqs.get(1).addDBRef(new DBRefEntry("UNIPROT", "1", "V12345"));
779
780     assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
781
782     // 2 protein mappings made
783     assertEquals(2, protein.getCodonFrames().size());
784     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
785     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
786
787     // one mapping for each of the cDNA sequences
788     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(0)).size());
789     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(1)).size());
790
791     // V12345 mapped to A22222
792     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
793             .get(0);
794     assertEquals(1, acf.getdnaSeqs().length);
795     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
796             acf.getdnaSeqs()[0]);
797
798     // V12346 mapped to A11111
799     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
800     assertEquals(1, acf.getdnaSeqs().length);
801     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
802             acf.getdnaSeqs()[0]);
803   }
804
805   /**
806    * Test the method that shows or hides sequence annotations by type(s) and
807    * selection group.
808    */
809   @Test(groups = { "Functional" })
810   public void testShowOrHideSequenceAnnotations()
811   {
812     SequenceI seq1 = new Sequence("Seq1", "AAA");
813     SequenceI seq2 = new Sequence("Seq2", "BBB");
814     SequenceI seq3 = new Sequence("Seq3", "CCC");
815     Annotation[] anns = new Annotation[] { new Annotation(2f) };
816     AlignmentAnnotation ann1 = new AlignmentAnnotation("Structure", "ann1",
817             anns);
818     ann1.setSequenceRef(seq1);
819     AlignmentAnnotation ann2 = new AlignmentAnnotation("Structure", "ann2",
820             anns);
821     ann2.setSequenceRef(seq2);
822     AlignmentAnnotation ann3 = new AlignmentAnnotation("Structure", "ann3",
823             anns);
824     AlignmentAnnotation ann4 = new AlignmentAnnotation("Temp", "ann4", anns);
825     ann4.setSequenceRef(seq1);
826     AlignmentAnnotation ann5 = new AlignmentAnnotation("Temp", "ann5", anns);
827     ann5.setSequenceRef(seq2);
828     AlignmentAnnotation ann6 = new AlignmentAnnotation("Temp", "ann6", anns);
829     AlignmentI al = new Alignment(new SequenceI[] { seq1, seq2, seq3 });
830     al.addAnnotation(ann1); // Structure for Seq1
831     al.addAnnotation(ann2); // Structure for Seq2
832     al.addAnnotation(ann3); // Structure for no sequence
833     al.addAnnotation(ann4); // Temp for seq1
834     al.addAnnotation(ann5); // Temp for seq2
835     al.addAnnotation(ann6); // Temp for no sequence
836     List<String> types = new ArrayList<String>();
837     List<SequenceI> scope = new ArrayList<SequenceI>();
838
839     /*
840      * Set all sequence related Structure to hidden (ann1, ann2)
841      */
842     types.add("Structure");
843     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, false,
844             false);
845     assertFalse(ann1.visible);
846     assertFalse(ann2.visible);
847     assertTrue(ann3.visible); // not sequence-related, not affected
848     assertTrue(ann4.visible); // not Structure, not affected
849     assertTrue(ann5.visible); // "
850     assertTrue(ann6.visible); // not sequence-related, not affected
851
852     /*
853      * Set Temp in {seq1, seq3} to hidden
854      */
855     types.clear();
856     types.add("Temp");
857     scope.add(seq1);
858     scope.add(seq3);
859     AlignmentUtils.showOrHideSequenceAnnotations(al, types, scope, false,
860             false);
861     assertFalse(ann1.visible); // unchanged
862     assertFalse(ann2.visible); // unchanged
863     assertTrue(ann3.visible); // not sequence-related, not affected
864     assertFalse(ann4.visible); // Temp for seq1 hidden
865     assertTrue(ann5.visible); // not in scope, not affected
866     assertTrue(ann6.visible); // not sequence-related, not affected
867
868     /*
869      * Set Temp in all sequences to hidden
870      */
871     types.clear();
872     types.add("Temp");
873     scope.add(seq1);
874     scope.add(seq3);
875     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, false,
876             false);
877     assertFalse(ann1.visible); // unchanged
878     assertFalse(ann2.visible); // unchanged
879     assertTrue(ann3.visible); // not sequence-related, not affected
880     assertFalse(ann4.visible); // Temp for seq1 hidden
881     assertFalse(ann5.visible); // Temp for seq2 hidden
882     assertTrue(ann6.visible); // not sequence-related, not affected
883
884     /*
885      * Set all types in {seq1, seq3} to visible
886      */
887     types.clear();
888     scope.clear();
889     scope.add(seq1);
890     scope.add(seq3);
891     AlignmentUtils.showOrHideSequenceAnnotations(al, types, scope, true,
892             true);
893     assertTrue(ann1.visible); // Structure for seq1 set visible
894     assertFalse(ann2.visible); // not in scope, unchanged
895     assertTrue(ann3.visible); // not sequence-related, not affected
896     assertTrue(ann4.visible); // Temp for seq1 set visible
897     assertFalse(ann5.visible); // not in scope, unchanged
898     assertTrue(ann6.visible); // not sequence-related, not affected
899
900     /*
901      * Set all types in all scope to hidden
902      */
903     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, true,
904             false);
905     assertFalse(ann1.visible);
906     assertFalse(ann2.visible);
907     assertTrue(ann3.visible); // not sequence-related, not affected
908     assertFalse(ann4.visible);
909     assertFalse(ann5.visible);
910     assertTrue(ann6.visible); // not sequence-related, not affected
911   }
912
913   /**
914    * Tests for the method that checks if one sequence cross-references another
915    */
916   @Test(groups = { "Functional" })
917   public void testHasCrossRef()
918   {
919     assertFalse(AlignmentUtils.hasCrossRef(null, null));
920     SequenceI seq1 = new Sequence("EMBL|A12345", "ABCDEF");
921     assertFalse(AlignmentUtils.hasCrossRef(seq1, null));
922     assertFalse(AlignmentUtils.hasCrossRef(null, seq1));
923     SequenceI seq2 = new Sequence("UNIPROT|V20192", "ABCDEF");
924     assertFalse(AlignmentUtils.hasCrossRef(seq1, seq2));
925
926     // different ref
927     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "v20193"));
928     assertFalse(AlignmentUtils.hasCrossRef(seq1, seq2));
929
930     // case-insensitive; version number is ignored
931     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "v20192"));
932     assertTrue(AlignmentUtils.hasCrossRef(seq1, seq2));
933
934     // right case!
935     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
936     assertTrue(AlignmentUtils.hasCrossRef(seq1, seq2));
937     // test is one-way only
938     assertFalse(AlignmentUtils.hasCrossRef(seq2, seq1));
939   }
940
941   /**
942    * Tests for the method that checks if either sequence cross-references the
943    * other
944    */
945   @Test(groups = { "Functional" })
946   public void testHaveCrossRef()
947   {
948     assertFalse(AlignmentUtils.hasCrossRef(null, null));
949     SequenceI seq1 = new Sequence("EMBL|A12345", "ABCDEF");
950     assertFalse(AlignmentUtils.haveCrossRef(seq1, null));
951     assertFalse(AlignmentUtils.haveCrossRef(null, seq1));
952     SequenceI seq2 = new Sequence("UNIPROT|V20192", "ABCDEF");
953     assertFalse(AlignmentUtils.haveCrossRef(seq1, seq2));
954
955     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
956     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
957     // next is true for haveCrossRef, false for hasCrossRef
958     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
959
960     // now the other way round
961     seq1.setDBRefs(null);
962     seq2.addDBRef(new DBRefEntry("EMBL", "1", "A12345"));
963     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
964     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
965
966     // now both ways
967     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
968     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
969     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
970   }
971
972   /**
973    * Test the method that extracts the cds-only part of a dna alignment.
974    */
975   @Test(groups = { "Functional" })
976   public void testMakeCdsAlignment()
977   {
978     /*
979      * scenario:
980      *     dna1 --> [4, 6] [10,12]        --> pep1 
981      *     dna2 --> [1, 3] [7, 9] [13,15] --> pep2
982      */
983     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
984     SequenceI dna2 = new Sequence("dna2", "GGGcccTTTaaaCCC");
985     SequenceI pep1 = new Sequence("pep1", "GF");
986     SequenceI pep2 = new Sequence("pep2", "GFP");
987     pep1.addDBRef(new DBRefEntry("UNIPROT", "0", "pep1"));
988     pep2.addDBRef(new DBRefEntry("UNIPROT", "0", "pep2"));
989     dna1.createDatasetSequence();
990     dna2.createDatasetSequence();
991     pep1.createDatasetSequence();
992     pep2.createDatasetSequence();
993     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2 });
994     dna.setDataset(null);
995
996     /*
997      * put a variant feature on dna2 base 8
998      * - should transfer to cds2 base 5
999      */
1000     dna2.addSequenceFeature(new SequenceFeature("variant", "hgmd", 8, 8,
1001             0f, null));
1002
1003     /*
1004      * need a sourceDbRef if we are to construct dbrefs to the CDS
1005      * sequence from the dna contig sequences
1006      */
1007     DBRefEntry dbref = new DBRefEntry("ENSEMBL", "0", "dna1");
1008     dna1.getDatasetSequence().addDBRef(dbref);
1009     org.testng.Assert.assertEquals(dbref, dna1.getPrimaryDBRefs().get(0));
1010     dbref = new DBRefEntry("ENSEMBL", "0", "dna2");
1011     dna2.getDatasetSequence().addDBRef(dbref);
1012     org.testng.Assert.assertEquals(dbref, dna2.getPrimaryDBRefs().get(0));
1013
1014     /*
1015      * CDS sequences are 'discovered' from dna-to-protein mappings on the alignment
1016      * dataset (e.g. added from dbrefs by CrossRef.findXrefSequences)
1017      */
1018     MapList mapfordna1 = new MapList(new int[] { 4, 6, 10, 12 }, new int[] {
1019         1, 2 }, 3, 1);
1020     AlignedCodonFrame acf = new AlignedCodonFrame();
1021     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(),
1022             mapfordna1);
1023     dna.addCodonFrame(acf);
1024     MapList mapfordna2 = new MapList(new int[] { 1, 3, 7, 9, 13, 15 },
1025             new int[] { 1, 3 }, 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.getTo());
1314     assertEquals("G(1) in CDS should map to G(4) in DNA", 4, mapping
1315             .getMap().getToPosition(1));
1316
1317     /*
1318      * dna1 to pep2
1319      */
1320     mappings = MappingUtils.findMappingsForSequence(pep2, dnaMappings);
1321     assertEquals(1, mappings.size());
1322     assertEquals(1, mappings.get(0).getMappings().size());
1323     assertSame(pep2.getDatasetSequence(), mappings.get(0).getMappings()
1324             .get(0).getMapping().getTo());
1325
1326     /*
1327      * dna1 to cds2
1328      */
1329     List<AlignedCodonFrame> dnaToCds2Mappings = MappingUtils
1330             .findMappingsForSequence(cds.get(1), dnaMappings);
1331     mapping = dnaToCds2Mappings.get(0).getMappings().get(0).getMapping();
1332     assertSame(cds.get(1).getDatasetSequence(), mapping.getTo());
1333     assertEquals("c(4) in CDS should map to c(7) in DNA", 7, mapping
1334             .getMap().getToPosition(4));
1335
1336     /*
1337      * dna1 to pep3
1338      */
1339     mappings = MappingUtils.findMappingsForSequence(pep3, dnaMappings);
1340     assertEquals(1, mappings.size());
1341     assertEquals(1, mappings.get(0).getMappings().size());
1342     assertSame(pep3.getDatasetSequence(), mappings.get(0).getMappings()
1343             .get(0).getMapping().getTo());
1344
1345     /*
1346      * dna1 to cds3
1347      */
1348     List<AlignedCodonFrame> dnaToCds3Mappings = MappingUtils
1349             .findMappingsForSequence(cds.get(2), dnaMappings);
1350     mapping = dnaToCds3Mappings.get(0).getMappings().get(0).getMapping();
1351     assertSame(cds.get(2).getDatasetSequence(), mapping.getTo());
1352     assertEquals("T(4) in CDS should map to T(10) in DNA", 10, mapping
1353             .getMap().getToPosition(4));
1354   }
1355
1356   @Test(groups = { "Functional" })
1357   public void testIsMappable()
1358   {
1359     SequenceI dna1 = new Sequence("dna1", "cgCAGtgGT");
1360     SequenceI aa1 = new Sequence("aa1", "RSG");
1361     AlignmentI al1 = new Alignment(new SequenceI[] { dna1 });
1362     AlignmentI al2 = new Alignment(new SequenceI[] { aa1 });
1363
1364     assertFalse(AlignmentUtils.isMappable(null, null));
1365     assertFalse(AlignmentUtils.isMappable(al1, null));
1366     assertFalse(AlignmentUtils.isMappable(null, al1));
1367     assertFalse(AlignmentUtils.isMappable(al1, al1));
1368     assertFalse(AlignmentUtils.isMappable(al2, al2));
1369
1370     assertTrue(AlignmentUtils.isMappable(al1, al2));
1371     assertTrue(AlignmentUtils.isMappable(al2, al1));
1372   }
1373
1374   /**
1375    * Test creating a mapping when the sequences involved do not start at residue
1376    * 1
1377    * 
1378    * @throws IOException
1379    */
1380   @Test(groups = { "Functional" })
1381   public void testMapCdnaToProtein_forSubsequence() throws IOException
1382   {
1383     SequenceI prot = new Sequence("UNIPROT|V12345", "E-I--Q", 10, 12);
1384     prot.createDatasetSequence();
1385
1386     SequenceI dna = new Sequence("EMBL|A33333", "GAA--AT-C-CAG", 40, 48);
1387     dna.createDatasetSequence();
1388
1389     MapList map = AlignmentUtils.mapCdnaToProtein(prot, dna);
1390     assertEquals(10, map.getToLowest());
1391     assertEquals(12, map.getToHighest());
1392     assertEquals(40, map.getFromLowest());
1393     assertEquals(48, map.getFromHighest());
1394   }
1395
1396   /**
1397    * Test for the alignSequenceAs method where we have protein mapped to protein
1398    */
1399   @Test(groups = { "Functional" })
1400   public void testAlignSequenceAs_mappedProteinProtein()
1401   {
1402
1403     SequenceI alignMe = new Sequence("Match", "MGAASEV");
1404     alignMe.createDatasetSequence();
1405     SequenceI alignFrom = new Sequence("Query", "LQTGYMGAASEVMFSPTRR");
1406     alignFrom.createDatasetSequence();
1407
1408     AlignedCodonFrame acf = new AlignedCodonFrame();
1409     // this is like a domain or motif match of part of a peptide sequence
1410     MapList map = new MapList(new int[] { 6, 12 }, new int[] { 1, 7 }, 1, 1);
1411     acf.addMap(alignFrom.getDatasetSequence(),
1412             alignMe.getDatasetSequence(), map);
1413
1414     AlignmentUtils.alignSequenceAs(alignMe, alignFrom, acf, "-", '-', true,
1415             true);
1416     assertEquals("-----MGAASEV-------", alignMe.getSequenceAsString());
1417   }
1418
1419   /**
1420    * Test for the alignSequenceAs method where there are trailing unmapped
1421    * residues in the model sequence
1422    */
1423   @Test(groups = { "Functional" })
1424   public void testAlignSequenceAs_withTrailingPeptide()
1425   {
1426     // map first 3 codons to KPF; G is a trailing unmapped residue
1427     MapList map = new MapList(new int[] { 1, 9 }, new int[] { 1, 3 }, 3, 1);
1428
1429     checkAlignSequenceAs("AAACCCTTT", "K-PFG", true, true, map,
1430             "AAA---CCCTTT---");
1431   }
1432
1433   /**
1434    * Tests for transferring features between mapped sequences
1435    */
1436   @Test(groups = { "Functional" })
1437   public void testTransferFeatures()
1438   {
1439     SequenceI dna = new Sequence("dna/20-34", "acgTAGcaaGCCcgt");
1440     SequenceI cds = new Sequence("cds/10-15", "TAGGCC");
1441
1442     // no overlap
1443     dna.addSequenceFeature(new SequenceFeature("type1", "desc1", 1, 2, 1f,
1444             null));
1445     // partial overlap - to [1, 1]
1446     dna.addSequenceFeature(new SequenceFeature("type2", "desc2", 3, 4, 2f,
1447             null));
1448     // exact overlap - to [1, 3]
1449     dna.addSequenceFeature(new SequenceFeature("type3", "desc3", 4, 6, 3f,
1450             null));
1451     // spanning overlap - to [2, 5]
1452     dna.addSequenceFeature(new SequenceFeature("type4", "desc4", 5, 11, 4f,
1453             null));
1454     // exactly overlaps whole mapped range [1, 6]
1455     dna.addSequenceFeature(new SequenceFeature("type5", "desc5", 4, 12, 5f,
1456             null));
1457     // no overlap (internal)
1458     dna.addSequenceFeature(new SequenceFeature("type6", "desc6", 7, 9, 6f,
1459             null));
1460     // no overlap (3' end)
1461     dna.addSequenceFeature(new SequenceFeature("type7", "desc7", 13, 15,
1462             7f, null));
1463     // overlap (3' end) - to [6, 6]
1464     dna.addSequenceFeature(new SequenceFeature("type8", "desc8", 12, 12,
1465             8f, null));
1466     // extended overlap - to [6, +]
1467     dna.addSequenceFeature(new SequenceFeature("type9", "desc9", 12, 13,
1468             9f, null));
1469
1470     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1471             new int[] { 1, 6 }, 1, 1);
1472
1473     /*
1474      * transferFeatures() will build 'partial overlap' for regions
1475      * that partially overlap 5' or 3' (start or end) of target sequence
1476      */
1477     AlignmentUtils.transferFeatures(dna, cds, map, null);
1478     SequenceFeature[] sfs = cds.getSequenceFeatures();
1479     assertEquals(6, sfs.length);
1480
1481     SequenceFeature sf = sfs[0];
1482     assertEquals("type2", sf.getType());
1483     assertEquals("desc2", sf.getDescription());
1484     assertEquals(2f, sf.getScore());
1485     assertEquals(1, sf.getBegin());
1486     assertEquals(1, sf.getEnd());
1487
1488     sf = sfs[1];
1489     assertEquals("type3", sf.getType());
1490     assertEquals("desc3", sf.getDescription());
1491     assertEquals(3f, sf.getScore());
1492     assertEquals(1, sf.getBegin());
1493     assertEquals(3, sf.getEnd());
1494
1495     sf = sfs[2];
1496     assertEquals("type4", sf.getType());
1497     assertEquals(2, sf.getBegin());
1498     assertEquals(5, sf.getEnd());
1499
1500     sf = sfs[3];
1501     assertEquals("type5", sf.getType());
1502     assertEquals(1, sf.getBegin());
1503     assertEquals(6, sf.getEnd());
1504
1505     sf = sfs[4];
1506     assertEquals("type8", sf.getType());
1507     assertEquals(6, sf.getBegin());
1508     assertEquals(6, sf.getEnd());
1509
1510     sf = sfs[5];
1511     assertEquals("type9", sf.getType());
1512     assertEquals(6, sf.getBegin());
1513     assertEquals(6, sf.getEnd());
1514   }
1515
1516   /**
1517    * Tests for transferring features between mapped sequences
1518    */
1519   @Test(groups = { "Functional" })
1520   public void testTransferFeatures_withOmit()
1521   {
1522     SequenceI dna = new Sequence("dna/20-34", "acgTAGcaaGCCcgt");
1523     SequenceI cds = new Sequence("cds/10-15", "TAGGCC");
1524
1525     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1526             new int[] { 1, 6 }, 1, 1);
1527
1528     // [5, 11] maps to [2, 5]
1529     dna.addSequenceFeature(new SequenceFeature("type4", "desc4", 5, 11, 4f,
1530             null));
1531     // [4, 12] maps to [1, 6]
1532     dna.addSequenceFeature(new SequenceFeature("type5", "desc5", 4, 12, 5f,
1533             null));
1534     // [12, 12] maps to [6, 6]
1535     dna.addSequenceFeature(new SequenceFeature("type8", "desc8", 12, 12,
1536             8f, null));
1537
1538     // desc4 and desc8 are the 'omit these' varargs
1539     AlignmentUtils.transferFeatures(dna, cds, map, null, "type4", "type8");
1540     SequenceFeature[] sfs = cds.getSequenceFeatures();
1541     assertEquals(1, sfs.length);
1542
1543     SequenceFeature sf = sfs[0];
1544     assertEquals("type5", sf.getType());
1545     assertEquals(1, sf.getBegin());
1546     assertEquals(6, sf.getEnd());
1547   }
1548
1549   /**
1550    * Tests for transferring features between mapped sequences
1551    */
1552   @Test(groups = { "Functional" })
1553   public void testTransferFeatures_withSelect()
1554   {
1555     SequenceI dna = new Sequence("dna/20-34", "acgTAGcaaGCCcgt");
1556     SequenceI cds = new Sequence("cds/10-15", "TAGGCC");
1557
1558     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1559             new int[] { 1, 6 }, 1, 1);
1560
1561     // [5, 11] maps to [2, 5]
1562     dna.addSequenceFeature(new SequenceFeature("type4", "desc4", 5, 11, 4f,
1563             null));
1564     // [4, 12] maps to [1, 6]
1565     dna.addSequenceFeature(new SequenceFeature("type5", "desc5", 4, 12, 5f,
1566             null));
1567     // [12, 12] maps to [6, 6]
1568     dna.addSequenceFeature(new SequenceFeature("type8", "desc8", 12, 12,
1569             8f, null));
1570
1571     // "type5" is the 'select this type' argument
1572     AlignmentUtils.transferFeatures(dna, cds, map, "type5");
1573     SequenceFeature[] sfs = cds.getSequenceFeatures();
1574     assertEquals(1, sfs.length);
1575
1576     SequenceFeature sf = sfs[0];
1577     assertEquals("type5", sf.getType());
1578     assertEquals(1, sf.getBegin());
1579     assertEquals(6, sf.getEnd());
1580   }
1581
1582   /**
1583    * Test the method that extracts the cds-only part of a dna alignment, for the
1584    * case where the cds should be aligned to match its nucleotide sequence.
1585    */
1586   @Test(groups = { "Functional" })
1587   public void testMakeCdsAlignment_alternativeTranscripts()
1588   {
1589     SequenceI dna1 = new Sequence("dna1", "aaaGGGCC-----CTTTaaaGGG");
1590     // alternative transcript of same dna skips CCC codon
1591     SequenceI dna2 = new Sequence("dna2", "aaaGGGCC-----cttTaaaGGG");
1592     // dna3 has no mapping (protein product) so should be ignored here
1593     SequenceI dna3 = new Sequence("dna3", "aaaGGGCCCCCGGGcttTaaaGGG");
1594     SequenceI pep1 = new Sequence("pep1", "GPFG");
1595     SequenceI pep2 = new Sequence("pep2", "GPG");
1596     dna1.createDatasetSequence();
1597     dna2.createDatasetSequence();
1598     dna3.createDatasetSequence();
1599     pep1.createDatasetSequence();
1600     pep2.createDatasetSequence();
1601
1602     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2, dna3 });
1603     dna.setDataset(null);
1604
1605     MapList map = new MapList(new int[] { 4, 12, 16, 18 },
1606             new int[] { 1, 4 }, 3, 1);
1607     AlignedCodonFrame acf = new AlignedCodonFrame();
1608     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
1609     dna.addCodonFrame(acf);
1610     map = new MapList(new int[] { 4, 8, 12, 12, 16, 18 },
1611             new int[] { 1, 3 }, 3, 1);
1612     acf = new AlignedCodonFrame();
1613     acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
1614     dna.addCodonFrame(acf);
1615
1616     AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
1617         dna1, dna2, dna3 }, dna.getDataset(), null);
1618     List<SequenceI> cdsSeqs = cds.getSequences();
1619     assertEquals(2, cdsSeqs.size());
1620     assertEquals("GGGCCCTTTGGG", cdsSeqs.get(0).getSequenceAsString());
1621     assertEquals("GGGCCTGGG", cdsSeqs.get(1).getSequenceAsString());
1622
1623     /*
1624      * verify shared, extended alignment dataset
1625      */
1626     assertSame(dna.getDataset(), cds.getDataset());
1627     assertTrue(dna.getDataset().getSequences()
1628             .contains(cdsSeqs.get(0).getDatasetSequence()));
1629     assertTrue(dna.getDataset().getSequences()
1630             .contains(cdsSeqs.get(1).getDatasetSequence()));
1631
1632     /*
1633      * Verify 6 mappings: dna1 to cds1, cds1 to pep1, dna1 to pep1
1634      * and the same for dna2/cds2/pep2
1635      */
1636     List<AlignedCodonFrame> mappings = cds.getCodonFrames();
1637     assertEquals(6, mappings.size());
1638
1639     /*
1640      * 2 mappings involve pep1
1641      */
1642     List<AlignedCodonFrame> pep1Mappings = MappingUtils
1643             .findMappingsForSequence(pep1, mappings);
1644     assertEquals(2, pep1Mappings.size());
1645
1646     /*
1647      * Get mapping of pep1 to cds1 and verify it
1648      * maps GPFG to 1-3,4-6,7-9,10-12
1649      */
1650     List<AlignedCodonFrame> pep1CdsMappings = MappingUtils
1651             .findMappingsForSequence(cds.getSequenceAt(0), pep1Mappings);
1652     assertEquals(1, pep1CdsMappings.size());
1653     SearchResults sr = MappingUtils.buildSearchResults(pep1, 1,
1654             pep1CdsMappings);
1655     assertEquals(1, sr.getResults().size());
1656     Match m = sr.getResults().get(0);
1657     assertEquals(cds.getSequenceAt(0).getDatasetSequence(), m.getSequence());
1658     assertEquals(1, m.getStart());
1659     assertEquals(3, m.getEnd());
1660     sr = MappingUtils.buildSearchResults(pep1, 2, pep1CdsMappings);
1661     m = sr.getResults().get(0);
1662     assertEquals(4, m.getStart());
1663     assertEquals(6, m.getEnd());
1664     sr = MappingUtils.buildSearchResults(pep1, 3, pep1CdsMappings);
1665     m = sr.getResults().get(0);
1666     assertEquals(7, m.getStart());
1667     assertEquals(9, m.getEnd());
1668     sr = MappingUtils.buildSearchResults(pep1, 4, pep1CdsMappings);
1669     m = sr.getResults().get(0);
1670     assertEquals(10, m.getStart());
1671     assertEquals(12, m.getEnd());
1672
1673     /*
1674      * Get mapping of pep2 to cds2 and verify it
1675      * maps GPG in pep2 to 1-3,4-6,7-9 in second CDS sequence
1676      */
1677     List<AlignedCodonFrame> pep2Mappings = MappingUtils
1678             .findMappingsForSequence(pep2, mappings);
1679     assertEquals(2, pep2Mappings.size());
1680     List<AlignedCodonFrame> pep2CdsMappings = MappingUtils
1681             .findMappingsForSequence(cds.getSequenceAt(1), pep2Mappings);
1682     assertEquals(1, pep2CdsMappings.size());
1683     sr = MappingUtils.buildSearchResults(pep2, 1, pep2CdsMappings);
1684     assertEquals(1, sr.getResults().size());
1685     m = sr.getResults().get(0);
1686     assertEquals(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
1687     assertEquals(1, m.getStart());
1688     assertEquals(3, m.getEnd());
1689     sr = MappingUtils.buildSearchResults(pep2, 2, pep2CdsMappings);
1690     m = sr.getResults().get(0);
1691     assertEquals(4, m.getStart());
1692     assertEquals(6, m.getEnd());
1693     sr = MappingUtils.buildSearchResults(pep2, 3, pep2CdsMappings);
1694     m = sr.getResults().get(0);
1695     assertEquals(7, m.getStart());
1696     assertEquals(9, m.getEnd());
1697   }
1698
1699   /**
1700    * Test the method that realigns protein to match mapped codon alignment.
1701    */
1702   @Test(groups = { "Functional" })
1703   public void testAlignProteinAsDna_incompleteStartCodon()
1704   {
1705     // seq1: incomplete start codon (not mapped), then [3, 11]
1706     SequenceI dna1 = new Sequence("Seq1", "ccAAA-TTT-GGG-");
1707     // seq2 codons are [4, 5], [8, 11]
1708     SequenceI dna2 = new Sequence("Seq2", "ccaAA-ttT-GGG-");
1709     // seq3 incomplete start codon at 'tt'
1710     SequenceI dna3 = new Sequence("Seq3", "ccaaa-ttt-GGG-");
1711     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2, dna3 });
1712     dna.setDataset(null);
1713
1714     // prot1 has 'X' for incomplete start codon (not mapped)
1715     SequenceI prot1 = new Sequence("Seq1", "XKFG"); // X for incomplete start
1716     SequenceI prot2 = new Sequence("Seq2", "NG");
1717     SequenceI prot3 = new Sequence("Seq3", "XG"); // X for incomplete start
1718     AlignmentI protein = new Alignment(new SequenceI[] { prot1, prot2,
1719         prot3 });
1720     protein.setDataset(null);
1721
1722     // map dna1 [3, 11] to prot1 [2, 4] KFG
1723     MapList map = new MapList(new int[] { 3, 11 }, new int[] { 2, 4 }, 3, 1);
1724     AlignedCodonFrame acf = new AlignedCodonFrame();
1725     acf.addMap(dna1.getDatasetSequence(), prot1.getDatasetSequence(), map);
1726
1727     // map dna2 [4, 5] [8, 11] to prot2 [1, 2] NG
1728     map = new MapList(new int[] { 4, 5, 8, 11 }, new int[] { 1, 2 }, 3, 1);
1729     acf.addMap(dna2.getDatasetSequence(), prot2.getDatasetSequence(), map);
1730
1731     // map dna3 [9, 11] to prot3 [2, 2] G
1732     map = new MapList(new int[] { 9, 11 }, new int[] { 2, 2 }, 3, 1);
1733     acf.addMap(dna3.getDatasetSequence(), prot3.getDatasetSequence(), map);
1734
1735     ArrayList<AlignedCodonFrame> acfs = new ArrayList<AlignedCodonFrame>();
1736     acfs.add(acf);
1737     protein.setCodonFrames(acfs);
1738
1739     /*
1740      * verify X is included in the aligned proteins, and placed just
1741      * before the first mapped residue 
1742      * CCT is between CCC and TTT
1743      */
1744     AlignmentUtils.alignProteinAsDna(protein, dna);
1745     assertEquals("XK-FG", prot1.getSequenceAsString());
1746     assertEquals("--N-G", prot2.getSequenceAsString());
1747     assertEquals("---XG", prot3.getSequenceAsString());
1748   }
1749
1750   /**
1751    * Tests for the method that maps the subset of a dna sequence that has CDS
1752    * (or subtype) feature - case where the start codon is incomplete.
1753    */
1754   @Test(groups = "Functional")
1755   public void testFindCdsPositions_fivePrimeIncomplete()
1756   {
1757     SequenceI dnaSeq = new Sequence("dna", "aaagGGCCCaaaTTTttt");
1758     dnaSeq.createDatasetSequence();
1759     SequenceI ds = dnaSeq.getDatasetSequence();
1760
1761     // CDS for dna 5-6 (incomplete codon), 7-9
1762     SequenceFeature sf = new SequenceFeature("CDS", "", 5, 9, 0f, null);
1763     sf.setPhase("2"); // skip 2 bases to start of next codon
1764     ds.addSequenceFeature(sf);
1765     // CDS for dna 13-15
1766     sf = new SequenceFeature("CDS_predicted", "", 13, 15, 0f, null);
1767     ds.addSequenceFeature(sf);
1768
1769     List<int[]> ranges = AlignmentUtils.findCdsPositions(dnaSeq);
1770
1771     /*
1772      * check the mapping starts with the first complete codon
1773      */
1774     assertEquals(6, MappingUtils.getLength(ranges));
1775     assertEquals(2, ranges.size());
1776     assertEquals(7, ranges.get(0)[0]);
1777     assertEquals(9, ranges.get(0)[1]);
1778     assertEquals(13, ranges.get(1)[0]);
1779     assertEquals(15, ranges.get(1)[1]);
1780   }
1781
1782   /**
1783    * Tests for the method that maps the subset of a dna sequence that has CDS
1784    * (or subtype) feature.
1785    */
1786   @Test(groups = "Functional")
1787   public void testFindCdsPositions()
1788   {
1789     SequenceI dnaSeq = new Sequence("dna", "aaaGGGcccAAATTTttt");
1790     dnaSeq.createDatasetSequence();
1791     SequenceI ds = dnaSeq.getDatasetSequence();
1792
1793     // CDS for dna 10-12
1794     SequenceFeature sf = new SequenceFeature("CDS_predicted", "", 10, 12,
1795             0f, null);
1796     sf.setStrand("+");
1797     ds.addSequenceFeature(sf);
1798     // CDS for dna 4-6
1799     sf = new SequenceFeature("CDS", "", 4, 6, 0f, null);
1800     sf.setStrand("+");
1801     ds.addSequenceFeature(sf);
1802     // exon feature should be ignored here
1803     sf = new SequenceFeature("exon", "", 7, 9, 0f, null);
1804     ds.addSequenceFeature(sf);
1805
1806     List<int[]> ranges = AlignmentUtils.findCdsPositions(dnaSeq);
1807     /*
1808      * verify ranges { [4-6], [12-10] }
1809      * note CDS ranges are ordered ascending even if the CDS
1810      * features are not
1811      */
1812     assertEquals(6, MappingUtils.getLength(ranges));
1813     assertEquals(2, ranges.size());
1814     assertEquals(4, ranges.get(0)[0]);
1815     assertEquals(6, ranges.get(0)[1]);
1816     assertEquals(10, ranges.get(1)[0]);
1817     assertEquals(12, ranges.get(1)[1]);
1818   }
1819
1820   /**
1821    * Test the method that computes a map of codon variants for each protein
1822    * position from "sequence_variant" features on dna
1823    */
1824   @Test(groups = "Functional")
1825   public void testBuildDnaVariantsMap()
1826   {
1827     SequenceI dna = new Sequence("dna", "atgAAATTTGGGCCCtag");
1828     MapList map = new MapList(new int[] { 1, 18 }, new int[] { 1, 5 }, 3, 1);
1829
1830     /*
1831      * first with no variants on dna
1832      */
1833     LinkedHashMap<Integer, List<DnaVariant>[]> variantsMap = AlignmentUtils
1834             .buildDnaVariantsMap(dna, map);
1835     assertTrue(variantsMap.isEmpty());
1836
1837     /*
1838      * single allele codon 1, on base 1
1839      */
1840     SequenceFeature sf1 = new SequenceFeature("sequence_variant", "", 1, 1,
1841             0f, null);
1842     sf1.setValue("alleles", "T");
1843     sf1.setValue("ID", "sequence_variant:rs758803211");
1844     dna.addSequenceFeature(sf1);
1845
1846     /*
1847      * two alleles codon 2, on bases 2 and 3 (distinct variants)
1848      */
1849     SequenceFeature sf2 = new SequenceFeature("sequence_variant", "", 5, 5,
1850             0f, null);
1851     sf2.setValue("alleles", "T");
1852     sf2.setValue("ID", "sequence_variant:rs758803212");
1853     dna.addSequenceFeature(sf2);
1854     SequenceFeature sf3 = new SequenceFeature("sequence_variant", "", 6, 6,
1855             0f, null);
1856     sf3.setValue("alleles", "G");
1857     sf3.setValue("ID", "sequence_variant:rs758803213");
1858     dna.addSequenceFeature(sf3);
1859
1860     /*
1861      * two alleles codon 3, both on base 2 (one variant)
1862      */
1863     SequenceFeature sf4 = new SequenceFeature("sequence_variant", "", 8, 8,
1864             0f, null);
1865     sf4.setValue("alleles", "C, G");
1866     sf4.setValue("ID", "sequence_variant:rs758803214");
1867     dna.addSequenceFeature(sf4);
1868
1869     // no alleles on codon 4
1870
1871     /*
1872      * alleles on codon 5 on all 3 bases (distinct variants)
1873      */
1874     SequenceFeature sf5 = new SequenceFeature("sequence_variant", "", 13,
1875             13, 0f, null);
1876     sf5.setValue("alleles", "C, G"); // (C duplicates given base value)
1877     sf5.setValue("ID", "sequence_variant:rs758803215");
1878     dna.addSequenceFeature(sf5);
1879     SequenceFeature sf6 = new SequenceFeature("sequence_variant", "", 14,
1880             14, 0f, null);
1881     sf6.setValue("alleles", "g, a"); // should force to upper-case
1882     sf6.setValue("ID", "sequence_variant:rs758803216");
1883     dna.addSequenceFeature(sf6);
1884     SequenceFeature sf7 = new SequenceFeature("sequence_variant", "", 15,
1885             15, 0f, null);
1886     sf7.setValue("alleles", "A, T");
1887     sf7.setValue("ID", "sequence_variant:rs758803217");
1888     dna.addSequenceFeature(sf7);
1889
1890     /*
1891      * build map - expect variants on positions 1, 2, 3, 5
1892      */
1893     variantsMap = AlignmentUtils.buildDnaVariantsMap(dna, map);
1894     assertEquals(4, variantsMap.size());
1895
1896     /*
1897      * protein residue 1: variant on codon (ATG) base 1, not on 2 or 3
1898      */
1899     List<DnaVariant>[] pep1Variants = variantsMap.get(1);
1900     assertEquals(3, pep1Variants.length);
1901     assertEquals(1, pep1Variants[0].size());
1902     assertEquals("A", pep1Variants[0].get(0).base); // codon[1] base
1903     assertSame(sf1, pep1Variants[0].get(0).variant); // codon[1] variant
1904     assertEquals(1, pep1Variants[1].size());
1905     assertEquals("T", pep1Variants[1].get(0).base); // codon[2] base
1906     assertNull(pep1Variants[1].get(0).variant); // no variant here
1907     assertEquals(1, pep1Variants[2].size());
1908     assertEquals("G", pep1Variants[2].get(0).base); // codon[3] base
1909     assertNull(pep1Variants[2].get(0).variant); // no variant here
1910
1911     /*
1912      * protein residue 2: variants on codon (AAA) bases 2 and 3
1913      */
1914     List<DnaVariant>[] pep2Variants = variantsMap.get(2);
1915     assertEquals(3, pep2Variants.length);
1916     assertEquals(1, pep2Variants[0].size());
1917     // codon[1] base recorded while processing variant on codon[2]
1918     assertEquals("A", pep2Variants[0].get(0).base);
1919     assertNull(pep2Variants[0].get(0).variant); // no variant here
1920     // codon[2] base and variant:
1921     assertEquals(1, pep2Variants[1].size());
1922     assertEquals("A", pep2Variants[1].get(0).base);
1923     assertSame(sf2, pep2Variants[1].get(0).variant);
1924     // codon[3] base was recorded when processing codon[2] variant
1925     // and then the variant for codon[3] added to it
1926     assertEquals(1, pep2Variants[2].size());
1927     assertEquals("A", pep2Variants[2].get(0).base);
1928     assertSame(sf3, pep2Variants[2].get(0).variant);
1929
1930     /*
1931      * protein residue 3: variants on codon (TTT) base 2 only
1932      */
1933     List<DnaVariant>[] pep3Variants = variantsMap.get(3);
1934     assertEquals(3, pep3Variants.length);
1935     assertEquals(1, pep3Variants[0].size());
1936     assertEquals("T", pep3Variants[0].get(0).base); // codon[1] base
1937     assertNull(pep3Variants[0].get(0).variant); // no variant here
1938     assertEquals(1, pep3Variants[1].size());
1939     assertEquals("T", pep3Variants[1].get(0).base); // codon[2] base
1940     assertSame(sf4, pep3Variants[1].get(0).variant); // codon[2] variant
1941     assertEquals(1, pep3Variants[2].size());
1942     assertEquals("T", pep3Variants[2].get(0).base); // codon[3] base
1943     assertNull(pep3Variants[2].get(0).variant); // no variant here
1944
1945     /*
1946      * three variants on protein position 5
1947      */
1948     List<DnaVariant>[] pep5Variants = variantsMap.get(5);
1949     assertEquals(3, pep5Variants.length);
1950     assertEquals(1, pep5Variants[0].size());
1951     assertEquals("C", pep5Variants[0].get(0).base); // codon[1] base
1952     assertSame(sf5, pep5Variants[0].get(0).variant); // codon[1] variant
1953     assertEquals(1, pep5Variants[1].size());
1954     assertEquals("C", pep5Variants[1].get(0).base); // codon[2] base
1955     assertSame(sf6, pep5Variants[1].get(0).variant); // codon[2] variant
1956     assertEquals(1, pep5Variants[2].size());
1957     assertEquals("C", pep5Variants[2].get(0).base); // codon[3] base
1958     assertSame(sf7, pep5Variants[2].get(0).variant); // codon[3] variant
1959   }
1960
1961   /**
1962    * Tests for the method that computes all peptide variants given codon
1963    * variants
1964    */
1965   @Test(groups = "Functional")
1966   public void testComputePeptideVariants()
1967   {
1968     /*
1969      * scenario: AAATTTCCC codes for KFP
1970      * variants:
1971      *           GAA -> E             source: Ensembl
1972      *           CAA -> Q             source: dbSNP
1973      *           AAG synonymous       source: COSMIC
1974      *           AAT -> N             source: Ensembl
1975      *           ...TTC synonymous    source: dbSNP
1976      *           ......CAC,CGC -> H,R source: COSMIC
1977      *                 (one variant with two alleles)
1978      */
1979     SequenceI peptide = new Sequence("pep/10-12", "KFP");
1980
1981     /*
1982      * two distinct variants for codon 1 position 1
1983      * second one has clinical significance
1984      */
1985     String ensembl = "Ensembl";
1986     String dbSnp = "dbSNP";
1987     String cosmic = "COSMIC";
1988     SequenceFeature sf1 = new SequenceFeature("sequence_variant", "", 1, 1,
1989             0f, ensembl);
1990     sf1.setValue("alleles", "A,G"); // GAA -> E
1991     sf1.setValue("ID", "var1.125A>G");
1992     SequenceFeature sf2 = new SequenceFeature("sequence_variant", "", 1, 1,
1993             0f, dbSnp);
1994     sf2.setValue("alleles", "A,C"); // CAA -> Q
1995     sf2.setValue("ID", "var2");
1996     sf2.setValue("clinical_significance", "Dodgy");
1997     SequenceFeature sf3 = new SequenceFeature("sequence_variant", "", 3, 3,
1998             0f, cosmic);
1999     sf3.setValue("alleles", "A,G"); // synonymous
2000     sf3.setValue("ID", "var3");
2001     sf3.setValue("clinical_significance", "None");
2002     SequenceFeature sf4 = new SequenceFeature("sequence_variant", "", 3, 3,
2003             0f, ensembl);
2004     sf4.setValue("alleles", "A,T"); // AAT -> N
2005     sf4.setValue("ID", "sequence_variant:var4"); // prefix gets stripped off
2006     sf4.setValue("clinical_significance", "Benign");
2007     SequenceFeature sf5 = new SequenceFeature("sequence_variant", "", 6, 6,
2008             0f, dbSnp);
2009     sf5.setValue("alleles", "T,C"); // synonymous
2010     sf5.setValue("ID", "var5");
2011     sf5.setValue("clinical_significance", "Bad");
2012     SequenceFeature sf6 = new SequenceFeature("sequence_variant", "", 8, 8,
2013             0f, cosmic);
2014     sf6.setValue("alleles", "C,A,G"); // CAC,CGC -> H,R
2015     sf6.setValue("ID", "var6");
2016     sf6.setValue("clinical_significance", "Good");
2017
2018     List<DnaVariant> codon1Variants = new ArrayList<DnaVariant>();
2019     List<DnaVariant> codon2Variants = new ArrayList<DnaVariant>();
2020     List<DnaVariant> codon3Variants = new ArrayList<DnaVariant>();
2021     List<DnaVariant> codonVariants[] = new ArrayList[3];
2022     codonVariants[0] = codon1Variants;
2023     codonVariants[1] = codon2Variants;
2024     codonVariants[2] = codon3Variants;
2025
2026     /*
2027      * compute variants for protein position 1
2028      */
2029     codon1Variants.add(new DnaVariant("A", sf1));
2030     codon1Variants.add(new DnaVariant("A", sf2));
2031     codon2Variants.add(new DnaVariant("A"));
2032     codon2Variants.add(new DnaVariant("A"));
2033     codon3Variants.add(new DnaVariant("A", sf3));
2034     codon3Variants.add(new DnaVariant("A", sf4));
2035     AlignmentUtils.computePeptideVariants(peptide, 1, codonVariants);
2036
2037     /*
2038      * compute variants for protein position 2
2039      */
2040     codon1Variants.clear();
2041     codon2Variants.clear();
2042     codon3Variants.clear();
2043     codon1Variants.add(new DnaVariant("T"));
2044     codon2Variants.add(new DnaVariant("T"));
2045     codon3Variants.add(new DnaVariant("T", sf5));
2046     AlignmentUtils.computePeptideVariants(peptide, 2, codonVariants);
2047
2048     /*
2049      * compute variants for protein position 3
2050      */
2051     codon1Variants.clear();
2052     codon2Variants.clear();
2053     codon3Variants.clear();
2054     codon1Variants.add(new DnaVariant("C"));
2055     codon2Variants.add(new DnaVariant("C", sf6));
2056     codon3Variants.add(new DnaVariant("C"));
2057     AlignmentUtils.computePeptideVariants(peptide, 3, codonVariants);
2058
2059     /*
2060      * verify added sequence features for
2061      * var1 K -> E Ensembl
2062      * var2 K -> Q dbSNP
2063      * var4 K -> N Ensembl
2064      * var6 P -> H COSMIC
2065      * var6 P -> R COSMIC
2066      */
2067     SequenceFeature[] sfs = peptide.getSequenceFeatures();
2068     assertEquals(5, sfs.length);
2069
2070     SequenceFeature sf = sfs[0];
2071     assertEquals(1, sf.getBegin());
2072     assertEquals(1, sf.getEnd());
2073     assertEquals("p.Lys1Glu", sf.getDescription());
2074     assertEquals("var1.125A>G", sf.getValue("ID"));
2075     assertNull(sf.getValue("clinical_significance"));
2076     assertEquals("ID=var1.125A>G", sf.getAttributes());
2077     assertEquals(1, sf.links.size());
2078     // link to variation is urlencoded
2079     assertEquals(
2080             "p.Lys1Glu var1.125A>G|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var1.125A%3EG",
2081             sf.links.get(0));
2082     assertEquals(ensembl, sf.getFeatureGroup());
2083
2084     sf = sfs[1];
2085     assertEquals(1, sf.getBegin());
2086     assertEquals(1, sf.getEnd());
2087     assertEquals("p.Lys1Gln", sf.getDescription());
2088     assertEquals("var2", sf.getValue("ID"));
2089     assertEquals("Dodgy", sf.getValue("clinical_significance"));
2090     assertEquals("ID=var2;clinical_significance=Dodgy", sf.getAttributes());
2091     assertEquals(1, sf.links.size());
2092     assertEquals(
2093             "p.Lys1Gln var2|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var2",
2094             sf.links.get(0));
2095     assertEquals(dbSnp, sf.getFeatureGroup());
2096
2097     sf = sfs[2];
2098     assertEquals(1, sf.getBegin());
2099     assertEquals(1, sf.getEnd());
2100     assertEquals("p.Lys1Asn", sf.getDescription());
2101     assertEquals("var4", sf.getValue("ID"));
2102     assertEquals("Benign", sf.getValue("clinical_significance"));
2103     assertEquals("ID=var4;clinical_significance=Benign", sf.getAttributes());
2104     assertEquals(1, sf.links.size());
2105     assertEquals(
2106             "p.Lys1Asn var4|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var4",
2107             sf.links.get(0));
2108     assertEquals(ensembl, sf.getFeatureGroup());
2109
2110     // var5 generates two distinct protein variant features
2111     sf = sfs[3];
2112     assertEquals(3, sf.getBegin());
2113     assertEquals(3, sf.getEnd());
2114     assertEquals("p.Pro3His", sf.getDescription());
2115     assertEquals("var6", sf.getValue("ID"));
2116     assertEquals("Good", sf.getValue("clinical_significance"));
2117     assertEquals("ID=var6;clinical_significance=Good", sf.getAttributes());
2118     assertEquals(1, sf.links.size());
2119     assertEquals(
2120             "p.Pro3His var6|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var6",
2121             sf.links.get(0));
2122     assertEquals(cosmic, sf.getFeatureGroup());
2123
2124     sf = sfs[4];
2125     assertEquals(3, sf.getBegin());
2126     assertEquals(3, sf.getEnd());
2127     assertEquals("p.Pro3Arg", sf.getDescription());
2128     assertEquals("var6", sf.getValue("ID"));
2129     assertEquals("Good", sf.getValue("clinical_significance"));
2130     assertEquals("ID=var6;clinical_significance=Good", sf.getAttributes());
2131     assertEquals(1, sf.links.size());
2132     assertEquals(
2133             "p.Pro3Arg var6|http://www.ensembl.org/Homo_sapiens/Variation/Summary?v=var6",
2134             sf.links.get(0));
2135     assertEquals(cosmic, sf.getFeatureGroup());
2136   }
2137
2138   /**
2139    * Tests for the method that maps the subset of a dna sequence that has CDS
2140    * (or subtype) feature, with CDS strand = '-' (reverse)
2141    */
2142   // test turned off as currently findCdsPositions is not strand-dependent
2143   // left in case it comes around again...
2144   @Test(groups = "Functional", enabled = false)
2145   public void testFindCdsPositions_reverseStrand()
2146   {
2147     SequenceI dnaSeq = new Sequence("dna", "aaaGGGcccAAATTTttt");
2148     dnaSeq.createDatasetSequence();
2149     SequenceI ds = dnaSeq.getDatasetSequence();
2150
2151     // CDS for dna 4-6
2152     SequenceFeature sf = new SequenceFeature("CDS", "", 4, 6, 0f, null);
2153     sf.setStrand("-");
2154     ds.addSequenceFeature(sf);
2155     // exon feature should be ignored here
2156     sf = new SequenceFeature("exon", "", 7, 9, 0f, null);
2157     ds.addSequenceFeature(sf);
2158     // CDS for dna 10-12
2159     sf = new SequenceFeature("CDS_predicted", "", 10, 12, 0f, null);
2160     sf.setStrand("-");
2161     ds.addSequenceFeature(sf);
2162
2163     List<int[]> ranges = AlignmentUtils.findCdsPositions(dnaSeq);
2164     /*
2165      * verify ranges { [12-10], [6-4] }
2166      */
2167     assertEquals(6, MappingUtils.getLength(ranges));
2168     assertEquals(2, ranges.size());
2169     assertEquals(12, ranges.get(0)[0]);
2170     assertEquals(10, ranges.get(0)[1]);
2171     assertEquals(6, ranges.get(1)[0]);
2172     assertEquals(4, ranges.get(1)[1]);
2173   }
2174
2175   /**
2176    * Tests for the method that maps the subset of a dna sequence that has CDS
2177    * (or subtype) feature - reverse strand case where the start codon is
2178    * incomplete.
2179    */
2180   @Test(groups = "Functional", enabled = false)
2181   // test turned off as currently findCdsPositions is not strand-dependent
2182   // left in case it comes around again...
2183   public void testFindCdsPositions_reverseStrandThreePrimeIncomplete()
2184   {
2185     SequenceI dnaSeq = new Sequence("dna", "aaagGGCCCaaaTTTttt");
2186     dnaSeq.createDatasetSequence();
2187     SequenceI ds = dnaSeq.getDatasetSequence();
2188
2189     // CDS for dna 5-9
2190     SequenceFeature sf = new SequenceFeature("CDS", "", 5, 9, 0f, null);
2191     sf.setStrand("-");
2192     ds.addSequenceFeature(sf);
2193     // CDS for dna 13-15
2194     sf = new SequenceFeature("CDS_predicted", "", 13, 15, 0f, null);
2195     sf.setStrand("-");
2196     sf.setPhase("2"); // skip 2 bases to start of next codon
2197     ds.addSequenceFeature(sf);
2198
2199     List<int[]> ranges = AlignmentUtils.findCdsPositions(dnaSeq);
2200
2201     /*
2202      * check the mapping starts with the first complete codon
2203      * expect ranges [13, 13], [9, 5]
2204      */
2205     assertEquals(6, MappingUtils.getLength(ranges));
2206     assertEquals(2, ranges.size());
2207     assertEquals(13, ranges.get(0)[0]);
2208     assertEquals(13, ranges.get(0)[1]);
2209     assertEquals(9, ranges.get(1)[0]);
2210     assertEquals(5, ranges.get(1)[1]);
2211   }
2212
2213   @Test(groups = "Functional")
2214   public void testAlignAs_alternateTranscriptsUngapped()
2215   {
2216     SequenceI dna1 = new Sequence("dna1", "cccGGGTTTaaa");
2217     SequenceI dna2 = new Sequence("dna2", "CCCgggtttAAA");
2218     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2 });
2219     ((Alignment) dna).createDatasetAlignment();
2220     SequenceI cds1 = new Sequence("cds1", "GGGTTT");
2221     SequenceI cds2 = new Sequence("cds2", "CCCAAA");
2222     AlignmentI cds = new Alignment(new SequenceI[] { cds1, cds2 });
2223     ((Alignment) cds).createDatasetAlignment();
2224
2225     AlignedCodonFrame acf = new AlignedCodonFrame();
2226     MapList map = new MapList(new int[] { 4, 9 }, new int[] { 1, 6 }, 1, 1);
2227     acf.addMap(dna1.getDatasetSequence(), cds1.getDatasetSequence(), map);
2228     map = new MapList(new int[] { 1, 3, 10, 12 }, new int[] { 1, 6 }, 1, 1);
2229     acf.addMap(dna2.getDatasetSequence(), cds2.getDatasetSequence(), map);
2230
2231     /*
2232      * verify CDS alignment is as:
2233      *   cccGGGTTTaaa (cdna)
2234      *   CCCgggtttAAA (cdna)
2235      *   
2236      *   ---GGGTTT--- (cds)
2237      *   CCC------AAA (cds)
2238      */
2239     dna.addCodonFrame(acf);
2240     AlignmentUtils.alignAs(cds, dna);
2241     assertEquals("---GGGTTT", cds.getSequenceAt(0).getSequenceAsString());
2242     assertEquals("CCC------AAA", cds.getSequenceAt(1).getSequenceAsString());
2243   }
2244
2245   @Test(groups = { "Functional" })
2246   public void testAddMappedPositions()
2247   {
2248     SequenceI from = new Sequence("dna", "ggAA-ATcc-TT-g");
2249     SequenceI seq1 = new Sequence("cds", "AAATTT");
2250     from.createDatasetSequence();
2251     seq1.createDatasetSequence();
2252     Mapping mapping = new Mapping(seq1, new MapList(
2253             new int[] { 3, 6, 9, 10 }, new int[] { 1, 6 }, 1, 1));
2254     Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2255     AlignmentUtils.addMappedPositions(seq1, from, mapping, map);
2256
2257     /*
2258      * verify map has seq1 residues in columns 3,4,6,7,11,12
2259      */
2260     assertEquals(6, map.size());
2261     assertEquals('A', map.get(3).get(seq1).charValue());
2262     assertEquals('A', map.get(4).get(seq1).charValue());
2263     assertEquals('A', map.get(6).get(seq1).charValue());
2264     assertEquals('T', map.get(7).get(seq1).charValue());
2265     assertEquals('T', map.get(11).get(seq1).charValue());
2266     assertEquals('T', map.get(12).get(seq1).charValue());
2267
2268     /*
2269      * 
2270      */
2271   }
2272
2273   /**
2274    * Test case where the mapping 'from' range includes a stop codon which is
2275    * absent in the 'to' range
2276    */
2277   @Test(groups = { "Functional" })
2278   public void testAddMappedPositions_withStopCodon()
2279   {
2280     SequenceI from = new Sequence("dna", "ggAA-ATcc-TT-g");
2281     SequenceI seq1 = new Sequence("cds", "AAATTT");
2282     from.createDatasetSequence();
2283     seq1.createDatasetSequence();
2284     Mapping mapping = new Mapping(seq1, new MapList(
2285             new int[] { 3, 6, 9, 10 }, new int[] { 1, 6 }, 1, 1));
2286     Map<Integer, Map<SequenceI, Character>> map = new TreeMap<Integer, Map<SequenceI, Character>>();
2287     AlignmentUtils.addMappedPositions(seq1, from, mapping, map);
2288
2289     /*
2290      * verify map has seq1 residues in columns 3,4,6,7,11,12
2291      */
2292     assertEquals(6, map.size());
2293     assertEquals('A', map.get(3).get(seq1).charValue());
2294     assertEquals('A', map.get(4).get(seq1).charValue());
2295     assertEquals('A', map.get(6).get(seq1).charValue());
2296     assertEquals('T', map.get(7).get(seq1).charValue());
2297     assertEquals('T', map.get(11).get(seq1).charValue());
2298     assertEquals('T', map.get(12).get(seq1).charValue());
2299   }
2300
2301   /**
2302    * Test for the case where the products for which we want CDS are specified.
2303    * This is to represent the case where EMBL has CDS mappings to both Uniprot
2304    * and EMBLCDSPROTEIN. makeCdsAlignment() should only return the mappings for
2305    * the protein sequences specified.
2306    */
2307   @Test(groups = { "Functional" })
2308   public void testMakeCdsAlignment_filterProducts()
2309   {
2310     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
2311     SequenceI dna2 = new Sequence("dna2", "GGGcccTTTaaaCCC");
2312     SequenceI pep1 = new Sequence("Uniprot|pep1", "GF");
2313     SequenceI pep2 = new Sequence("Uniprot|pep2", "GFP");
2314     SequenceI pep3 = new Sequence("EMBL|pep3", "GF");
2315     SequenceI pep4 = new Sequence("EMBL|pep4", "GFP");
2316     dna1.createDatasetSequence();
2317     dna2.createDatasetSequence();
2318     pep1.createDatasetSequence();
2319     pep2.createDatasetSequence();
2320     pep3.createDatasetSequence();
2321     pep4.createDatasetSequence();
2322     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2 });
2323     dna.setDataset(null);
2324     AlignmentI emblPeptides = new Alignment(new SequenceI[] { pep3, pep4 });
2325     emblPeptides.setDataset(null);
2326
2327     AlignedCodonFrame acf = new AlignedCodonFrame();
2328     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
2329             new int[] { 1, 2 }, 3, 1);
2330     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
2331     acf.addMap(dna1.getDatasetSequence(), pep3.getDatasetSequence(), map);
2332     dna.addCodonFrame(acf);
2333
2334     acf = new AlignedCodonFrame();
2335     map = new MapList(new int[] { 1, 3, 7, 9, 13, 15 }, new int[] { 1, 3 },
2336             3, 1);
2337     acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
2338     acf.addMap(dna2.getDatasetSequence(), pep4.getDatasetSequence(), map);
2339     dna.addCodonFrame(acf);
2340
2341     /*
2342      * execute method under test to find CDS for EMBL peptides only
2343      */
2344     AlignmentI cds = AlignmentUtils.makeCdsAlignment(new SequenceI[] {
2345         dna1, dna2 }, dna.getDataset(), emblPeptides.getSequencesArray());
2346
2347     assertEquals(2, cds.getSequences().size());
2348     assertEquals("GGGTTT", cds.getSequenceAt(0).getSequenceAsString());
2349     assertEquals("GGGTTTCCC", cds.getSequenceAt(1).getSequenceAsString());
2350
2351     /*
2352      * verify shared, extended alignment dataset
2353      */
2354     assertSame(dna.getDataset(), cds.getDataset());
2355     assertTrue(dna.getDataset().getSequences()
2356             .contains(cds.getSequenceAt(0).getDatasetSequence()));
2357     assertTrue(dna.getDataset().getSequences()
2358             .contains(cds.getSequenceAt(1).getDatasetSequence()));
2359
2360     /*
2361      * Verify mappings from CDS to peptide, cDNA to CDS, and cDNA to peptide
2362      * the mappings are on the shared alignment dataset
2363      */
2364     List<AlignedCodonFrame> cdsMappings = cds.getDataset().getCodonFrames();
2365     /*
2366      * 6 mappings, 2*(DNA->CDS), 2*(DNA->Pep), 2*(CDS->Pep) 
2367      */
2368     assertEquals(6, cdsMappings.size());
2369
2370     /*
2371      * verify that mapping sets for dna and cds alignments are different
2372      * [not current behaviour - all mappings are on the alignment dataset]  
2373      */
2374     // select -> subselect type to test.
2375     // Assert.assertNotSame(dna.getCodonFrames(), cds.getCodonFrames());
2376     // assertEquals(4, dna.getCodonFrames().size());
2377     // assertEquals(4, cds.getCodonFrames().size());
2378
2379     /*
2380      * Two mappings involve pep3 (dna to pep3, cds to pep3)
2381      * Mapping from pep3 to GGGTTT in first new exon sequence
2382      */
2383     List<AlignedCodonFrame> pep3Mappings = MappingUtils
2384             .findMappingsForSequence(pep3, cdsMappings);
2385     assertEquals(2, pep3Mappings.size());
2386     List<AlignedCodonFrame> mappings = MappingUtils
2387             .findMappingsForSequence(cds.getSequenceAt(0), pep3Mappings);
2388     assertEquals(1, mappings.size());
2389
2390     // map G to GGG
2391     SearchResults sr = MappingUtils.buildSearchResults(pep3, 1, mappings);
2392     assertEquals(1, sr.getResults().size());
2393     Match m = sr.getResults().get(0);
2394     assertSame(cds.getSequenceAt(0).getDatasetSequence(), m.getSequence());
2395     assertEquals(1, m.getStart());
2396     assertEquals(3, m.getEnd());
2397     // map F to TTT
2398     sr = MappingUtils.buildSearchResults(pep3, 2, mappings);
2399     m = sr.getResults().get(0);
2400     assertSame(cds.getSequenceAt(0).getDatasetSequence(), m.getSequence());
2401     assertEquals(4, m.getStart());
2402     assertEquals(6, m.getEnd());
2403
2404     /*
2405      * Two mappings involve pep4 (dna to pep4, cds to pep4)
2406      * Verify mapping from pep4 to GGGTTTCCC in second new exon sequence
2407      */
2408     List<AlignedCodonFrame> pep4Mappings = MappingUtils
2409             .findMappingsForSequence(pep4, cdsMappings);
2410     assertEquals(2, pep4Mappings.size());
2411     mappings = MappingUtils.findMappingsForSequence(cds.getSequenceAt(1),
2412             pep4Mappings);
2413     assertEquals(1, mappings.size());
2414     // map G to GGG
2415     sr = MappingUtils.buildSearchResults(pep4, 1, mappings);
2416     assertEquals(1, sr.getResults().size());
2417     m = sr.getResults().get(0);
2418     assertSame(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
2419     assertEquals(1, m.getStart());
2420     assertEquals(3, m.getEnd());
2421     // map F to TTT
2422     sr = MappingUtils.buildSearchResults(pep4, 2, mappings);
2423     m = sr.getResults().get(0);
2424     assertSame(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
2425     assertEquals(4, m.getStart());
2426     assertEquals(6, m.getEnd());
2427     // map P to CCC
2428     sr = MappingUtils.buildSearchResults(pep4, 3, mappings);
2429     m = sr.getResults().get(0);
2430     assertSame(cds.getSequenceAt(1).getDatasetSequence(), m.getSequence());
2431     assertEquals(7, m.getStart());
2432     assertEquals(9, m.getEnd());
2433   }
2434
2435   /**
2436    * Test the method that just copies aligned sequences, provided all sequences
2437    * to be aligned share the aligned sequence's dataset
2438    */
2439   @Test(groups = "Functional")
2440   public void testAlignAsSameSequences()
2441   {
2442     SequenceI dna1 = new Sequence("dna1", "cccGGGTTTaaa");
2443     SequenceI dna2 = new Sequence("dna2", "CCCgggtttAAA");
2444     AlignmentI al1 = new Alignment(new SequenceI[] { dna1, dna2 });
2445     ((Alignment) al1).createDatasetAlignment();
2446
2447     SequenceI dna3 = new Sequence(dna1);
2448     SequenceI dna4 = new Sequence(dna2);
2449     assertSame(dna3.getDatasetSequence(), dna1.getDatasetSequence());
2450     assertSame(dna4.getDatasetSequence(), dna2.getDatasetSequence());
2451     String seq1 = "-cc-GG-GT-TT--aaa";
2452     dna3.setSequence(seq1);
2453     String seq2 = "C--C-Cgg--gtt-tAA-A-";
2454     dna4.setSequence(seq2);
2455     AlignmentI al2 = new Alignment(new SequenceI[] { dna3, dna4 });
2456     ((Alignment) al2).createDatasetAlignment();
2457
2458     assertTrue(AlignmentUtils.alignAsSameSequences(al1, al2));
2459     assertEquals(seq1, al1.getSequenceAt(0).getSequenceAsString());
2460     assertEquals(seq2, al1.getSequenceAt(1).getSequenceAsString());
2461
2462     /*
2463      * add another sequence to 'aligned' - should still succeed, since
2464      * unaligned sequences still share a dataset with aligned sequences
2465      */
2466     SequenceI dna5 = new Sequence("dna5", "CCCgggtttAAA");
2467     dna5.createDatasetSequence();
2468     al2.addSequence(dna5);
2469     assertTrue(AlignmentUtils.alignAsSameSequences(al1, al2));
2470     assertEquals(seq1, al1.getSequenceAt(0).getSequenceAsString());
2471     assertEquals(seq2, al1.getSequenceAt(1).getSequenceAsString());
2472
2473     /*
2474      * add another sequence to 'unaligned' - should fail, since now not
2475      * all unaligned sequences share a dataset with aligned sequences
2476      */
2477     SequenceI dna6 = new Sequence("dna6", "CCCgggtttAAA");
2478     dna6.createDatasetSequence();
2479     al1.addSequence(dna6);
2480     // JAL-2110 JBP Comment: what's the use case for this behaviour ?
2481     assertFalse(AlignmentUtils.alignAsSameSequences(al1, al2));
2482   }
2483
2484   @Test(groups = "Functional")
2485   public void testAlignAsSameSequencesMultipleSubSeq()
2486   {
2487     SequenceI dna1 = new Sequence("dna1", "cccGGGTTTaaa");
2488     SequenceI dna2 = new Sequence("dna2", "CCCgggtttAAA");
2489     SequenceI as1 = dna1.deriveSequence();
2490     SequenceI as2 = dna1.deriveSequence().getSubSequence(3, 7);
2491     SequenceI as3 = dna2.deriveSequence();
2492     as1.insertCharAt(6, 5, '-');
2493     String s_as1 = as1.getSequenceAsString();
2494     as2.insertCharAt(6, 5, '-');
2495     String s_as2 = as2.getSequenceAsString();
2496     as3.insertCharAt(6, 5, '-');
2497     String s_as3 = as3.getSequenceAsString();
2498     AlignmentI aligned = new Alignment(new SequenceI[] { as1, as2, as3 });
2499
2500     // why do we need to cast this still ?
2501     ((Alignment) aligned).createDatasetAlignment();
2502     SequenceI uas1 = dna1.deriveSequence();
2503     SequenceI uas2 = dna1.deriveSequence().getSubSequence(3, 7);
2504     SequenceI uas3 = dna2.deriveSequence();
2505     AlignmentI tobealigned = new Alignment(new SequenceI[] { uas1, uas2,
2506         uas3 });
2507     ((Alignment) tobealigned).createDatasetAlignment();
2508
2509     assertTrue(AlignmentUtils.alignAsSameSequences(tobealigned, aligned));
2510     assertEquals(s_as1, uas1.getSequenceAsString());
2511     assertEquals(s_as2, uas2.getSequenceAsString());
2512     assertEquals(s_as3, uas3.getSequenceAsString());
2513   }
2514
2515 }