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