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