insignificant test file changes
[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.Comparison;
38 import jalview.util.MapList;
39
40 import java.io.IOException;
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
247                 SequenceI x = dbr.getMap().getTo();
248 //                System.out.println(alignment.toString());
249 //                System.out.println(dbr);
250 //                System.out.println("map " + dbr.getMap());
251 //                System.out.println("to " + dbr.getMap().getTo());
252 //                if (x.toString().indexOf("ENSP00000395337") >= 0)
253 //                {
254 //                  // The TO name here is "ENSP00000395337"
255 //                  // But the name in the table is "LDAH_HUMAN"
256 //                  System.out.println(x.getSequenceAsString());
257 //                  SequenceI y = alignment.getSequenceAt(0);
258 //                  System.out.println(y.getSequenceAsString());
259 //                  System.out.println(x.getSequenceAsString()
260 //                          .equals(y.getSequenceAsString()));
261 //
262 //                }
263                 if (alignment.findIndex(x) == -1)
264                 {
265                   if (raiseAssert)
266                   {
267                     Assert.fail(message
268                             + " DBRefEntry " + dbr + " for sequence "
269                             + seqds
270                             + " in alignment has map to sequence not in dataset");
271                   }
272                   return false;
273                 }
274               }
275             }
276           }
277         }
278       }
279       // finally, verify codonmappings involve only dataset sequences.
280       if (alignment.getCodonFrames() != null)
281       {
282         for (AlignedCodonFrame alc : alignment.getCodonFrames())
283         {
284           for (SequenceToSequenceMapping ssm : alc.getMappings())
285           {
286             if (ssm.getFromSeq().getDatasetSequence() != null)
287             {
288               if (raiseAssert)
289               {
290                 Assert.fail(message
291                         + " CodonFrame-SSM-FromSeq is not a dataset sequence");
292               }
293               return false;
294             }
295             if (alignment.findIndex(ssm.getFromSeq()) == -1)
296             {
297
298               if (raiseAssert)
299               {
300                 Assert.fail(message
301                         + " CodonFrame-SSM-FromSeq is not contained in dataset");
302               }
303               return false;
304             }
305             if (ssm.getMapping().getTo().getDatasetSequence() != null)
306             {
307               if (raiseAssert)
308               {
309                 Assert.fail(message
310                         + " CodonFrame-SSM-Mapping-ToSeq is not a dataset sequence");
311               }
312               return false;
313             }
314             if (alignment.findIndex(ssm.getMapping().getTo()) == -1)
315             {
316
317               if (raiseAssert)
318               {
319                 Assert.fail(message
320                         + " CodonFrame-SSM-Mapping-ToSeq is not contained in dataset");
321               }
322               return false;
323             }
324           }
325         }
326       }
327     }
328     return true; // all relationships verified!
329   }
330
331   /**
332    * call verifyAlignmentDatasetRefs with and without assertion raising enabled,
333    * to check expected pass/fail actually occurs in both conditions
334    * 
335    * @param al
336    * @param expected
337    * @param msg
338    */
339   private void assertVerifyAlignment(AlignmentI al, boolean expected,
340           String msg)
341   {
342     if (expected)
343     {
344       try
345       {
346
347         Assert.assertTrue(verifyAlignmentDatasetRefs(al, true, null),
348                 "Valid test alignment failed when raiseAsserts enabled:"
349                         + msg);
350       } catch (AssertionError ae)
351       {
352         ae.printStackTrace();
353         Assert.fail(
354                 "Valid test alignment raised assertion errors when raiseAsserts enabled: "
355                         + msg, ae);
356       }
357       // also check validation passes with asserts disabled
358       Assert.assertTrue(verifyAlignmentDatasetRefs(al, false, null),
359               "Valid test alignment tested false when raiseAsserts disabled:"
360                       + msg);
361     }
362     else
363     {
364       boolean assertRaised = false;
365       try
366       {
367         verifyAlignmentDatasetRefs(al, true, null);
368       } catch (AssertionError ae)
369       {
370         // expected behaviour
371         assertRaised = true;
372       }
373       if (!assertRaised)
374       {
375         Assert.fail("Invalid test alignment passed when raiseAsserts enabled:"
376                 + msg);
377       }
378       // also check validation passes with asserts disabled
379       Assert.assertFalse(verifyAlignmentDatasetRefs(al, false, null),
380               "Invalid test alignment tested true when raiseAsserts disabled:"
381                       + msg);
382     }
383   }
384
385   @Test(groups = { "Functional" })
386   public void testVerifyAlignmentDatasetRefs()
387   {
388     SequenceI sq1 = new Sequence("sq1", "ASFDD"), sq2 = new Sequence("sq2",
389             "TTTTTT");
390
391     // construct simple valid alignment dataset
392     Alignment al = new Alignment(new SequenceI[] { sq1, sq2 });
393     // expect this to pass
394     assertVerifyAlignment(al, true, "Simple valid alignment didn't verify");
395
396     // check test for sequence->datasetSequence validity
397     sq1.setDatasetSequence(sq2);
398     assertVerifyAlignment(al, false,
399             "didn't detect dataset sequence with a dataset sequence reference.");
400
401     sq1.setDatasetSequence(null);
402     assertVerifyAlignment(
403             al,
404             true,
405             "didn't reinstate validity after nulling dataset sequence dataset reference");
406
407     // now create dataset and check again
408     al.createDatasetAlignment();
409     assertNotNull(al.getDataset());
410
411     assertVerifyAlignment(al, true,
412             "verify failed after createDatasetAlignment");
413
414     // create a dbref on sq1 with a sequence ref to sq2
415     DBRefEntry dbrs1tos2 = new DBRefEntry("UNIPROT", "1", "Q111111");
416     dbrs1tos2.setMap(new Mapping(sq2.getDatasetSequence(),
417             new int[] { 1, 5 }, new int[] { 2, 6 }, 1, 1));
418     sq1.getDatasetSequence().addDBRef(dbrs1tos2);
419     assertVerifyAlignment(al, true,
420             "verify failed after addition of valid DBRefEntry/map");
421     // now create a dbref on a new sequence which maps to another sequence
422     // outside of the dataset
423     SequenceI sqout = new Sequence("sqout", "ututututucagcagcag"), sqnew = new Sequence(
424             "sqnew", "EEERRR");
425     DBRefEntry sqnewsqout = new DBRefEntry("ENAFOO", "1", "R000001");
426     sqnewsqout.setMap(new Mapping(sqout, new int[] { 1, 6 }, new int[] { 1,
427         18 }, 1, 3));
428     al.getDataset().addSequence(sqnew);
429
430     assertVerifyAlignment(al, true,
431             "verify failed after addition of new sequence to dataset");
432     // now start checking exception conditions
433     sqnew.addDBRef(sqnewsqout);
434     assertVerifyAlignment(
435             al,
436             false,
437             "verify passed when a dbref with map to sequence outside of dataset was added");
438     // make the verify pass by adding the outsider back in
439     al.getDataset().addSequence(sqout);
440     assertVerifyAlignment(al, true,
441             "verify should have passed after adding dbref->to sequence in to dataset");
442     // and now the same for a codon mapping...
443     SequenceI sqanotherout = new Sequence("sqanotherout",
444             "aggtutaggcagcagcag");
445
446     AlignedCodonFrame alc = new AlignedCodonFrame();
447     alc.addMap(sqanotherout, sqnew, new MapList(new int[] { 1, 6 },
448             new int[] { 1, 18 }, 3, 1));
449
450     al.addCodonFrame(alc);
451     Assert.assertEquals(al.getDataset().getCodonFrames().size(), 1);
452
453     assertVerifyAlignment(
454             al,
455             false,
456             "verify passed when alCodonFrame mapping to sequence outside of dataset was added");
457     // make the verify pass by adding the outsider back in
458     al.getDataset().addSequence(sqanotherout);
459     assertVerifyAlignment(
460             al,
461             true,
462             "verify should have passed once all sequences involved in alCodonFrame were added to dataset");
463     al.getDataset().addSequence(sqanotherout);
464     assertVerifyAlignment(al, false,
465             "verify should have failed when a sequence was added twice to the dataset");
466     al.getDataset().deleteSequence(sqanotherout);
467     assertVerifyAlignment(al, true,
468             "verify should have passed after duplicate entry for sequence was removed");
469   }
470
471   /**
472    * checks that the sequence data for an alignment's dataset is non-redundant.
473    * Fails if there are sequences with same id, sequence, start, and.
474    */
475
476   public static void assertDatasetIsNormalised(AlignmentI al)
477   {
478     assertDatasetIsNormalised(al, null);
479   }
480
481   /**
482    * checks that the sequence data for an alignment's dataset is non-redundant.
483    * Fails if there are sequences with same id, sequence, start, and.
484    * 
485    * @param al
486    *          - alignment to verify
487    * @param message
488    *          - null or message prepended to exception message.
489    */
490   public static void assertDatasetIsNormalised(AlignmentI al, String message)
491   {
492     if (al.getDataset() != null)
493     {
494       assertDatasetIsNormalised(al.getDataset(), message);
495       return;
496     }
497     /*
498      * look for pairs of sequences with same ID, start, end, and sequence
499      */
500     List<SequenceI> seqSet = al.getSequences();
501     for (int p = 0; p < seqSet.size(); p++)
502     {
503       SequenceI pSeq = seqSet.get(p);
504       for (int q = p + 1; q < seqSet.size(); q++)
505       {
506         SequenceI qSeq = seqSet.get(q);
507         if (pSeq.getStart() != qSeq.getStart())
508         {
509           continue;
510         }
511         if (pSeq.getEnd() != qSeq.getEnd())
512         {
513           continue;
514         }
515         if (!pSeq.getName().equals(qSeq.getName()))
516         {
517           continue;
518         }
519         if (!Arrays.equals(pSeq.getSequence(), qSeq.getSequence()))
520         {
521           continue;
522         }
523         Assert.fail((message == null ? "" : message + " :")
524                 + "Found similar sequences at position " + p + " and " + q
525                 + "\n" + pSeq.toString());
526       }
527     }
528   }
529
530   @Test(groups = { "Functional", "Asserts" })
531   public void testAssertDatasetIsNormalised()
532   {
533     Sequence sq1 = new Sequence("s1/1-4", "asdf");
534     Sequence sq1shift = new Sequence("s1/2-5", "asdf");
535     Sequence sq1seqd = new Sequence("s1/1-4", "asdt");
536     Sequence sq2 = new Sequence("s2/1-4", "asdf");
537     Sequence sq1dup = new Sequence("s1/1-4", "asdf");
538
539     Alignment al = new Alignment(new SequenceI[] { sq1 });
540     al.setDataset(null);
541
542     try
543     {
544       assertDatasetIsNormalised(al);
545     } catch (AssertionError ae)
546     {
547       Assert.fail("Single sequence should be valid normalised dataset.");
548     }
549     al.addSequence(sq2);
550     try
551     {
552       assertDatasetIsNormalised(al);
553     } catch (AssertionError ae)
554     {
555       Assert.fail("Two different sequences should be valid normalised dataset.");
556     }
557     /*
558      * now change sq2's name in the alignment. should still be valid
559      */
560     al.findName(sq2.getName()).setName("sq1");
561     try
562     {
563       assertDatasetIsNormalised(al);
564     } catch (AssertionError ae)
565     {
566       Assert.fail("Two different sequences in dataset, but same name in alignment, should be valid normalised dataset.");
567     }
568
569     al.addSequence(sq1seqd);
570     try
571     {
572       assertDatasetIsNormalised(al);
573     } catch (AssertionError ae)
574     {
575       Assert.fail("sq1 and sq1 with different sequence should be distinct.");
576     }
577
578     al.addSequence(sq1shift);
579     try
580     {
581       assertDatasetIsNormalised(al);
582     } catch (AssertionError ae)
583     {
584       Assert.fail("sq1 and sq1 with different start/end should be distinct.");
585     }
586     /*
587      * finally, the failure case
588      */
589     al.addSequence(sq1dup);
590     boolean ssertRaised = false;
591     try
592     {
593       assertDatasetIsNormalised(al);
594
595     } catch (AssertionError ae)
596     {
597       ssertRaised = true;
598     }
599     if (!ssertRaised)
600     {
601       Assert.fail("Expected identical sequence to raise exception.");
602     }
603   }
604
605   /*
606    * Read in Stockholm format test data including secondary structure
607    * annotations.
608    */
609   @BeforeMethod(alwaysRun = true)
610   public void setUp() throws IOException
611   {
612     al = loadAlignment(TEST_DATA, FileFormat.Stockholm);
613     int i = 0;
614     for (AlignmentAnnotation ann : al.getAlignmentAnnotation())
615     {
616       ann.setCalcId("CalcIdFor" + al.getSequenceAt(i).getName());
617       i++;
618     }
619   }
620
621   /**
622    * Test method that returns annotations that match on calcId.
623    */
624   @Test(groups = { "Functional" })
625   public void testFindAnnotation_byCalcId()
626   {
627     Iterable<AlignmentAnnotation> anns = al
628             .findAnnotation("CalcIdForD.melanogaster.2");
629     Iterator<AlignmentAnnotation> iter = anns.iterator();
630     assertTrue(iter.hasNext());
631     AlignmentAnnotation ann = iter.next();
632     assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
633     assertFalse(iter.hasNext());
634
635     // invalid id
636     anns = al.findAnnotation("CalcIdForD.melanogaster.?");
637     assertFalse(iter.hasNext());
638     anns = al.findAnnotation(null);
639     assertFalse(iter.hasNext());
640   }
641
642   /**
643    * Test method that returns annotations that match on reference sequence,
644    * label, or calcId.
645    */
646   @Test(groups = { "Functional" })
647   public void testFindAnnotations_bySeqLabelandorCalcId()
648   {
649     // TODO: finish testFindAnnotations_bySeqLabelandorCalcId test
650     /* Note - this is an incomplete test - need to check null or
651      * non-null [ matches, not matches ] behaviour for each of the three
652      * parameters..*/
653
654     // search for a single, unique calcId with wildcards on other params
655     Iterable<AlignmentAnnotation> anns = al.findAnnotations(null,
656             "CalcIdForD.melanogaster.2", null);
657     Iterator<AlignmentAnnotation> iter = anns.iterator();
658     assertTrue(iter.hasNext());
659     AlignmentAnnotation ann = iter.next();
660     assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
661     assertFalse(iter.hasNext());
662
663     // save reference to test sequence reference parameter
664     SequenceI rseq = ann.sequenceRef;
665
666     // search for annotation associated with a single sequence
667     anns = al.findAnnotations(rseq, null, null);
668     iter = anns.iterator();
669     assertTrue(iter.hasNext());
670     ann = iter.next();
671     assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
672     assertFalse(iter.hasNext());
673
674     // search for annotation with a non-existant calcId
675     anns = al.findAnnotations(null, "CalcIdForD.melanogaster.?", null);
676     iter = anns.iterator();
677     assertFalse(iter.hasNext());
678
679     // search for annotation with a particular label - expect three
680     anns = al.findAnnotations(null, null, "Secondary Structure");
681     iter = anns.iterator();
682     assertTrue(iter.hasNext());
683     iter.next();
684     assertTrue(iter.hasNext());
685     iter.next();
686     assertTrue(iter.hasNext());
687     iter.next();
688     // third found.. so
689     assertFalse(iter.hasNext());
690
691     // search for annotation on one sequence with a particular label - expect
692     // one
693     SequenceI sqfound;
694     anns = al.findAnnotations(sqfound = al.getSequenceAt(1), null,
695             "Secondary Structure");
696     iter = anns.iterator();
697     assertTrue(iter.hasNext());
698     // expect reference to sequence 1 in the alignment
699     assertTrue(sqfound == iter.next().sequenceRef);
700     assertFalse(iter.hasNext());
701
702     // null on all parameters == find all annotations
703     anns = al.findAnnotations(null, null, null);
704     iter = anns.iterator();
705     int n = al.getAlignmentAnnotation().length;
706     while (iter.hasNext())
707     {
708       n--;
709       iter.next();
710     }
711     assertTrue("Found " + n + " fewer annotations from search.", n == 0);
712   }
713
714   @Test(groups = { "Functional" })
715   public void testDeleteAllAnnotations_includingAutocalculated()
716   {
717     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
718             "Consensus", 0.5);
719     aa.autoCalculated = true;
720     al.addAnnotation(aa);
721     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
722     assertEquals("Wrong number of annotations before deleting", 4,
723             anns.length);
724     al.deleteAllAnnotations(true);
725     assertEquals("Not all deleted", 0, al.getAlignmentAnnotation().length);
726   }
727
728   @Test(groups = { "Functional" })
729   public void testDeleteAllAnnotations_excludingAutocalculated()
730   {
731     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
732             "Consensus", 0.5);
733     aa.autoCalculated = true;
734     al.addAnnotation(aa);
735     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
736     assertEquals("Wrong number of annotations before deleting", 4,
737             anns.length);
738     al.deleteAllAnnotations(false);
739     assertEquals("Not just one annotation left", 1,
740             al.getAlignmentAnnotation().length);
741   }
742
743   /**
744    * Tests for realigning as per a supplied alignment: Dna as Dna.
745    * 
746    * Note: AlignedCodonFrame's state variables are named for protein-to-cDNA
747    * mapping, but can be exploited for a general 'sequence-to-sequence' mapping
748    * as here.
749    * 
750    * @throws IOException
751    */
752   @Test(groups = { "Functional" })
753   public void testAlignAs_dnaAsDna() throws IOException
754   {
755     // aligned cDNA:
756     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
757     // unaligned cDNA:
758     AlignmentI al2 = loadAlignment(CDNA_SEQS_2, FileFormat.Fasta);
759
760     /*
761      * Make mappings between sequences. The 'aligned cDNA' is playing the role
762      * of what would normally be protein here.
763      */
764     makeMappings(al1, al2);
765
766     ((Alignment) al2).alignAs(al1, false, true);
767     assertEquals("GC-TC--GUC-GTACT", al2.getSequenceAt(0)
768             .getSequenceAsString());
769     assertEquals("-GG-GTC--AGG--CAGT", al2.getSequenceAt(1)
770             .getSequenceAsString());
771   }
772
773   /**
774    * Aligning protein from cDNA.
775    * 
776    * @throws IOException
777    */
778   @Test(groups = { "Functional" })
779   public void testAlignAs_proteinAsCdna() throws IOException
780   {
781     // see also AlignmentUtilsTests
782     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
783     AlignmentI al2 = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
784     makeMappings(al1, al2);
785
786     // Fudge - alignProteinAsCdna expects mappings to be on protein
787     al2.getCodonFrames().addAll(al1.getCodonFrames());
788
789     ((Alignment) al2).alignAs(al1, false, true);
790     assertEquals("K-Q-Y-L-", al2.getSequenceAt(0).getSequenceAsString());
791     assertEquals("-R-F-P-W", al2.getSequenceAt(1).getSequenceAsString());
792   }
793
794   /**
795    * Test aligning cdna as per protein alignment.
796    * 
797    * @throws IOException
798    */
799   @Test(groups = { "Functional" }, enabled = true)
800   // TODO review / update this test after redesign of alignAs method
801   public void testAlignAs_cdnaAsProtein() throws IOException
802   {
803     /*
804      * Load alignments and add mappings for cDNA to protein
805      */
806     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
807     AlignmentI al2 = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
808     makeMappings(al1, al2);
809
810     /*
811      * Realign DNA; currently keeping existing gaps in introns only
812      */
813     ((Alignment) al1).alignAs(al2, false, true);
814     assertEquals("ACG---GCUCCA------ACT---", al1.getSequenceAt(0)
815             .getSequenceAsString());
816     assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
817             .getSequenceAsString());
818   }
819
820   /**
821    * Test aligning cdna as per protein - single sequences
822    * 
823    * @throws IOException
824    */
825   @Test(groups = { "Functional" }, enabled = true)
826   // TODO review / update this test after redesign of alignAs method
827   public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
828   {
829     /*
830      * simple case insert one gap
831      */
832     verifyAlignAs(">dna\nCAAaaa\n", ">protein\nQ-K\n", "CAA---aaa");
833
834     /*
835      * simple case but with sequence offsets
836      */
837     verifyAlignAs(">dna/5-10\nCAAaaa\n", ">protein/20-21\nQ-K\n",
838             "CAA---aaa");
839
840     /*
841      * insert gaps as per protein, drop gaps within codons
842      */
843     verifyAlignAs(">dna/10-18\nCA-Aa-aa--AGA\n", ">aa/6-8\n-Q-K--R\n",
844             "---CAA---aaa------AGA");
845   }
846
847   /**
848    * Helper method that makes mappings and then aligns the first alignment as
849    * the second
850    * 
851    * @param fromSeqs
852    * @param toSeqs
853    * @param expected
854    * @throws IOException
855    */
856   public void verifyAlignAs(String fromSeqs, String toSeqs, String expected)
857           throws IOException
858   {
859     /*
860      * Load alignments and add mappings from nucleotide to protein (or from
861      * first to second if both the same type)
862      */
863     AlignmentI al1 = loadAlignment(fromSeqs, FileFormat.Fasta);
864     AlignmentI al2 = loadAlignment(toSeqs, FileFormat.Fasta);
865     makeMappings(al1, al2);
866
867     /*
868      * Realign DNA; currently keeping existing gaps in introns only
869      */
870     ((Alignment) al1).alignAs(al2, false, true);
871     assertEquals(expected, al1.getSequenceAt(0).getSequenceAsString());
872   }
873
874   /**
875    * Helper method to make mappings between sequences, and add the mappings to
876    * the 'mapped from' alignment
877    * 
878    * @param alFrom
879    * @param alTo
880    */
881   public void makeMappings(AlignmentI alFrom, AlignmentI alTo)
882   {
883     int ratio = (alFrom.isNucleotide() == alTo.isNucleotide() ? 1 : 3);
884
885     AlignedCodonFrame acf = new AlignedCodonFrame();
886
887     for (int i = 0; i < alFrom.getHeight(); i++)
888     {
889       SequenceI seqFrom = alFrom.getSequenceAt(i);
890       SequenceI seqTo = alTo.getSequenceAt(i);
891       MapList ml = new MapList(new int[] { seqFrom.getStart(),
892           seqFrom.getEnd() },
893               new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
894       acf.addMap(seqFrom, seqTo, ml);
895     }
896
897     /*
898      * not sure whether mappings 'belong' or protein or nucleotide
899      * alignment, so adding to both ;~)
900      */
901     alFrom.addCodonFrame(acf);
902     alTo.addCodonFrame(acf);
903   }
904
905   /**
906    * Test aligning dna as per protein alignment, for the case where there are
907    * introns (i.e. some dna sites have no mapping from a peptide).
908    * 
909    * @throws IOException
910    */
911   @Test(groups = { "Functional" }, enabled = false)
912   // TODO review / update this test after redesign of alignAs method
913   public void testAlignAs_dnaAsProtein_withIntrons() throws IOException
914   {
915     /*
916      * Load alignments and add mappings for cDNA to protein
917      */
918     String dna1 = "A-Aa-gG-GCC-cT-TT";
919     String dna2 = "c--CCGgg-TT--T-AA-A";
920     AlignmentI al1 = loadAlignment(">Dna1/6-17\n" + dna1
921             + "\n>Dna2/20-31\n" + dna2 + "\n", FileFormat.Fasta);
922     AlignmentI al2 = loadAlignment(
923             ">Pep1/7-9\n-P--YK\n>Pep2/11-13\nG-T--F\n", FileFormat.Fasta);
924     AlignedCodonFrame acf = new AlignedCodonFrame();
925     // Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
926     // Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
927     MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
928     { 7, 9 }, 3, 1);
929     acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
930     MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
931         13 }, 3, 1);
932     acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
933     al2.addCodonFrame(acf);
934
935     /*
936      * Align ignoring gaps in dna introns and exons
937      */
938     ((Alignment) al1).alignAs(al2, false, false);
939     assertEquals("---AAagG------GCCcTTT", al1.getSequenceAt(0)
940             .getSequenceAsString());
941     // note 1 gap in protein corresponds to 'gg-' in DNA (3 positions)
942     assertEquals("cCCGgg-TTT------AAA", al1.getSequenceAt(1)
943             .getSequenceAsString());
944
945     /*
946      * Reset and realign, preserving gaps in dna introns and exons
947      */
948     al1.getSequenceAt(0).setSequence(dna1);
949     al1.getSequenceAt(1).setSequence(dna2);
950     ((Alignment) al1).alignAs(al2, true, true);
951     // String dna1 = "A-Aa-gG-GCC-cT-TT";
952     // String dna2 = "c--CCGgg-TT--T-AA-A";
953     // assumption: we include 'the greater of' protein/dna gap lengths, not both
954     assertEquals("---A-Aa-gG------GCC-cT-TT", al1.getSequenceAt(0)
955             .getSequenceAsString());
956     assertEquals("c--CCGgg-TT--T------AA-A", al1.getSequenceAt(1)
957             .getSequenceAsString());
958   }
959
960   @Test(groups = "Functional")
961   public void testCopyConstructor() throws IOException
962   {
963     AlignmentI protein = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
964     // create sequence and alignment datasets
965     protein.setDataset(null);
966     AlignedCodonFrame acf = new AlignedCodonFrame();
967     List<AlignedCodonFrame> acfList = Arrays.asList(new AlignedCodonFrame[]
968     { acf });
969     protein.getDataset().setCodonFrames(acfList);
970     AlignmentI copy = new Alignment(protein);
971
972     /*
973      * copy has different aligned sequences but the same dataset sequences
974      */
975     assertFalse(copy.getSequenceAt(0) == protein.getSequenceAt(0));
976     assertFalse(copy.getSequenceAt(1) == protein.getSequenceAt(1));
977     assertSame(copy.getSequenceAt(0).getDatasetSequence(), protein
978             .getSequenceAt(0).getDatasetSequence());
979     assertSame(copy.getSequenceAt(1).getDatasetSequence(), protein
980             .getSequenceAt(1).getDatasetSequence());
981
982     // TODO should the copy constructor copy the dataset?
983     // or make a new one referring to the same dataset sequences??
984     assertNull(copy.getDataset());
985     // TODO test metadata is copied when AlignmentI is a dataset
986
987     // assertArrayEquals(copy.getDataset().getSequencesArray(), protein
988     // .getDataset().getSequencesArray());
989   }
990
991   /**
992    * Test behaviour of createDataset
993    * 
994    * @throws IOException
995    */
996   @Test(groups = "Functional")
997   public void testCreateDatasetAlignment() throws IOException
998   {
999     AlignmentI protein = new FormatAdapter().readFile(AA_SEQS_1,
1000             DataSourceType.PASTE, FileFormat.Fasta);
1001     /*
1002      * create a dataset sequence on first sequence
1003      * leave the second without one
1004      */
1005     protein.getSequenceAt(0).createDatasetSequence();
1006     assertNotNull(protein.getSequenceAt(0).getDatasetSequence());
1007     assertNull(protein.getSequenceAt(1).getDatasetSequence());
1008
1009     /*
1010      * add a mapping to the alignment
1011      */
1012     AlignedCodonFrame acf = new AlignedCodonFrame();
1013     protein.addCodonFrame(acf);
1014     assertNull(protein.getDataset());
1015     assertTrue(protein.getCodonFrames().contains(acf));
1016
1017     /*
1018      * create the alignment dataset
1019      * note this creates sequence datasets where missing
1020      * as a side-effect (in this case, on seq2
1021      */
1022     // TODO promote this method to AlignmentI
1023     ((Alignment) protein).createDatasetAlignment();
1024
1025     AlignmentI ds = protein.getDataset();
1026
1027     // side-effect: dataset created on second sequence
1028     assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
1029     // dataset alignment has references to dataset sequences
1030     assertEquals(ds.getSequenceAt(0), protein.getSequenceAt(0)
1031             .getDatasetSequence());
1032     assertEquals(ds.getSequenceAt(1), protein.getSequenceAt(1)
1033             .getDatasetSequence());
1034
1035     // codon frames should have been moved to the dataset
1036     // getCodonFrames() should delegate to the dataset:
1037     assertTrue(protein.getCodonFrames().contains(acf));
1038     // prove the codon frames are indeed on the dataset:
1039     assertTrue(ds.getCodonFrames().contains(acf));
1040   }
1041
1042   /**
1043    * tests the addition of *all* sequences referred to by a sequence being added
1044    * to the dataset
1045    */
1046   @Test(groups = "Functional")
1047   public void testCreateDatasetAlignmentWithMappedToSeqs()
1048   {
1049     // Alignment with two sequences, gapped.
1050     SequenceI sq1 = new Sequence("sq1", "A--SDF");
1051     SequenceI sq2 = new Sequence("sq2", "G--TRQ");
1052
1053     // cross-references to two more sequences.
1054     DBRefEntry dbr = new DBRefEntry("SQ1", "", "sq3");
1055     SequenceI sq3 = new Sequence("sq3", "VWANG");
1056     dbr.setMap(new Mapping(sq3, new MapList(new int[] { 1, 4 }, new int[] {
1057         2, 5 }, 1, 1)));
1058     sq1.addDBRef(dbr);
1059
1060     SequenceI sq4 = new Sequence("sq4", "ERKWI");
1061     DBRefEntry dbr2 = new DBRefEntry("SQ2", "", "sq4");
1062     dbr2.setMap(new Mapping(sq4, new MapList(new int[] { 1, 4 }, new int[] {
1063         2, 5 }, 1, 1)));
1064     sq2.addDBRef(dbr2);
1065     // and a 1:1 codonframe mapping between them.
1066     AlignedCodonFrame alc = new AlignedCodonFrame();
1067     alc.addMap(sq1, sq2, new MapList(new int[] { 1, 4 },
1068             new int[] { 1, 4 }, 1, 1));
1069
1070     AlignmentI protein = new Alignment(new SequenceI[] { sq1, sq2 });
1071
1072     /*
1073      * create the alignment dataset
1074      * note this creates sequence datasets where missing
1075      * as a side-effect (in this case, on seq2
1076      */
1077
1078     // TODO promote this method to AlignmentI
1079     ((Alignment) protein).createDatasetAlignment();
1080
1081     AlignmentI ds = protein.getDataset();
1082
1083     // should be 4 sequences in dataset - two materialised, and two propagated
1084     // from dbref
1085     assertEquals(4, ds.getHeight());
1086     assertTrue(ds.getSequences().contains(sq1.getDatasetSequence()));
1087     assertTrue(ds.getSequences().contains(sq2.getDatasetSequence()));
1088     assertTrue(ds.getSequences().contains(sq3));
1089     assertTrue(ds.getSequences().contains(sq4));
1090     // Should have one codon frame mapping between sq1 and sq2 via dataset
1091     // sequences
1092     assertEquals(ds.getCodonFrame(sq1.getDatasetSequence()),
1093             ds.getCodonFrame(sq2.getDatasetSequence()));
1094   }
1095
1096   @Test(groups = "Functional")
1097   public void testAddCodonFrame()
1098   {
1099     AlignmentI align = new Alignment(new SequenceI[] {});
1100     AlignedCodonFrame acf = new AlignedCodonFrame();
1101     align.addCodonFrame(acf);
1102     assertEquals(1, align.getCodonFrames().size());
1103     assertTrue(align.getCodonFrames().contains(acf));
1104     // can't add the same object twice:
1105     align.addCodonFrame(acf);
1106     assertEquals(1, align.getCodonFrames().size());
1107
1108     // create dataset alignment - mappings move to dataset
1109     ((Alignment) align).createDatasetAlignment();
1110     assertSame(align.getCodonFrames(), align.getDataset().getCodonFrames());
1111     assertEquals(1, align.getCodonFrames().size());
1112
1113     AlignedCodonFrame acf2 = new AlignedCodonFrame();
1114     align.addCodonFrame(acf2);
1115     assertTrue(align.getDataset().getCodonFrames().contains(acf));
1116   }
1117
1118   @Test(groups = "Functional")
1119   public void testAddSequencePreserveDatasetIntegrity()
1120   {
1121     Sequence seq = new Sequence("testSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1122     Alignment align = new Alignment(new SequenceI[] { seq });
1123     align.createDatasetAlignment();
1124     AlignmentI ds = align.getDataset();
1125     SequenceI copy = new Sequence(seq);
1126     copy.insertCharAt(3, 5, '-');
1127     align.addSequence(copy);
1128     Assert.assertEquals(align.getDataset().getHeight(), 1,
1129             "Dataset shouldn't have more than one sequence.");
1130
1131     Sequence seq2 = new Sequence("newtestSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1132     align.addSequence(seq2);
1133     Assert.assertEquals(align.getDataset().getHeight(), 2,
1134             "Dataset should now have two sequences.");
1135
1136     assertAlignmentDatasetRefs(align,
1137             "addSequence broke dataset reference integrity");
1138   }
1139
1140   /**
1141    * Tests that dbrefs with mappings to sequence get updated if the sequence
1142    * acquires a dataset sequence
1143    */
1144   @Test(groups = "Functional")
1145   public void testCreateDataset_updateDbrefMappings()
1146   {
1147     SequenceI pep = new Sequence("pep", "ASD");
1148     SequenceI dna = new Sequence("dna", "aaaGCCTCGGATggg");
1149     SequenceI cds = new Sequence("cds", "GCCTCGGAT");
1150
1151     // add dbref from dna to peptide
1152     DBRefEntry dbr = new DBRefEntry("UNIPROT", "", "pep");
1153     dbr.setMap(new Mapping(pep, new MapList(new int[] { 4, 15 }, new int[] {
1154         1, 4 }, 3, 1)));
1155     dna.addDBRef(dbr);
1156
1157     // add dbref from dna to peptide
1158     DBRefEntry dbr2 = new DBRefEntry("UNIPROT", "", "pep");
1159     dbr2.setMap(new Mapping(pep, new MapList(new int[] { 1, 12 }, new int[]
1160     { 1, 4 }, 3, 1)));
1161     cds.addDBRef(dbr2);
1162
1163     // add dbref from peptide to dna
1164     DBRefEntry dbr3 = new DBRefEntry("EMBL", "", "dna");
1165     dbr3.setMap(new Mapping(dna, new MapList(new int[] { 1, 4 }, new int[] {
1166         4, 15 }, 1, 3)));
1167     pep.addDBRef(dbr3);
1168
1169     // add dbref from peptide to cds
1170     DBRefEntry dbr4 = new DBRefEntry("EMBLCDS", "", "cds");
1171     dbr4.setMap(new Mapping(cds, new MapList(new int[] { 1, 4 }, new int[] {
1172         1, 12 }, 1, 3)));
1173     pep.addDBRef(dbr4);
1174
1175     AlignmentI protein = new Alignment(new SequenceI[] { pep });
1176
1177     /*
1178      * create the alignment dataset
1179      */
1180     ((Alignment) protein).createDatasetAlignment();
1181
1182     AlignmentI ds = protein.getDataset();
1183
1184     // should be 3 sequences in dataset
1185     assertEquals(3, ds.getHeight());
1186     assertTrue(ds.getSequences().contains(pep.getDatasetSequence()));
1187     assertTrue(ds.getSequences().contains(dna));
1188     assertTrue(ds.getSequences().contains(cds));
1189
1190     /*
1191      * verify peptide.cdsdbref.peptidedbref is now mapped to peptide dataset
1192      */
1193     List<DBRefEntry> dbRefs = pep.getDBRefs();
1194     assertEquals(2, dbRefs.size());
1195     assertSame(dna, dbRefs.get(0).map.to);
1196     assertSame(cds, dbRefs.get(1).map.to);
1197     assertEquals(1, dna.getDBRefs().size());
1198     assertSame(pep.getDatasetSequence(), dna.getDBRefs().get(0).map.to);
1199     assertEquals(1, cds.getDBRefs().size());
1200     assertSame(pep.getDatasetSequence(), cds.getDBRefs().get(0).map.to);
1201   }
1202
1203   @Test(groups = { "Functional" })
1204   public void testFindGroup()
1205   {
1206     SequenceI seq1 = new Sequence("seq1", "ABCDEF---GHI");
1207     SequenceI seq2 = new Sequence("seq2", "---JKLMNO---");
1208     AlignmentI a = new Alignment(new SequenceI[] { seq1, seq2 });
1209
1210     assertNull(a.findGroup(null, 0));
1211     assertNull(a.findGroup(seq1, 1));
1212     assertNull(a.findGroup(seq1, -1));
1213
1214     /*
1215      * add a group consisting of just "DEF"
1216      */
1217     SequenceGroup sg1 = new SequenceGroup();
1218     sg1.addSequence(seq1, false);
1219     sg1.setStartRes(3);
1220     sg1.setEndRes(5);
1221     a.addGroup(sg1);
1222
1223     assertNull(a.findGroup(seq1, 2)); // position not in group
1224     assertNull(a.findGroup(seq1, 6)); // position not in group
1225     assertNull(a.findGroup(seq2, 5)); // sequence not in group
1226     assertSame(a.findGroup(seq1, 3), sg1); // yes
1227     assertSame(a.findGroup(seq1, 4), sg1);
1228     assertSame(a.findGroup(seq1, 5), sg1);
1229
1230     /*
1231      * add a group consisting of 
1232      * EF--
1233      * KLMN
1234      */
1235     SequenceGroup sg2 = new SequenceGroup();
1236     sg2.addSequence(seq1, false);
1237     sg2.addSequence(seq2, false);
1238     sg2.setStartRes(4);
1239     sg2.setEndRes(7);
1240     a.addGroup(sg2);
1241
1242     assertNull(a.findGroup(seq1, 2)); // unchanged
1243     assertSame(a.findGroup(seq1, 3), sg1); // unchanged
1244     /*
1245      * if a residue is in more than one group, method returns
1246      * the first found (in order groups were added)
1247      */
1248     assertSame(a.findGroup(seq1, 4), sg1);
1249     assertSame(a.findGroup(seq1, 5), sg1);
1250
1251     /*
1252      * seq2 only belongs to the second group
1253      */
1254     assertSame(a.findGroup(seq2, 4), sg2);
1255     assertSame(a.findGroup(seq2, 5), sg2);
1256     assertSame(a.findGroup(seq2, 6), sg2);
1257     assertSame(a.findGroup(seq2, 7), sg2);
1258     assertNull(a.findGroup(seq2, 3));
1259     assertNull(a.findGroup(seq2, 8));
1260   }
1261
1262   @Test(groups = { "Functional" })
1263   public void testDeleteSequenceByIndex()
1264   {
1265     // create random alignment
1266     AlignmentGenerator gen = new AlignmentGenerator(false);
1267     AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1268
1269     // delete sequence 10, alignment reduced by 1
1270     int height = a.getAbsoluteHeight();
1271     a.deleteSequence(10);
1272     assertEquals(a.getAbsoluteHeight(), height - 1);
1273
1274     // try to delete -ve index, nothing happens
1275     a.deleteSequence(-1);
1276     assertEquals(a.getAbsoluteHeight(), height - 1);
1277
1278     // try to delete beyond end of alignment, nothing happens
1279     a.deleteSequence(14);
1280     assertEquals(a.getAbsoluteHeight(), height - 1);
1281   }
1282
1283   @Test(groups = { "Functional" })
1284   public void testDeleteSequenceBySeq()
1285   {
1286     // create random alignment
1287     AlignmentGenerator gen = new AlignmentGenerator(false);
1288     AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1289
1290     // delete sequence 10, alignment reduced by 1
1291     int height = a.getAbsoluteHeight();
1292     SequenceI seq = a.getSequenceAt(10);
1293     a.deleteSequence(seq);
1294     assertEquals(a.getAbsoluteHeight(), height - 1);
1295
1296     // try to delete non-existent sequence, nothing happens
1297     seq = new Sequence("cds", "GCCTCGGAT");
1298     assertEquals(a.getAbsoluteHeight(), height - 1);
1299   }
1300
1301   @Test(groups = { "Functional" })
1302   public void testDeleteHiddenSequence()
1303   {
1304     // create random alignment
1305     AlignmentGenerator gen = new AlignmentGenerator(false);
1306     AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1307
1308     // delete a sequence which is hidden, check it is NOT removed from hidden
1309     // sequences
1310     int height = a.getAbsoluteHeight();
1311     SequenceI seq = a.getSequenceAt(2);
1312     a.getHiddenSequences().hideSequence(seq);
1313     assertEquals(a.getHiddenSequences().getSize(), 1);
1314     a.deleteSequence(2);
1315     assertEquals(a.getAbsoluteHeight(), height - 1);
1316     assertEquals(a.getHiddenSequences().getSize(), 1);
1317
1318     // delete a sequence which is not hidden, check hiddenSequences are not
1319     // affected
1320     a.deleteSequence(10);
1321     assertEquals(a.getAbsoluteHeight(), height - 2);
1322     assertEquals(a.getHiddenSequences().getSize(), 1);
1323   }
1324
1325   @Test(
1326     groups = "Functional",
1327     expectedExceptions = { IllegalArgumentException.class })
1328   public void testSetDataset_selfReference()
1329   {
1330     SequenceI seq = new Sequence("a", "a");
1331     AlignmentI alignment = new Alignment(new SequenceI[] { seq });
1332     alignment.setDataset(alignment);
1333   }
1334
1335   @Test(groups = "Functional")
1336   public void testAppend()
1337   {
1338     SequenceI seq = new Sequence("seq1", "FRMLPSRT-A--L-");
1339     AlignmentI alignment = new Alignment(new SequenceI[] { seq });
1340     alignment.setGapCharacter('-');
1341     SequenceI seq2 = new Sequence("seq1", "KP..L.FQII.");
1342     AlignmentI alignment2 = new Alignment(new SequenceI[] { seq2 });
1343     alignment2.setGapCharacter('.');
1344
1345     alignment.append(alignment2);
1346
1347     assertEquals('-', alignment.getGapCharacter());
1348     assertSame(seq, alignment.getSequenceAt(0));
1349     assertEquals("KP--L-FQII-", alignment.getSequenceAt(1)
1350             .getSequenceAsString());
1351
1352     // todo test coverage for annotations, mappings, groups,
1353     // hidden sequences, properties
1354   }
1355
1356   /**
1357    * test that calcId == null on findOrCreate doesn't raise an NPE, and yields
1358    * an annotation with a null calcId
1359    * 
1360    */
1361   @Test(groups = "Functional")
1362   public void testFindOrCreateForNullCalcId()
1363   {
1364     SequenceI seq = new Sequence("seq1", "FRMLPSRT-A--L-");
1365     AlignmentI alignment = new Alignment(new SequenceI[] { seq });
1366
1367     AlignmentAnnotation ala = alignment.findOrCreateAnnotation(
1368             "Temperature Factor", null, false, seq, null);
1369     assertNotNull(ala);
1370     assertEquals(seq, ala.sequenceRef);
1371     assertEquals("", ala.calcId);
1372   }
1373
1374   @Test(groups = "Functional")
1375   public void testPropagateInsertions()
1376   {
1377     // create an alignment with no gaps - this will be the profile seq and other
1378     // JPRED seqs
1379     AlignmentGenerator gen = new AlignmentGenerator(false);
1380     AlignmentI al = gen.generate(25, 10, 1234, 0, 0);
1381
1382     // get the profileseq
1383     SequenceI profileseq = al.getSequenceAt(0);
1384     SequenceI gappedseq = new Sequence(profileseq);
1385     gappedseq.insertCharAt(5, al.getGapCharacter());
1386     gappedseq.insertCharAt(6, al.getGapCharacter());
1387     gappedseq.insertCharAt(7, al.getGapCharacter());
1388     gappedseq.insertCharAt(8, al.getGapCharacter());
1389
1390     // force different kinds of padding
1391     al.getSequenceAt(3).deleteChars(2, 23);
1392     al.getSequenceAt(4).deleteChars(2, 27);
1393     al.getSequenceAt(5).deleteChars(10, 27);
1394
1395     // create an alignment view with the gapped sequence
1396     SequenceI[] seqs = new SequenceI[1];
1397     seqs[0] = gappedseq;
1398     AlignmentI newal = new Alignment(seqs);
1399     HiddenColumns hidden = new HiddenColumns();
1400     hidden.hideColumns(15, 17);
1401
1402     AlignmentView view = new AlignmentView(newal, hidden, null, true, false,
1403             false);
1404
1405     // confirm that original contigs are as expected
1406     Iterator<int[]> visible = hidden.getVisContigsIterator(0, 25, false);
1407     int[] region = visible.next();
1408     assertEquals("[0, 14]", Arrays.toString(region));
1409     region = visible.next();
1410     assertEquals("[18, 24]", Arrays.toString(region));
1411
1412     // propagate insertions
1413     HiddenColumns result = al.propagateInsertions(profileseq, view);
1414
1415     // confirm that the contigs have changed to account for the gaps
1416     visible = result.getVisContigsIterator(0, 25, false);
1417     region = visible.next();
1418     assertEquals("[0, 10]", Arrays.toString(region));
1419     region = visible.next();
1420     assertEquals("[14, 24]", Arrays.toString(region));
1421
1422     // confirm the alignment has been changed so that the other sequences have
1423     // gaps inserted where the columns are hidden
1424     assertFalse(Comparison.isGap(al.getSequenceAt(1).getSequence()[10]));
1425     assertTrue(Comparison.isGap(al.getSequenceAt(1).getSequence()[11]));
1426     assertTrue(Comparison.isGap(al.getSequenceAt(1).getSequence()[12]));
1427     assertTrue(Comparison.isGap(al.getSequenceAt(1).getSequence()[13]));
1428     assertFalse(Comparison.isGap(al.getSequenceAt(1).getSequence()[14]));
1429
1430   }
1431
1432   @Test(groups = "Functional")
1433   public void testPropagateInsertionsOverlap()
1434   {
1435     // test propagateInsertions where gaps and hiddenColumns overlap
1436
1437     // create an alignment with no gaps - this will be the profile seq and other
1438     // JPRED seqs
1439     AlignmentGenerator gen = new AlignmentGenerator(false);
1440     AlignmentI al = gen.generate(20, 10, 1234, 0, 0);
1441
1442     // get the profileseq
1443     SequenceI profileseq = al.getSequenceAt(0);
1444     SequenceI gappedseq = new Sequence(profileseq);
1445     gappedseq.insertCharAt(5, al.getGapCharacter());
1446     gappedseq.insertCharAt(6, al.getGapCharacter());
1447     gappedseq.insertCharAt(7, al.getGapCharacter());
1448     gappedseq.insertCharAt(8, al.getGapCharacter());
1449
1450     // create an alignment view with the gapped sequence
1451     SequenceI[] seqs = new SequenceI[1];
1452     seqs[0] = gappedseq;
1453     AlignmentI newal = new Alignment(seqs);
1454
1455     // hide columns so that some overlap with the gaps
1456     HiddenColumns hidden = new HiddenColumns();
1457     hidden.hideColumns(7, 10);
1458
1459     AlignmentView view = new AlignmentView(newal, hidden, null, true, false,
1460             false);
1461
1462     // confirm that original contigs are as expected
1463     Iterator<int[]> visible = hidden.getVisContigsIterator(0, 20, false);
1464     int[] region = visible.next();
1465     assertEquals("[0, 6]", Arrays.toString(region));
1466     region = visible.next();
1467     assertEquals("[11, 19]", Arrays.toString(region));
1468     assertFalse(visible.hasNext());
1469
1470     // propagate insertions
1471     HiddenColumns result = al.propagateInsertions(profileseq, view);
1472
1473     // confirm that the contigs have changed to account for the gaps
1474     visible = result.getVisContigsIterator(0, 20, false);
1475     region = visible.next();
1476     assertEquals("[0, 4]", Arrays.toString(region));
1477     region = visible.next();
1478     assertEquals("[7, 19]", Arrays.toString(region));
1479     assertFalse(visible.hasNext());
1480
1481     // confirm the alignment has been changed so that the other sequences have
1482     // gaps inserted where the columns are hidden
1483     assertFalse(Comparison.isGap(al.getSequenceAt(1).getSequence()[4]));
1484     assertTrue(Comparison.isGap(al.getSequenceAt(1).getSequence()[5]));
1485     assertTrue(Comparison.isGap(al.getSequenceAt(1).getSequence()[6]));
1486     assertFalse(Comparison.isGap(al.getSequenceAt(1).getSequence()[7]));
1487   }
1488
1489   @Test(groups = { "Functional" })
1490   public void testPadGaps()
1491   {
1492     SequenceI seq1 = new Sequence("seq1", "ABCDEF--");
1493     SequenceI seq2 = new Sequence("seq2", "-JKLMNO--");
1494     SequenceI seq3 = new Sequence("seq2", "-PQR");
1495     AlignmentI a = new Alignment(new SequenceI[] { seq1, seq2, seq3 });
1496     a.setGapCharacter('.'); // this replaces existing gaps
1497     assertEquals("ABCDEF..", seq1.getSequenceAsString());
1498     a.padGaps();
1499     // trailing gaps are pruned, short sequences padded with gap character
1500     assertEquals("ABCDEF.", seq1.getSequenceAsString());
1501     assertEquals(".JKLMNO", seq2.getSequenceAsString());
1502     assertEquals(".PQR...", seq3.getSequenceAsString());
1503   }
1504
1505   /**
1506    * Test for setHiddenColumns, to check it returns true if the hidden columns
1507    * have changed, else false
1508    */
1509   @Test(groups = { "Functional" })
1510   public void testSetHiddenColumns()
1511   {
1512     AlignmentI al = new Alignment(new SequenceI[] {});
1513     assertFalse(al.getHiddenColumns().hasHiddenColumns());
1514
1515     HiddenColumns hc = new HiddenColumns();
1516     assertFalse(al.setHiddenColumns(hc)); // no change
1517     assertSame(hc, al.getHiddenColumns());
1518
1519     hc.hideColumns(2, 4);
1520     assertTrue(al.getHiddenColumns().hasHiddenColumns());
1521
1522     /*
1523      * set a different object but with the same columns hidden
1524      */
1525     HiddenColumns hc2 = new HiddenColumns();
1526     hc2.hideColumns(2, 4);
1527     assertFalse(al.setHiddenColumns(hc2)); // no change
1528     assertSame(hc2, al.getHiddenColumns());
1529
1530     assertTrue(al.setHiddenColumns(null));
1531     assertNull(al.getHiddenColumns());
1532     assertTrue(al.setHiddenColumns(hc));
1533     assertSame(hc, al.getHiddenColumns());
1534
1535     al.getHiddenColumns().hideColumns(10, 12);
1536     hc2.hideColumns(10, 12);
1537     assertFalse(al.setHiddenColumns(hc2)); // no change
1538
1539     /*
1540      * hide columns 15-16 then 17-18 in hc
1541      * hide columns 15-18 in hc2
1542      * these are not now 'equal' objects even though they
1543      * represent the same set of columns
1544      */
1545     assertSame(hc2, al.getHiddenColumns());
1546     hc.hideColumns(15, 16);
1547     hc.hideColumns(17, 18);
1548     hc2.hideColumns(15, 18);
1549     assertFalse(hc.equals(hc2));
1550     assertTrue(al.setHiddenColumns(hc)); // 'changed'
1551   }
1552
1553   @Test(groups = { "Functional" })
1554   public void testGetWidth()
1555   {
1556     SequenceI seq1 = new Sequence("seq1", "ABCDEF--");
1557     SequenceI seq2 = new Sequence("seq2", "-JKLMNO--");
1558     SequenceI seq3 = new Sequence("seq2", "-PQR");
1559     AlignmentI a = new Alignment(new SequenceI[] { seq1, seq2, seq3 });
1560
1561     assertEquals(9, a.getWidth());
1562
1563     // width includes hidden columns
1564     a.getHiddenColumns().hideColumns(2, 5);
1565     assertEquals(9, a.getWidth());
1566   }
1567
1568   @Test(groups = { "Functional" })
1569   public void testGetVisibleWidth()
1570   {
1571     SequenceI seq1 = new Sequence("seq1", "ABCDEF--");
1572     SequenceI seq2 = new Sequence("seq2", "-JKLMNO--");
1573     SequenceI seq3 = new Sequence("seq2", "-PQR");
1574     AlignmentI a = new Alignment(new SequenceI[] { seq1, seq2, seq3 });
1575
1576     assertEquals(9, a.getVisibleWidth());
1577
1578     // width excludes hidden columns
1579     a.getHiddenColumns().hideColumns(2, 5);
1580     assertEquals(5, a.getVisibleWidth());
1581   }
1582 }