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