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