JAL-653 AlignedCodonFrame collections changed from Set to List
[jalview.git] / test / jalview / analysis / AlignmentUtilsTests.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.analysis;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertFalse;
25 import static org.testng.AssertJUnit.assertNull;
26 import static org.testng.AssertJUnit.assertSame;
27 import static org.testng.AssertJUnit.assertTrue;
28
29 import jalview.datamodel.AlignedCodonFrame;
30 import jalview.datamodel.Alignment;
31 import jalview.datamodel.AlignmentAnnotation;
32 import jalview.datamodel.AlignmentI;
33 import jalview.datamodel.Annotation;
34 import jalview.datamodel.DBRefEntry;
35 import jalview.datamodel.Mapping;
36 import jalview.datamodel.SearchResults;
37 import jalview.datamodel.SearchResults.Match;
38 import jalview.datamodel.Sequence;
39 import jalview.datamodel.SequenceI;
40 import jalview.io.AppletFormatAdapter;
41 import jalview.io.FormatAdapter;
42 import jalview.util.MapList;
43 import jalview.util.MappingUtils;
44
45 import java.io.IOException;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.HashSet;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Map;
52 import java.util.Set;
53
54 import org.testng.annotations.Test;
55
56 public class AlignmentUtilsTests
57 {
58   // @formatter:off
59   private static final String TEST_DATA = 
60           "# STOCKHOLM 1.0\n" +
61           "#=GS D.melanogaster.1 AC AY119185.1/838-902\n" +
62           "#=GS D.melanogaster.2 AC AC092237.1/57223-57161\n" +
63           "#=GS D.melanogaster.3 AC AY060611.1/560-627\n" +
64           "D.melanogaster.1          G.AGCC.CU...AUGAUCGA\n" +
65           "#=GR D.melanogaster.1 SS  ................((((\n" +
66           "D.melanogaster.2          C.AUUCAACU.UAUGAGGAU\n" +
67           "#=GR D.melanogaster.2 SS  ................((((\n" +
68           "D.melanogaster.3          G.UGGCGCU..UAUGACGCA\n" +
69           "#=GR D.melanogaster.3 SS  (.(((...(....(((((((\n" +
70           "//";
71
72   private static final String AA_SEQS_1 = 
73           ">Seq1Name\n" +
74           "K-QY--L\n" +
75           ">Seq2Name\n" +
76           "-R-FP-W-\n";
77
78   private static final String CDNA_SEQS_1 = 
79           ">Seq1Name\n" +
80           "AC-GG--CUC-CAA-CT\n" +
81           ">Seq2Name\n" +
82           "-CG-TTA--ACG---AAGT\n";
83
84   private static final String CDNA_SEQS_2 = 
85           ">Seq1Name\n" +
86           "GCTCGUCGTACT\n" +
87           ">Seq2Name\n" +
88           "GGGTCAGGCAGT\n";
89   // @formatter:on
90
91   // public static Sequence ts=new
92   // Sequence("short","ASDASDASDASDASDASDASDASDASDASDASDASDASD");
93   public static Sequence ts = new Sequence("short",
94           "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm");
95
96   @Test(groups = { "Functional" })
97   public void testExpandContext()
98   {
99     AlignmentI al = new Alignment(new Sequence[] {});
100     for (int i = 4; i < 14; i += 2)
101     {
102       SequenceI s1 = ts.deriveSequence().getSubSequence(i, i + 7);
103       al.addSequence(s1);
104     }
105     System.out.println(new AppletFormatAdapter().formatSequences("Clustal",
106             al, true));
107     for (int flnk = -1; flnk < 25; flnk++)
108     {
109       AlignmentI exp = AlignmentUtils.expandContext(al, flnk);
110       System.out.println("\nFlank size: " + flnk);
111       System.out.println(new AppletFormatAdapter().formatSequences(
112               "Clustal", exp, true));
113       if (flnk == -1)
114       {
115         /*
116          * Full expansion to complete sequences
117          */
118         for (SequenceI sq : exp.getSequences())
119         {
120           String ung = sq.getSequenceAsString().replaceAll("-+", "");
121           final String errorMsg = "Flanking sequence not the same as original dataset sequence.\n"
122                   + ung
123                   + "\n"
124                   + sq.getDatasetSequence().getSequenceAsString();
125           assertTrue(errorMsg, ung.equalsIgnoreCase(sq.getDatasetSequence()
126                   .getSequenceAsString()));
127         }
128       }
129       else if (flnk == 24)
130       {
131         /*
132          * Last sequence is fully expanded, others have leading gaps to match
133          */
134         assertTrue(exp.getSequenceAt(4).getSequenceAsString()
135                 .startsWith("abc"));
136         assertTrue(exp.getSequenceAt(3).getSequenceAsString()
137                 .startsWith("--abc"));
138         assertTrue(exp.getSequenceAt(2).getSequenceAsString()
139                 .startsWith("----abc"));
140         assertTrue(exp.getSequenceAt(1).getSequenceAsString()
141                 .startsWith("------abc"));
142         assertTrue(exp.getSequenceAt(0).getSequenceAsString()
143                 .startsWith("--------abc"));
144       }
145     }
146   }
147
148   /**
149    * Test that annotations are correctly adjusted by expandContext
150    */
151   @Test(groups = { "Functional" })
152   public void testExpandContext_annotation()
153   {
154     AlignmentI al = new Alignment(new Sequence[] {});
155     SequenceI ds = new Sequence("Seq1", "ABCDEFGHI");
156     // subsequence DEF:
157     SequenceI seq1 = ds.deriveSequence().getSubSequence(3, 6);
158     al.addSequence(seq1);
159
160     /*
161      * Annotate DEF with 4/5/6 respectively
162      */
163     Annotation[] anns = new Annotation[] { new Annotation(4),
164         new Annotation(5), new Annotation(6) };
165     AlignmentAnnotation ann = new AlignmentAnnotation("SS",
166             "secondary structure", anns);
167     seq1.addAlignmentAnnotation(ann);
168
169     /*
170      * The annotations array should match aligned positions
171      */
172     assertEquals(3, ann.annotations.length);
173     assertEquals(4, ann.annotations[0].value, 0.001);
174     assertEquals(5, ann.annotations[1].value, 0.001);
175     assertEquals(6, ann.annotations[2].value, 0.001);
176
177     /*
178      * Check annotation to sequence position mappings before expanding the
179      * sequence; these are set up in Sequence.addAlignmentAnnotation ->
180      * Annotation.setSequenceRef -> createSequenceMappings
181      */
182     assertNull(ann.getAnnotationForPosition(1));
183     assertNull(ann.getAnnotationForPosition(2));
184     assertNull(ann.getAnnotationForPosition(3));
185     assertEquals(4, ann.getAnnotationForPosition(4).value, 0.001);
186     assertEquals(5, ann.getAnnotationForPosition(5).value, 0.001);
187     assertEquals(6, ann.getAnnotationForPosition(6).value, 0.001);
188     assertNull(ann.getAnnotationForPosition(7));
189     assertNull(ann.getAnnotationForPosition(8));
190     assertNull(ann.getAnnotationForPosition(9));
191
192     /*
193      * Expand the subsequence to the full sequence abcDEFghi
194      */
195     AlignmentI expanded = AlignmentUtils.expandContext(al, -1);
196     assertEquals("abcDEFghi", expanded.getSequenceAt(0)
197             .getSequenceAsString());
198
199     /*
200      * Confirm the alignment and sequence have the same SS annotation,
201      * referencing the expanded sequence
202      */
203     ann = expanded.getSequenceAt(0).getAnnotation()[0];
204     assertSame(ann, expanded.getAlignmentAnnotation()[0]);
205     assertSame(expanded.getSequenceAt(0), ann.sequenceRef);
206
207     /*
208      * The annotations array should have null values except for annotated
209      * positions
210      */
211     assertNull(ann.annotations[0]);
212     assertNull(ann.annotations[1]);
213     assertNull(ann.annotations[2]);
214     assertEquals(4, ann.annotations[3].value, 0.001);
215     assertEquals(5, ann.annotations[4].value, 0.001);
216     assertEquals(6, ann.annotations[5].value, 0.001);
217     assertNull(ann.annotations[6]);
218     assertNull(ann.annotations[7]);
219     assertNull(ann.annotations[8]);
220
221     /*
222      * sequence position mappings should be unchanged
223      */
224     assertNull(ann.getAnnotationForPosition(1));
225     assertNull(ann.getAnnotationForPosition(2));
226     assertNull(ann.getAnnotationForPosition(3));
227     assertEquals(4, ann.getAnnotationForPosition(4).value, 0.001);
228     assertEquals(5, ann.getAnnotationForPosition(5).value, 0.001);
229     assertEquals(6, ann.getAnnotationForPosition(6).value, 0.001);
230     assertNull(ann.getAnnotationForPosition(7));
231     assertNull(ann.getAnnotationForPosition(8));
232     assertNull(ann.getAnnotationForPosition(9));
233   }
234
235   /**
236    * Test method that returns a map of lists of sequences by sequence name.
237    * 
238    * @throws IOException
239    */
240   @Test(groups = { "Functional" })
241   public void testGetSequencesByName() throws IOException
242   {
243     final String data = ">Seq1Name\nKQYL\n" + ">Seq2Name\nRFPW\n"
244             + ">Seq1Name\nABCD\n";
245     AlignmentI al = loadAlignment(data, "FASTA");
246     Map<String, List<SequenceI>> map = AlignmentUtils
247             .getSequencesByName(al);
248     assertEquals(2, map.keySet().size());
249     assertEquals(2, map.get("Seq1Name").size());
250     assertEquals("KQYL", map.get("Seq1Name").get(0).getSequenceAsString());
251     assertEquals("ABCD", map.get("Seq1Name").get(1).getSequenceAsString());
252     assertEquals(1, map.get("Seq2Name").size());
253     assertEquals("RFPW", map.get("Seq2Name").get(0).getSequenceAsString());
254   }
255
256   /**
257    * Helper method to load an alignment and ensure dataset sequences are set up.
258    * 
259    * @param data
260    * @param format
261    *          TODO
262    * @return
263    * @throws IOException
264    */
265   protected AlignmentI loadAlignment(final String data, String format)
266           throws IOException
267   {
268     AlignmentI a = new FormatAdapter().readFile(data,
269             AppletFormatAdapter.PASTE, format);
270     a.setDataset(null);
271     return a;
272   }
273
274   /**
275    * Test mapping of protein to cDNA, for the case where we have no sequence
276    * cross-references, so mappings are made first-served 1-1 where sequences
277    * translate.
278    * 
279    * @throws IOException
280    */
281   @Test(groups = { "Functional" })
282   public void testMapProteinAlignmentToCdna_noXrefs() throws IOException
283   {
284     List<SequenceI> protseqs = new ArrayList<SequenceI>();
285     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
286     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
287     protseqs.add(new Sequence("UNIPROT|V12347", "SAR"));
288     AlignmentI protein = new Alignment(protseqs.toArray(new SequenceI[3]));
289     protein.setDataset(null);
290
291     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
292     dnaseqs.add(new Sequence("EMBL|A11111", "TCAGCACGC")); // = SAR
293     dnaseqs.add(new Sequence("EMBL|A22222", "GAGATACAA")); // = EIQ
294     dnaseqs.add(new Sequence("EMBL|A33333", "GAAATCCAG")); // = EIQ
295     dnaseqs.add(new Sequence("EMBL|A44444", "GAAATTCAG")); // = EIQ
296     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[4]));
297     cdna.setDataset(null);
298
299     assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
300
301     // 3 mappings made, each from 1 to 1 sequence
302     assertEquals(3, protein.getCodonFrames().size());
303     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
304     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
305     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(2)).size());
306
307     // V12345 mapped to A22222
308     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
309             .get(0);
310     assertEquals(1, acf.getdnaSeqs().length);
311     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
312             acf.getdnaSeqs()[0]);
313     Mapping[] protMappings = acf.getProtMappings();
314     assertEquals(1, protMappings.length);
315     MapList mapList = protMappings[0].getMap();
316     assertEquals(3, mapList.getFromRatio());
317     assertEquals(1, mapList.getToRatio());
318     assertTrue(Arrays.equals(new int[] { 1, 9 }, mapList.getFromRanges()
319             .get(0)));
320     assertEquals(1, mapList.getFromRanges().size());
321     assertTrue(Arrays.equals(new int[] { 1, 3 },
322             mapList.getToRanges().get(0)));
323     assertEquals(1, mapList.getToRanges().size());
324
325     // V12346 mapped to A33333
326     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
327     assertEquals(1, acf.getdnaSeqs().length);
328     assertEquals(cdna.getSequenceAt(2).getDatasetSequence(),
329             acf.getdnaSeqs()[0]);
330
331     // V12347 mapped to A11111
332     acf = protein.getCodonFrame(protein.getSequenceAt(2)).get(0);
333     assertEquals(1, acf.getdnaSeqs().length);
334     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
335             acf.getdnaSeqs()[0]);
336
337     // no mapping involving the 'extra' A44444
338     assertTrue(protein.getCodonFrame(cdna.getSequenceAt(3)).isEmpty());
339   }
340
341   /**
342    * Test for the alignSequenceAs method that takes two sequences and a mapping.
343    */
344   @Test(groups = { "Functional" })
345   public void testAlignSequenceAs_withMapping_noIntrons()
346   {
347     MapList map = new MapList(new int[] { 1, 6 }, new int[] { 1, 2 }, 3, 1);
348
349     /*
350      * No existing gaps in dna:
351      */
352     checkAlignSequenceAs("GGGAAA", "-A-L-", false, false, map,
353             "---GGG---AAA");
354
355     /*
356      * Now introduce gaps in dna but ignore them when realigning.
357      */
358     checkAlignSequenceAs("-G-G-G-A-A-A-", "-A-L-", false, false, map,
359             "---GGG---AAA");
360
361     /*
362      * Now include gaps in dna when realigning. First retaining 'mapped' gaps
363      * only, i.e. those within the exon region.
364      */
365     checkAlignSequenceAs("-G-G--G-A--A-A-", "-A-L-", true, false, map,
366             "---G-G--G---A--A-A");
367
368     /*
369      * Include all gaps in dna when realigning (within and without the exon
370      * region). The leading gap, and the gaps between codons, are subsumed by
371      * the protein alignment gap.
372      */
373     checkAlignSequenceAs("-G-GG--AA-A-", "-A-L-", true, true, map,
374             "---G-GG---AA-A-");
375
376     /*
377      * Include only unmapped gaps in dna when realigning (outside the exon
378      * region). The leading gap, and the gaps between codons, are subsumed by
379      * the protein alignment gap.
380      */
381     checkAlignSequenceAs("-G-GG--AA-A-", "-A-L-", false, true, map,
382             "---GGG---AAA-");
383   }
384
385   /**
386    * Test for the alignSequenceAs method that takes two sequences and a mapping.
387    */
388   @Test(groups = { "Functional" })
389   public void testAlignSequenceAs_withMapping_withIntrons()
390   {
391     /*
392      * Exons at codon 2 (AAA) and 4 (TTT)
393      */
394     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
395             new int[] { 1, 2 }, 3, 1);
396
397     /*
398      * Simple case: no gaps in dna
399      */
400     checkAlignSequenceAs("GGGAAACCCTTTGGG", "--A-L-", false, false, map,
401             "GGG---AAACCCTTTGGG");
402
403     /*
404      * Add gaps to dna - but ignore when realigning.
405      */
406     checkAlignSequenceAs("-G-G-G--A--A---AC-CC-T-TT-GG-G-", "--A-L-",
407             false, false, map, "GGG---AAACCCTTTGGG");
408
409     /*
410      * Add gaps to dna - include within exons only when realigning.
411      */
412     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
413             true, false, map, "GGG---A--A---ACCCT-TTGGG");
414
415     /*
416      * Include gaps outside exons only when realigning.
417      */
418     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
419             false, true, map, "-G-G-GAAAC-CCTTT-GG-G-");
420
421     /*
422      * Include gaps following first intron if we are 'preserving mapped gaps'
423      */
424     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
425             true, true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
426
427     /*
428      * Include all gaps in dna when realigning.
429      */
430     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
431             true, true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
432   }
433
434   /**
435    * Test for the case where not all of the protein sequence is mapped to cDNA.
436    */
437   @Test(groups = { "Functional" })
438   public void testAlignSequenceAs_withMapping_withUnmappedProtein()
439   {
440     /*
441      * Exons at codon 2 (AAA) and 4 (TTT) mapped to A and P
442      */
443     final MapList map = new MapList(new int[] { 4, 6, 10, 12 }, new int[] {
444         1, 1, 3, 3 }, 3, 1);
445
446     /*
447      * Expect alignment does nothing (aborts realignment). Change this test
448      * first if different behaviour wanted.
449      */
450     checkAlignSequenceAs("gggAAAcccTTTggg", "-A-L-P-", false, false, map,
451             "gggAAAccc---TTTggg");
452   }
453
454   /**
455    * Helper method that performs and verifies the method under test.
456    * 
457    * @param alignee
458    *          the sequence to be realigned
459    * @param alignModel
460    *          the sequence whose alignment is to be copied
461    * @param preserveMappedGaps
462    * @param preserveUnmappedGaps
463    * @param map
464    * @param expected
465    */
466   protected void checkAlignSequenceAs(final String alignee,
467           final String alignModel, final boolean preserveMappedGaps,
468           final boolean preserveUnmappedGaps, MapList map,
469           final String expected)
470   {
471     SequenceI alignMe = new Sequence("Seq1", alignee);
472     alignMe.createDatasetSequence();
473     SequenceI alignFrom = new Sequence("Seq2", alignModel);
474     alignFrom.createDatasetSequence();
475     AlignedCodonFrame acf = new AlignedCodonFrame();
476     acf.addMap(alignMe.getDatasetSequence(), alignFrom.getDatasetSequence(), map);
477
478     AlignmentUtils.alignSequenceAs(alignMe, alignFrom, acf, "---", '-',
479             preserveMappedGaps, preserveUnmappedGaps);
480     assertEquals(expected, alignMe.getSequenceAsString());
481   }
482
483   /**
484    * Test for the alignSequenceAs method where we preserve gaps in introns only.
485    */
486   @Test(groups = { "Functional" })
487   public void testAlignSequenceAs_keepIntronGapsOnly()
488   {
489
490     /*
491      * Intron GGGAAA followed by exon CCCTTT
492      */
493     MapList map = new MapList(new int[] { 7, 12 }, new int[] { 1, 2 }, 3, 1);
494
495     checkAlignSequenceAs("GG-G-AA-A-C-CC-T-TT", "AL", false, true, map,
496             "GG-G-AA-ACCCTTT");
497   }
498
499   /**
500    * Test for the method that generates an aligned translated sequence from one
501    * mapping.
502    */
503   @Test(groups = { "Functional" })
504   public void testGetAlignedTranslation_dnaLikeProtein()
505   {
506     // dna alignment will be replaced
507     SequenceI dna = new Sequence("Seq1", "T-G-CC-A--T-TAC-CAG-");
508     dna.createDatasetSequence();
509     // protein alignment will be 'applied' to dna
510     SequenceI protein = new Sequence("Seq1", "-CH-Y--Q-");
511     protein.createDatasetSequence();
512     MapList map = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 }, 3, 1);
513     AlignedCodonFrame acf = new AlignedCodonFrame();
514     acf.addMap(dna.getDatasetSequence(), protein.getDatasetSequence(), map);
515
516     final SequenceI aligned = AlignmentUtils.getAlignedTranslation(protein,
517             '-', acf);
518     assertEquals("---TGCCAT---TAC------CAG---",
519             aligned.getSequenceAsString());
520     assertSame(aligned.getDatasetSequence(), dna.getDatasetSequence());
521   }
522
523   /**
524    * Test the method that realigns protein to match mapped codon alignment.
525    */
526   @Test(groups = { "Functional" })
527   public void testAlignProteinAsDna()
528   {
529     // seq1 codons are [1,2,3] [4,5,6] [7,8,9] [10,11,12]
530     SequenceI dna1 = new Sequence("Seq1", "TGCCATTACCAG-");
531     // seq2 codons are [1,3,4] [5,6,7] [8,9,10] [11,12,13]
532     SequenceI dna2 = new Sequence("Seq2", "T-GCCATTACCAG");
533     // seq3 codons are [1,2,3] [4,5,7] [8,9,10] [11,12,13]
534     SequenceI dna3 = new Sequence("Seq3", "TGCCA-TTACCAG");
535     AlignmentI dna = new Alignment(new SequenceI[] { dna1, dna2, dna3 });
536     dna.setDataset(null);
537
538     // protein alignment will be realigned like dna
539     SequenceI prot1 = new Sequence("Seq1", "CHYQ");
540     SequenceI prot2 = new Sequence("Seq2", "CHYQ");
541     SequenceI prot3 = new Sequence("Seq3", "CHYQ");
542     SequenceI prot4 = new Sequence("Seq4", "R-QSV"); // unmapped, unchanged
543     AlignmentI protein = new Alignment(new SequenceI[] { prot1, prot2,
544         prot3, prot4 });
545     protein.setDataset(null);
546
547     MapList map = new MapList(new int[] { 1, 12 }, new int[] { 1, 4 }, 3, 1);
548     AlignedCodonFrame acf = new AlignedCodonFrame();
549     acf.addMap(dna1.getDatasetSequence(), prot1.getDatasetSequence(), map);
550     acf.addMap(dna2.getDatasetSequence(), prot2.getDatasetSequence(), map);
551     acf.addMap(dna3.getDatasetSequence(), prot3.getDatasetSequence(), map);
552     protein.setCodonFrames(new ArrayList<AlignedCodonFrame>());
553
554     /*
555      * Translated codon order is [1,2,3] [1,3,4] [4,5,6] [4,5,7] [5,6,7] [7,8,9]
556      * [8,9,10] [10,11,12] [11,12,13]
557      */
558     AlignmentUtils.alignProteinAsDna(protein, dna);
559     assertEquals("C-H--Y-Q-", prot1.getSequenceAsString());
560     assertEquals("-C--H-Y-Q", prot2.getSequenceAsString());
561     assertEquals("C--H--Y-Q", prot3.getSequenceAsString());
562     assertEquals("R-QSV", prot4.getSequenceAsString());
563   }
564
565   /**
566    * Test the method that tests whether a CDNA sequence translates to a protein
567    * sequence
568    */
569   @Test(groups = { "Functional" })
570   public void testTranslatesAs()
571   {
572     assertTrue(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(), 0,
573             "FPKG".toCharArray()));
574     // with start codon (not in protein)
575     assertTrue(AlignmentUtils.translatesAs("atgtttcccaaaggg".toCharArray(),
576             3, "FPKG".toCharArray()));
577     // with stop codon1 (not in protein)
578     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtaa".toCharArray(),
579             0, "FPKG".toCharArray()));
580     // with stop codon1 (in protein as *)
581     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtaa".toCharArray(),
582             0, "FPKG*".toCharArray()));
583     // with stop codon2 (not in protein)
584     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtag".toCharArray(),
585             0, "FPKG".toCharArray()));
586     // with stop codon3 (not in protein)
587     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtga".toCharArray(),
588             0, "FPKG".toCharArray()));
589     // with start and stop codon1
590     assertTrue(AlignmentUtils.translatesAs(
591             "atgtttcccaaagggtaa".toCharArray(), 3, "FPKG".toCharArray()));
592     // with start and stop codon1 (in protein as *)
593     assertTrue(AlignmentUtils.translatesAs(
594             "atgtttcccaaagggtaa".toCharArray(), 3, "FPKG*".toCharArray()));
595     // with start and stop codon2
596     assertTrue(AlignmentUtils.translatesAs(
597             "atgtttcccaaagggtag".toCharArray(), 3, "FPKG".toCharArray()));
598     // with start and stop codon3
599     assertTrue(AlignmentUtils.translatesAs(
600             "atgtttcccaaagggtga".toCharArray(), 3, "FPKG".toCharArray()));
601
602     // with embedded stop codon
603     assertTrue(AlignmentUtils.translatesAs(
604             "atgtttTAGcccaaaTAAgggtga".toCharArray(), 3,
605             "F*PK*G".toCharArray()));
606
607     // wrong protein
608     assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
609             0, "FPMG".toCharArray()));
610   }
611
612   /**
613    * Test mapping of protein to cDNA, for cases where the cDNA has start and/or
614    * stop codons in addition to the protein coding sequence.
615    * 
616    * @throws IOException
617    */
618   @Test(groups = { "Functional" })
619   public void testMapProteinAlignmentToCdna_withStartAndStopCodons()
620           throws IOException
621   {
622     List<SequenceI> protseqs = new ArrayList<SequenceI>();
623     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
624     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
625     protseqs.add(new Sequence("UNIPROT|V12347", "SAR"));
626     AlignmentI protein = new Alignment(protseqs.toArray(new SequenceI[3]));
627     protein.setDataset(null);
628
629     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
630     // start + SAR:
631     dnaseqs.add(new Sequence("EMBL|A11111", "ATGTCAGCACGC"));
632     // = EIQ + stop
633     dnaseqs.add(new Sequence("EMBL|A22222", "GAGATACAATAA"));
634     // = start +EIQ + stop
635     dnaseqs.add(new Sequence("EMBL|A33333", "ATGGAAATCCAGTAG"));
636     dnaseqs.add(new Sequence("EMBL|A44444", "GAAATTCAG"));
637     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[4]));
638     cdna.setDataset(null);
639
640     assertTrue(AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna));
641
642     // 3 mappings made, each from 1 to 1 sequence
643     assertEquals(3, protein.getCodonFrames().size());
644     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
645     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
646     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(2)).size());
647
648     // V12345 mapped from A22222
649     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
650             .get(0);
651     assertEquals(1, acf.getdnaSeqs().length);
652     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
653             acf.getdnaSeqs()[0]);
654     Mapping[] protMappings = acf.getProtMappings();
655     assertEquals(1, protMappings.length);
656     MapList mapList = protMappings[0].getMap();
657     assertEquals(3, mapList.getFromRatio());
658     assertEquals(1, mapList.getToRatio());
659     assertTrue(Arrays.equals(new int[] { 1, 9 }, mapList.getFromRanges()
660             .get(0)));
661     assertEquals(1, mapList.getFromRanges().size());
662     assertTrue(Arrays.equals(new int[] { 1, 3 },
663             mapList.getToRanges().get(0)));
664     assertEquals(1, mapList.getToRanges().size());
665
666     // V12346 mapped from A33333 starting position 4
667     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
668     assertEquals(1, acf.getdnaSeqs().length);
669     assertEquals(cdna.getSequenceAt(2).getDatasetSequence(),
670             acf.getdnaSeqs()[0]);
671     protMappings = acf.getProtMappings();
672     assertEquals(1, protMappings.length);
673     mapList = protMappings[0].getMap();
674     assertEquals(3, mapList.getFromRatio());
675     assertEquals(1, mapList.getToRatio());
676     assertTrue(Arrays.equals(new int[] { 4, 12 }, mapList.getFromRanges()
677             .get(0)));
678     assertEquals(1, mapList.getFromRanges().size());
679     assertTrue(Arrays.equals(new int[] { 1, 3 },
680             mapList.getToRanges().get(0)));
681     assertEquals(1, mapList.getToRanges().size());
682
683     // V12347 mapped to A11111 starting position 4
684     acf = protein.getCodonFrame(protein.getSequenceAt(2)).get(0);
685     assertEquals(1, acf.getdnaSeqs().length);
686     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
687             acf.getdnaSeqs()[0]);
688     protMappings = acf.getProtMappings();
689     assertEquals(1, protMappings.length);
690     mapList = protMappings[0].getMap();
691     assertEquals(3, mapList.getFromRatio());
692     assertEquals(1, mapList.getToRatio());
693     assertTrue(Arrays.equals(new int[] { 4, 12 }, mapList.getFromRanges()
694             .get(0)));
695     assertEquals(1, mapList.getFromRanges().size());
696     assertTrue(Arrays.equals(new int[] { 1, 3 },
697             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<SequenceI>();
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<SequenceI>();
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<SequenceI>();
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<SequenceI>();
799     dnaseqs.add(new Sequence("EMBL|A11111", "GAAATCCAG")); // = EIQ
800     dnaseqs.add(new Sequence("EMBL|A22222", "GAAATTCAG")); // = EIQ
801     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[dnaseqs
802             .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", anns);
854     ann4.setSequenceRef(seq1);
855     AlignmentAnnotation ann5 = new AlignmentAnnotation("Temp", "ann5", anns);
856     ann5.setSequenceRef(seq2);
857     AlignmentAnnotation ann6 = new AlignmentAnnotation("Temp", "ann6", anns);
858     AlignmentI al = new Alignment(new SequenceI[] { seq1, seq2, seq3 });
859     al.addAnnotation(ann1); // Structure for Seq1
860     al.addAnnotation(ann2); // Structure for Seq2
861     al.addAnnotation(ann3); // Structure for no sequence
862     al.addAnnotation(ann4); // Temp for seq1
863     al.addAnnotation(ann5); // Temp for seq2
864     al.addAnnotation(ann6); // Temp for no sequence
865     List<String> types = new ArrayList<String>();
866     List<SequenceI> scope = new ArrayList<SequenceI>();
867
868     /*
869      * Set all sequence related Structure to hidden (ann1, ann2)
870      */
871     types.add("Structure");
872     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, false,
873             false);
874     assertFalse(ann1.visible);
875     assertFalse(ann2.visible);
876     assertTrue(ann3.visible); // not sequence-related, not affected
877     assertTrue(ann4.visible); // not Structure, not affected
878     assertTrue(ann5.visible); // "
879     assertTrue(ann6.visible); // not sequence-related, not affected
880
881     /*
882      * Set Temp in {seq1, seq3} to hidden
883      */
884     types.clear();
885     types.add("Temp");
886     scope.add(seq1);
887     scope.add(seq3);
888     AlignmentUtils.showOrHideSequenceAnnotations(al, types, scope, false,
889             false);
890     assertFalse(ann1.visible); // unchanged
891     assertFalse(ann2.visible); // unchanged
892     assertTrue(ann3.visible); // not sequence-related, not affected
893     assertFalse(ann4.visible); // Temp for seq1 hidden
894     assertTrue(ann5.visible); // not in scope, not affected
895     assertTrue(ann6.visible); // not sequence-related, not affected
896
897     /*
898      * Set Temp in all sequences to hidden
899      */
900     types.clear();
901     types.add("Temp");
902     scope.add(seq1);
903     scope.add(seq3);
904     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, false,
905             false);
906     assertFalse(ann1.visible); // unchanged
907     assertFalse(ann2.visible); // unchanged
908     assertTrue(ann3.visible); // not sequence-related, not affected
909     assertFalse(ann4.visible); // Temp for seq1 hidden
910     assertFalse(ann5.visible); // Temp for seq2 hidden
911     assertTrue(ann6.visible); // not sequence-related, not affected
912
913     /*
914      * Set all types in {seq1, seq3} to visible
915      */
916     types.clear();
917     scope.clear();
918     scope.add(seq1);
919     scope.add(seq3);
920     AlignmentUtils.showOrHideSequenceAnnotations(al, types, scope, true,
921             true);
922     assertTrue(ann1.visible); // Structure for seq1 set visible
923     assertFalse(ann2.visible); // not in scope, unchanged
924     assertTrue(ann3.visible); // not sequence-related, not affected
925     assertTrue(ann4.visible); // Temp for seq1 set visible
926     assertFalse(ann5.visible); // not in scope, unchanged
927     assertTrue(ann6.visible); // not sequence-related, not affected
928
929     /*
930      * Set all types in all scope to hidden
931      */
932     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, true,
933             false);
934     assertFalse(ann1.visible);
935     assertFalse(ann2.visible);
936     assertTrue(ann3.visible); // not sequence-related, not affected
937     assertFalse(ann4.visible);
938     assertFalse(ann5.visible);
939     assertTrue(ann6.visible); // not sequence-related, not affected
940   }
941
942   /**
943    * Tests for the method that checks if one sequence cross-references another
944    */
945   @Test(groups = { "Functional" })
946   public void testHasCrossRef()
947   {
948     assertFalse(AlignmentUtils.hasCrossRef(null, null));
949     SequenceI seq1 = new Sequence("EMBL|A12345", "ABCDEF");
950     assertFalse(AlignmentUtils.hasCrossRef(seq1, null));
951     assertFalse(AlignmentUtils.hasCrossRef(null, seq1));
952     SequenceI seq2 = new Sequence("UNIPROT|V20192", "ABCDEF");
953     assertFalse(AlignmentUtils.hasCrossRef(seq1, seq2));
954
955     // different ref
956     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "v20193"));
957     assertFalse(AlignmentUtils.hasCrossRef(seq1, seq2));
958
959     // case-insensitive; version number is ignored
960     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "v20192"));
961     assertTrue(AlignmentUtils.hasCrossRef(seq1, seq2));
962
963     // right case!
964     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
965     assertTrue(AlignmentUtils.hasCrossRef(seq1, seq2));
966     // test is one-way only
967     assertFalse(AlignmentUtils.hasCrossRef(seq2, seq1));
968   }
969
970   /**
971    * Tests for the method that checks if either sequence cross-references the
972    * other
973    */
974   @Test(groups = { "Functional" })
975   public void testHaveCrossRef()
976   {
977     assertFalse(AlignmentUtils.hasCrossRef(null, null));
978     SequenceI seq1 = new Sequence("EMBL|A12345", "ABCDEF");
979     assertFalse(AlignmentUtils.haveCrossRef(seq1, null));
980     assertFalse(AlignmentUtils.haveCrossRef(null, seq1));
981     SequenceI seq2 = new Sequence("UNIPROT|V20192", "ABCDEF");
982     assertFalse(AlignmentUtils.haveCrossRef(seq1, seq2));
983
984     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
985     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
986     // next is true for haveCrossRef, false for hasCrossRef
987     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
988
989     // now the other way round
990     seq1.setDBRef(null);
991     seq2.addDBRef(new DBRefEntry("EMBL", "1", "A12345"));
992     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
993     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
994
995     // now both ways
996     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
997     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
998     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
999   }
1000
1001   /**
1002    * Test the method that extracts the exon-only part of a dna alignment.
1003    */
1004   @Test(groups = { "Functional" })
1005   public void testMakeExonAlignment()
1006   {
1007     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
1008     SequenceI dna2 = new Sequence("dna2", "GGGcccTTTaaaCCC");
1009     SequenceI pep1 = new Sequence("pep1", "GF");
1010     SequenceI pep2 = new Sequence("pep2", "GFP");
1011     dna1.createDatasetSequence();
1012     dna2.createDatasetSequence();
1013     pep1.createDatasetSequence();
1014     pep2.createDatasetSequence();
1015
1016     List<AlignedCodonFrame> mappings = new ArrayList<AlignedCodonFrame>();
1017     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1018             new int[] { 1, 2 }, 3, 1);
1019     AlignedCodonFrame acf = new AlignedCodonFrame();
1020     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
1021     mappings.add(acf);
1022     map = new MapList(new int[] { 1, 3, 7, 9, 13, 15 }, new int[] { 1, 3 },
1023             3, 1);
1024     acf = new AlignedCodonFrame();
1025     acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
1026     mappings.add(acf);
1027
1028     AlignmentI exons = AlignmentUtils.makeExonAlignment(new SequenceI[] {
1029         dna1, dna2 }, mappings);
1030     assertEquals(2, exons.getSequences().size());
1031     assertEquals("GGGTTT", exons.getSequenceAt(0).getSequenceAsString());
1032     assertEquals("GGGTTTCCC", exons.getSequenceAt(1).getSequenceAsString());
1033
1034     /*
1035      * Verify updated mappings
1036      */
1037     assertEquals(2, mappings.size());
1038
1039     /*
1040      * Mapping from pep1 to GGGTTT in first new exon sequence
1041      */
1042     List<AlignedCodonFrame> pep1Mapping = MappingUtils
1043             .findMappingsForSequence(pep1, mappings);
1044     assertEquals(1, pep1Mapping.size());
1045     // map G to GGG
1046     SearchResults sr = MappingUtils.buildSearchResults(pep1, 1, mappings);
1047     assertEquals(1, sr.getResults().size());
1048     Match m = sr.getResults().get(0);
1049     assertEquals(exons.getSequenceAt(0).getDatasetSequence(),
1050             m.getSequence());
1051     assertEquals(1, m.getStart());
1052     assertEquals(3, m.getEnd());
1053     // map F to TTT
1054     sr = MappingUtils.buildSearchResults(pep1, 2, mappings);
1055     m = sr.getResults().get(0);
1056     assertEquals(exons.getSequenceAt(0).getDatasetSequence(),
1057             m.getSequence());
1058     assertEquals(4, m.getStart());
1059     assertEquals(6, m.getEnd());
1060
1061     /*
1062      * Mapping from pep2 to GGGTTTCCC in second new exon sequence
1063      */
1064     List<AlignedCodonFrame> pep2Mapping = MappingUtils
1065             .findMappingsForSequence(pep2, mappings);
1066     assertEquals(1, pep2Mapping.size());
1067     // map G to GGG
1068     sr = MappingUtils.buildSearchResults(pep2, 1, mappings);
1069     assertEquals(1, sr.getResults().size());
1070     m = sr.getResults().get(0);
1071     assertEquals(exons.getSequenceAt(1).getDatasetSequence(),
1072             m.getSequence());
1073     assertEquals(1, m.getStart());
1074     assertEquals(3, m.getEnd());
1075     // map F to TTT
1076     sr = MappingUtils.buildSearchResults(pep2, 2, mappings);
1077     m = sr.getResults().get(0);
1078     assertEquals(exons.getSequenceAt(1).getDatasetSequence(),
1079             m.getSequence());
1080     assertEquals(4, m.getStart());
1081     assertEquals(6, m.getEnd());
1082     // map P to CCC
1083     sr = MappingUtils.buildSearchResults(pep2, 3, mappings);
1084     m = sr.getResults().get(0);
1085     assertEquals(exons.getSequenceAt(1).getDatasetSequence(),
1086             m.getSequence());
1087     assertEquals(7, m.getStart());
1088     assertEquals(9, m.getEnd());
1089   }
1090
1091   /**
1092    * Test the method that makes an exon-only sequence from a DNA sequence and
1093    * its product mapping. Test includes the expected case that the DNA sequence
1094    * already has a protein product (Uniprot translation) which in turn has an
1095    * x-ref to the EMBLCDS record.
1096    */
1097   @Test(groups = { "Functional" })
1098   public void testMakeExonSequences()
1099   {
1100     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
1101     SequenceI pep1 = new Sequence("pep1", "GF");
1102     dna1.createDatasetSequence();
1103     pep1.createDatasetSequence();
1104     pep1.getDatasetSequence().addDBRef(
1105             new DBRefEntry("EMBLCDS", "2", "A12345"));
1106
1107     /*
1108      * Make the mapping from dna to protein. The protein sequence has a DBRef to
1109      * EMBLCDS|A12345.
1110      */
1111     Set<AlignedCodonFrame> mappings = new HashSet<AlignedCodonFrame>();
1112     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1113             new int[] { 1, 2 }, 3, 1);
1114     AlignedCodonFrame acf = new AlignedCodonFrame();
1115     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
1116     mappings.add(acf);
1117
1118     AlignedCodonFrame newMapping = new AlignedCodonFrame();
1119     List<SequenceI> exons = AlignmentUtils.makeExonSequences(dna1, acf,
1120             newMapping);
1121     assertEquals(1, exons.size());
1122     SequenceI exon = exons.get(0);
1123
1124     assertEquals("GGGTTT", exon.getSequenceAsString());
1125     assertEquals("dna1|A12345", exon.getName());
1126     assertEquals(1, exon.getDBRef().length);
1127     DBRefEntry cdsRef = exon.getDBRef()[0];
1128     assertEquals("EMBLCDS", cdsRef.getSource());
1129     assertEquals("2", cdsRef.getVersion());
1130     assertEquals("A12345", cdsRef.getAccessionId());
1131   }
1132
1133   /**
1134    * Test the method that makes an exon-only alignment from a DNA sequence and
1135    * its product mappings, for the case where there are multiple exon mappings
1136    * to different protein products.
1137    */
1138   @Test(groups = { "Functional" })
1139   public void testMakeExonAlignment_multipleProteins()
1140   {
1141     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
1142     SequenceI pep1 = new Sequence("pep1", "GF"); // GGGTTT
1143     SequenceI pep2 = new Sequence("pep2", "KP"); // aaaccc
1144     SequenceI pep3 = new Sequence("pep3", "KF"); // aaaTTT
1145     dna1.createDatasetSequence();
1146     pep1.createDatasetSequence();
1147     pep2.createDatasetSequence();
1148     pep3.createDatasetSequence();
1149     pep1.getDatasetSequence().addDBRef(
1150             new DBRefEntry("EMBLCDS", "2", "A12345"));
1151     pep2.getDatasetSequence().addDBRef(
1152             new DBRefEntry("EMBLCDS", "3", "A12346"));
1153     pep3.getDatasetSequence().addDBRef(
1154             new DBRefEntry("EMBLCDS", "4", "A12347"));
1155
1156     /*
1157      * Make the mappings from dna to protein. Using LinkedHashset is a
1158      * convenience so results are in the input order. There is no assertion that
1159      * the generated exon sequences are in any particular order.
1160      */
1161     List<AlignedCodonFrame> mappings = new ArrayList<AlignedCodonFrame>();
1162     // map ...GGG...TTT to GF
1163     MapList map = new MapList(new int[] { 4, 6, 10, 12 },
1164             new int[] { 1, 2 }, 3, 1);
1165     AlignedCodonFrame acf = new AlignedCodonFrame();
1166     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
1167     mappings.add(acf);
1168
1169     // map aaa...ccc to KP
1170     map = new MapList(new int[] { 1, 3, 7, 9 }, new int[] { 1, 2 }, 3, 1);
1171     acf = new AlignedCodonFrame();
1172     acf.addMap(dna1.getDatasetSequence(), pep2.getDatasetSequence(), map);
1173     mappings.add(acf);
1174
1175     // map aaa......TTT to KF
1176     map = new MapList(new int[] { 1, 3, 10, 12 }, new int[] { 1, 2 }, 3, 1);
1177     acf = new AlignedCodonFrame();
1178     acf.addMap(dna1.getDatasetSequence(), pep3.getDatasetSequence(), map);
1179     mappings.add(acf);
1180
1181     /*
1182      * Create the Exon alignment; also replaces the dna-to-protein mappings with
1183      * exon-to-protein and exon-to-dna mappings
1184      */
1185     AlignmentI exal = AlignmentUtils.makeExonAlignment(
1186             new SequenceI[] { dna1 }, mappings);
1187
1188     /*
1189      * Verify we have 3 exon sequences, mapped to pep1/2/3 respectively
1190      */
1191     List<SequenceI> exons = exal.getSequences();
1192     assertEquals(3, exons.size());
1193
1194     SequenceI exon = exons.get(0);
1195     assertEquals("GGGTTT", exon.getSequenceAsString());
1196     assertEquals("dna1|A12345", exon.getName());
1197     assertEquals(1, exon.getDBRef().length);
1198     DBRefEntry cdsRef = exon.getDBRef()[0];
1199     assertEquals("EMBLCDS", cdsRef.getSource());
1200     assertEquals("2", cdsRef.getVersion());
1201     assertEquals("A12345", cdsRef.getAccessionId());
1202
1203     exon = exons.get(1);
1204     assertEquals("aaaccc", exon.getSequenceAsString());
1205     assertEquals("dna1|A12346", exon.getName());
1206     assertEquals(1, exon.getDBRef().length);
1207     cdsRef = exon.getDBRef()[0];
1208     assertEquals("EMBLCDS", cdsRef.getSource());
1209     assertEquals("3", cdsRef.getVersion());
1210     assertEquals("A12346", cdsRef.getAccessionId());
1211
1212     exon = exons.get(2);
1213     assertEquals("aaaTTT", exon.getSequenceAsString());
1214     assertEquals("dna1|A12347", exon.getName());
1215     assertEquals(1, exon.getDBRef().length);
1216     cdsRef = exon.getDBRef()[0];
1217     assertEquals("EMBLCDS", cdsRef.getSource());
1218     assertEquals("4", cdsRef.getVersion());
1219     assertEquals("A12347", cdsRef.getAccessionId());
1220
1221     /*
1222      * Verify there are mappings from each exon sequence to its protein product
1223      * and also to its dna source
1224      */
1225     Iterator<AlignedCodonFrame> newMappingsIterator = mappings.iterator();
1226
1227     // mappings for dna1 - exon1 - pep1
1228     AlignedCodonFrame exonMapping = newMappingsIterator.next();
1229     List<Mapping> dnaMappings = exonMapping.getMappingsForSequence(dna1);
1230     assertEquals(1, dnaMappings.size());
1231     assertSame(exons.get(0).getDatasetSequence(), dnaMappings.get(0)
1232             .getTo());
1233     assertEquals("G(1) in CDS should map to G(4) in DNA", 4, dnaMappings
1234             .get(0).getMap().getToPosition(1));
1235     List<Mapping> peptideMappings = exonMapping
1236             .getMappingsForSequence(pep1);
1237     assertEquals(1, peptideMappings.size());
1238     assertSame(pep1.getDatasetSequence(), peptideMappings.get(0).getTo());
1239
1240     // mappings for dna1 - exon2 - pep2
1241     exonMapping = newMappingsIterator.next();
1242     dnaMappings = exonMapping.getMappingsForSequence(dna1);
1243     assertEquals(1, dnaMappings.size());
1244     assertSame(exons.get(1).getDatasetSequence(), dnaMappings.get(0)
1245             .getTo());
1246     assertEquals("c(4) in CDS should map to c(7) in DNA", 7, dnaMappings
1247             .get(0).getMap().getToPosition(4));
1248     peptideMappings = exonMapping.getMappingsForSequence(pep2);
1249     assertEquals(1, peptideMappings.size());
1250     assertSame(pep2.getDatasetSequence(), peptideMappings.get(0).getTo());
1251
1252     // mappings for dna1 - exon3 - pep3
1253     exonMapping = newMappingsIterator.next();
1254     dnaMappings = exonMapping.getMappingsForSequence(dna1);
1255     assertEquals(1, dnaMappings.size());
1256     assertSame(exons.get(2).getDatasetSequence(), dnaMappings.get(0)
1257             .getTo());
1258     assertEquals("T(4) in CDS should map to T(10) in DNA", 10, dnaMappings
1259             .get(0).getMap().getToPosition(4));
1260     peptideMappings = exonMapping.getMappingsForSequence(pep3);
1261     assertEquals(1, peptideMappings.size());
1262     assertSame(pep3.getDatasetSequence(), peptideMappings.get(0).getTo());
1263   }
1264
1265   @Test(groups = { "Functional" })
1266   public void testIsMappable()
1267   {
1268     SequenceI dna1 = new Sequence("dna1", "cgCAGtgGT");
1269     SequenceI aa1 = new Sequence("aa1", "RSG");
1270     AlignmentI al1 = new Alignment(new SequenceI[] { dna1 });
1271     AlignmentI al2 = new Alignment(new SequenceI[] { aa1 });
1272
1273     assertFalse(AlignmentUtils.isMappable(null, null));
1274     assertFalse(AlignmentUtils.isMappable(al1, null));
1275     assertFalse(AlignmentUtils.isMappable(null, al1));
1276     assertFalse(AlignmentUtils.isMappable(al1, al1));
1277     assertFalse(AlignmentUtils.isMappable(al2, al2));
1278
1279     assertTrue(AlignmentUtils.isMappable(al1, al2));
1280     assertTrue(AlignmentUtils.isMappable(al2, al1));
1281   }
1282
1283   /**
1284    * Test creating a mapping when the sequences involved do not start at residue
1285    * 1
1286    * 
1287    * @throws IOException
1288    */
1289   @Test(groups = { "Functional" })
1290   public void testMapProteinSequenceToCdna_forSubsequence()
1291           throws IOException
1292   {
1293     SequenceI prot = new Sequence("UNIPROT|V12345", "E-I--Q", 10, 12);
1294     prot.createDatasetSequence();
1295
1296     SequenceI dna = new Sequence("EMBL|A33333", "GAA--AT-C-CAG", 40, 48);
1297     dna.createDatasetSequence();
1298
1299     MapList map = AlignmentUtils.mapProteinSequenceToCdna(prot, dna);
1300     assertEquals(10, map.getToLowest());
1301     assertEquals(12, map.getToHighest());
1302     assertEquals(40, map.getFromLowest());
1303     assertEquals(48, map.getFromHighest());
1304   }
1305
1306   /**
1307    * Test for the alignSequenceAs method where we have protein mapped to protein
1308    */
1309   @Test(groups = { "Functional" })
1310   public void testAlignSequenceAs_mappedProteinProtein()
1311   {
1312   
1313     SequenceI alignMe = new Sequence("Match", "MGAASEV");
1314     alignMe.createDatasetSequence();
1315     SequenceI alignFrom = new Sequence("Query", "LQTGYMGAASEVMFSPTRR");
1316     alignFrom.createDatasetSequence();
1317
1318     AlignedCodonFrame acf = new AlignedCodonFrame();
1319     // this is like a domain or motif match of part of a peptide sequence
1320     MapList map = new MapList(new int[] { 6, 12 }, new int[] { 1, 7 }, 1, 1);
1321     acf.addMap(alignFrom.getDatasetSequence(),
1322             alignMe.getDatasetSequence(), map);
1323     
1324     AlignmentUtils.alignSequenceAs(alignMe, alignFrom, acf, "-", '-', true,
1325             true);
1326     assertEquals("-----MGAASEV-------", alignMe.getSequenceAsString());
1327   }
1328
1329   /**
1330    * Test for the alignSequenceAs method where there are trailing unmapped
1331    * residues in the model sequence
1332    */
1333   @Test(groups = { "Functional" })
1334   public void testAlignSequenceAs_withTrailingPeptide()
1335   {
1336     // map first 3 codons to KPF; G is a trailing unmapped residue
1337     MapList map = new MapList(new int[] { 1, 9 }, new int[] { 1, 3 }, 3, 1);
1338   
1339     checkAlignSequenceAs("AAACCCTTT", "K-PFG", true, true, map,
1340             "AAA---CCCTTT---");
1341   }
1342 }