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