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