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