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