b4b0e126bd309fabff7dee6eca50bc4eb04bb4c0
[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(al2, al1);
185
186     ((Alignment) al2).alignAs(al1, false, true);
187     assertEquals("GC-TC--GUC-GTA-CT", 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     ((Alignment) al2).alignAs(al1, false, true);
207     assertEquals("K-Q-Y-L-", al2.getSequenceAt(0).getSequenceAsString());
208     assertEquals("-R-F-P-W", al2.getSequenceAt(1).getSequenceAsString());
209   }
210
211   /**
212    * Aligning protein from cDNA for a single sequence. This is the 'simple' case
213    * (as there is no need to compute codon 'alignments') but worth testing
214    * before tackling the multiple sequence case.
215    * 
216    * @throws IOException
217    */
218   @Test(groups = { "Functional" })
219   public void testAlignAs_proteinAsCdna_singleSequence() throws IOException
220   {
221     /*
222      * simplest case remove all gaps
223      */
224     verifyAlignAs(">protein\n-Q-K-\n", ">dna\nCAAaaa\n", "QK");
225
226     /*
227      * with sequence offsets
228      */
229     verifyAlignAs(">protein/12-13\n-Q-K-\n", ">dna/20-25\nCAAaaa\n", "QK");
230   }
231
232   /**
233    * Test aligning cdna as per protein alignment.
234    * 
235    * @throws IOException
236    */
237   @Test(groups = { "Functional" })
238   public void testAlignAs_cdnaAsProtein() throws IOException
239   {
240     /*
241      * Load alignments and add mappings for cDNA to protein
242      */
243     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
244     AlignmentI al2 = loadAlignment(AA_SEQS_1, "FASTA");
245     makeMappings(al1, al2);
246
247     /*
248      * Realign DNA; currently keeping existing gaps in introns only
249      */
250     ((Alignment) al1).alignAs(al2, false, true);
251     assertEquals("ACG---GCUCCA------ACT", al1.getSequenceAt(0)
252             .getSequenceAsString());
253     assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
254             .getSequenceAsString());
255   }
256
257   /**
258    * Test aligning cdna as per protein - single sequences
259    * 
260    * @throws IOException
261    */
262   @Test(groups = { "Functional" })
263   public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
264   {
265     /*
266      * simple case insert one gap
267      */
268     verifyAlignAs(">dna\nCAAaaa\n", ">protein\nQ-K\n", "CAA---aaa");
269
270     /*
271      * simple case but with sequence offsets
272      */
273     verifyAlignAs(">dna/5-10\nCAAaaa\n", ">protein/20-21\nQ-K\n",
274             "CAA---aaa");
275
276     /*
277      * insert gaps as per protein, drop gaps within codons
278      */
279     verifyAlignAs(">dna/10-18\nCA-Aa-aa--AGA\n", ">aa/6-8\n-Q-K--R\n",
280             "---CAA---aaa------AGA");
281   }
282
283   /**
284    * Helper method that makes mappings and then aligns the first alignment as
285    * the second
286    * 
287    * @param fromSeqs
288    * @param toSeqs
289    * @param expected
290    * @throws IOException
291    */
292   public void verifyAlignAs(String fromSeqs, String toSeqs, String expected)
293           throws IOException
294   {
295     /*
296      * Load alignments and add mappings from nucleotide to protein (or from
297      * first to second if both the same type)
298      */
299     AlignmentI al1 = loadAlignment(fromSeqs, "FASTA");
300     AlignmentI al2 = loadAlignment(toSeqs, "FASTA");
301     makeMappings(al1, al2);
302
303     /*
304      * Realign DNA; currently keeping existing gaps in introns only
305      */
306     ((Alignment) al1).alignAs(al2, false, true);
307     assertEquals(expected, al1.getSequenceAt(0).getSequenceAsString());
308   }
309
310   /**
311    * Helper method to make mappings from protein to dna sequences, and add the
312    * mappings to the protein alignment
313    * 
314    * @param alFrom
315    * @param alTo
316    */
317   public void makeMappings(AlignmentI alFrom, AlignmentI alTo)
318   {
319     AlignmentI prot = !alFrom.isNucleotide() ? alFrom : alTo;
320     AlignmentI nuc = alFrom == prot ? alTo : alFrom;
321
322     int ratio = (alFrom.isNucleotide() == alTo.isNucleotide() ? 1 : 3);
323
324     AlignedCodonFrame acf = new AlignedCodonFrame();
325
326     for (int i = 0; i < nuc.getHeight(); i++)
327     {
328       SequenceI seqFrom = nuc.getSequenceAt(i);
329       SequenceI seqTo = prot.getSequenceAt(i);
330       MapList ml = new MapList(new int[] { seqFrom.getStart(),
331           seqFrom.getEnd() },
332               new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
333       acf.addMap(seqFrom, seqTo, ml);
334     }
335
336     prot.addCodonFrame(acf);
337   }
338
339   /**
340    * Test aligning dna as per protein alignment, for the case where there are
341    * introns (i.e. some dna sites have no mapping from a peptide).
342    * 
343    * @throws IOException
344    */
345   @Test(groups = { "Functional" })
346   public void testAlignAs_dnaAsProtein_withIntrons() throws IOException
347   {
348     /*
349      * Load alignments and add mappings for cDNA to protein
350      */
351     String dna1 = "A-Aa-gG-GCC-cT-TT";
352     String dna2 = "c--CCGgg-TT--T-AA-A";
353     AlignmentI al1 = loadAlignment(">Seq1/6-17\n" + dna1
354             + "\n>Seq2/20-31\n" + dna2 + "\n", "FASTA");
355     AlignmentI al2 = loadAlignment(
356             ">Seq1/7-9\n-P--YK\n>Seq2/11-13\nG-T--F\n", "FASTA");
357     AlignedCodonFrame acf = new AlignedCodonFrame();
358     // Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
359     // Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
360     // TODO sequence offsets
361     MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
362     { 7, 9 }, 3, 1);
363     acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
364     MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
365         13 }, 3, 1);
366     acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
367     al2.addCodonFrame(acf);
368
369     /*
370      * Align ignoring gaps in dna introns and exons
371      */
372     ((Alignment) al1).alignAs(al2, false, false);
373     assertEquals("---AAagG------GCCcTTT", al1.getSequenceAt(0)
374             .getSequenceAsString());
375     // note 1 gap in protein corresponds to 'gg-' in DNA (3 positions)
376     assertEquals("cCCGgg-TTT------AAA", al1.getSequenceAt(1)
377             .getSequenceAsString());
378
379     /*
380      * Reset and realign, preserving gaps in dna introns and exons
381      */
382     al1.getSequenceAt(0).setSequence(dna1);
383     al1.getSequenceAt(1).setSequence(dna2);
384     ((Alignment) al1).alignAs(al2, true, true);
385     // String dna1 = "A-Aa-gG-GCC-cT-TT";
386     // String dna2 = "c--CCGgg-TT--T-AA-A";
387     // assumption: we include 'the greater of' protein/dna gap lengths, not both
388     assertEquals("---A-Aa-gG------GCC-cT-TT", al1.getSequenceAt(0)
389             .getSequenceAsString());
390     assertEquals("c--CCGgg-TT--T------AA-A", al1.getSequenceAt(1)
391             .getSequenceAsString());
392   }
393
394   @Test(groups = "Functional")
395   public void testCopyConstructor() throws IOException
396   {
397     AlignmentI protein = loadAlignment(AA_SEQS_1, FormatAdapter.PASTE);
398     // create sequence and alignment datasets
399     protein.setDataset(null);
400     AlignedCodonFrame acf = new AlignedCodonFrame();
401     List<AlignedCodonFrame> acfList = Arrays.asList(new AlignedCodonFrame[]
402     { acf });
403     protein.getDataset().setCodonFrames(acfList);
404     AlignmentI copy = new Alignment(protein);
405
406     /*
407      * copy has different aligned sequences but the same dataset sequences
408      */
409     assertFalse(copy.getSequenceAt(0) == protein.getSequenceAt(0));
410     assertFalse(copy.getSequenceAt(1) == protein.getSequenceAt(1));
411     assertSame(copy.getSequenceAt(0).getDatasetSequence(), protein
412             .getSequenceAt(0).getDatasetSequence());
413     assertSame(copy.getSequenceAt(1).getDatasetSequence(), protein
414             .getSequenceAt(1).getDatasetSequence());
415
416     // TODO should the copy constructor copy the dataset?
417     // or make a new one referring to the same dataset sequences??
418     assertNull(copy.getDataset());
419     // assertArrayEquals(copy.getDataset().getSequencesArray(), protein
420     // .getDataset().getSequencesArray());
421   }
422
423   /**
424    * Test behaviour of createDataset
425    * 
426    * @throws IOException
427    */
428   @Test(groups = "Functional")
429   public void testCreateDatasetAlignment() throws IOException
430   {
431     AlignmentI protein = new FormatAdapter().readFile(AA_SEQS_1,
432             AppletFormatAdapter.PASTE, "FASTA");
433     /*
434      * create a dataset sequence on first sequence
435      * leave the second without one
436      */
437     protein.getSequenceAt(0).createDatasetSequence();
438     assertNotNull(protein.getSequenceAt(0).getDatasetSequence());
439     assertNull(protein.getSequenceAt(1).getDatasetSequence());
440
441     /*
442      * add a mapping to the alignment
443      */
444     AlignedCodonFrame acf = new AlignedCodonFrame();
445     protein.addCodonFrame(acf);
446     assertNull(protein.getDataset());
447     assertTrue(protein.getCodonFrames().contains(acf));
448
449     /*
450      * create the alignment dataset
451      * note this creates sequence datasets where missing
452      * as a side-effect (in this case, on seq2
453      */
454     // TODO promote this method to AlignmentI
455     ((Alignment) protein).createDatasetAlignment();
456
457     // TODO this method should return AlignmentI not Alignment !!
458     Alignment ds = protein.getDataset();
459
460     // side-effect: dataset created on second sequence
461     assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
462     // dataset alignment has references to dataset sequences
463     assertEquals(ds.getSequenceAt(0), protein.getSequenceAt(0)
464             .getDatasetSequence());
465     assertEquals(ds.getSequenceAt(1), protein.getSequenceAt(1)
466             .getDatasetSequence());
467
468     // codon frames should have been moved to the dataset
469     // getCodonFrames() should delegate to the dataset:
470     assertTrue(protein.getCodonFrames().contains(acf));
471     // prove the codon frames are indeed on the dataset:
472     assertTrue(ds.getCodonFrames().contains(acf));
473   }
474
475   @Test(groups = "Functional")
476   public void testAddCodonFrame()
477   {
478     AlignmentI align = new Alignment(new SequenceI[] {});
479     AlignedCodonFrame acf = new AlignedCodonFrame();
480     align.addCodonFrame(acf);
481     assertEquals(1, align.getCodonFrames().size());
482     assertTrue(align.getCodonFrames().contains(acf));
483     // can't add the same object twice:
484     align.addCodonFrame(acf);
485     assertEquals(1, align.getCodonFrames().size());
486
487     // create dataset alignment - mappings move to dataset
488     ((Alignment) align).createDatasetAlignment();
489     assertSame(align.getCodonFrames(), align.getDataset().getCodonFrames());
490     assertEquals(1, align.getCodonFrames().size());
491
492     AlignedCodonFrame acf2 = new AlignedCodonFrame();
493     align.addCodonFrame(acf2);
494     assertTrue(align.getDataset().getCodonFrames().contains(acf));
495   }
496 }