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