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