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