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