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