JAL-2446 merged to spike branch
[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.analysis.AlignmentGenerator;
31 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
32 import jalview.gui.JvOptionPane;
33 import jalview.io.DataSourceType;
34 import jalview.io.FileFormat;
35 import jalview.io.FileFormatI;
36 import jalview.io.FormatAdapter;
37 import jalview.util.MapList;
38
39 import java.io.IOException;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Iterator;
43 import java.util.List;
44
45 import org.testng.Assert;
46 import org.testng.annotations.BeforeClass;
47 import org.testng.annotations.BeforeMethod;
48 import org.testng.annotations.Test;
49
50 /**
51  * Unit tests for Alignment datamodel.
52  * 
53  * @author gmcarstairs
54  *
55  */
56 public class AlignmentTest
57 {
58
59   @BeforeClass(alwaysRun = true)
60   public void setUpJvOptionPane()
61   {
62     JvOptionPane.setInteractiveMode(false);
63     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
64   }
65
66   // @formatter:off
67   private static final String TEST_DATA = 
68           "# STOCKHOLM 1.0\n" +
69           "#=GS D.melanogaster.1 AC AY119185.1/838-902\n" +
70           "#=GS D.melanogaster.2 AC AC092237.1/57223-57161\n" +
71           "#=GS D.melanogaster.3 AC AY060611.1/560-627\n" +
72           "D.melanogaster.1          G.AGCC.CU...AUGAUCGA\n" +
73           "#=GR D.melanogaster.1 SS  ................((((\n" +
74           "D.melanogaster.2          C.AUUCAACU.UAUGAGGAU\n" +
75           "#=GR D.melanogaster.2 SS  ................((((\n" +
76           "D.melanogaster.3          G.UGGCGCU..UAUGACGCA\n" +
77           "#=GR D.melanogaster.3 SS  (.(((...(....(((((((\n" +
78           "//";
79
80   private static final String AA_SEQS_1 = 
81           ">Seq1Name/5-8\n" +
82           "K-QY--L\n" +
83           ">Seq2Name/12-15\n" +
84           "-R-FP-W-\n";
85
86   private static final String CDNA_SEQS_1 = 
87           ">Seq1Name/100-111\n" +
88           "AC-GG--CUC-CAA-CT\n" +
89           ">Seq2Name/200-211\n" +
90           "-CG-TTA--ACG---AAGT\n";
91
92   private static final String CDNA_SEQS_2 = 
93           ">Seq1Name/50-61\n" +
94           "GCTCGUCGTACT\n" +
95           ">Seq2Name/60-71\n" +
96           "GGGTCAGGCAGT\n";
97   // @formatter:on
98
99   private AlignmentI al;
100
101   /**
102    * Helper method to load an alignment and ensure dataset sequences are set up.
103    * 
104    * @param data
105    * @param format
106    *          TODO
107    * @return
108    * @throws IOException
109    */
110   protected AlignmentI loadAlignment(final String data, FileFormatI format)
111           throws IOException
112   {
113     AlignmentI a = new FormatAdapter().readFile(data, DataSourceType.PASTE,
114             format);
115     a.setDataset(null);
116     return a;
117   }
118
119   /**
120    * assert wrapper: tests all references in the given alignment are consistent
121    * 
122    * @param alignment
123    */
124   public static void assertAlignmentDatasetRefs(AlignmentI alignment)
125   {
126     verifyAlignmentDatasetRefs(alignment, true, null);
127   }
128
129   /**
130    * assert wrapper: tests all references in the given alignment are consistent
131    * 
132    * @param alignment
133    * @param message
134    *          - prefixed to any assert failed messages
135    */
136   public static void assertAlignmentDatasetRefs(AlignmentI alignment,
137           String message)
138   {
139     verifyAlignmentDatasetRefs(alignment, true, message);
140   }
141
142   /**
143    * verify sequence and dataset references are properly contained within
144    * dataset
145    * 
146    * @param alignment
147    *          - the alignmentI object to verify (either alignment or dataset)
148    * @param raiseAssert
149    *          - when set, testng assertions are raised.
150    * @param message
151    *          - null or a string message to prepend to the assert failed
152    *          messages.
153    * @return true if alignment references were in order, otherwise false.
154    */
155   public static boolean verifyAlignmentDatasetRefs(AlignmentI alignment,
156           boolean raiseAssert, String message)
157   {
158     if (message == null)
159     {
160       message = "";
161     }
162     if (alignment == null)
163     {
164       if (raiseAssert)
165       {
166         Assert.fail(message + "Alignment for verification was null.");
167       }
168       return false;
169     }
170     if (alignment.getDataset() != null)
171     {
172       AlignmentI dataset = alignment.getDataset();
173       // check all alignment sequences have their dataset within the dataset
174       for (SequenceI seq : alignment.getSequences())
175       {
176         SequenceI seqds = seq.getDatasetSequence();
177         if (seqds.getDatasetSequence() != null)
178         {
179           if (raiseAssert)
180           {
181             Assert.fail(message
182                     + " Alignment contained a sequence who's dataset sequence has a second dataset reference.");
183           }
184           return false;
185         }
186         if (dataset.findIndex(seqds) == -1)
187         {
188           if (raiseAssert)
189           {
190             Assert.fail(message
191                     + " Alignment contained a sequence who's dataset sequence was not in the dataset.");
192           }
193           return false;
194         }
195       }
196       return verifyAlignmentDatasetRefs(alignment.getDataset(),
197               raiseAssert, message);
198     }
199     else
200     {
201       int dsp = -1;
202       // verify all dataset sequences
203       for (SequenceI seqds : alignment.getSequences())
204       {
205         dsp++;
206         if (seqds.getDatasetSequence() != null)
207         {
208           if (raiseAssert)
209           {
210             Assert.fail(message
211                     + " Dataset contained a sequence with non-null dataset reference (ie not a dataset sequence!)");
212           }
213           return false;
214         }
215         int foundp = alignment.findIndex(seqds);
216         if (foundp != dsp)
217         {
218           if (raiseAssert)
219           {
220             Assert.fail(message
221                     + " Dataset sequence array contains a reference at "
222                     + dsp + " to a sequence first seen at " + foundp + " ("
223                     + seqds.toString() + ")");
224           }
225           return false;
226         }
227         if (seqds.getDBRefs() != null)
228         {
229           for (DBRefEntry dbr : seqds.getDBRefs())
230           {
231             if (dbr.getMap() != null)
232             {
233               SequenceI seqdbrmapto = dbr.getMap().getTo();
234               if (seqdbrmapto != null)
235               {
236                 if (seqdbrmapto.getDatasetSequence() != null)
237                 {
238                   if (raiseAssert)
239                   {
240                     Assert.fail(message
241                             + " DBRefEntry for sequence in alignment had map to sequence which was not a dataset sequence");
242                   }
243                   return false;
244
245                 }
246                 if (alignment.findIndex(dbr.getMap().getTo()) == -1)
247                 {
248                   if (raiseAssert)
249                   {
250                     Assert.fail(message
251                             + " DBRefEntry for sequence in alignment had map to sequence not in dataset");
252                   }
253                   return false;
254                 }
255               }
256             }
257           }
258         }
259       }
260       // finally, verify codonmappings involve only dataset sequences.
261       if (alignment.getCodonFrames() != null)
262       {
263         for (AlignedCodonFrame alc : alignment.getCodonFrames())
264         {
265           for (SequenceToSequenceMapping ssm : alc.getMappings())
266           {
267             if (ssm.getFromSeq().getDatasetSequence() != null)
268             {
269               if (raiseAssert)
270               {
271                 Assert.fail(message
272                         + " CodonFrame-SSM-FromSeq is not a dataset sequence");
273               }
274               return false;
275             }
276             if (alignment.findIndex(ssm.getFromSeq()) == -1)
277             {
278
279               if (raiseAssert)
280               {
281                 Assert.fail(message
282                         + " CodonFrame-SSM-FromSeq is not contained in dataset");
283               }
284               return false;
285             }
286             if (ssm.getMapping().getTo().getDatasetSequence() != null)
287             {
288               if (raiseAssert)
289               {
290                 Assert.fail(message
291                         + " CodonFrame-SSM-Mapping-ToSeq is not a dataset sequence");
292               }
293               return false;
294             }
295             if (alignment.findIndex(ssm.getMapping().getTo()) == -1)
296             {
297
298               if (raiseAssert)
299               {
300                 Assert.fail(message
301                         + " CodonFrame-SSM-Mapping-ToSeq is not contained in dataset");
302               }
303               return false;
304             }
305           }
306         }
307       }
308     }
309     return true; // all relationships verified!
310   }
311
312   /**
313    * call verifyAlignmentDatasetRefs with and without assertion raising enabled,
314    * to check expected pass/fail actually occurs in both conditions
315    * 
316    * @param al
317    * @param expected
318    * @param msg
319    */
320   private void assertVerifyAlignment(AlignmentI al, boolean expected,
321           String msg)
322   {
323     if (expected)
324     {
325       try
326       {
327
328         Assert.assertTrue(verifyAlignmentDatasetRefs(al, true, null),
329                 "Valid test alignment failed when raiseAsserts enabled:"
330                         + msg);
331       } catch (AssertionError ae)
332       {
333         ae.printStackTrace();
334         Assert.fail(
335                 "Valid test alignment raised assertion errors when raiseAsserts enabled: "
336                         + msg, ae);
337       }
338       // also check validation passes with asserts disabled
339       Assert.assertTrue(verifyAlignmentDatasetRefs(al, false, null),
340               "Valid test alignment tested false when raiseAsserts disabled:"
341                       + msg);
342     }
343     else
344     {
345       boolean assertRaised = false;
346       try
347       {
348         verifyAlignmentDatasetRefs(al, true, null);
349       } catch (AssertionError ae)
350       {
351         // expected behaviour
352         assertRaised = true;
353       }
354       if (!assertRaised)
355       {
356         Assert.fail("Invalid test alignment passed when raiseAsserts enabled:"
357                 + msg);
358       }
359       // also check validation passes with asserts disabled
360       Assert.assertFalse(verifyAlignmentDatasetRefs(al, false, null),
361               "Invalid test alignment tested true when raiseAsserts disabled:"
362                       + msg);
363     }
364   }
365
366   @Test(groups = { "Functional" })
367   public void testVerifyAlignmentDatasetRefs()
368   {
369     SequenceI sq1 = new Sequence("sq1", "ASFDD"), sq2 = new Sequence("sq2",
370             "TTTTTT");
371
372     // construct simple valid alignment dataset
373     Alignment al = new Alignment(new SequenceI[] { sq1, sq2 });
374     // expect this to pass
375     assertVerifyAlignment(al, true, "Simple valid alignment didn't verify");
376
377     // check test for sequence->datasetSequence validity
378     sq1.setDatasetSequence(sq2);
379     assertVerifyAlignment(al, false,
380             "didn't detect dataset sequence with a dataset sequence reference.");
381
382     sq1.setDatasetSequence(null);
383     assertVerifyAlignment(
384             al,
385             true,
386             "didn't reinstate validity after nulling dataset sequence dataset reference");
387
388     // now create dataset and check again
389     al.createDatasetAlignment();
390     assertNotNull(al.getDataset());
391
392     assertVerifyAlignment(al, true,
393             "verify failed after createDatasetAlignment");
394
395     // create a dbref on sq1 with a sequence ref to sq2
396     DBRefEntry dbrs1tos2 = new DBRefEntry("UNIPROT", "1", "Q111111");
397     dbrs1tos2.setMap(new Mapping(sq2.getDatasetSequence(),
398             new int[] { 1, 5 }, new int[] { 2, 6 }, 1, 1));
399     sq1.getDatasetSequence().addDBRef(dbrs1tos2);
400     assertVerifyAlignment(al, true,
401             "verify failed after addition of valid DBRefEntry/map");
402     // now create a dbref on a new sequence which maps to another sequence
403     // outside of the dataset
404     SequenceI sqout = new Sequence("sqout", "ututututucagcagcag"), sqnew = new Sequence(
405             "sqnew", "EEERRR");
406     DBRefEntry sqnewsqout = new DBRefEntry("ENAFOO", "1", "R000001");
407     sqnewsqout.setMap(new Mapping(sqout, new int[] { 1, 6 }, new int[] { 1,
408         18 }, 1, 3));
409     al.getDataset().addSequence(sqnew);
410
411     assertVerifyAlignment(al, true,
412             "verify failed after addition of new sequence to dataset");
413     // now start checking exception conditions
414     sqnew.addDBRef(sqnewsqout);
415     assertVerifyAlignment(
416             al,
417             false,
418             "verify passed when a dbref with map to sequence outside of dataset was added");
419     // make the verify pass by adding the outsider back in
420     al.getDataset().addSequence(sqout);
421     assertVerifyAlignment(al, true,
422             "verify should have passed after adding dbref->to sequence in to dataset");
423     // and now the same for a codon mapping...
424     SequenceI sqanotherout = new Sequence("sqanotherout",
425             "aggtutaggcagcagcag");
426
427     AlignedCodonFrame alc = new AlignedCodonFrame();
428     alc.addMap(sqanotherout, sqnew, new MapList(new int[] { 1, 6 },
429             new int[] { 1, 18 }, 3, 1));
430
431     al.addCodonFrame(alc);
432     Assert.assertEquals(al.getDataset().getCodonFrames().size(), 1);
433
434     assertVerifyAlignment(
435             al,
436             false,
437             "verify passed when alCodonFrame mapping to sequence outside of dataset was added");
438     // make the verify pass by adding the outsider back in
439     al.getDataset().addSequence(sqanotherout);
440     assertVerifyAlignment(
441             al,
442             true,
443             "verify should have passed once all sequences involved in alCodonFrame were added to dataset");
444     al.getDataset().addSequence(sqanotherout);
445     assertVerifyAlignment(al, false,
446             "verify should have failed when a sequence was added twice to the dataset");
447     al.getDataset().deleteSequence(sqanotherout);
448     assertVerifyAlignment(al, true,
449             "verify should have passed after duplicate entry for sequence was removed");
450   }
451
452   /**
453    * checks that the sequence data for an alignment's dataset is non-redundant.
454    * Fails if there are sequences with same id, sequence, start, and.
455    */
456
457   public static void assertDatasetIsNormalised(AlignmentI al)
458   {
459     assertDatasetIsNormalised(al, null);
460   }
461
462   /**
463    * checks that the sequence data for an alignment's dataset is non-redundant.
464    * Fails if there are sequences with same id, sequence, start, and.
465    * 
466    * @param al
467    *          - alignment to verify
468    * @param message
469    *          - null or message prepended to exception message.
470    */
471   public static void assertDatasetIsNormalised(AlignmentI al, String message)
472   {
473     if (al.getDataset() != null)
474     {
475       assertDatasetIsNormalised(al.getDataset(), message);
476       return;
477     }
478     /*
479      * look for pairs of sequences with same ID, start, end, and sequence
480      */
481     List<SequenceI> seqSet = al.getSequences();
482     for (int p = 0; p < seqSet.size(); p++)
483     {
484       SequenceI pSeq = seqSet.get(p);
485       for (int q = p + 1; q < seqSet.size(); q++)
486       {
487         SequenceI qSeq = seqSet.get(q);
488         if (pSeq.getStart() != qSeq.getStart())
489         {
490           continue;
491         }
492         if (pSeq.getEnd() != qSeq.getEnd())
493         {
494           continue;
495         }
496         if (!pSeq.getName().equals(qSeq.getName()))
497         {
498           continue;
499         }
500         if (!Arrays.equals(pSeq.getSequence(), qSeq.getSequence()))
501         {
502           continue;
503         }
504         Assert.fail((message == null ? "" : message + " :")
505                 + "Found similar sequences at position " + p + " and " + q
506                 + "\n" + pSeq.toString());
507       }
508     }
509   }
510
511   @Test(groups = { "Functional", "Asserts" })
512   public void testAssertDatasetIsNormalised()
513   {
514     Sequence sq1 = new Sequence("s1/1-4", "asdf");
515     Sequence sq1shift = new Sequence("s1/2-5", "asdf");
516     Sequence sq1seqd = new Sequence("s1/1-4", "asdt");
517     Sequence sq2 = new Sequence("s2/1-4", "asdf");
518     Sequence sq1dup = new Sequence("s1/1-4", "asdf");
519
520     Alignment al = new Alignment(new SequenceI[] { sq1 });
521     al.setDataset(null);
522
523     try
524     {
525       assertDatasetIsNormalised(al);
526     } catch (AssertionError ae)
527     {
528       Assert.fail("Single sequence should be valid normalised dataset.");
529     }
530     al.addSequence(sq2);
531     try
532     {
533       assertDatasetIsNormalised(al);
534     } catch (AssertionError ae)
535     {
536       Assert.fail("Two different sequences should be valid normalised dataset.");
537     }
538     /*
539      * now change sq2's name in the alignment. should still be valid
540      */
541     al.findName(sq2.getName()).setName("sq1");
542     try
543     {
544       assertDatasetIsNormalised(al);
545     } catch (AssertionError ae)
546     {
547       Assert.fail("Two different sequences in dataset, but same name in alignment, should be valid normalised dataset.");
548     }
549
550     al.addSequence(sq1seqd);
551     try
552     {
553       assertDatasetIsNormalised(al);
554     } catch (AssertionError ae)
555     {
556       Assert.fail("sq1 and sq1 with different sequence should be distinct.");
557     }
558
559     al.addSequence(sq1shift);
560     try
561     {
562       assertDatasetIsNormalised(al);
563     } catch (AssertionError ae)
564     {
565       Assert.fail("sq1 and sq1 with different start/end should be distinct.");
566     }
567     /*
568      * finally, the failure case
569      */
570     al.addSequence(sq1dup);
571     boolean ssertRaised = false;
572     try
573     {
574       assertDatasetIsNormalised(al);
575
576     } catch (AssertionError ae)
577     {
578       ssertRaised = true;
579     }
580     if (!ssertRaised)
581     {
582       Assert.fail("Expected identical sequence to raise exception.");
583     }
584   }
585
586   /*
587    * Read in Stockholm format test data including secondary structure
588    * annotations.
589    */
590   @BeforeMethod(alwaysRun = true)
591   public void setUp() throws IOException
592   {
593     al = loadAlignment(TEST_DATA, FileFormat.Stockholm);
594     int i = 0;
595     for (AlignmentAnnotation ann : al.getAlignmentAnnotation())
596     {
597       ann.setCalcId("CalcIdFor" + al.getSequenceAt(i).getName());
598       i++;
599     }
600   }
601
602   /**
603    * Test method that returns annotations that match on calcId.
604    */
605   @Test(groups = { "Functional" })
606   public void testFindAnnotation_byCalcId()
607   {
608     Iterable<AlignmentAnnotation> anns = al
609             .findAnnotation("CalcIdForD.melanogaster.2");
610     Iterator<AlignmentAnnotation> iter = anns.iterator();
611     assertTrue(iter.hasNext());
612     AlignmentAnnotation ann = iter.next();
613     assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
614     assertFalse(iter.hasNext());
615
616     // invalid id
617     anns = al.findAnnotation("CalcIdForD.melanogaster.?");
618     assertFalse(iter.hasNext());
619     anns = al.findAnnotation(null);
620     assertFalse(iter.hasNext());
621   }
622
623   /**
624    * Test method that returns annotations that match on reference sequence,
625    * label, or calcId.
626    */
627   @Test(groups = { "Functional" })
628   public void testFindAnnotations_bySeqLabelandorCalcId()
629   {
630     // TODO: finish testFindAnnotations_bySeqLabelandorCalcId test
631     /* Note - this is an incomplete test - need to check null or
632      * non-null [ matches, not matches ] behaviour for each of the three
633      * parameters..*/
634
635     // search for a single, unique calcId with wildcards on other params
636     Iterable<AlignmentAnnotation> anns = al.findAnnotations(null,
637             "CalcIdForD.melanogaster.2", null);
638     Iterator<AlignmentAnnotation> iter = anns.iterator();
639     assertTrue(iter.hasNext());
640     AlignmentAnnotation ann = iter.next();
641     assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
642     assertFalse(iter.hasNext());
643
644     // save reference to test sequence reference parameter
645     SequenceI rseq = ann.sequenceRef;
646
647     // search for annotation associated with a single sequence
648     anns = al.findAnnotations(rseq, null, null);
649     iter = anns.iterator();
650     assertTrue(iter.hasNext());
651     ann = iter.next();
652     assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
653     assertFalse(iter.hasNext());
654
655     // search for annotation with a non-existant calcId
656     anns = al.findAnnotations(null, "CalcIdForD.melanogaster.?", null);
657     iter = anns.iterator();
658     assertFalse(iter.hasNext());
659
660     // search for annotation with a particular label - expect three
661     anns = al.findAnnotations(null, null, "Secondary Structure");
662     iter = anns.iterator();
663     assertTrue(iter.hasNext());
664     iter.next();
665     assertTrue(iter.hasNext());
666     iter.next();
667     assertTrue(iter.hasNext());
668     iter.next();
669     // third found.. so
670     assertFalse(iter.hasNext());
671
672     // null on all parameters == find all annotations
673     anns = al.findAnnotations(null, null, null);
674     iter = anns.iterator();
675     int n = al.getAlignmentAnnotation().length;
676     while (iter.hasNext())
677     {
678       n--;
679       iter.next();
680     }
681     assertTrue("Found " + n + " fewer annotations from search.", n == 0);
682   }
683
684   @Test(groups = { "Functional" })
685   public void testDeleteAllAnnotations_includingAutocalculated()
686   {
687     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
688             "Consensus", 0.5);
689     aa.autoCalculated = true;
690     al.addAnnotation(aa);
691     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
692     assertEquals("Wrong number of annotations before deleting", 4,
693             anns.length);
694     al.deleteAllAnnotations(true);
695     assertEquals("Not all deleted", 0, al.getAlignmentAnnotation().length);
696   }
697
698   @Test(groups = { "Functional" })
699   public void testDeleteAllAnnotations_excludingAutocalculated()
700   {
701     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
702             "Consensus", 0.5);
703     aa.autoCalculated = true;
704     al.addAnnotation(aa);
705     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
706     assertEquals("Wrong number of annotations before deleting", 4,
707             anns.length);
708     al.deleteAllAnnotations(false);
709     assertEquals("Not just one annotation left", 1,
710             al.getAlignmentAnnotation().length);
711   }
712
713   /**
714    * Tests for realigning as per a supplied alignment: Dna as Dna.
715    * 
716    * Note: AlignedCodonFrame's state variables are named for protein-to-cDNA
717    * mapping, but can be exploited for a general 'sequence-to-sequence' mapping
718    * as here.
719    * 
720    * @throws IOException
721    */
722   @Test(groups = { "Functional" })
723   public void testAlignAs_dnaAsDna() throws IOException
724   {
725     // aligned cDNA:
726     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
727     // unaligned cDNA:
728     AlignmentI al2 = loadAlignment(CDNA_SEQS_2, FileFormat.Fasta);
729
730     /*
731      * Make mappings between sequences. The 'aligned cDNA' is playing the role
732      * of what would normally be protein here.
733      */
734     makeMappings(al1, al2);
735
736     ((Alignment) al2).alignAs(al1, false, true);
737     assertEquals("GC-TC--GUC-GTACT", al2.getSequenceAt(0)
738             .getSequenceAsString());
739     assertEquals("-GG-GTC--AGG--CAGT", al2.getSequenceAt(1)
740             .getSequenceAsString());
741   }
742
743   /**
744    * Aligning protein from cDNA.
745    * 
746    * @throws IOException
747    */
748   @Test(groups = { "Functional" })
749   public void testAlignAs_proteinAsCdna() throws IOException
750   {
751     // see also AlignmentUtilsTests
752     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
753     AlignmentI al2 = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
754     makeMappings(al1, al2);
755
756     // Fudge - alignProteinAsCdna expects mappings to be on protein
757     al2.getCodonFrames().addAll(al1.getCodonFrames());
758
759     ((Alignment) al2).alignAs(al1, false, true);
760     assertEquals("K-Q-Y-L-", al2.getSequenceAt(0).getSequenceAsString());
761     assertEquals("-R-F-P-W", al2.getSequenceAt(1).getSequenceAsString());
762   }
763
764   /**
765    * Test aligning cdna as per protein alignment.
766    * 
767    * @throws IOException
768    */
769   @Test(groups = { "Functional" }, enabled = true)
770   // TODO review / update this test after redesign of alignAs method
771   public void testAlignAs_cdnaAsProtein() throws IOException
772   {
773     /*
774      * Load alignments and add mappings for cDNA to protein
775      */
776     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
777     AlignmentI al2 = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
778     makeMappings(al1, al2);
779
780     /*
781      * Realign DNA; currently keeping existing gaps in introns only
782      */
783     ((Alignment) al1).alignAs(al2, false, true);
784     assertEquals("ACG---GCUCCA------ACT---", al1.getSequenceAt(0)
785             .getSequenceAsString());
786     assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
787             .getSequenceAsString());
788   }
789
790   /**
791    * Test aligning cdna as per protein - single sequences
792    * 
793    * @throws IOException
794    */
795   @Test(groups = { "Functional" }, enabled = true)
796   // TODO review / update this test after redesign of alignAs method
797   public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
798   {
799     /*
800      * simple case insert one gap
801      */
802     verifyAlignAs(">dna\nCAAaaa\n", ">protein\nQ-K\n", "CAA---aaa");
803
804     /*
805      * simple case but with sequence offsets
806      */
807     verifyAlignAs(">dna/5-10\nCAAaaa\n", ">protein/20-21\nQ-K\n",
808             "CAA---aaa");
809
810     /*
811      * insert gaps as per protein, drop gaps within codons
812      */
813     verifyAlignAs(">dna/10-18\nCA-Aa-aa--AGA\n", ">aa/6-8\n-Q-K--R\n",
814             "---CAA---aaa------AGA");
815   }
816
817   /**
818    * Helper method that makes mappings and then aligns the first alignment as
819    * the second
820    * 
821    * @param fromSeqs
822    * @param toSeqs
823    * @param expected
824    * @throws IOException
825    */
826   public void verifyAlignAs(String fromSeqs, String toSeqs, String expected)
827           throws IOException
828   {
829     /*
830      * Load alignments and add mappings from nucleotide to protein (or from
831      * first to second if both the same type)
832      */
833     AlignmentI al1 = loadAlignment(fromSeqs, FileFormat.Fasta);
834     AlignmentI al2 = loadAlignment(toSeqs, FileFormat.Fasta);
835     makeMappings(al1, al2);
836
837     /*
838      * Realign DNA; currently keeping existing gaps in introns only
839      */
840     ((Alignment) al1).alignAs(al2, false, true);
841     assertEquals(expected, al1.getSequenceAt(0).getSequenceAsString());
842   }
843
844   /**
845    * Helper method to make mappings between sequences, and add the mappings to
846    * the 'mapped from' alignment
847    * 
848    * @param alFrom
849    * @param alTo
850    */
851   public void makeMappings(AlignmentI alFrom, AlignmentI alTo)
852   {
853     int ratio = (alFrom.isNucleotide() == alTo.isNucleotide() ? 1 : 3);
854
855     AlignedCodonFrame acf = new AlignedCodonFrame();
856
857     for (int i = 0; i < alFrom.getHeight(); i++)
858     {
859       SequenceI seqFrom = alFrom.getSequenceAt(i);
860       SequenceI seqTo = alTo.getSequenceAt(i);
861       MapList ml = new MapList(new int[] { seqFrom.getStart(),
862           seqFrom.getEnd() },
863               new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
864       acf.addMap(seqFrom, seqTo, ml);
865     }
866
867     /*
868      * not sure whether mappings 'belong' or protein or nucleotide
869      * alignment, so adding to both ;~)
870      */
871     alFrom.addCodonFrame(acf);
872     alTo.addCodonFrame(acf);
873   }
874
875   /**
876    * Test aligning dna as per protein alignment, for the case where there are
877    * introns (i.e. some dna sites have no mapping from a peptide).
878    * 
879    * @throws IOException
880    */
881   @Test(groups = { "Functional" }, enabled = false)
882   // TODO review / update this test after redesign of alignAs method
883   public void testAlignAs_dnaAsProtein_withIntrons() throws IOException
884   {
885     /*
886      * Load alignments and add mappings for cDNA to protein
887      */
888     String dna1 = "A-Aa-gG-GCC-cT-TT";
889     String dna2 = "c--CCGgg-TT--T-AA-A";
890     AlignmentI al1 = loadAlignment(">Dna1/6-17\n" + dna1
891             + "\n>Dna2/20-31\n" + dna2 + "\n", FileFormat.Fasta);
892     AlignmentI al2 = loadAlignment(
893             ">Pep1/7-9\n-P--YK\n>Pep2/11-13\nG-T--F\n", FileFormat.Fasta);
894     AlignedCodonFrame acf = new AlignedCodonFrame();
895     // Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
896     // Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
897     MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
898     { 7, 9 }, 3, 1);
899     acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
900     MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
901         13 }, 3, 1);
902     acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
903     al2.addCodonFrame(acf);
904
905     /*
906      * Align ignoring gaps in dna introns and exons
907      */
908     ((Alignment) al1).alignAs(al2, false, false);
909     assertEquals("---AAagG------GCCcTTT", al1.getSequenceAt(0)
910             .getSequenceAsString());
911     // note 1 gap in protein corresponds to 'gg-' in DNA (3 positions)
912     assertEquals("cCCGgg-TTT------AAA", al1.getSequenceAt(1)
913             .getSequenceAsString());
914
915     /*
916      * Reset and realign, preserving gaps in dna introns and exons
917      */
918     al1.getSequenceAt(0).setSequence(dna1);
919     al1.getSequenceAt(1).setSequence(dna2);
920     ((Alignment) al1).alignAs(al2, true, true);
921     // String dna1 = "A-Aa-gG-GCC-cT-TT";
922     // String dna2 = "c--CCGgg-TT--T-AA-A";
923     // assumption: we include 'the greater of' protein/dna gap lengths, not both
924     assertEquals("---A-Aa-gG------GCC-cT-TT", al1.getSequenceAt(0)
925             .getSequenceAsString());
926     assertEquals("c--CCGgg-TT--T------AA-A", al1.getSequenceAt(1)
927             .getSequenceAsString());
928   }
929
930   @Test(groups = "Functional")
931   public void testCopyConstructor() throws IOException
932   {
933     AlignmentI protein = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
934     // create sequence and alignment datasets
935     protein.setDataset(null);
936     AlignedCodonFrame acf = new AlignedCodonFrame();
937     List<AlignedCodonFrame> acfList = Arrays.asList(new AlignedCodonFrame[]
938     { acf });
939     protein.getDataset().setCodonFrames(acfList);
940     AlignmentI copy = new Alignment(protein);
941
942     /*
943      * copy has different aligned sequences but the same dataset sequences
944      */
945     assertFalse(copy.getSequenceAt(0) == protein.getSequenceAt(0));
946     assertFalse(copy.getSequenceAt(1) == protein.getSequenceAt(1));
947     assertSame(copy.getSequenceAt(0).getDatasetSequence(), protein
948             .getSequenceAt(0).getDatasetSequence());
949     assertSame(copy.getSequenceAt(1).getDatasetSequence(), protein
950             .getSequenceAt(1).getDatasetSequence());
951
952     // TODO should the copy constructor copy the dataset?
953     // or make a new one referring to the same dataset sequences??
954     assertNull(copy.getDataset());
955     // TODO test metadata is copied when AlignmentI is a dataset
956
957     // assertArrayEquals(copy.getDataset().getSequencesArray(), protein
958     // .getDataset().getSequencesArray());
959   }
960
961   /**
962    * Test behaviour of createDataset
963    * 
964    * @throws IOException
965    */
966   @Test(groups = "Functional")
967   public void testCreateDatasetAlignment() throws IOException
968   {
969     AlignmentI protein = new FormatAdapter().readFile(AA_SEQS_1,
970             DataSourceType.PASTE, FileFormat.Fasta);
971     /*
972      * create a dataset sequence on first sequence
973      * leave the second without one
974      */
975     protein.getSequenceAt(0).createDatasetSequence();
976     assertNotNull(protein.getSequenceAt(0).getDatasetSequence());
977     assertNull(protein.getSequenceAt(1).getDatasetSequence());
978
979     /*
980      * add a mapping to the alignment
981      */
982     AlignedCodonFrame acf = new AlignedCodonFrame();
983     protein.addCodonFrame(acf);
984     assertNull(protein.getDataset());
985     assertTrue(protein.getCodonFrames().contains(acf));
986
987     /*
988      * create the alignment dataset
989      * note this creates sequence datasets where missing
990      * as a side-effect (in this case, on seq2
991      */
992     // TODO promote this method to AlignmentI
993     ((Alignment) protein).createDatasetAlignment();
994
995     AlignmentI ds = protein.getDataset();
996
997     // side-effect: dataset created on second sequence
998     assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
999     // dataset alignment has references to dataset sequences
1000     assertEquals(ds.getSequenceAt(0), protein.getSequenceAt(0)
1001             .getDatasetSequence());
1002     assertEquals(ds.getSequenceAt(1), protein.getSequenceAt(1)
1003             .getDatasetSequence());
1004
1005     // codon frames should have been moved to the dataset
1006     // getCodonFrames() should delegate to the dataset:
1007     assertTrue(protein.getCodonFrames().contains(acf));
1008     // prove the codon frames are indeed on the dataset:
1009     assertTrue(ds.getCodonFrames().contains(acf));
1010   }
1011
1012   /**
1013    * tests the addition of *all* sequences referred to by a sequence being added
1014    * to the dataset
1015    */
1016   @Test(groups = "Functional")
1017   public void testCreateDatasetAlignmentWithMappedToSeqs()
1018   {
1019     // Alignment with two sequences, gapped.
1020     SequenceI sq1 = new Sequence("sq1", "A--SDF");
1021     SequenceI sq2 = new Sequence("sq2", "G--TRQ");
1022
1023     // cross-references to two more sequences.
1024     DBRefEntry dbr = new DBRefEntry("SQ1", "", "sq3");
1025     SequenceI sq3 = new Sequence("sq3", "VWANG");
1026     dbr.setMap(new Mapping(sq3, new MapList(new int[] { 1, 4 }, new int[] {
1027         2, 5 }, 1, 1)));
1028     sq1.addDBRef(dbr);
1029
1030     SequenceI sq4 = new Sequence("sq4", "ERKWI");
1031     DBRefEntry dbr2 = new DBRefEntry("SQ2", "", "sq4");
1032     dbr2.setMap(new Mapping(sq4, new MapList(new int[] { 1, 4 }, new int[] {
1033         2, 5 }, 1, 1)));
1034     sq2.addDBRef(dbr2);
1035     // and a 1:1 codonframe mapping between them.
1036     AlignedCodonFrame alc = new AlignedCodonFrame();
1037     alc.addMap(sq1, sq2, new MapList(new int[] { 1, 4 },
1038             new int[] { 1, 4 }, 1, 1));
1039
1040     AlignmentI protein = new Alignment(new SequenceI[] { sq1, sq2 });
1041
1042     /*
1043      * create the alignment dataset
1044      * note this creates sequence datasets where missing
1045      * as a side-effect (in this case, on seq2
1046      */
1047
1048     // TODO promote this method to AlignmentI
1049     ((Alignment) protein).createDatasetAlignment();
1050
1051     AlignmentI ds = protein.getDataset();
1052
1053     // should be 4 sequences in dataset - two materialised, and two propagated
1054     // from dbref
1055     assertEquals(4, ds.getHeight());
1056     assertTrue(ds.getSequences().contains(sq1.getDatasetSequence()));
1057     assertTrue(ds.getSequences().contains(sq2.getDatasetSequence()));
1058     assertTrue(ds.getSequences().contains(sq3));
1059     assertTrue(ds.getSequences().contains(sq4));
1060     // Should have one codon frame mapping between sq1 and sq2 via dataset
1061     // sequences
1062     assertEquals(ds.getCodonFrame(sq1.getDatasetSequence()),
1063             ds.getCodonFrame(sq2.getDatasetSequence()));
1064   }
1065
1066   @Test(groups = "Functional")
1067   public void testAddCodonFrame()
1068   {
1069     AlignmentI align = new Alignment(new SequenceI[] {});
1070     AlignedCodonFrame acf = new AlignedCodonFrame();
1071     align.addCodonFrame(acf);
1072     assertEquals(1, align.getCodonFrames().size());
1073     assertTrue(align.getCodonFrames().contains(acf));
1074     // can't add the same object twice:
1075     align.addCodonFrame(acf);
1076     assertEquals(1, align.getCodonFrames().size());
1077
1078     // create dataset alignment - mappings move to dataset
1079     ((Alignment) align).createDatasetAlignment();
1080     assertSame(align.getCodonFrames(), align.getDataset().getCodonFrames());
1081     assertEquals(1, align.getCodonFrames().size());
1082
1083     AlignedCodonFrame acf2 = new AlignedCodonFrame();
1084     align.addCodonFrame(acf2);
1085     assertTrue(align.getDataset().getCodonFrames().contains(acf));
1086   }
1087
1088   @Test(groups = "Functional")
1089   public void testAddSequencePreserveDatasetIntegrity()
1090   {
1091     Sequence seq = new Sequence("testSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1092     Alignment align = new Alignment(new SequenceI[] { seq });
1093     align.createDatasetAlignment();
1094     AlignmentI ds = align.getDataset();
1095     SequenceI copy = new Sequence(seq);
1096     copy.insertCharAt(3, 5, '-');
1097     align.addSequence(copy);
1098     Assert.assertEquals(align.getDataset().getHeight(), 1,
1099             "Dataset shouldn't have more than one sequence.");
1100
1101     Sequence seq2 = new Sequence("newtestSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1102     align.addSequence(seq2);
1103     Assert.assertEquals(align.getDataset().getHeight(), 2,
1104             "Dataset should now have two sequences.");
1105
1106     assertAlignmentDatasetRefs(align,
1107             "addSequence broke dataset reference integrity");
1108   }
1109
1110   @Test(groups = "Functional")
1111   public void getVisibleStartAndEndIndexTest()
1112   {
1113     Sequence seq = new Sequence("testSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1114     AlignmentI align = new Alignment(new SequenceI[] { seq });
1115     ArrayList<int[]> hiddenCols = new ArrayList<int[]>();
1116
1117     int[] startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1118     assertEquals(0, startEnd[0]);
1119     assertEquals(25, startEnd[1]);
1120
1121     hiddenCols.add(new int[] { 0, 0 });
1122     startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1123     assertEquals(1, startEnd[0]);
1124     assertEquals(25, startEnd[1]);
1125
1126     hiddenCols.add(new int[] { 6, 9 });
1127     hiddenCols.add(new int[] { 11, 12 });
1128     startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1129     assertEquals(1, startEnd[0]);
1130     assertEquals(25, startEnd[1]);
1131
1132     hiddenCols.add(new int[] { 24, 25 });
1133     startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1134     System.out.println(startEnd[0] + " : " + startEnd[1]);
1135     assertEquals(1, startEnd[0]);
1136     assertEquals(23, startEnd[1]);
1137   }
1138
1139   /**
1140    * Tests that dbrefs with mappings to sequence get updated if the sequence
1141    * acquires a dataset sequence
1142    */
1143   @Test(groups = "Functional")
1144   public void testCreateDataset_updateDbrefMappings()
1145   {
1146     SequenceI pep = new Sequence("pep", "ASD");
1147     SequenceI dna = new Sequence("dna", "aaaGCCTCGGATggg");
1148     SequenceI cds = new Sequence("cds", "GCCTCGGAT");
1149
1150     // add dbref from dna to peptide
1151     DBRefEntry dbr = new DBRefEntry("UNIPROT", "", "pep");
1152     dbr.setMap(new Mapping(pep, new MapList(new int[] { 4, 15 }, new int[] {
1153         1, 4 }, 3, 1)));
1154     dna.addDBRef(dbr);
1155
1156     // add dbref from dna to peptide
1157     DBRefEntry dbr2 = new DBRefEntry("UNIPROT", "", "pep");
1158     dbr2.setMap(new Mapping(pep, new MapList(new int[] { 1, 12 }, new int[]
1159     { 1, 4 }, 3, 1)));
1160     cds.addDBRef(dbr2);
1161
1162     // add dbref from peptide to dna
1163     DBRefEntry dbr3 = new DBRefEntry("EMBL", "", "dna");
1164     dbr3.setMap(new Mapping(dna, new MapList(new int[] { 1, 4 }, new int[] {
1165         4, 15 }, 1, 3)));
1166     pep.addDBRef(dbr3);
1167
1168     // add dbref from peptide to cds
1169     DBRefEntry dbr4 = new DBRefEntry("EMBLCDS", "", "cds");
1170     dbr4.setMap(new Mapping(cds, new MapList(new int[] { 1, 4 }, new int[] {
1171         1, 12 }, 1, 3)));
1172     pep.addDBRef(dbr4);
1173
1174     AlignmentI protein = new Alignment(new SequenceI[] { pep });
1175
1176     /*
1177      * create the alignment dataset
1178      */
1179     ((Alignment) protein).createDatasetAlignment();
1180
1181     AlignmentI ds = protein.getDataset();
1182
1183     // should be 3 sequences in dataset
1184     assertEquals(3, ds.getHeight());
1185     assertTrue(ds.getSequences().contains(pep.getDatasetSequence()));
1186     assertTrue(ds.getSequences().contains(dna));
1187     assertTrue(ds.getSequences().contains(cds));
1188
1189     /*
1190      * verify peptide.cdsdbref.peptidedbref is now mapped to peptide dataset
1191      */
1192     DBRefEntry[] dbRefs = pep.getDBRefs();
1193     assertEquals(2, dbRefs.length);
1194     assertSame(dna, dbRefs[0].map.to);
1195     assertSame(cds, dbRefs[1].map.to);
1196     assertEquals(1, dna.getDBRefs().length);
1197     assertSame(pep.getDatasetSequence(), dna.getDBRefs()[0].map.to);
1198     assertEquals(1, cds.getDBRefs().length);
1199     assertSame(pep.getDatasetSequence(), cds.getDBRefs()[0].map.to);
1200   }
1201
1202   @Test(groups = { "Functional" })
1203   public void testFindGroup()
1204   {
1205     SequenceI seq1 = new Sequence("seq1", "ABCDEF---GHI");
1206     SequenceI seq2 = new Sequence("seq2", "---JKLMNO---");
1207     AlignmentI a = new Alignment(new SequenceI[] { seq1, seq2 });
1208
1209     assertNull(a.findGroup(null, 0));
1210     assertNull(a.findGroup(seq1, 1));
1211     assertNull(a.findGroup(seq1, -1));
1212
1213     /*
1214      * add a group consisting of just "DEF"
1215      */
1216     SequenceGroup sg1 = new SequenceGroup();
1217     sg1.addSequence(seq1, false);
1218     sg1.setStartRes(3);
1219     sg1.setEndRes(5);
1220     a.addGroup(sg1);
1221
1222     assertNull(a.findGroup(seq1, 2)); // position not in group
1223     assertNull(a.findGroup(seq1, 6)); // position not in group
1224     assertNull(a.findGroup(seq2, 5)); // sequence not in group
1225     assertSame(a.findGroup(seq1, 3), sg1); // yes
1226     assertSame(a.findGroup(seq1, 4), sg1);
1227     assertSame(a.findGroup(seq1, 5), sg1);
1228
1229     /*
1230      * add a group consisting of 
1231      * EF--
1232      * KLMN
1233      */
1234     SequenceGroup sg2 = new SequenceGroup();
1235     sg2.addSequence(seq1, false);
1236     sg2.addSequence(seq2, false);
1237     sg2.setStartRes(4);
1238     sg2.setEndRes(7);
1239     a.addGroup(sg2);
1240
1241     assertNull(a.findGroup(seq1, 2)); // unchanged
1242     assertSame(a.findGroup(seq1, 3), sg1); // unchanged
1243     /*
1244      * if a residue is in more than one group, method returns
1245      * the first found (in order groups were added)
1246      */
1247     assertSame(a.findGroup(seq1, 4), sg1);
1248     assertSame(a.findGroup(seq1, 5), sg1);
1249
1250     /*
1251      * seq2 only belongs to the second group
1252      */
1253     assertSame(a.findGroup(seq2, 4), sg2);
1254     assertSame(a.findGroup(seq2, 5), sg2);
1255     assertSame(a.findGroup(seq2, 6), sg2);
1256     assertSame(a.findGroup(seq2, 7), sg2);
1257     assertNull(a.findGroup(seq2, 3));
1258     assertNull(a.findGroup(seq2, 8));
1259   }
1260
1261   @Test(groups = { "Functional" })
1262   public void testDeleteSequenceByIndex()
1263   {
1264     // create random alignment
1265     AlignmentGenerator gen = new AlignmentGenerator(false);
1266     AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1267
1268     // delete sequence 10, alignment reduced by 1
1269     int height = a.getAbsoluteHeight();
1270     a.deleteSequence(10);
1271     assertEquals(a.getAbsoluteHeight(), height - 1);
1272
1273     // try to delete -ve index, nothing happens
1274     a.deleteSequence(-1);
1275     assertEquals(a.getAbsoluteHeight(), height - 1);
1276
1277     // try to delete beyond end of alignment, nothing happens
1278     a.deleteSequence(14);
1279     assertEquals(a.getAbsoluteHeight(), height - 1);
1280   }
1281
1282   @Test(groups = { "Functional" })
1283   public void testDeleteSequenceBySeq()
1284   {
1285     // create random alignment
1286     AlignmentGenerator gen = new AlignmentGenerator(false);
1287     AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1288
1289     // delete sequence 10, alignment reduced by 1
1290     int height = a.getAbsoluteHeight();
1291     SequenceI seq = a.getSequenceAt(10);
1292     a.deleteSequence(seq);
1293     assertEquals(a.getAbsoluteHeight(), height - 1);
1294
1295     // try to delete non-existent sequence, nothing happens
1296     seq = new Sequence("cds", "GCCTCGGAT");
1297     assertEquals(a.getAbsoluteHeight(), height - 1);
1298   }
1299
1300   @Test(groups = { "Functional" })
1301   public void testDeleteHiddenSequence()
1302   {
1303     // create random alignment
1304     AlignmentGenerator gen = new AlignmentGenerator(false);
1305     AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1306
1307     // delete a sequence which is hidden, check it is NOT removed from hidden
1308     // sequences
1309     int height = a.getAbsoluteHeight();
1310     SequenceI seq = a.getSequenceAt(2);
1311     a.getHiddenSequences().hideSequence(seq);
1312     assertEquals(a.getHiddenSequences().getSize(), 1);
1313     a.deleteSequence(2);
1314     assertEquals(a.getAbsoluteHeight(), height - 1);
1315     assertEquals(a.getHiddenSequences().getSize(), 1);
1316
1317     // delete a sequence which is not hidden, check hiddenSequences are not
1318     // affected
1319     a.deleteSequence(10);
1320     assertEquals(a.getAbsoluteHeight(), height - 2);
1321     assertEquals(a.getHiddenSequences().getSize(), 1);
1322   }
1323
1324   @Test(
1325     groups = "Functional",
1326     expectedExceptions = { IllegalArgumentException.class })
1327   public void testSetDataset_selfReference()
1328   {
1329     SequenceI seq = new Sequence("a", "a");
1330     AlignmentI alignment = new Alignment(new SequenceI[] { seq });
1331     alignment.setDataset(alignment);
1332   }
1333 }