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