JAL-2154 new assert to check reference integrity for an alignment, and a dataset...
[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.Assert;
41 import org.testng.annotations.BeforeMethod;
42 import org.testng.annotations.Test;
43
44 /**
45  * Unit tests for Alignment datamodel.
46  * 
47  * @author gmcarstairs
48  *
49  */
50 public class AlignmentTest
51 {
52   // @formatter:off
53   private static final String TEST_DATA = 
54           "# STOCKHOLM 1.0\n" +
55           "#=GS D.melanogaster.1 AC AY119185.1/838-902\n" +
56           "#=GS D.melanogaster.2 AC AC092237.1/57223-57161\n" +
57           "#=GS D.melanogaster.3 AC AY060611.1/560-627\n" +
58           "D.melanogaster.1          G.AGCC.CU...AUGAUCGA\n" +
59           "#=GR D.melanogaster.1 SS  ................((((\n" +
60           "D.melanogaster.2          C.AUUCAACU.UAUGAGGAU\n" +
61           "#=GR D.melanogaster.2 SS  ................((((\n" +
62           "D.melanogaster.3          G.UGGCGCU..UAUGACGCA\n" +
63           "#=GR D.melanogaster.3 SS  (.(((...(....(((((((\n" +
64           "//";
65
66   private static final String AA_SEQS_1 = 
67           ">Seq1Name/5-8\n" +
68           "K-QY--L\n" +
69           ">Seq2Name/12-15\n" +
70           "-R-FP-W-\n";
71
72   private static final String CDNA_SEQS_1 = 
73           ">Seq1Name/100-111\n" +
74           "AC-GG--CUC-CAA-CT\n" +
75           ">Seq2Name/200-211\n" +
76           "-CG-TTA--ACG---AAGT\n";
77
78   private static final String CDNA_SEQS_2 = 
79           ">Seq1Name/50-61\n" +
80           "GCTCGUCGTACT\n" +
81           ">Seq2Name/60-71\n" +
82           "GGGTCAGGCAGT\n";
83   // @formatter:on
84
85   private AlignmentI al;
86
87   /**
88    * Helper method to load an alignment and ensure dataset sequences are set up.
89    * 
90    * @param data
91    * @param format
92    *          TODO
93    * @return
94    * @throws IOException
95    */
96   protected AlignmentI loadAlignment(final String data, String format)
97           throws IOException
98   {
99     AlignmentI a = new FormatAdapter().readFile(data,
100             AppletFormatAdapter.PASTE, format);
101     a.setDataset(null);
102     return a;
103   }
104
105   /**
106    * verify sequence and dataset references are properly contained within
107    * dataset
108    * 
109    * @param alignment
110    *          - the alignmentI object to verify (either alignment or dataset)
111    * @param raiseAssert
112    *          - when set, testng assertions are raised.
113    * @return true if alignment references were in order, otherwise false.
114    */
115   public static boolean verifyAlignmentDatasetRefs(AlignmentI alignment,
116           boolean raiseAssert)
117   {
118     if (alignment.getDataset() != null)
119     {
120       AlignmentI dataset = alignment.getDataset();
121       // check all alignment sequences have their dataset within the dataset
122       for (SequenceI seq : alignment.getSequences())
123       {
124         SequenceI seqds = seq.getDatasetSequence();
125         if (seqds.getDatasetSequence() != null)
126         {
127           if (raiseAssert)
128           {
129             Assert.fail("Alignment contained a sequence who's dataset sequence has a second dataset reference.");
130           }
131           return false;
132         }
133         if (dataset.findIndex(seqds) == -1)
134         {
135           if (raiseAssert)
136           {
137             Assert.fail("Alignment contained a sequence who's dataset sequence was not in the dataset.");
138           }
139           return false;
140         }
141       }
142       return verifyAlignmentDatasetRefs(alignment.getDataset(), raiseAssert);
143     }
144     else
145     {
146       // verify all dataset sequences
147       for (SequenceI seqds : alignment.getSequences())
148       {
149         if (seqds.getDatasetSequence() != null)
150         {
151           if (raiseAssert)
152           {
153             Assert.fail("Dataset contained a sequence with non-null dataset reference (ie not a dataset sequence!)");
154           }
155           return false;
156         }
157         if (seqds.getDBRefs() != null)
158         {
159           for (DBRefEntry dbr : seqds.getDBRefs())
160           {
161             if (dbr.getMap() != null)
162             {
163               SequenceI seqdbrmapto = dbr.getMap().getTo();
164               if (seqdbrmapto != null)
165               {
166                 if (seqdbrmapto.getDatasetSequence() != null)
167                 {
168                   if (raiseAssert)
169                   {
170                     Assert.fail("DBRefEntry for sequence in alignment had map to sequence which was not a dataset sequence");
171                   }
172                   return false;
173
174                 }
175                 if (alignment.findIndex(dbr.getMap().getTo()) == -1)
176                 {
177                   if (raiseAssert)
178                   {
179                     Assert.fail("DBRefEntry for sequence in alignment had map to sequence not in dataset");
180                   }
181                   return false;
182                 }
183               }
184             }
185           }
186         }
187       }
188     }
189     return true; // all relationships verified!
190   }
191
192   /**
193    * call verifyAlignmentDatasetRefs with and without assertion raising enabled,
194    * to check expected pass/fail actually occurs in both conditions
195    * 
196    * @param al
197    * @param expected
198    * @param msg
199    */
200   private void assertVerifyAlignment(AlignmentI al, boolean expected,
201           String msg)
202   {
203     if (expected)
204     {
205       try
206       {
207
208         Assert.assertTrue(verifyAlignmentDatasetRefs(al, true),
209                 "Valid test alignment failed when raiseAsserts enabled:"
210                         + msg);
211       } catch (AssertionError ae)
212       {
213         ae.printStackTrace();
214         Assert.fail(
215                 "Valid test alignment raised assertion errors when raiseAsserts enabled: "
216                         + msg, ae);
217       }
218       // also check validation passes with asserts disabled
219       Assert.assertTrue(verifyAlignmentDatasetRefs(al, false),
220               "Valid test alignment failed when raiseAsserts disabled:"
221                       + msg);
222     }
223     else
224     {
225       try
226       {
227         Assert.assertFalse(verifyAlignmentDatasetRefs(al, true));
228         Assert.fail("Invalid test alignment passed but no assertion raised when raiseAsserts enabled:"
229                 + msg);
230       } catch (AssertionError ae)
231       {
232         // expected behaviour
233       }
234       // also check validation passes with asserts disabled
235       Assert.assertFalse(verifyAlignmentDatasetRefs(al, false),
236               "Invalid test alignment passed when raiseAsserts disabled:"
237                       + msg);
238     }
239   }
240   @Test(groups = { "Functional" })
241   public void testVerifyAlignmentDatasetRefs()
242   {
243     SequenceI sq1 = new Sequence("sq1", "ASFDD"), sq2 = new Sequence("sq2",
244             "TTTTTT");
245
246     // construct simple valid alignment dataset
247     Alignment al = new Alignment(new SequenceI[] {
248         sq1, sq2 });
249     // expect this to pass
250     assertVerifyAlignment(al, true, "Simple valid alignment didn't verify");
251
252     // check test for sequence->datasetSequence validity
253     sq1.setDatasetSequence(sq2);
254     assertVerifyAlignment(
255             al,
256             false,
257             "didn't detect dataset sequence with a dataset sequence reference.");
258
259     sq1.setDatasetSequence(null);
260     assertVerifyAlignment(
261             al,
262             true,
263             "didn't reinstate validity after nulling dataset sequence dataset reference");
264
265     // now create dataset and check again
266     al.createDatasetAlignment();
267     assertNotNull(al.getDataset());
268
269     assertVerifyAlignment(al, true,
270             "verify failed after createDatasetAlignment");
271
272     // create a dbref on sq1 with a sequence ref to sq2
273     DBRefEntry dbrs1tos2 = new DBRefEntry("UNIPROT", "1", "Q111111");
274     dbrs1tos2.setMap(new Mapping(sq2.getDatasetSequence(),
275             new int[] { 1, 5 }, new int[] { 2, 6 }, 1, 1));
276     sq1.getDatasetSequence().addDBRef(dbrs1tos2);
277     assertVerifyAlignment(al, true,
278             "verify failed after addition of valid DBRefEntry/map");
279     // now create a dbref on a new sequence which maps to another sequence
280     // outside of the dataset
281     SequenceI sqout = new Sequence("sqout", "ututututucagcagcag"), sqnew = new Sequence(
282             "sqnew", "EEERRR");
283     DBRefEntry sqnewsqout = new DBRefEntry("ENAFOO", "1", "R000001");
284     sqnewsqout.setMap(new Mapping(sqout, new int[] { 1, 6 }, new int[] { 1,
285         18 }, 1, 3));
286     al.getDataset().addSequence(sqnew);
287
288     assertVerifyAlignment(al, true,
289             "verify failed after addition of new sequence to dataset");
290     // now start checking exception conditions
291     sqnew.addDBRef(sqnewsqout);
292     assertVerifyAlignment(
293             al,
294             false,
295             "verify passed when a dbref with map to sequence outside of dataset was added");
296   }
297   /*
298    * Read in Stockholm format test data including secondary structure
299    * annotations.
300    */
301   @BeforeMethod(alwaysRun = true)
302   public void setUp() throws IOException
303   {
304     al = loadAlignment(TEST_DATA, "STH");
305     int i = 0;
306     for (AlignmentAnnotation ann : al.getAlignmentAnnotation())
307     {
308       ann.setCalcId("CalcIdFor" + al.getSequenceAt(i).getName());
309       i++;
310     }
311   }
312
313   /**
314    * Test method that returns annotations that match on calcId.
315    */
316   @Test(groups = { "Functional" })
317   public void testFindAnnotation_byCalcId()
318   {
319     Iterable<AlignmentAnnotation> anns = al
320             .findAnnotation("CalcIdForD.melanogaster.2");
321     Iterator<AlignmentAnnotation> iter = anns.iterator();
322     assertTrue(iter.hasNext());
323     AlignmentAnnotation ann = iter.next();
324     assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
325     assertFalse(iter.hasNext());
326   }
327
328   @Test(groups = { "Functional" })
329   public void testDeleteAllAnnotations_includingAutocalculated()
330   {
331     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
332             "Consensus", 0.5);
333     aa.autoCalculated = true;
334     al.addAnnotation(aa);
335     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
336     assertEquals("Wrong number of annotations before deleting", 4,
337             anns.length);
338     al.deleteAllAnnotations(true);
339     assertEquals("Not all deleted", 0, al.getAlignmentAnnotation().length);
340   }
341
342   @Test(groups = { "Functional" })
343   public void testDeleteAllAnnotations_excludingAutocalculated()
344   {
345     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
346             "Consensus", 0.5);
347     aa.autoCalculated = true;
348     al.addAnnotation(aa);
349     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
350     assertEquals("Wrong number of annotations before deleting", 4,
351             anns.length);
352     al.deleteAllAnnotations(false);
353     assertEquals("Not just one annotation left", 1,
354             al.getAlignmentAnnotation().length);
355   }
356
357   /**
358    * Tests for realigning as per a supplied alignment: Dna as Dna.
359    * 
360    * Note: AlignedCodonFrame's state variables are named for protein-to-cDNA
361    * mapping, but can be exploited for a general 'sequence-to-sequence' mapping
362    * as here.
363    * 
364    * @throws IOException
365    */
366   @Test(groups = { "Functional" })
367   public void testAlignAs_dnaAsDna() throws IOException
368   {
369     // aligned cDNA:
370     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
371     // unaligned cDNA:
372     AlignmentI al2 = loadAlignment(CDNA_SEQS_2, "FASTA");
373
374     /*
375      * Make mappings between sequences. The 'aligned cDNA' is playing the role
376      * of what would normally be protein here.
377      */
378     makeMappings(al1, al2);
379
380     ((Alignment) al2).alignAs(al1, false, true);
381     assertEquals("GC-TC--GUC-GTACT", al2.getSequenceAt(0)
382             .getSequenceAsString());
383     assertEquals("-GG-GTC--AGG--CAGT", al2.getSequenceAt(1)
384             .getSequenceAsString());
385   }
386
387   /**
388    * Aligning protein from cDNA.
389    * 
390    * @throws IOException
391    */
392   @Test(groups = { "Functional" })
393   public void testAlignAs_proteinAsCdna() throws IOException
394   {
395     // see also AlignmentUtilsTests
396     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
397     AlignmentI al2 = loadAlignment(AA_SEQS_1, "FASTA");
398     makeMappings(al1, al2);
399
400     // Fudge - alignProteinAsCdna expects mappings to be on protein
401     al2.getCodonFrames().addAll(al1.getCodonFrames());
402
403     ((Alignment) al2).alignAs(al1, false, true);
404     assertEquals("K-Q-Y-L-", al2.getSequenceAt(0).getSequenceAsString());
405     assertEquals("-R-F-P-W", al2.getSequenceAt(1).getSequenceAsString());
406   }
407
408   /**
409    * Test aligning cdna as per protein alignment.
410    * 
411    * @throws IOException
412    */
413   @Test(groups = { "Functional" }, enabled = true)
414   // TODO review / update this test after redesign of alignAs method
415   public void testAlignAs_cdnaAsProtein() throws IOException
416   {
417     /*
418      * Load alignments and add mappings for cDNA to protein
419      */
420     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
421     AlignmentI al2 = loadAlignment(AA_SEQS_1, "FASTA");
422     makeMappings(al1, al2);
423
424     /*
425      * Realign DNA; currently keeping existing gaps in introns only
426      */
427     ((Alignment) al1).alignAs(al2, false, true);
428     assertEquals("ACG---GCUCCA------ACT---", al1.getSequenceAt(0)
429             .getSequenceAsString());
430     assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
431             .getSequenceAsString());
432   }
433
434   /**
435    * Test aligning cdna as per protein - single sequences
436    * 
437    * @throws IOException
438    */
439   @Test(groups = { "Functional" }, enabled = true)
440   // TODO review / update this test after redesign of alignAs method
441   public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
442   {
443     /*
444      * simple case insert one gap
445      */
446     verifyAlignAs(">dna\nCAAaaa\n", ">protein\nQ-K\n", "CAA---aaa");
447
448     /*
449      * simple case but with sequence offsets
450      */
451     verifyAlignAs(">dna/5-10\nCAAaaa\n", ">protein/20-21\nQ-K\n",
452             "CAA---aaa");
453
454     /*
455      * insert gaps as per protein, drop gaps within codons
456      */
457     verifyAlignAs(">dna/10-18\nCA-Aa-aa--AGA\n", ">aa/6-8\n-Q-K--R\n",
458             "---CAA---aaa------AGA");
459   }
460
461   /**
462    * Helper method that makes mappings and then aligns the first alignment as
463    * the second
464    * 
465    * @param fromSeqs
466    * @param toSeqs
467    * @param expected
468    * @throws IOException
469    */
470   public void verifyAlignAs(String fromSeqs, String toSeqs, String expected)
471           throws IOException
472   {
473     /*
474      * Load alignments and add mappings from nucleotide to protein (or from
475      * first to second if both the same type)
476      */
477     AlignmentI al1 = loadAlignment(fromSeqs, "FASTA");
478     AlignmentI al2 = loadAlignment(toSeqs, "FASTA");
479     makeMappings(al1, al2);
480
481     /*
482      * Realign DNA; currently keeping existing gaps in introns only
483      */
484     ((Alignment) al1).alignAs(al2, false, true);
485     assertEquals(expected, al1.getSequenceAt(0).getSequenceAsString());
486   }
487
488   /**
489    * Helper method to make mappings between sequences, and add the mappings to
490    * the 'mapped from' alignment
491    * 
492    * @param alFrom
493    * @param alTo
494    */
495   public void makeMappings(AlignmentI alFrom, AlignmentI alTo)
496   {
497     int ratio = (alFrom.isNucleotide() == alTo.isNucleotide() ? 1 : 3);
498
499     AlignedCodonFrame acf = new AlignedCodonFrame();
500
501     for (int i = 0; i < alFrom.getHeight(); i++)
502     {
503       SequenceI seqFrom = alFrom.getSequenceAt(i);
504       SequenceI seqTo = alTo.getSequenceAt(i);
505       MapList ml = new MapList(new int[] { seqFrom.getStart(),
506           seqFrom.getEnd() },
507               new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
508       acf.addMap(seqFrom, seqTo, ml);
509     }
510
511     /*
512      * not sure whether mappings 'belong' or protein or nucleotide
513      * alignment, so adding to both ;~)
514      */
515     alFrom.addCodonFrame(acf);
516     alTo.addCodonFrame(acf);
517   }
518
519   /**
520    * Test aligning dna as per protein alignment, for the case where there are
521    * introns (i.e. some dna sites have no mapping from a peptide).
522    * 
523    * @throws IOException
524    */
525   @Test(groups = { "Functional" }, enabled = false)
526   // TODO review / update this test after redesign of alignAs method
527   public void testAlignAs_dnaAsProtein_withIntrons() throws IOException
528   {
529     /*
530      * Load alignments and add mappings for cDNA to protein
531      */
532     String dna1 = "A-Aa-gG-GCC-cT-TT";
533     String dna2 = "c--CCGgg-TT--T-AA-A";
534     AlignmentI al1 = loadAlignment(">Dna1/6-17\n" + dna1
535             + "\n>Dna2/20-31\n" + dna2 + "\n", "FASTA");
536     AlignmentI al2 = loadAlignment(
537             ">Pep1/7-9\n-P--YK\n>Pep2/11-13\nG-T--F\n", "FASTA");
538     AlignedCodonFrame acf = new AlignedCodonFrame();
539     // Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
540     // Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
541     MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
542     { 7, 9 }, 3, 1);
543     acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
544     MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
545         13 }, 3, 1);
546     acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
547     al2.addCodonFrame(acf);
548
549     /*
550      * Align ignoring gaps in dna introns and exons
551      */
552     ((Alignment) al1).alignAs(al2, false, false);
553     assertEquals("---AAagG------GCCcTTT", al1.getSequenceAt(0)
554             .getSequenceAsString());
555     // note 1 gap in protein corresponds to 'gg-' in DNA (3 positions)
556     assertEquals("cCCGgg-TTT------AAA", al1.getSequenceAt(1)
557             .getSequenceAsString());
558
559     /*
560      * Reset and realign, preserving gaps in dna introns and exons
561      */
562     al1.getSequenceAt(0).setSequence(dna1);
563     al1.getSequenceAt(1).setSequence(dna2);
564     ((Alignment) al1).alignAs(al2, true, true);
565     // String dna1 = "A-Aa-gG-GCC-cT-TT";
566     // String dna2 = "c--CCGgg-TT--T-AA-A";
567     // assumption: we include 'the greater of' protein/dna gap lengths, not both
568     assertEquals("---A-Aa-gG------GCC-cT-TT", al1.getSequenceAt(0)
569             .getSequenceAsString());
570     assertEquals("c--CCGgg-TT--T------AA-A", al1.getSequenceAt(1)
571             .getSequenceAsString());
572   }
573
574   @Test(groups = "Functional")
575   public void testCopyConstructor() throws IOException
576   {
577     AlignmentI protein = loadAlignment(AA_SEQS_1, FormatAdapter.PASTE);
578     // create sequence and alignment datasets
579     protein.setDataset(null);
580     AlignedCodonFrame acf = new AlignedCodonFrame();
581     List<AlignedCodonFrame> acfList = Arrays.asList(new AlignedCodonFrame[]
582     { acf });
583     protein.getDataset().setCodonFrames(acfList);
584     AlignmentI copy = new Alignment(protein);
585
586     /*
587      * copy has different aligned sequences but the same dataset sequences
588      */
589     assertFalse(copy.getSequenceAt(0) == protein.getSequenceAt(0));
590     assertFalse(copy.getSequenceAt(1) == protein.getSequenceAt(1));
591     assertSame(copy.getSequenceAt(0).getDatasetSequence(), protein
592             .getSequenceAt(0).getDatasetSequence());
593     assertSame(copy.getSequenceAt(1).getDatasetSequence(), protein
594             .getSequenceAt(1).getDatasetSequence());
595
596     // TODO should the copy constructor copy the dataset?
597     // or make a new one referring to the same dataset sequences??
598     assertNull(copy.getDataset());
599     // TODO test metadata is copied when AlignmentI is a dataset
600
601     // assertArrayEquals(copy.getDataset().getSequencesArray(), protein
602     // .getDataset().getSequencesArray());
603   }
604
605   /**
606    * Test behaviour of createDataset
607    * 
608    * @throws IOException
609    */
610   @Test(groups = "Functional")
611   public void testCreateDatasetAlignment() throws IOException
612   {
613     AlignmentI protein = new FormatAdapter().readFile(AA_SEQS_1,
614             AppletFormatAdapter.PASTE, "FASTA");
615     /*
616      * create a dataset sequence on first sequence
617      * leave the second without one
618      */
619     protein.getSequenceAt(0).createDatasetSequence();
620     assertNotNull(protein.getSequenceAt(0).getDatasetSequence());
621     assertNull(protein.getSequenceAt(1).getDatasetSequence());
622
623     /*
624      * add a mapping to the alignment
625      */
626     AlignedCodonFrame acf = new AlignedCodonFrame();
627     protein.addCodonFrame(acf);
628     assertNull(protein.getDataset());
629     assertTrue(protein.getCodonFrames().contains(acf));
630
631     /*
632      * create the alignment dataset
633      * note this creates sequence datasets where missing
634      * as a side-effect (in this case, on seq2
635      */
636     // TODO promote this method to AlignmentI
637     ((Alignment) protein).createDatasetAlignment();
638
639     AlignmentI ds = protein.getDataset();
640
641     // side-effect: dataset created on second sequence
642     assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
643     // dataset alignment has references to dataset sequences
644     assertEquals(ds.getSequenceAt(0), protein.getSequenceAt(0)
645             .getDatasetSequence());
646     assertEquals(ds.getSequenceAt(1), protein.getSequenceAt(1)
647             .getDatasetSequence());
648
649     // codon frames should have been moved to the dataset
650     // getCodonFrames() should delegate to the dataset:
651     assertTrue(protein.getCodonFrames().contains(acf));
652     // prove the codon frames are indeed on the dataset:
653     assertTrue(ds.getCodonFrames().contains(acf));
654   }
655
656   /**
657    * tests the addition of *all* sequences referred to by a sequence being added
658    * to the dataset
659    */
660   @Test(groups = "Functional")
661   public void testCreateDatasetAlignmentWithMappedToSeqs()
662   {
663     // Alignment with two sequences, gapped.
664     SequenceI sq1 = new Sequence("sq1", "A--SDF");
665     SequenceI sq2 = new Sequence("sq2", "G--TRQ");
666
667     // cross-references to two more sequences.
668     DBRefEntry dbr = new DBRefEntry("SQ1", "", "sq3");
669     SequenceI sq3 = new Sequence("sq3", "VWANG");
670     dbr.setMap(new Mapping(sq3, new MapList(new int[] { 1, 4 }, new int[] {
671         2, 5 }, 1, 1)));
672     sq1.addDBRef(dbr);
673
674     SequenceI sq4 = new Sequence("sq4", "ERKWI");
675     DBRefEntry dbr2 = new DBRefEntry("SQ2", "", "sq4");
676     dbr2.setMap(new Mapping(sq4, new MapList(new int[] { 1, 4 }, new int[] {
677         2, 5 }, 1, 1)));
678     sq2.addDBRef(dbr2);
679     // and a 1:1 codonframe mapping between them.
680     AlignedCodonFrame alc = new AlignedCodonFrame();
681     alc.addMap(sq1, sq2, new MapList(new int[] { 1, 4 },
682             new int[] { 1, 4 }, 1, 1));
683
684     AlignmentI protein = new Alignment(new SequenceI[] { sq1, sq2 });
685
686     /*
687      * create the alignment dataset
688      * note this creates sequence datasets where missing
689      * as a side-effect (in this case, on seq2
690      */
691
692     // TODO promote this method to AlignmentI
693     ((Alignment) protein).createDatasetAlignment();
694
695     AlignmentI ds = protein.getDataset();
696
697     // should be 4 sequences in dataset - two materialised, and two propagated
698     // from dbref
699     assertEquals(4, ds.getHeight());
700     assertTrue(ds.getSequences().contains(sq1.getDatasetSequence()));
701     assertTrue(ds.getSequences().contains(sq2.getDatasetSequence()));
702     assertTrue(ds.getSequences().contains(sq3));
703     assertTrue(ds.getSequences().contains(sq4));
704     // Should have one codon frame mapping between sq1 and sq2 via dataset
705     // sequences
706     assertEquals(ds.getCodonFrame(sq1.getDatasetSequence()),
707             ds.getCodonFrame(sq2.getDatasetSequence()));
708   }
709
710   @Test(groups = "Functional")
711   public void testAddCodonFrame()
712   {
713     AlignmentI align = new Alignment(new SequenceI[] {});
714     AlignedCodonFrame acf = new AlignedCodonFrame();
715     align.addCodonFrame(acf);
716     assertEquals(1, align.getCodonFrames().size());
717     assertTrue(align.getCodonFrames().contains(acf));
718     // can't add the same object twice:
719     align.addCodonFrame(acf);
720     assertEquals(1, align.getCodonFrames().size());
721
722     // create dataset alignment - mappings move to dataset
723     ((Alignment) align).createDatasetAlignment();
724     assertSame(align.getCodonFrames(), align.getDataset().getCodonFrames());
725     assertEquals(1, align.getCodonFrames().size());
726
727     AlignedCodonFrame acf2 = new AlignedCodonFrame();
728     align.addCodonFrame(acf2);
729     assertTrue(align.getDataset().getCodonFrames().contains(acf));
730   }
731
732   @Test(groups = "Functional")
733   public void getVisibleStartAndEndIndexTest()
734   {
735     Sequence seq = new Sequence("testSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
736     AlignmentI align = new Alignment(new SequenceI[] { seq });
737     ArrayList<int[]> hiddenCols = new ArrayList<int[]>();
738
739     int[] startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
740     assertEquals(0, startEnd[0]);
741     assertEquals(25, startEnd[1]);
742
743     hiddenCols.add(new int[] { 0, 0 });
744     startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
745     assertEquals(1, startEnd[0]);
746     assertEquals(25, startEnd[1]);
747
748     hiddenCols.add(new int[] { 6, 9 });
749     hiddenCols.add(new int[] { 11, 12 });
750     startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
751     assertEquals(1, startEnd[0]);
752     assertEquals(25, startEnd[1]);
753
754     hiddenCols.add(new int[] { 24, 25 });
755     startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
756     System.out.println(startEnd[0] + " : " + startEnd[1]);
757     assertEquals(1, startEnd[0]);
758     assertEquals(23, startEnd[1]);
759   }
760 }