JAL-1705 reworked AlignmentUtils.makeCdsAlignment and associated code
[jalview.git] / test / jalview / datamodel / AlignmentTest.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.datamodel;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertFalse;
25 import static org.testng.AssertJUnit.assertNotNull;
26 import static org.testng.AssertJUnit.assertNull;
27 import static org.testng.AssertJUnit.assertSame;
28 import static org.testng.AssertJUnit.assertTrue;
29
30 import jalview.io.AppletFormatAdapter;
31 import jalview.io.FormatAdapter;
32 import jalview.util.MapList;
33
34 import java.io.IOException;
35 import java.util.Arrays;
36 import java.util.Iterator;
37 import java.util.List;
38
39 import org.testng.annotations.BeforeMethod;
40 import org.testng.annotations.Test;
41
42 /**
43  * Unit tests for Alignment datamodel.
44  * 
45  * @author gmcarstairs
46  *
47  */
48 public class AlignmentTest
49 {
50   // @formatter:off
51   private static final String TEST_DATA = 
52           "# STOCKHOLM 1.0\n" +
53           "#=GS D.melanogaster.1 AC AY119185.1/838-902\n" +
54           "#=GS D.melanogaster.2 AC AC092237.1/57223-57161\n" +
55           "#=GS D.melanogaster.3 AC AY060611.1/560-627\n" +
56           "D.melanogaster.1          G.AGCC.CU...AUGAUCGA\n" +
57           "#=GR D.melanogaster.1 SS  ................((((\n" +
58           "D.melanogaster.2          C.AUUCAACU.UAUGAGGAU\n" +
59           "#=GR D.melanogaster.2 SS  ................((((\n" +
60           "D.melanogaster.3          G.UGGCGCU..UAUGACGCA\n" +
61           "#=GR D.melanogaster.3 SS  (.(((...(....(((((((\n" +
62           "//";
63
64   private static final String AA_SEQS_1 = 
65           ">Seq1Name/5-8\n" +
66           "K-QY--L\n" +
67           ">Seq2Name/12-15\n" +
68           "-R-FP-W-\n";
69
70   private static final String CDNA_SEQS_1 = 
71           ">Seq1Name/100-111\n" +
72           "AC-GG--CUC-CAA-CT\n" +
73           ">Seq2Name/200-211\n" +
74           "-CG-TTA--ACG---AAGT\n";
75
76   private static final String CDNA_SEQS_2 = 
77           ">Seq1Name/50-61\n" +
78           "GCTCGUCGTACT\n" +
79           ">Seq2Name/60-71\n" +
80           "GGGTCAGGCAGT\n";
81   // @formatter:on
82
83   private AlignmentI al;
84
85   /**
86    * Helper method to load an alignment and ensure dataset sequences are set up.
87    * 
88    * @param data
89    * @param format
90    *          TODO
91    * @return
92    * @throws IOException
93    */
94   protected AlignmentI loadAlignment(final String data, String format)
95           throws IOException
96   {
97     AlignmentI a = new FormatAdapter().readFile(data,
98             AppletFormatAdapter.PASTE, format);
99     a.setDataset(null);
100     return a;
101   }
102
103   /*
104    * Read in Stockholm format test data including secondary structure
105    * annotations.
106    */
107   @BeforeMethod(alwaysRun = true)
108   public void setUp() throws IOException
109   {
110     al = loadAlignment(TEST_DATA, "STH");
111     int i = 0;
112     for (AlignmentAnnotation ann : al.getAlignmentAnnotation())
113     {
114       ann.setCalcId("CalcIdFor" + al.getSequenceAt(i).getName());
115       i++;
116     }
117   }
118
119   /**
120    * Test method that returns annotations that match on calcId.
121    */
122   @Test(groups = { "Functional" })
123   public void testFindAnnotation_byCalcId()
124   {
125     Iterable<AlignmentAnnotation> anns = al
126             .findAnnotation("CalcIdForD.melanogaster.2");
127     Iterator<AlignmentAnnotation> iter = anns.iterator();
128     assertTrue(iter.hasNext());
129     AlignmentAnnotation ann = iter.next();
130     assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
131     assertFalse(iter.hasNext());
132   }
133
134   @Test(groups = { "Functional" })
135   public void testDeleteAllAnnotations_includingAutocalculated()
136   {
137     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
138             "Consensus", 0.5);
139     aa.autoCalculated = true;
140     al.addAnnotation(aa);
141     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
142     assertEquals("Wrong number of annotations before deleting", 4,
143             anns.length);
144     al.deleteAllAnnotations(true);
145     assertEquals("Not all deleted", 0, al.getAlignmentAnnotation().length);
146   }
147
148   @Test(groups = { "Functional" })
149   public void testDeleteAllAnnotations_excludingAutocalculated()
150   {
151     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
152             "Consensus", 0.5);
153     aa.autoCalculated = true;
154     al.addAnnotation(aa);
155     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
156     assertEquals("Wrong number of annotations before deleting", 4,
157             anns.length);
158     al.deleteAllAnnotations(false);
159     assertEquals("Not just one annotation left", 1,
160             al.getAlignmentAnnotation().length);
161   }
162
163   /**
164    * Tests for realigning as per a supplied alignment: Dna as Dna.
165    * 
166    * Note: AlignedCodonFrame's state variables are named for protein-to-cDNA
167    * mapping, but can be exploited for a general 'sequence-to-sequence' mapping
168    * as here.
169    * 
170    * @throws IOException
171    */
172   @Test(groups = { "Functional" })
173   public void testAlignAs_dnaAsDna() throws IOException
174   {
175     // aligned cDNA:
176     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
177     // unaligned cDNA:
178     AlignmentI al2 = loadAlignment(CDNA_SEQS_2, "FASTA");
179
180     /*
181      * Make mappings between sequences. The 'aligned cDNA' is playing the role
182      * of what would normally be protein here.
183      */
184     makeMappings(al1, al2);
185
186     ((Alignment) al2).alignAs(al1, false, true);
187     assertEquals("GC-TC--GUC-GTACT", al2.getSequenceAt(0)
188             .getSequenceAsString());
189     assertEquals("-GG-GTC--AGG--CAGT", al2.getSequenceAt(1)
190             .getSequenceAsString());
191   }
192
193   /**
194    * Aligning protein from cDNA.
195    * 
196    * @throws IOException
197    */
198   @Test(groups = { "Functional" })
199   public void testAlignAs_proteinAsCdna() throws IOException
200   {
201     // see also AlignmentUtilsTests
202     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
203     AlignmentI al2 = loadAlignment(AA_SEQS_1, "FASTA");
204     makeMappings(al1, al2);
205
206     // Fudge - alignProteinAsCdna expects mappings to be on protein
207     al2.getCodonFrames().addAll(al1.getCodonFrames());
208
209     ((Alignment) al2).alignAs(al1, false, true);
210     assertEquals("K-Q-Y-L-", al2.getSequenceAt(0).getSequenceAsString());
211     assertEquals("-R-F-P-W", al2.getSequenceAt(1).getSequenceAsString());
212   }
213
214   /**
215    * Test aligning cdna as per protein alignment.
216    * 
217    * @throws IOException
218    */
219   @Test(groups = { "Functional" }, enabled = false)
220   // TODO review / update this test after redesign of alignAs method
221   public void testAlignAs_cdnaAsProtein() throws IOException
222   {
223     /*
224      * Load alignments and add mappings for cDNA to protein
225      */
226     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
227     AlignmentI al2 = loadAlignment(AA_SEQS_1, "FASTA");
228     makeMappings(al1, al2);
229
230     /*
231      * Realign DNA; currently keeping existing gaps in introns only
232      */
233     ((Alignment) al1).alignAs(al2, false, true);
234     assertEquals("ACG---GCUCCA------ACT", al1.getSequenceAt(0)
235             .getSequenceAsString());
236     assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
237             .getSequenceAsString());
238   }
239
240   /**
241    * Test aligning cdna as per protein - single sequences
242    * 
243    * @throws IOException
244    */
245   @Test(groups = { "Functional" }, enabled = false)
246   // TODO review / update this test after redesign of alignAs method
247   public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
248   {
249     /*
250      * simple case insert one gap
251      */
252     verifyAlignAs(">dna\nCAAaaa\n", ">protein\nQ-K\n", "CAA---aaa");
253
254     /*
255      * simple case but with sequence offsets
256      */
257     verifyAlignAs(">dna/5-10\nCAAaaa\n", ">protein/20-21\nQ-K\n",
258             "CAA---aaa");
259
260     /*
261      * insert gaps as per protein, drop gaps within codons
262      */
263     verifyAlignAs(">dna/10-18\nCA-Aa-aa--AGA\n", ">aa/6-8\n-Q-K--R\n",
264             "---CAA---aaa------AGA");
265   }
266
267   /**
268    * Helper method that makes mappings and then aligns the first alignment as
269    * the second
270    * 
271    * @param fromSeqs
272    * @param toSeqs
273    * @param expected
274    * @throws IOException
275    */
276   public void verifyAlignAs(String fromSeqs, String toSeqs, String expected)
277           throws IOException
278   {
279     /*
280      * Load alignments and add mappings from nucleotide to protein (or from
281      * first to second if both the same type)
282      */
283     AlignmentI al1 = loadAlignment(fromSeqs, "FASTA");
284     AlignmentI al2 = loadAlignment(toSeqs, "FASTA");
285     makeMappings(al1, al2);
286
287     /*
288      * Realign DNA; currently keeping existing gaps in introns only
289      */
290     ((Alignment) al1).alignAs(al2, false, true);
291     assertEquals(expected, al1.getSequenceAt(0).getSequenceAsString());
292   }
293
294   /**
295    * Helper method to make mappings between sequences, and add the mappings to
296    * the 'mapped from' alignment
297    * 
298    * @param alFrom
299    * @param alTo
300    */
301   public void makeMappings(AlignmentI alFrom, AlignmentI alTo)
302   {
303     int ratio = (alFrom.isNucleotide() == alTo.isNucleotide() ? 1 : 3);
304
305     AlignedCodonFrame acf = new AlignedCodonFrame();
306
307     for (int i = 0; i < alFrom.getHeight(); i++)
308     {
309       SequenceI seqFrom = alFrom.getSequenceAt(i);
310       SequenceI seqTo = alTo.getSequenceAt(i);
311       MapList ml = new MapList(new int[] { seqFrom.getStart(),
312           seqFrom.getEnd() },
313               new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
314       acf.addMap(seqFrom, seqTo, ml);
315     }
316
317     alFrom.addCodonFrame(acf);
318   }
319
320   /**
321    * Test aligning dna as per protein alignment, for the case where there are
322    * introns (i.e. some dna sites have no mapping from a peptide).
323    * 
324    * @throws IOException
325    */
326   @Test(groups = { "Functional" }, enabled = false)
327   // TODO review / update this test after redesign of alignAs method
328   public void testAlignAs_dnaAsProtein_withIntrons() throws IOException
329   {
330     /*
331      * Load alignments and add mappings for cDNA to protein
332      */
333     String dna1 = "A-Aa-gG-GCC-cT-TT";
334     String dna2 = "c--CCGgg-TT--T-AA-A";
335     AlignmentI al1 = loadAlignment(">Dna1/6-17\n" + dna1
336             + "\n>Dna2/20-31\n" + dna2 + "\n", "FASTA");
337     AlignmentI al2 = loadAlignment(
338             ">Pep1/7-9\n-P--YK\n>Pep2/11-13\nG-T--F\n", "FASTA");
339     AlignedCodonFrame acf = new AlignedCodonFrame();
340     // Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
341     // Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
342     MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
343     { 7, 9 }, 3, 1);
344     acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
345     MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
346         13 }, 3, 1);
347     acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
348     al2.addCodonFrame(acf);
349
350     /*
351      * Align ignoring gaps in dna introns and exons
352      */
353     ((Alignment) al1).alignAs(al2, false, false);
354     assertEquals("---AAagG------GCCcTTT", al1.getSequenceAt(0)
355             .getSequenceAsString());
356     // note 1 gap in protein corresponds to 'gg-' in DNA (3 positions)
357     assertEquals("cCCGgg-TTT------AAA", al1.getSequenceAt(1)
358             .getSequenceAsString());
359
360     /*
361      * Reset and realign, preserving gaps in dna introns and exons
362      */
363     al1.getSequenceAt(0).setSequence(dna1);
364     al1.getSequenceAt(1).setSequence(dna2);
365     ((Alignment) al1).alignAs(al2, true, true);
366     // String dna1 = "A-Aa-gG-GCC-cT-TT";
367     // String dna2 = "c--CCGgg-TT--T-AA-A";
368     // assumption: we include 'the greater of' protein/dna gap lengths, not both
369     assertEquals("---A-Aa-gG------GCC-cT-TT", al1.getSequenceAt(0)
370             .getSequenceAsString());
371     assertEquals("c--CCGgg-TT--T------AA-A", al1.getSequenceAt(1)
372             .getSequenceAsString());
373   }
374
375   @Test(groups = "Functional")
376   public void testCopyConstructor() throws IOException
377   {
378     AlignmentI protein = loadAlignment(AA_SEQS_1, FormatAdapter.PASTE);
379     // create sequence and alignment datasets
380     protein.setDataset(null);
381     AlignedCodonFrame acf = new AlignedCodonFrame();
382     List<AlignedCodonFrame> acfList = Arrays.asList(new AlignedCodonFrame[]
383     { acf });
384     protein.getDataset().setCodonFrames(acfList);
385     AlignmentI copy = new Alignment(protein);
386
387     /*
388      * copy has different aligned sequences but the same dataset sequences
389      */
390     assertFalse(copy.getSequenceAt(0) == protein.getSequenceAt(0));
391     assertFalse(copy.getSequenceAt(1) == protein.getSequenceAt(1));
392     assertSame(copy.getSequenceAt(0).getDatasetSequence(), protein
393             .getSequenceAt(0).getDatasetSequence());
394     assertSame(copy.getSequenceAt(1).getDatasetSequence(), protein
395             .getSequenceAt(1).getDatasetSequence());
396
397     // TODO should the copy constructor copy the dataset?
398     // or make a new one referring to the same dataset sequences??
399     assertNull(copy.getDataset());
400     // assertArrayEquals(copy.getDataset().getSequencesArray(), protein
401     // .getDataset().getSequencesArray());
402   }
403
404   /**
405    * Test behaviour of createDataset
406    * 
407    * @throws IOException
408    */
409   @Test(groups = "Functional")
410   public void testCreateDatasetAlignment() throws IOException
411   {
412     AlignmentI protein = new FormatAdapter().readFile(AA_SEQS_1,
413             AppletFormatAdapter.PASTE, "FASTA");
414     /*
415      * create a dataset sequence on first sequence
416      * leave the second without one
417      */
418     protein.getSequenceAt(0).createDatasetSequence();
419     assertNotNull(protein.getSequenceAt(0).getDatasetSequence());
420     assertNull(protein.getSequenceAt(1).getDatasetSequence());
421
422     /*
423      * add a mapping to the alignment
424      */
425     AlignedCodonFrame acf = new AlignedCodonFrame();
426     protein.addCodonFrame(acf);
427     assertNull(protein.getDataset());
428     assertTrue(protein.getCodonFrames().contains(acf));
429
430     /*
431      * create the alignment dataset
432      * note this creates sequence datasets where missing
433      * as a side-effect (in this case, on seq2
434      */
435     // TODO promote this method to AlignmentI
436     ((Alignment) protein).createDatasetAlignment();
437
438     // TODO this method should return AlignmentI not Alignment !!
439     Alignment ds = protein.getDataset();
440
441     // side-effect: dataset created on second sequence
442     assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
443     // dataset alignment has references to dataset sequences
444     assertEquals(ds.getSequenceAt(0), protein.getSequenceAt(0)
445             .getDatasetSequence());
446     assertEquals(ds.getSequenceAt(1), protein.getSequenceAt(1)
447             .getDatasetSequence());
448
449     // codon frames should have been moved to the dataset
450     // getCodonFrames() should delegate to the dataset:
451     assertTrue(protein.getCodonFrames().contains(acf));
452     // prove the codon frames are indeed on the dataset:
453     assertTrue(ds.getCodonFrames().contains(acf));
454   }
455
456   @Test(groups = "Functional")
457   public void testAddCodonFrame()
458   {
459     AlignmentI align = new Alignment(new SequenceI[] {});
460     AlignedCodonFrame acf = new AlignedCodonFrame();
461     align.addCodonFrame(acf);
462     assertEquals(1, align.getCodonFrames().size());
463     assertTrue(align.getCodonFrames().contains(acf));
464     // can't add the same object twice:
465     align.addCodonFrame(acf);
466     assertEquals(1, align.getCodonFrames().size());
467
468     // create dataset alignment - mappings move to dataset
469     ((Alignment) align).createDatasetAlignment();
470     assertSame(align.getCodonFrames(), align.getDataset().getCodonFrames());
471     assertEquals(1, align.getCodonFrames().size());
472
473     AlignedCodonFrame acf2 = new AlignedCodonFrame();
474     align.addCodonFrame(acf2);
475     assertTrue(align.getDataset().getCodonFrames().contains(acf));
476   }
477 }