JAL-1636 translate stop codon as '*', mouseover * as STOP
[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
24 import static org.testng.AssertJUnit.assertEquals;
25 import static org.testng.AssertJUnit.assertFalse;
26 import static org.testng.AssertJUnit.assertNull;
27 import static org.testng.AssertJUnit.assertSame;
28 import static org.testng.AssertJUnit.assertTrue;
29
30 import jalview.datamodel.AlignedCodonFrame;
31 import jalview.datamodel.Alignment;
32 import jalview.datamodel.AlignmentAnnotation;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.Annotation;
35 import jalview.datamodel.DBRefEntry;
36 import jalview.datamodel.Mapping;
37 import jalview.datamodel.SearchResults;
38 import jalview.datamodel.SearchResults.Match;
39 import jalview.datamodel.Sequence;
40 import jalview.datamodel.SequenceI;
41 import jalview.io.AppletFormatAdapter;
42 import jalview.io.FormatAdapter;
43 import jalview.util.MapList;
44 import jalview.util.MappingUtils;
45
46 import java.io.IOException;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.Collections;
50 import java.util.HashSet;
51 import java.util.Iterator;
52 import java.util.LinkedHashSet;
53 import java.util.List;
54 import java.util.Map;
55 import java.util.Set;
56
57 import org.testng.annotations.Test;
58
59 public class AlignmentUtilsTests
60 {
61   // @formatter:off
62   private static final String TEST_DATA = 
63           "# STOCKHOLM 1.0\n" +
64           "#=GS D.melanogaster.1 AC AY119185.1/838-902\n" +
65           "#=GS D.melanogaster.2 AC AC092237.1/57223-57161\n" +
66           "#=GS D.melanogaster.3 AC AY060611.1/560-627\n" +
67           "D.melanogaster.1          G.AGCC.CU...AUGAUCGA\n" +
68           "#=GR D.melanogaster.1 SS  ................((((\n" +
69           "D.melanogaster.2          C.AUUCAACU.UAUGAGGAU\n" +
70           "#=GR D.melanogaster.2 SS  ................((((\n" +
71           "D.melanogaster.3          G.UGGCGCU..UAUGACGCA\n" +
72           "#=GR D.melanogaster.3 SS  (.(((...(....(((((((\n" +
73           "//";
74
75   private static final String AA_SEQS_1 = 
76           ">Seq1Name\n" +
77           "K-QY--L\n" +
78           ">Seq2Name\n" +
79           "-R-FP-W-\n";
80
81   private static final String CDNA_SEQS_1 = 
82           ">Seq1Name\n" +
83           "AC-GG--CUC-CAA-CT\n" +
84           ">Seq2Name\n" +
85           "-CG-TTA--ACG---AAGT\n";
86
87   private static final String CDNA_SEQS_2 = 
88           ">Seq1Name\n" +
89           "GCTCGUCGTACT\n" +
90           ">Seq2Name\n" +
91           "GGGTCAGGCAGT\n";
92   // @formatter:on
93
94   // public static Sequence ts=new
95   // Sequence("short","ASDASDASDASDASDASDASDASDASDASDASDASDASD");
96   public static Sequence ts = new Sequence("short",
97           "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm");
98
99   @Test(groups ={ "Functional" })
100   public void testExpandContext()
101   {
102     AlignmentI al = new Alignment(new Sequence[] {});
103     for (int i = 4; i < 14; i += 2)
104     {
105       SequenceI s1=ts.deriveSequence().getSubSequence(i, i+7);
106       al.addSequence(s1);
107     }
108     System.out.println(new AppletFormatAdapter().formatSequences("Clustal", al, true));
109     for (int flnk=-1;flnk<25; flnk++)
110     {
111       AlignmentI exp = AlignmentUtils.expandContext(al, flnk);
112       System.out.println("\nFlank size: " + flnk);
113       System.out.println(new AppletFormatAdapter().formatSequences(
114               "Clustal", exp, true));
115       if (flnk == -1)
116       {
117         /*
118          * Full expansion to complete sequences
119          */
120         for (SequenceI sq : exp.getSequences())
121         {
122           String ung = sq.getSequenceAsString().replaceAll("-+", "");
123           final String errorMsg = "Flanking sequence not the same as original dataset sequence.\n"
124                   + ung
125                   + "\n"
126                   + sq.getDatasetSequence().getSequenceAsString();
127           assertTrue(errorMsg, ung.equalsIgnoreCase(sq.getDatasetSequence()
128                   .getSequenceAsString()));
129         }
130       }
131       else if (flnk == 24)
132       {
133         /*
134          * Last sequence is fully expanded, others have leading gaps to match
135          */
136         assertTrue(exp.getSequenceAt(4).getSequenceAsString()
137                 .startsWith("abc"));
138         assertTrue(exp.getSequenceAt(3).getSequenceAsString()
139                 .startsWith("--abc"));
140         assertTrue(exp.getSequenceAt(2).getSequenceAsString()
141                 .startsWith("----abc"));
142         assertTrue(exp.getSequenceAt(1).getSequenceAsString()
143                 .startsWith("------abc"));
144         assertTrue(exp.getSequenceAt(0).getSequenceAsString()
145                 .startsWith("--------abc"));
146       }
147     }
148   }
149
150   /**
151    * Test that annotations are correctly adjusted by expandContext
152    */
153   @Test(groups ={ "Functional" })
154   public void testExpandContext_annotation()
155   {
156     AlignmentI al = new Alignment(new Sequence[]
157     {});
158     SequenceI ds = new Sequence("Seq1", "ABCDEFGHI");
159     // subsequence DEF:
160     SequenceI seq1 = ds.deriveSequence().getSubSequence(3, 6);
161     al.addSequence(seq1);
162
163     /*
164      * Annotate DEF with 4/5/6 respectively
165      */
166     Annotation[] anns = new Annotation[]
167     { new Annotation(4), new Annotation(5), new Annotation(6) };
168     AlignmentAnnotation ann = new AlignmentAnnotation("SS",
169             "secondary structure", anns);
170     seq1.addAlignmentAnnotation(ann);
171
172     /*
173      * The annotations array should match aligned positions
174      */
175     assertEquals(3, ann.annotations.length);
176     assertEquals(4, ann.annotations[0].value, 0.001);
177     assertEquals(5, ann.annotations[1].value, 0.001);
178     assertEquals(6, ann.annotations[2].value, 0.001);
179
180     /*
181      * Check annotation to sequence position mappings before expanding the
182      * sequence; these are set up in Sequence.addAlignmentAnnotation ->
183      * Annotation.setSequenceRef -> createSequenceMappings
184      */
185     assertNull(ann.getAnnotationForPosition(1));
186     assertNull(ann.getAnnotationForPosition(2));
187     assertNull(ann.getAnnotationForPosition(3));
188     assertEquals(4, ann.getAnnotationForPosition(4).value, 0.001);
189     assertEquals(5, ann.getAnnotationForPosition(5).value, 0.001);
190     assertEquals(6, ann.getAnnotationForPosition(6).value, 0.001);
191     assertNull(ann.getAnnotationForPosition(7));
192     assertNull(ann.getAnnotationForPosition(8));
193     assertNull(ann.getAnnotationForPosition(9));
194
195     /*
196      * Expand the subsequence to the full sequence abcDEFghi
197      */
198     AlignmentI expanded = AlignmentUtils.expandContext(al, -1);
199     assertEquals("abcDEFghi", expanded.getSequenceAt(0)
200             .getSequenceAsString());
201
202     /*
203      * Confirm the alignment and sequence have the same SS annotation,
204      * referencing the expanded sequence
205      */
206     ann = expanded.getSequenceAt(0).getAnnotation()[0];
207     assertSame(ann, expanded.getAlignmentAnnotation()[0]);
208     assertSame(expanded.getSequenceAt(0), ann.sequenceRef);
209
210     /*
211      * The annotations array should have null values except for annotated
212      * positions
213      */
214     assertNull(ann.annotations[0]);
215     assertNull(ann.annotations[1]);
216     assertNull(ann.annotations[2]);
217     assertEquals(4, ann.annotations[3].value, 0.001);
218     assertEquals(5, ann.annotations[4].value, 0.001);
219     assertEquals(6, ann.annotations[5].value, 0.001);
220     assertNull(ann.annotations[6]);
221     assertNull(ann.annotations[7]);
222     assertNull(ann.annotations[8]);
223
224     /*
225      * sequence position mappings should be unchanged
226      */
227     assertNull(ann.getAnnotationForPosition(1));
228     assertNull(ann.getAnnotationForPosition(2));
229     assertNull(ann.getAnnotationForPosition(3));
230     assertEquals(4, ann.getAnnotationForPosition(4).value, 0.001);
231     assertEquals(5, ann.getAnnotationForPosition(5).value, 0.001);
232     assertEquals(6, ann.getAnnotationForPosition(6).value, 0.001);
233     assertNull(ann.getAnnotationForPosition(7));
234     assertNull(ann.getAnnotationForPosition(8));
235     assertNull(ann.getAnnotationForPosition(9));
236   }
237
238   /**
239    * Test method that returns a map of lists of sequences by sequence name.
240    * 
241    * @throws IOException
242    */
243   @Test(groups ={ "Functional" })
244   public void testGetSequencesByName() throws IOException
245   {
246     final String data = ">Seq1Name\nKQYL\n" + ">Seq2Name\nRFPW\n"
247             + ">Seq1Name\nABCD\n";
248     AlignmentI al = loadAlignment(data, "FASTA");
249     Map<String, List<SequenceI>> map = AlignmentUtils
250             .getSequencesByName(al);
251     assertEquals(2, map.keySet().size());
252     assertEquals(2, map.get("Seq1Name").size());
253     assertEquals("KQYL", map.get("Seq1Name").get(0).getSequenceAsString());
254     assertEquals("ABCD", map.get("Seq1Name").get(1).getSequenceAsString());
255     assertEquals(1, map.get("Seq2Name").size());
256     assertEquals("RFPW", map.get("Seq2Name").get(0).getSequenceAsString());
257   }
258   /**
259    * Helper method to load an alignment and ensure dataset sequences are set up.
260    * 
261    * @param data
262    * @param format TODO
263    * @return
264    * @throws IOException
265    */
266   protected AlignmentI loadAlignment(final String data, String format) 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 testMapProteinToCdna_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.mapProteinToCdna(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(
309             protein.getSequenceAt(0)).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[]
319     { 1, 9 }, mapList.getFromRanges().get(0)));
320     assertEquals(1, mapList.getFromRanges().size());
321     assertTrue(Arrays.equals(new int[]
322     { 1, 3 }, 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[]
348     { 1, 6 }, new int[]
349     { 1, 2 }, 3, 1);
350
351     /*
352      * No existing gaps in dna:
353      */
354     checkAlignSequenceAs("GGGAAA", "-A-L-", false, false, map,
355             "---GGG---AAA");
356
357     /*
358      * Now introduce gaps in dna but ignore them when realigning.
359      */
360     checkAlignSequenceAs("-G-G-G-A-A-A-", "-A-L-", false, false, map,
361             "---GGG---AAA");
362
363     /*
364      * Now include gaps in dna when realigning. First retaining 'mapped' gaps
365      * only, i.e. those within the exon region.
366      */
367     checkAlignSequenceAs("-G-G--G-A--A-A-", "-A-L-", true, false, map,
368             "---G-G--G---A--A-A");
369
370     /*
371      * Include all gaps in dna when realigning (within and without the exon
372      * region). The leading gap, and the gaps between codons, are subsumed by
373      * the protein alignment gap.
374      */
375     checkAlignSequenceAs("-G-GG--AA-A-", "-A-L-", true, true, map,
376             "---G-GG---AA-A-");
377
378     /*
379      * Include only unmapped gaps in dna when realigning (outside the exon
380      * region). The leading gap, and the gaps between codons, are subsumed by
381      * the protein alignment gap.
382      */
383     checkAlignSequenceAs("-G-GG--AA-A-", "-A-L-", false, true, map,
384             "---GGG---AAA-");
385   }
386
387   /**
388    * Test for the alignSequenceAs method that takes two sequences and a mapping.
389    */
390   @Test(groups ={ "Functional" })
391   public void testAlignSequenceAs_withMapping_withIntrons()
392   {
393     /*
394      * Exons at codon 2 (AAA) and 4 (TTT)
395      */
396     MapList map = new MapList(new int[]
397     { 4, 6, 10, 12 }, new int[]
398     { 1, 2 }, 3, 1);
399
400     /*
401      * Simple case: no gaps in dna
402      */
403     checkAlignSequenceAs("GGGAAACCCTTTGGG", "--A-L-", false, false, map,
404             "GGG---AAACCCTTTGGG");
405
406     /*
407      * Add gaps to dna - but ignore when realigning.
408      */
409     checkAlignSequenceAs("-G-G-G--A--A---AC-CC-T-TT-GG-G-", "--A-L-",
410             false, false, map, "GGG---AAACCCTTTGGG");
411
412     /*
413      * Add gaps to dna - include within exons only when realigning.
414      */
415     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
416             true, false, map, "GGG---A--A---ACCCT-TTGGG");
417
418     /*
419      * Include gaps outside exons only when realigning.
420      */
421     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
422             false, true, map, "-G-G-GAAAC-CCTTT-GG-G-");
423
424     /*
425      * Include gaps following first intron if we are 'preserving mapped gaps'
426      */
427     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
428             true, true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
429
430     /*
431      * Include all gaps in dna when realigning.
432      */
433     checkAlignSequenceAs("-G-G-G--A--A---A-C-CC-T-TT-GG-G-", "--A-L-",
434             true, true, map, "-G-G-G--A--A---A-C-CC-T-TT-GG-G-");
435   }
436
437   /**
438    * Test for the case where not all of the protein sequence is mapped to cDNA.
439    */
440   @Test(groups ={ "Functional" })
441   public void testAlignSequenceAs_withMapping_withUnmappedProtein()
442   {
443     
444     /*
445      * Exons at codon 2 (AAA) and 4 (TTT) mapped to A and P
446      */
447     final MapList map = new MapList(new int[]
448     { 4, 6, 10, 12 }, new int[]
449     { 1, 1, 3, 3 }, 3, 1);
450     
451
452     /*
453      * Expect alignment does nothing (aborts realignment). Change this test
454      * first if different behaviour wanted.
455      */
456     checkAlignSequenceAs("GGGAAACCCTTTGGG", "-A-L-P-", false,
457             false, map, "GGGAAACCCTTTGGG");
458   }
459
460   /**
461    * Helper method that performs and verifies the method under test.
462    * 
463    * @param dnaSeq
464    * @param proteinSeq
465    * @param preserveMappedGaps
466    * @param preserveUnmappedGaps
467    * @param map
468    * @param expected
469    */
470   protected void checkAlignSequenceAs(final String dnaSeq,
471           final String proteinSeq, final boolean preserveMappedGaps,
472           final boolean preserveUnmappedGaps, MapList map,
473           final String expected)
474   {
475     SequenceI dna = new Sequence("Seq1", dnaSeq);
476     dna.createDatasetSequence();
477     SequenceI protein = new Sequence("Seq1", proteinSeq);
478     protein.createDatasetSequence();
479     AlignedCodonFrame acf = new AlignedCodonFrame();
480     acf.addMap(dna.getDatasetSequence(), protein.getDatasetSequence(), map);
481
482     AlignmentUtils.alignSequenceAs(dna, protein, acf, "---", '-',
483             preserveMappedGaps, preserveUnmappedGaps);
484     assertEquals(expected, dna.getSequenceAsString());
485   }
486
487   /**
488    * Test for the alignSequenceAs method where we preserve gaps in introns only.
489    */
490   @Test(groups ={ "Functional" })
491   public void testAlignSequenceAs_keepIntronGapsOnly()
492   {
493
494     /*
495      * Intron GGGAAA followed by exon CCCTTT
496      */
497     MapList map = new MapList(new int[]
498     { 7, 12 }, new int[]
499     { 1, 2 }, 3, 1);
500     
501     checkAlignSequenceAs("GG-G-AA-A-C-CC-T-TT", "AL",
502             false, true, map, "GG-G-AA-ACCCTTT");
503   }
504
505   /**
506    * Test for the method that generates an aligned translated sequence from one
507    * mapping.
508    */
509   @Test(groups ={ "Functional" })
510   public void testGetAlignedTranslation_dnaLikeProtein()
511   {
512     // dna alignment will be replaced
513     SequenceI dna = new Sequence("Seq1", "T-G-CC-A--T-TAC-CAG-");
514     dna.createDatasetSequence();
515     // protein alignment will be 'applied' to dna
516     SequenceI protein = new Sequence("Seq1", "-CH-Y--Q-");
517     protein.createDatasetSequence();
518     MapList map = new MapList(new int[]
519     { 1, 12 }, new int[]
520     { 1, 4 }, 3, 1);
521     AlignedCodonFrame acf = new AlignedCodonFrame();
522     acf.addMap(dna.getDatasetSequence(), protein.getDatasetSequence(), map);
523
524     final SequenceI aligned = AlignmentUtils
525                 .getAlignedTranslation(protein, '-', acf);
526     assertEquals("---TGCCAT---TAC------CAG---", aligned.getSequenceAsString());
527     assertSame(aligned.getDatasetSequence(), dna.getDatasetSequence());
528   }
529
530   /**
531    * Test the method that realigns protein to match mapped codon alignment.
532    */
533   @Test(groups ={ "Functional" })
534   public void testAlignProteinAsDna()
535   {
536     // seq1 codons are [1,2,3] [4,5,6] [7,8,9] [10,11,12]
537     SequenceI dna1 = new Sequence("Seq1", "TGCCATTACCAG-");
538     // seq2 codons are [1,3,4] [5,6,7] [8,9,10] [11,12,13]
539     SequenceI dna2 = new Sequence("Seq2", "T-GCCATTACCAG");
540     // seq3 codons are [1,2,3] [4,5,7] [8,9,10] [11,12,13]
541     SequenceI dna3 = new Sequence("Seq3", "TGCCA-TTACCAG");
542     AlignmentI dna = new Alignment(new SequenceI[]
543     { dna1, dna2, dna3 });
544     dna.setDataset(null);
545
546     // protein alignment will be realigned like dna
547     SequenceI prot1 = new Sequence("Seq1", "CHYQ");
548     SequenceI prot2 = new Sequence("Seq2", "CHYQ");
549     SequenceI prot3 = new Sequence("Seq3", "CHYQ");
550     AlignmentI protein = new Alignment(new SequenceI[]
551     { prot1, prot2, prot3 });
552     protein.setDataset(null);
553
554     MapList map = new MapList(new int[]
555     { 1, 12 }, new int[]
556     { 1, 4 }, 3, 1);
557     AlignedCodonFrame acf = new AlignedCodonFrame();
558     acf.addMap(dna1.getDatasetSequence(), prot1.getDatasetSequence(), map);
559     acf.addMap(dna2.getDatasetSequence(), prot2.getDatasetSequence(), map);
560     acf.addMap(dna3.getDatasetSequence(), prot3.getDatasetSequence(), map);
561     protein.setCodonFrames(Collections.singleton(acf));
562
563     /*
564      * Translated codon order is [1,2,3] [1,3,4] [4,5,6] [4,5,7] [5,6,7] [7,8,9]
565      * [8,9,10] [10,11,12] [11,12,13]
566      */
567     AlignmentUtils.alignProteinAsDna(protein, dna);
568     assertEquals("C-H--Y-Q-", prot1.getSequenceAsString());
569     assertEquals("-C--H-Y-Q", prot2.getSequenceAsString());
570     assertEquals("C--H--Y-Q", prot3.getSequenceAsString());
571   }
572
573   /**
574    * Test the method that tests whether a CDNA sequence translates to a protein
575    * sequence
576    */
577   @Test(groups ={ "Functional" })
578   public void testTranslatesAs()
579   {
580     assertTrue(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(), 0,
581             "FPKG".toCharArray()));
582     // with start codon (not in protein)
583     assertTrue(AlignmentUtils.translatesAs("atgtttcccaaaggg".toCharArray(),
584             3, "FPKG".toCharArray()));
585     // with stop codon1 (not in protein)
586     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtaa".toCharArray(),
587             0, "FPKG".toCharArray()));
588     // with stop codon1 (in protein as *)
589     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtaa".toCharArray(),
590             0, "FPKG*".toCharArray()));
591     // with stop codon2 (not in protein)
592     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtag".toCharArray(),
593             0, "FPKG".toCharArray()));
594     // with stop codon3 (not in protein)
595     assertTrue(AlignmentUtils.translatesAs("tttcccaaagggtga".toCharArray(),
596             0, "FPKG".toCharArray()));
597     // with start and stop codon1
598     assertTrue(AlignmentUtils.translatesAs(
599             "atgtttcccaaagggtaa".toCharArray(), 3, "FPKG".toCharArray()));
600     // with start and stop codon1 (in protein as *)
601     assertTrue(AlignmentUtils.translatesAs(
602             "atgtttcccaaagggtaa".toCharArray(), 3, "FPKG*".toCharArray()));
603     // with start and stop codon2
604     assertTrue(AlignmentUtils.translatesAs(
605             "atgtttcccaaagggtag".toCharArray(), 3, "FPKG".toCharArray()));
606     // with start and stop codon3
607     assertTrue(AlignmentUtils.translatesAs(
608             "atgtttcccaaagggtga".toCharArray(), 3, "FPKG".toCharArray()));
609
610     // with embedded stop codon
611     assertTrue(AlignmentUtils.translatesAs(
612             "atgtttTAGcccaaaTAAgggtga".toCharArray(), 3,
613             "F*PK*G".toCharArray()));
614
615     // wrong protein
616     assertFalse(AlignmentUtils.translatesAs("tttcccaaaggg".toCharArray(),
617             0,
618             "FPMG".toCharArray()));
619   }
620
621   /**
622    * Test mapping of protein to cDNA, for cases where the cDNA has start and/or
623    * stop codons in addition to the protein coding sequence.
624    * 
625    * @throws IOException
626    */
627   @Test(groups ={ "Functional" })
628   public void testMapProteinToCdna_withStartAndStopCodons()
629           throws IOException
630   {
631     List<SequenceI> protseqs = new ArrayList<SequenceI>();
632     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
633     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
634     protseqs.add(new Sequence("UNIPROT|V12347", "SAR"));
635     AlignmentI protein = new Alignment(protseqs.toArray(new SequenceI[3]));
636     protein.setDataset(null);
637   
638     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
639     // start + SAR:
640     dnaseqs.add(new Sequence("EMBL|A11111", "ATGTCAGCACGC"));
641     // = EIQ + stop
642     dnaseqs.add(new Sequence("EMBL|A22222", "GAGATACAATAA"));
643     // = start +EIQ + stop
644     dnaseqs.add(new Sequence("EMBL|A33333", "ATGGAAATCCAGTAG"));
645     dnaseqs.add(new Sequence("EMBL|A44444", "GAAATTCAG"));
646     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[4]));
647     cdna.setDataset(null);
648   
649     assertTrue(AlignmentUtils.mapProteinToCdna(protein, cdna));
650
651     // 3 mappings made, each from 1 to 1 sequence
652     assertEquals(3, protein.getCodonFrames().size());
653     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
654     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
655     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(2)).size());
656   
657     // V12345 mapped from A22222
658     AlignedCodonFrame acf = protein.getCodonFrame(
659             protein.getSequenceAt(0)).get(0);
660     assertEquals(1, acf.getdnaSeqs().length);
661     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
662             acf.getdnaSeqs()[0]);
663     Mapping[] protMappings = acf.getProtMappings();
664     assertEquals(1, protMappings.length);
665     MapList mapList = protMappings[0].getMap();
666     assertEquals(3, mapList.getFromRatio());
667     assertEquals(1, mapList.getToRatio());
668     assertTrue(Arrays.equals(new int[]
669     { 1, 9 }, mapList.getFromRanges().get(0)));
670     assertEquals(1, mapList.getFromRanges().size());
671     assertTrue(Arrays.equals(new int[]
672     { 1, 3 }, mapList.getToRanges().get(0)));
673     assertEquals(1, mapList.getToRanges().size());
674
675     // V12346 mapped from A33333 starting position 4
676     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
677     assertEquals(1, acf.getdnaSeqs().length);
678     assertEquals(cdna.getSequenceAt(2).getDatasetSequence(),
679             acf.getdnaSeqs()[0]);
680     protMappings = acf.getProtMappings();
681     assertEquals(1, protMappings.length);
682     mapList = protMappings[0].getMap();
683     assertEquals(3, mapList.getFromRatio());
684     assertEquals(1, mapList.getToRatio());
685     assertTrue(Arrays.equals(new int[]
686     { 4, 12 }, mapList.getFromRanges().get(0)));
687     assertEquals(1, mapList.getFromRanges().size());
688     assertTrue(Arrays.equals(new int[]
689     { 1, 3 }, mapList.getToRanges().get(0)));
690     assertEquals(1, mapList.getToRanges().size());
691   
692     // V12347 mapped to A11111 starting position 4
693     acf = protein.getCodonFrame(protein.getSequenceAt(2)).get(0);
694     assertEquals(1, acf.getdnaSeqs().length);
695     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
696             acf.getdnaSeqs()[0]);
697     protMappings = acf.getProtMappings();
698     assertEquals(1, protMappings.length);
699     mapList = protMappings[0].getMap();
700     assertEquals(3, mapList.getFromRatio());
701     assertEquals(1, mapList.getToRatio());
702     assertTrue(Arrays.equals(new int[]
703     { 4, 12 }, mapList.getFromRanges().get(0)));
704     assertEquals(1, mapList.getFromRanges().size());
705     assertTrue(Arrays.equals(new int[]
706     { 1, 3 }, mapList.getToRanges().get(0)));
707     assertEquals(1, mapList.getToRanges().size());
708   
709     // no mapping involving the 'extra' A44444
710     assertTrue(protein.getCodonFrame(cdna.getSequenceAt(3)).isEmpty());
711   }
712
713   /**
714    * Test mapping of protein to cDNA, for the case where we have some sequence
715    * cross-references. Verify that 1-to-many mappings are made where
716    * cross-references exist and sequences are mappable.
717    * 
718    * @throws IOException
719    */
720   @Test(groups ={ "Functional" })
721   public void testMapProteinToCdna_withXrefs() throws IOException
722   {
723     List<SequenceI> protseqs = new ArrayList<SequenceI>();
724     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
725     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
726     protseqs.add(new Sequence("UNIPROT|V12347", "SAR"));
727     AlignmentI protein = new Alignment(protseqs.toArray(new SequenceI[3]));
728     protein.setDataset(null);
729   
730     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
731     dnaseqs.add(new Sequence("EMBL|A11111", "TCAGCACGC")); // = SAR
732     dnaseqs.add(new Sequence("EMBL|A22222", "ATGGAGATACAA")); // = start + EIQ
733     dnaseqs.add(new Sequence("EMBL|A33333", "GAAATCCAG")); // = EIQ
734     dnaseqs.add(new Sequence("EMBL|A44444", "GAAATTCAG")); // = EIQ
735     dnaseqs.add(new Sequence("EMBL|A55555", "GAGATTCAG")); // = EIQ
736     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[5]));
737     cdna.setDataset(null);
738   
739     // Xref A22222 to V12345 (should get mapped)
740     dnaseqs.get(1).addDBRef(new DBRefEntry("UNIPROT", "1", "V12345"));
741     // Xref V12345 to A44444 (should get mapped)
742     protseqs.get(0).addDBRef(new DBRefEntry("EMBL", "1", "A44444"));
743     // Xref A33333 to V12347 (sequence mismatch - should not get mapped)
744     dnaseqs.get(2).addDBRef(new DBRefEntry("UNIPROT", "1", "V12347"));
745     // as V12345 is mapped to A22222 and A44444, this leaves V12346 unmapped.
746     // it should get paired up with the unmapped A33333
747     // A11111 should be mapped to V12347
748     // A55555 is spare and has no xref so is not mapped
749
750     assertTrue(AlignmentUtils.mapProteinToCdna(protein, cdna));
751
752     // 4 protein mappings made for 3 proteins, 2 to V12345, 1 each to V12346/7
753     assertEquals(3, protein.getCodonFrames().size());
754     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
755     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
756     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(2)).size());
757
758     // one mapping for each of the first 4 cDNA sequences
759     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(0)).size());
760     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(1)).size());
761     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(2)).size());
762     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(3)).size());
763   
764     // V12345 mapped to A22222 and A44444
765     AlignedCodonFrame acf = protein.getCodonFrame(
766             protein.getSequenceAt(0)).get(0);
767     assertEquals(2, acf.getdnaSeqs().length);
768     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
769             acf.getdnaSeqs()[0]);
770     assertEquals(cdna.getSequenceAt(3).getDatasetSequence(),
771             acf.getdnaSeqs()[1]);
772   
773     // V12346 mapped to A33333
774     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
775     assertEquals(1, acf.getdnaSeqs().length);
776     assertEquals(cdna.getSequenceAt(2).getDatasetSequence(),
777             acf.getdnaSeqs()[0]);
778   
779     // V12347 mapped to A11111
780     acf = protein.getCodonFrame(protein.getSequenceAt(2)).get(0);
781     assertEquals(1, acf.getdnaSeqs().length);
782     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
783             acf.getdnaSeqs()[0]);
784   
785     // no mapping involving the 'extra' A55555
786     assertTrue(protein.getCodonFrame(cdna.getSequenceAt(4)).isEmpty());
787   }
788
789   /**
790    * Test mapping of protein to cDNA, for the case where we have some sequence
791    * cross-references. Verify that once we have made an xref mapping we don't
792    * also map un-xrefd sequeces.
793    * 
794    * @throws IOException
795    */
796   @Test(groups ={ "Functional" })
797   public void testMapProteinToCdna_prioritiseXrefs() throws IOException
798   {
799     List<SequenceI> protseqs = new ArrayList<SequenceI>();
800     protseqs.add(new Sequence("UNIPROT|V12345", "EIQ"));
801     protseqs.add(new Sequence("UNIPROT|V12346", "EIQ"));
802     AlignmentI protein = new Alignment(
803             protseqs.toArray(new SequenceI[protseqs.size()]));
804     protein.setDataset(null);
805   
806     List<SequenceI> dnaseqs = new ArrayList<SequenceI>();
807     dnaseqs.add(new Sequence("EMBL|A11111", "GAAATCCAG")); // = EIQ
808     dnaseqs.add(new Sequence("EMBL|A22222", "GAAATTCAG")); // = EIQ
809     AlignmentI cdna = new Alignment(dnaseqs.toArray(new SequenceI[dnaseqs
810             .size()]));
811     cdna.setDataset(null);
812   
813     // Xref A22222 to V12345 (should get mapped)
814     // A11111 should then be mapped to the unmapped V12346
815     dnaseqs.get(1).addDBRef(new DBRefEntry("UNIPROT", "1", "V12345"));
816   
817     assertTrue(AlignmentUtils.mapProteinToCdna(protein, cdna));
818   
819     // 2 protein mappings made
820     assertEquals(2, protein.getCodonFrames().size());
821     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(0)).size());
822     assertEquals(1, protein.getCodonFrame(protein.getSequenceAt(1)).size());
823   
824     // one mapping for each of the cDNA sequences
825     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(0)).size());
826     assertEquals(1, protein.getCodonFrame(cdna.getSequenceAt(1)).size());
827   
828     // V12345 mapped to A22222
829     AlignedCodonFrame acf = protein.getCodonFrame(protein.getSequenceAt(0))
830             .get(0);
831     assertEquals(1, acf.getdnaSeqs().length);
832     assertEquals(cdna.getSequenceAt(1).getDatasetSequence(),
833             acf.getdnaSeqs()[0]);
834   
835     // V12346 mapped to A11111
836     acf = protein.getCodonFrame(protein.getSequenceAt(1)).get(0);
837     assertEquals(1, acf.getdnaSeqs().length);
838     assertEquals(cdna.getSequenceAt(0).getDatasetSequence(),
839             acf.getdnaSeqs()[0]);
840   }
841
842   /**
843    * Test the method that shows or hides sequence annotations by type(s) and
844    * selection group.
845    */
846   @Test(groups ={ "Functional" })
847   public void testShowOrHideSequenceAnnotations()
848   {
849     SequenceI seq1 = new Sequence("Seq1", "AAA");
850     SequenceI seq2 = new Sequence("Seq2", "BBB");
851     SequenceI seq3 = new Sequence("Seq3", "CCC");
852     Annotation[] anns = new Annotation[]
853     { new Annotation(2f) };
854     AlignmentAnnotation ann1 = new AlignmentAnnotation("Structure", "ann1",
855             anns);
856     ann1.setSequenceRef(seq1);
857     AlignmentAnnotation ann2 = new AlignmentAnnotation("Structure", "ann2",
858             anns);
859     ann2.setSequenceRef(seq2);
860     AlignmentAnnotation ann3 = new AlignmentAnnotation("Structure", "ann3",
861             anns);
862     AlignmentAnnotation ann4 = new AlignmentAnnotation("Temp", "ann4", anns);
863     ann4.setSequenceRef(seq1);
864     AlignmentAnnotation ann5 = new AlignmentAnnotation("Temp", "ann5", anns);
865     ann5.setSequenceRef(seq2);
866     AlignmentAnnotation ann6 = new AlignmentAnnotation("Temp", "ann6", anns);
867     AlignmentI al = new Alignment(new SequenceI[] {seq1, seq2, seq3});
868     al.addAnnotation(ann1); // Structure for Seq1
869     al.addAnnotation(ann2); // Structure for Seq2
870     al.addAnnotation(ann3); // Structure for no sequence
871     al.addAnnotation(ann4); // Temp for seq1
872     al.addAnnotation(ann5); // Temp for seq2
873     al.addAnnotation(ann6); // Temp for no sequence
874     List<String> types = new ArrayList<String>();
875     List<SequenceI> scope = new ArrayList<SequenceI>();
876
877     /*
878      * Set all sequence related Structure to hidden (ann1, ann2)
879      */
880     types.add("Structure");
881     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, false,
882             false);
883     assertFalse(ann1.visible);
884     assertFalse(ann2.visible);
885     assertTrue(ann3.visible); // not sequence-related, not affected
886     assertTrue(ann4.visible); // not Structure, not affected
887     assertTrue(ann5.visible); // "
888     assertTrue(ann6.visible); // not sequence-related, not affected
889
890     /*
891      * Set Temp in {seq1, seq3} to hidden
892      */
893     types.clear();
894     types.add("Temp");
895     scope.add(seq1);
896     scope.add(seq3);
897     AlignmentUtils.showOrHideSequenceAnnotations(al, types, scope, false,
898             false);
899     assertFalse(ann1.visible); // unchanged
900     assertFalse(ann2.visible); // unchanged
901     assertTrue(ann3.visible); // not sequence-related, not affected
902     assertFalse(ann4.visible); // Temp for seq1 hidden
903     assertTrue(ann5.visible); // not in scope, not affected
904     assertTrue(ann6.visible); // not sequence-related, not affected
905
906     /*
907      * Set Temp in all sequences to hidden
908      */
909     types.clear();
910     types.add("Temp");
911     scope.add(seq1);
912     scope.add(seq3);
913     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, false,
914             false);
915     assertFalse(ann1.visible); // unchanged
916     assertFalse(ann2.visible); // unchanged
917     assertTrue(ann3.visible); // not sequence-related, not affected
918     assertFalse(ann4.visible); // Temp for seq1 hidden
919     assertFalse(ann5.visible); // Temp for seq2 hidden
920     assertTrue(ann6.visible); // not sequence-related, not affected
921
922     /*
923      * Set all types in {seq1, seq3} to visible
924      */
925     types.clear();
926     scope.clear();
927     scope.add(seq1);
928     scope.add(seq3);
929     AlignmentUtils.showOrHideSequenceAnnotations(al, types, scope, true,
930             true);
931     assertTrue(ann1.visible); // Structure for seq1 set visible
932     assertFalse(ann2.visible); // not in scope, unchanged
933     assertTrue(ann3.visible); // not sequence-related, not affected
934     assertTrue(ann4.visible); // Temp for seq1 set visible
935     assertFalse(ann5.visible); // not in scope, unchanged
936     assertTrue(ann6.visible); // not sequence-related, not affected
937
938     /*
939      * Set all types in all scope to hidden
940      */
941     AlignmentUtils.showOrHideSequenceAnnotations(al, types, null, true,
942             false);
943     assertFalse(ann1.visible);
944     assertFalse(ann2.visible);
945     assertTrue(ann3.visible); // not sequence-related, not affected
946     assertFalse(ann4.visible);
947     assertFalse(ann5.visible);
948     assertTrue(ann6.visible); // not sequence-related, not affected
949   }
950
951   /**
952    * Tests for the method that checks if one sequence cross-references another
953    */
954   @Test(groups ={ "Functional" })
955   public void testHasCrossRef()
956   {
957     assertFalse(AlignmentUtils.hasCrossRef(null, null));
958     SequenceI seq1 = new Sequence("EMBL|A12345", "ABCDEF");
959     assertFalse(AlignmentUtils.hasCrossRef(seq1, null));
960     assertFalse(AlignmentUtils.hasCrossRef(null, seq1));
961     SequenceI seq2 = new Sequence("UNIPROT|V20192", "ABCDEF");
962     assertFalse(AlignmentUtils.hasCrossRef(seq1, seq2));
963   
964     // different ref
965     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "v20193"));
966     assertFalse(AlignmentUtils.hasCrossRef(seq1, seq2));
967   
968     // case-insensitive; version number is ignored
969     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "v20192"));
970     assertTrue(AlignmentUtils.hasCrossRef(seq1, seq2));
971   
972     // right case!
973     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
974     assertTrue(AlignmentUtils.hasCrossRef(seq1, seq2));
975     // test is one-way only
976     assertFalse(AlignmentUtils.hasCrossRef(seq2, seq1));
977   }
978
979   /**
980    * Tests for the method that checks if either sequence cross-references the
981    * other
982    */
983   @Test(groups ={ "Functional" })
984   public void testHaveCrossRef()
985   {
986     assertFalse(AlignmentUtils.hasCrossRef(null, null));
987     SequenceI seq1 = new Sequence("EMBL|A12345", "ABCDEF");
988     assertFalse(AlignmentUtils.haveCrossRef(seq1, null));
989     assertFalse(AlignmentUtils.haveCrossRef(null, seq1));
990     SequenceI seq2 = new Sequence("UNIPROT|V20192", "ABCDEF");
991     assertFalse(AlignmentUtils.haveCrossRef(seq1, seq2));
992   
993     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
994     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
995     // next is true for haveCrossRef, false for hasCrossRef
996     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
997   
998     // now the other way round
999     seq1.setDBRef(null);
1000     seq2.addDBRef(new DBRefEntry("EMBL", "1", "A12345"));
1001     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
1002     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
1003   
1004     // now both ways
1005     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "V20192"));
1006     assertTrue(AlignmentUtils.haveCrossRef(seq1, seq2));
1007     assertTrue(AlignmentUtils.haveCrossRef(seq2, seq1));
1008   }
1009
1010   /**
1011    * Test the method that extracts the exon-only part of a dna alignment.
1012    */
1013   @Test(groups ={ "Functional" })
1014   public void testMakeExonAlignment()
1015   {
1016     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
1017     SequenceI dna2 = new Sequence("dna2", "GGGcccTTTaaaCCC");
1018     SequenceI pep1 = new Sequence("pep1", "GF");
1019     SequenceI pep2 = new Sequence("pep2", "GFP");
1020     dna1.createDatasetSequence();
1021     dna2.createDatasetSequence();
1022     pep1.createDatasetSequence();
1023     pep2.createDatasetSequence();
1024
1025     Set<AlignedCodonFrame> mappings = new HashSet<AlignedCodonFrame>();
1026     MapList map = new MapList(new int[]
1027     { 4, 6, 10, 12 }, new int[]
1028     { 1, 2 }, 3, 1);
1029     AlignedCodonFrame acf = new AlignedCodonFrame();
1030     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
1031     mappings.add(acf);
1032     map = new MapList(new int[]
1033     { 1, 3, 7, 9, 13, 15 }, new int[]
1034     { 1, 3 }, 3, 1);
1035     acf = new AlignedCodonFrame();
1036     acf.addMap(dna2.getDatasetSequence(), pep2.getDatasetSequence(), map);
1037     mappings.add(acf);
1038     
1039     AlignmentI exons = AlignmentUtils.makeExonAlignment(new SequenceI[]
1040     { dna1, dna2 }, mappings);
1041     assertEquals(2, exons.getSequences().size());
1042     assertEquals("GGGTTT", exons.getSequenceAt(0).getSequenceAsString());
1043     assertEquals("GGGTTTCCC", exons.getSequenceAt(1).getSequenceAsString());
1044
1045     /*
1046      * Verify updated mappings
1047      */
1048     assertEquals(2, mappings.size());
1049
1050     /*
1051      * Mapping from pep1 to GGGTTT in first new exon sequence
1052      */
1053     List<AlignedCodonFrame> pep1Mapping = MappingUtils
1054             .findMappingsForSequence(pep1, mappings);
1055     assertEquals(1, pep1Mapping.size());
1056     // map G to GGG
1057     SearchResults sr = MappingUtils.buildSearchResults(pep1, 1, mappings);
1058     assertEquals(1, sr.getResults().size());
1059     Match m = sr.getResults().get(0);
1060     assertEquals(exons.getSequenceAt(0).getDatasetSequence(),
1061             m.getSequence());
1062     assertEquals(1, m.getStart());
1063     assertEquals(3, m.getEnd());
1064     // map F to TTT
1065     sr = MappingUtils.buildSearchResults(pep1, 2, mappings);
1066     m = sr.getResults().get(0);
1067     assertEquals(exons.getSequenceAt(0).getDatasetSequence(),
1068             m.getSequence());
1069     assertEquals(4, m.getStart());
1070     assertEquals(6, m.getEnd());
1071
1072     /*
1073      * Mapping from pep2 to GGGTTTCCC in second new exon sequence
1074      */
1075     List<AlignedCodonFrame> pep2Mapping = MappingUtils
1076             .findMappingsForSequence(pep2, mappings);
1077     assertEquals(1, pep2Mapping.size());
1078     // map G to GGG
1079     sr = MappingUtils.buildSearchResults(pep2, 1, mappings);
1080     assertEquals(1, sr.getResults().size());
1081     m = sr.getResults().get(0);
1082     assertEquals(exons.getSequenceAt(1).getDatasetSequence(),
1083             m.getSequence());
1084     assertEquals(1, m.getStart());
1085     assertEquals(3, m.getEnd());
1086     // map F to TTT
1087     sr = MappingUtils.buildSearchResults(pep2, 2, mappings);
1088     m = sr.getResults().get(0);
1089     assertEquals(exons.getSequenceAt(1).getDatasetSequence(),
1090             m.getSequence());
1091     assertEquals(4, m.getStart());
1092     assertEquals(6, m.getEnd());
1093     // map P to CCC
1094     sr = MappingUtils.buildSearchResults(pep2, 3, mappings);
1095     m = sr.getResults().get(0);
1096     assertEquals(exons.getSequenceAt(1).getDatasetSequence(),
1097             m.getSequence());
1098     assertEquals(7, m.getStart());
1099     assertEquals(9, m.getEnd());
1100   }
1101
1102   /**
1103    * Test the method that makes an exon-only sequence from a DNA sequence and
1104    * its product mapping. Test includes the expected case that the DNA sequence
1105    * already has a protein product (Uniprot translation) which in turn has an
1106    * x-ref to the EMBLCDS record.
1107    */
1108   @Test(groups ={ "Functional" })
1109   public void testMakeExonSequences()
1110   {
1111     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
1112     SequenceI pep1 = new Sequence("pep1", "GF");
1113     dna1.createDatasetSequence();
1114     pep1.createDatasetSequence();
1115     pep1.getDatasetSequence().addDBRef(
1116             new DBRefEntry("EMBLCDS", "2", "A12345"));
1117
1118     /*
1119      * Make the mapping from dna to protein. The protein sequence has a DBRef to
1120      * EMBLCDS|A12345.
1121      */
1122     Set<AlignedCodonFrame> mappings = new HashSet<AlignedCodonFrame>();
1123     MapList map = new MapList(new int[]
1124     { 4, 6, 10, 12 }, new int[]
1125     { 1, 2 }, 3, 1);
1126     AlignedCodonFrame acf = new AlignedCodonFrame();
1127     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
1128     mappings.add(acf);
1129
1130     AlignedCodonFrame newMapping = new AlignedCodonFrame();
1131     List<SequenceI> exons = AlignmentUtils.makeExonSequences(dna1, acf,
1132             newMapping);
1133     assertEquals(1, exons.size());
1134     SequenceI exon = exons.get(0);
1135
1136     assertEquals("GGGTTT", exon.getSequenceAsString());
1137     assertEquals("dna1|A12345", exon.getName());
1138     assertEquals(1, exon.getDBRef().length);
1139     DBRefEntry cdsRef = exon.getDBRef()[0];
1140     assertEquals("EMBLCDS", cdsRef.getSource());
1141     assertEquals("2", cdsRef.getVersion());
1142     assertEquals("A12345", cdsRef.getAccessionId());
1143   }
1144
1145   /**
1146    * Test the method that makes an exon-only alignment from a DNA sequence and
1147    * its product mappings, for the case where there are multiple exon mappings
1148    * to different protein products.
1149    */
1150   @Test(groups ={ "Functional" })
1151   public void testMakeExonAlignment_multipleProteins()
1152   {
1153     SequenceI dna1 = new Sequence("dna1", "aaaGGGcccTTTaaa");
1154     SequenceI pep1 = new Sequence("pep1", "GF"); // GGGTTT
1155     SequenceI pep2 = new Sequence("pep2", "KP"); // aaaccc
1156     SequenceI pep3 = new Sequence("pep3", "KF"); // aaaTTT
1157     dna1.createDatasetSequence();
1158     pep1.createDatasetSequence();
1159     pep2.createDatasetSequence();
1160     pep3.createDatasetSequence();
1161     pep1.getDatasetSequence().addDBRef(
1162             new DBRefEntry("EMBLCDS", "2", "A12345"));
1163     pep2.getDatasetSequence().addDBRef(
1164             new DBRefEntry("EMBLCDS", "3", "A12346"));
1165     pep3.getDatasetSequence().addDBRef(
1166             new DBRefEntry("EMBLCDS", "4", "A12347"));
1167
1168     /*
1169      * Make the mappings from dna to protein. Using LinkedHashset is a
1170      * convenience so results are in the input order. There is no assertion that
1171      * the generated exon sequences are in any particular order.
1172      */
1173     Set<AlignedCodonFrame> mappings = new LinkedHashSet<AlignedCodonFrame>();
1174     // map ...GGG...TTT to GF
1175     MapList map = new MapList(new int[]
1176     { 4, 6, 10, 12 }, new int[]
1177     { 1, 2 }, 3, 1);
1178     AlignedCodonFrame acf = new AlignedCodonFrame();
1179     acf.addMap(dna1.getDatasetSequence(), pep1.getDatasetSequence(), map);
1180     mappings.add(acf);
1181
1182     // map aaa...ccc to KP
1183     map = new MapList(new int[]
1184     { 1, 3, 7, 9 }, new int[]
1185     { 1, 2 }, 3, 1);
1186     acf = new AlignedCodonFrame();
1187     acf.addMap(dna1.getDatasetSequence(), pep2.getDatasetSequence(), map);
1188     mappings.add(acf);
1189
1190     // map aaa......TTT to KF
1191     map = new MapList(new int[]
1192     { 1, 3, 10, 12 }, new int[]
1193     { 1, 2 }, 3, 1);
1194     acf = new AlignedCodonFrame();
1195     acf.addMap(dna1.getDatasetSequence(), pep3.getDatasetSequence(), map);
1196     mappings.add(acf);
1197
1198     /*
1199      * Create the Exon alignment; also replaces the dna-to-protein mappings with
1200      * exon-to-protein and exon-to-dna mappings
1201      */
1202     AlignmentI exal = AlignmentUtils.makeExonAlignment(new SequenceI[]
1203     { dna1 }, mappings);
1204
1205     /*
1206      * Verify we have 3 exon sequences, mapped to pep1/2/3 respectively
1207      */
1208     List<SequenceI> exons = exal.getSequences();
1209     assertEquals(3, exons.size());
1210
1211     SequenceI exon = exons.get(0);
1212     assertEquals("GGGTTT", exon.getSequenceAsString());
1213     assertEquals("dna1|A12345", exon.getName());
1214     assertEquals(1, exon.getDBRef().length);
1215     DBRefEntry cdsRef = exon.getDBRef()[0];
1216     assertEquals("EMBLCDS", cdsRef.getSource());
1217     assertEquals("2", cdsRef.getVersion());
1218     assertEquals("A12345", cdsRef.getAccessionId());
1219
1220     exon = exons.get(1);
1221     assertEquals("aaaccc", exon.getSequenceAsString());
1222     assertEquals("dna1|A12346", exon.getName());
1223     assertEquals(1, exon.getDBRef().length);
1224     cdsRef = exon.getDBRef()[0];
1225     assertEquals("EMBLCDS", cdsRef.getSource());
1226     assertEquals("3", cdsRef.getVersion());
1227     assertEquals("A12346", cdsRef.getAccessionId());
1228
1229     exon = exons.get(2);
1230     assertEquals("aaaTTT", exon.getSequenceAsString());
1231     assertEquals("dna1|A12347", exon.getName());
1232     assertEquals(1, exon.getDBRef().length);
1233     cdsRef = exon.getDBRef()[0];
1234     assertEquals("EMBLCDS", cdsRef.getSource());
1235     assertEquals("4", cdsRef.getVersion());
1236     assertEquals("A12347", cdsRef.getAccessionId());
1237
1238     /*
1239      * Verify there are mappings from each exon sequence to its protein product
1240      * and also to its dna source
1241      */
1242     Iterator<AlignedCodonFrame> newMappingsIterator = mappings.iterator();
1243
1244     // mappings for dna1 - exon1 - pep1
1245     AlignedCodonFrame exonMapping = newMappingsIterator.next();
1246     List<Mapping> dnaMappings = exonMapping.getMappingsForSequence(dna1);
1247     assertEquals(1, dnaMappings.size());
1248     assertSame(exons.get(0).getDatasetSequence(), dnaMappings.get(0)
1249             .getTo());
1250     assertEquals("G(1) in CDS should map to G(4) in DNA", 4, dnaMappings
1251             .get(0).getMap().getToPosition(1));
1252     List<Mapping> peptideMappings = exonMapping
1253             .getMappingsForSequence(pep1);
1254     assertEquals(1, peptideMappings.size());
1255     assertSame(pep1.getDatasetSequence(), peptideMappings.get(0).getTo());
1256
1257     // mappings for dna1 - exon2 - pep2
1258     exonMapping = newMappingsIterator.next();
1259     dnaMappings = exonMapping.getMappingsForSequence(dna1);
1260     assertEquals(1, dnaMappings.size());
1261     assertSame(exons.get(1).getDatasetSequence(), dnaMappings.get(0)
1262             .getTo());
1263     assertEquals("c(4) in CDS should map to c(7) in DNA", 7, dnaMappings
1264             .get(0).getMap().getToPosition(4));
1265     peptideMappings = exonMapping.getMappingsForSequence(pep2);
1266     assertEquals(1, peptideMappings.size());
1267     assertSame(pep2.getDatasetSequence(), peptideMappings.get(0).getTo());
1268
1269     // mappings for dna1 - exon3 - pep3
1270     exonMapping = newMappingsIterator.next();
1271     dnaMappings = exonMapping.getMappingsForSequence(dna1);
1272     assertEquals(1, dnaMappings.size());
1273     assertSame(exons.get(2).getDatasetSequence(), dnaMappings.get(0)
1274             .getTo());
1275     assertEquals("T(4) in CDS should map to T(10) in DNA", 10, dnaMappings
1276             .get(0).getMap().getToPosition(4));
1277     peptideMappings = exonMapping.getMappingsForSequence(pep3);
1278     assertEquals(1, peptideMappings.size());
1279     assertSame(pep3.getDatasetSequence(), peptideMappings.get(0).getTo());
1280   }
1281
1282   @Test(groups = { "Functional" })
1283   public void testIsMappable()
1284   {
1285     SequenceI dna1 = new Sequence("dna1", "cgCAGtgGT");
1286     SequenceI aa1 = new Sequence("aa1", "RSG");
1287     AlignmentI al1 = new Alignment(new SequenceI[] { dna1 });
1288     AlignmentI al2 = new Alignment(new SequenceI[] { aa1 });
1289
1290     assertFalse(AlignmentUtils.isMappable(null, null));
1291     assertFalse(AlignmentUtils.isMappable(al1, null));
1292     assertFalse(AlignmentUtils.isMappable(null, al1));
1293     assertFalse(AlignmentUtils.isMappable(al1, al1));
1294     assertFalse(AlignmentUtils.isMappable(al2, al2));
1295
1296     assertTrue(AlignmentUtils.isMappable(al1, al2));
1297     assertTrue(AlignmentUtils.isMappable(al2, al1));
1298   }
1299 }