7ad9436c858f8ef2fed092007d4d26a6550a73d8
[jalview.git] / test / jalview / datamodel / AlignmentTest.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.datamodel;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertFalse;
25 import static org.testng.AssertJUnit.assertNotNull;
26 import static org.testng.AssertJUnit.assertNull;
27 import static org.testng.AssertJUnit.assertSame;
28 import static org.testng.AssertJUnit.assertTrue;
29
30 import jalview.datamodel.AlignedCodonFrame.SequenceToSequenceMapping;
31 import jalview.io.AppletFormatAdapter;
32 import jalview.io.FormatAdapter;
33 import jalview.util.MapList;
34
35 import java.io.IOException;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Iterator;
39 import java.util.List;
40
41 import org.testng.Assert;
42 import org.testng.annotations.BeforeMethod;
43 import org.testng.annotations.Test;
44
45 /**
46  * Unit tests for Alignment datamodel.
47  * 
48  * @author gmcarstairs
49  *
50  */
51 public class AlignmentTest
52 {
53   // @formatter:off
54   private static final String TEST_DATA = 
55           "# STOCKHOLM 1.0\n" +
56           "#=GS D.melanogaster.1 AC AY119185.1/838-902\n" +
57           "#=GS D.melanogaster.2 AC AC092237.1/57223-57161\n" +
58           "#=GS D.melanogaster.3 AC AY060611.1/560-627\n" +
59           "D.melanogaster.1          G.AGCC.CU...AUGAUCGA\n" +
60           "#=GR D.melanogaster.1 SS  ................((((\n" +
61           "D.melanogaster.2          C.AUUCAACU.UAUGAGGAU\n" +
62           "#=GR D.melanogaster.2 SS  ................((((\n" +
63           "D.melanogaster.3          G.UGGCGCU..UAUGACGCA\n" +
64           "#=GR D.melanogaster.3 SS  (.(((...(....(((((((\n" +
65           "//";
66
67   private static final String AA_SEQS_1 = 
68           ">Seq1Name/5-8\n" +
69           "K-QY--L\n" +
70           ">Seq2Name/12-15\n" +
71           "-R-FP-W-\n";
72
73   private static final String CDNA_SEQS_1 = 
74           ">Seq1Name/100-111\n" +
75           "AC-GG--CUC-CAA-CT\n" +
76           ">Seq2Name/200-211\n" +
77           "-CG-TTA--ACG---AAGT\n";
78
79   private static final String CDNA_SEQS_2 = 
80           ">Seq1Name/50-61\n" +
81           "GCTCGUCGTACT\n" +
82           ">Seq2Name/60-71\n" +
83           "GGGTCAGGCAGT\n";
84   // @formatter:on
85
86   private AlignmentI al;
87
88   /**
89    * Helper method to load an alignment and ensure dataset sequences are set up.
90    * 
91    * @param data
92    * @param format
93    *          TODO
94    * @return
95    * @throws IOException
96    */
97   protected AlignmentI loadAlignment(final String data, String format)
98           throws IOException
99   {
100     AlignmentI a = new FormatAdapter().readFile(data,
101             AppletFormatAdapter.PASTE, format);
102     a.setDataset(null);
103     return a;
104   }
105
106   /**
107    * assert wrapper: tests all references in the given alignment are consistent
108    * 
109    * @param alignment
110    */
111   public static void assertAlignmentDatasetRefs(AlignmentI alignment)
112   {
113     verifyAlignmentDatasetRefs(alignment, true, null);
114   }
115
116   /**
117    * assert wrapper: tests all references in the given alignment are consistent
118    * 
119    * @param alignment
120    * @param message
121    *          - prefixed to any assert failed messages
122    */
123   public static void assertAlignmentDatasetRefs(AlignmentI alignment,
124           String message)
125   {
126     verifyAlignmentDatasetRefs(alignment, true, message);
127   }
128
129   /**
130    * verify sequence and dataset references are properly contained within
131    * dataset
132    * 
133    * @param alignment
134    *          - the alignmentI object to verify (either alignment or dataset)
135    * @param raiseAssert
136    *          - when set, testng assertions are raised.
137    *          @param message
138    *          - null or a string message to prepend to the assert failed messages.
139    * @return true if alignment references were in order, otherwise false.
140    */
141   public static boolean verifyAlignmentDatasetRefs(AlignmentI alignment,
142           boolean raiseAssert, String message)
143   {
144     if (message==null) { message = ""; }
145     if (alignment == null)
146     {
147       if (raiseAssert)
148       {
149         Assert.fail(message+"Alignment for verification was null.");
150       }
151       return false;
152     }
153     if (alignment.getDataset() != null)
154     {
155       AlignmentI dataset = alignment.getDataset();
156       // check all alignment sequences have their dataset within the dataset
157       for (SequenceI seq : alignment.getSequences())
158       {
159         SequenceI seqds = seq.getDatasetSequence();
160         if (seqds.getDatasetSequence() != null)
161         {
162           if (raiseAssert)
163           {
164             Assert.fail(message+" Alignment contained a sequence who's dataset sequence has a second dataset reference.");
165           }
166           return false;
167         }
168         if (dataset.findIndex(seqds) == -1)
169         {
170           if (raiseAssert)
171           {
172             Assert.fail(message+" Alignment contained a sequence who's dataset sequence was not in the dataset.");
173           }
174           return false;
175         }
176       }
177       return verifyAlignmentDatasetRefs(alignment.getDataset(), raiseAssert, message);
178     }
179     else
180     {
181       int dsp = -1;
182       // verify all dataset sequences
183       for (SequenceI seqds : alignment.getSequences())
184       {
185         dsp++;
186         if (seqds.getDatasetSequence() != null)
187         {
188           if (raiseAssert)
189           {
190             Assert.fail(message+" Dataset contained a sequence with non-null dataset reference (ie not a dataset sequence!)");
191           }
192           return false;
193         }
194         int foundp = alignment.findIndex(seqds);
195         if (foundp != dsp)
196         {
197           if (raiseAssert)
198           {
199             Assert.fail(message
200                     + " Dataset sequence array contains a reference at "
201                     + dsp + " to a sequence first seen at " + foundp + " ("
202                     + seqds.toString() + ")");
203           }
204           return false;
205         }
206         if (seqds.getDBRefs() != null)
207         {
208           for (DBRefEntry dbr : seqds.getDBRefs())
209           {
210             if (dbr.getMap() != null)
211             {
212               SequenceI seqdbrmapto = dbr.getMap().getTo();
213               if (seqdbrmapto != null)
214               {
215                 if (seqdbrmapto.getDatasetSequence() != null)
216                 {
217                   if (raiseAssert)
218                   {
219                     Assert.fail(message+" DBRefEntry for sequence in alignment had map to sequence which was not a dataset sequence");
220                   }
221                   return false;
222
223                 }
224                 if (alignment.findIndex(dbr.getMap().getTo()) == -1)
225                 {
226                   if (raiseAssert)
227                   {
228                     Assert.fail(message+" DBRefEntry for sequence in alignment had map to sequence not in dataset");
229                   }
230                   return false;
231                 }
232               }
233             }
234           }
235         }
236       }
237       // finally, verify codonmappings involve only dataset sequences.
238       if (alignment.getCodonFrames() != null)
239       {
240         for (AlignedCodonFrame alc : alignment.getCodonFrames())
241         {
242           for (SequenceToSequenceMapping ssm : alc.getMappings())
243           {
244             if (ssm.getFromSeq().getDatasetSequence() != null)
245             {
246               if (raiseAssert)
247               {
248                 Assert.fail(message+" CodonFrame-SSM-FromSeq is not a dataset sequence");
249               }
250               return false;
251             }
252             if (alignment.findIndex(ssm.getFromSeq()) == -1)
253             {
254
255               if (raiseAssert)
256               {
257                 Assert.fail(message+" CodonFrame-SSM-FromSeq is not contained in dataset");
258               }
259               return false;
260             }
261             if (ssm.getMapping().getTo().getDatasetSequence() != null)
262             {
263               if (raiseAssert)
264               {
265                 Assert.fail(message+" CodonFrame-SSM-Mapping-ToSeq is not a dataset sequence");
266               }
267               return false;
268             }
269             if (alignment.findIndex(ssm.getMapping().getTo()) == -1)
270             {
271
272               if (raiseAssert)
273               {
274                 Assert.fail(message+" CodonFrame-SSM-Mapping-ToSeq is not contained in dataset");
275               }
276               return false;
277             }
278           }
279         }
280       }
281     }
282     return true; // all relationships verified!
283   }
284
285   /**
286    * call verifyAlignmentDatasetRefs with and without assertion raising enabled,
287    * to check expected pass/fail actually occurs in both conditions
288    * 
289    * @param al
290    * @param expected
291    * @param msg
292    */
293   private void assertVerifyAlignment(AlignmentI al, boolean expected,
294           String msg)
295   {
296     if (expected)
297     {
298       try
299       {
300
301         Assert.assertTrue(verifyAlignmentDatasetRefs(al, true, null),
302                 "Valid test alignment failed when raiseAsserts enabled:"
303                         + msg);
304       } catch (AssertionError ae)
305       {
306         ae.printStackTrace();
307         Assert.fail(
308                 "Valid test alignment raised assertion errors when raiseAsserts enabled: "
309                         + msg, ae);
310       }
311       // also check validation passes with asserts disabled
312       Assert.assertTrue(verifyAlignmentDatasetRefs(al, false, null),
313               "Valid test alignment tested false when raiseAsserts disabled:"
314                       + msg);
315     }
316     else
317     {
318       boolean assertRaised = false;
319       try
320       {
321         verifyAlignmentDatasetRefs(al, true, null);
322       } catch (AssertionError ae)
323       {
324         // expected behaviour
325         assertRaised = true;
326       }
327       if (!assertRaised)
328       {
329         Assert.fail("Invalid test alignment passed when raiseAsserts enabled:"
330                 + msg);
331       }
332       // also check validation passes with asserts disabled
333       Assert.assertFalse(verifyAlignmentDatasetRefs(al, false, null),
334               "Invalid test alignment tested true when raiseAsserts disabled:"
335                       + msg);
336     }
337   }
338   @Test(groups = { "Functional" })
339   public void testVerifyAlignmentDatasetRefs()
340   {
341     SequenceI sq1 = new Sequence("sq1", "ASFDD"), sq2 = new Sequence("sq2",
342             "TTTTTT");
343
344     // construct simple valid alignment dataset
345     Alignment al = new Alignment(new SequenceI[] {
346         sq1, sq2 });
347     // expect this to pass
348     assertVerifyAlignment(al, true, "Simple valid alignment didn't verify");
349
350     // check test for sequence->datasetSequence validity
351     sq1.setDatasetSequence(sq2);
352     assertVerifyAlignment(
353             al,
354             false,
355             "didn't detect dataset sequence with a dataset sequence reference.");
356
357     sq1.setDatasetSequence(null);
358     assertVerifyAlignment(
359             al,
360             true,
361             "didn't reinstate validity after nulling dataset sequence dataset reference");
362
363     // now create dataset and check again
364     al.createDatasetAlignment();
365     assertNotNull(al.getDataset());
366
367     assertVerifyAlignment(al, true,
368             "verify failed after createDatasetAlignment");
369
370     // create a dbref on sq1 with a sequence ref to sq2
371     DBRefEntry dbrs1tos2 = new DBRefEntry("UNIPROT", "1", "Q111111");
372     dbrs1tos2.setMap(new Mapping(sq2.getDatasetSequence(),
373             new int[] { 1, 5 }, new int[] { 2, 6 }, 1, 1));
374     sq1.getDatasetSequence().addDBRef(dbrs1tos2);
375     assertVerifyAlignment(al, true,
376             "verify failed after addition of valid DBRefEntry/map");
377     // now create a dbref on a new sequence which maps to another sequence
378     // outside of the dataset
379     SequenceI sqout = new Sequence("sqout", "ututututucagcagcag"), sqnew = new Sequence(
380             "sqnew", "EEERRR");
381     DBRefEntry sqnewsqout = new DBRefEntry("ENAFOO", "1", "R000001");
382     sqnewsqout.setMap(new Mapping(sqout, new int[] { 1, 6 }, new int[] { 1,
383         18 }, 1, 3));
384     al.getDataset().addSequence(sqnew);
385
386     assertVerifyAlignment(al, true,
387             "verify failed after addition of new sequence to dataset");
388     // now start checking exception conditions
389     sqnew.addDBRef(sqnewsqout);
390     assertVerifyAlignment(
391             al,
392             false,
393             "verify passed when a dbref with map to sequence outside of dataset was added");
394     // make the verify pass by adding the outsider back in
395     al.getDataset().addSequence(sqout);
396     assertVerifyAlignment(al, true,
397             "verify should have passed after adding dbref->to sequence in to dataset");
398     // and now the same for a codon mapping...
399     SequenceI sqanotherout = new Sequence("sqanotherout",
400             "aggtutaggcagcagcag");
401
402     AlignedCodonFrame alc = new AlignedCodonFrame();
403     alc.addMap(sqanotherout, sqnew, new MapList(new int[] { 1, 6 },
404             new int[] { 1, 18 }, 3, 1));
405
406     al.addCodonFrame(alc);
407     Assert.assertEquals(al.getDataset().getCodonFrames().size(), 1);
408
409     assertVerifyAlignment(
410             al,
411             false,
412             "verify passed when alCodonFrame mapping to sequence outside of dataset was added");
413     // make the verify pass by adding the outsider back in
414     al.getDataset().addSequence(sqanotherout);
415     assertVerifyAlignment(
416             al,
417             true,
418             "verify should have passed once all sequences involved in alCodonFrame were added to dataset");
419     al.getDataset().addSequence(sqanotherout);
420     assertVerifyAlignment(al, false,
421             "verify should have failed when a sequence was added twice to the dataset");
422     al.getDataset().deleteSequence(sqanotherout);
423     assertVerifyAlignment(al, true,
424             "verify should have passed after duplicate entry for sequence was removed");
425   }
426
427   /**
428    * checks that the sequence data for an alignment's dataset is non-redundant.
429    * Fails if there are sequences with same id, sequence, start, and.
430    */
431
432   public static void assertDatasetIsNormalised(AlignmentI al)
433   {
434     assertDatasetIsNormalised(al, null);
435   }
436
437   /**
438    * checks that the sequence data for an alignment's dataset is non-redundant.
439    * Fails if there are sequences with same id, sequence, start, and.
440    * 
441    * @param al
442    *          - alignment to verify
443    * @param message
444    *          - null or message prepended to exception message.
445    */
446   public static void assertDatasetIsNormalised(AlignmentI al, String message)
447   {
448     if (al.getDataset()!=null)
449     {
450       assertDatasetIsNormalised(al.getDataset(), message);
451       return;
452     }
453     /*
454      * look for pairs of sequences with same ID, start, end, and sequence
455      */
456     List<SequenceI> seqSet = al.getSequences();
457     for (int p=0;p<seqSet.size(); p++)
458     {
459       SequenceI pSeq = seqSet.get(p);
460       for (int q=p+1; q<seqSet.size(); q++)
461       {
462         SequenceI qSeq = seqSet.get(q);
463         if (pSeq.getStart()!=qSeq.getStart())
464         {
465           continue;
466         }
467         if (pSeq.getEnd()!=qSeq.getEnd())
468         {
469           continue;
470         }
471         if (!pSeq.getName().equals(qSeq.getName()))
472         {
473           continue;
474         }
475         if (!Arrays.equals(pSeq.getSequence(), qSeq.getSequence()))
476         {
477           continue;
478         }
479         Assert.fail((message == null ? "" : message + " :")
480                 + "Found similar sequences at position " + p + " and " + q
481                 + "\n" + pSeq.toString());
482       }
483     }
484   }
485   
486   @Test(groups = { "Functional", "Asserts" })
487   public void testAssertDatasetIsNormalised()
488   {
489     Sequence sq1 = new Sequence("s1/1-4", "asdf");
490     Sequence sq1shift = new Sequence("s1/2-5", "asdf");
491     Sequence sq1seqd = new Sequence("s1/1-4", "asdt");
492     Sequence sq2 = new Sequence("s2/1-4", "asdf");
493     Sequence sq1dup = new Sequence("s1/1-4", "asdf");
494
495     Alignment al = new Alignment(new SequenceI[] { sq1 });
496     al.setDataset(null);
497
498     try
499     {
500       assertDatasetIsNormalised(al);
501     } catch (AssertionError ae)
502     {
503       Assert.fail("Single sequence should be valid normalised dataset.");
504     }
505     al.addSequence(sq2);
506     try
507     {
508       assertDatasetIsNormalised(al);
509     } catch (AssertionError ae)
510     {
511       Assert.fail("Two different sequences should be valid normalised dataset.");
512     }
513     /*
514      * now change sq2's name in the alignment. should still be valid
515      */
516     al.findName(sq2.getName()).setName("sq1");
517     try
518     {
519       assertDatasetIsNormalised(al);
520     } catch (AssertionError ae)
521     {
522       Assert.fail("Two different sequences in dataset, but same name in alignment, should be valid normalised dataset.");
523     }
524
525     al.addSequence(sq1seqd);
526     try
527     {
528       assertDatasetIsNormalised(al);
529     } catch (AssertionError ae)
530     {
531       Assert.fail("sq1 and sq1 with different sequence should be distinct.");
532     }
533
534     al.addSequence(sq1shift);
535     try
536     {
537       assertDatasetIsNormalised(al);
538     } catch (AssertionError ae)
539     {
540       Assert.fail("sq1 and sq1 with different start/end should be distinct.");
541     }
542     /*
543      * finally, the failure case
544      */
545     al.addSequence(sq1dup);
546     boolean ssertRaised = false;
547     try
548     {
549       assertDatasetIsNormalised(al);
550
551     } catch (AssertionError ae)
552     {
553       ssertRaised = true;
554     }
555     if (!ssertRaised)
556     {
557       Assert.fail("Expected identical sequence to raise exception.");
558     }
559   }
560   /*
561    * Read in Stockholm format test data including secondary structure
562    * annotations.
563    */
564   @BeforeMethod(alwaysRun = true)
565   public void setUp() throws IOException
566   {
567     al = loadAlignment(TEST_DATA, "STH");
568     int i = 0;
569     for (AlignmentAnnotation ann : al.getAlignmentAnnotation())
570     {
571       ann.setCalcId("CalcIdFor" + al.getSequenceAt(i).getName());
572       i++;
573     }
574   }
575
576   /**
577    * Test method that returns annotations that match on calcId.
578    */
579   @Test(groups = { "Functional" })
580   public void testFindAnnotation_byCalcId()
581   {
582     Iterable<AlignmentAnnotation> anns = al
583             .findAnnotation("CalcIdForD.melanogaster.2");
584     Iterator<AlignmentAnnotation> iter = anns.iterator();
585     assertTrue(iter.hasNext());
586     AlignmentAnnotation ann = iter.next();
587     assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
588     assertFalse(iter.hasNext());
589   }
590
591   @Test(groups = { "Functional" })
592   public void testDeleteAllAnnotations_includingAutocalculated()
593   {
594     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
595             "Consensus", 0.5);
596     aa.autoCalculated = true;
597     al.addAnnotation(aa);
598     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
599     assertEquals("Wrong number of annotations before deleting", 4,
600             anns.length);
601     al.deleteAllAnnotations(true);
602     assertEquals("Not all deleted", 0, al.getAlignmentAnnotation().length);
603   }
604
605   @Test(groups = { "Functional" })
606   public void testDeleteAllAnnotations_excludingAutocalculated()
607   {
608     AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
609             "Consensus", 0.5);
610     aa.autoCalculated = true;
611     al.addAnnotation(aa);
612     AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
613     assertEquals("Wrong number of annotations before deleting", 4,
614             anns.length);
615     al.deleteAllAnnotations(false);
616     assertEquals("Not just one annotation left", 1,
617             al.getAlignmentAnnotation().length);
618   }
619
620   /**
621    * Tests for realigning as per a supplied alignment: Dna as Dna.
622    * 
623    * Note: AlignedCodonFrame's state variables are named for protein-to-cDNA
624    * mapping, but can be exploited for a general 'sequence-to-sequence' mapping
625    * as here.
626    * 
627    * @throws IOException
628    */
629   @Test(groups = { "Functional" })
630   public void testAlignAs_dnaAsDna() throws IOException
631   {
632     // aligned cDNA:
633     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
634     // unaligned cDNA:
635     AlignmentI al2 = loadAlignment(CDNA_SEQS_2, "FASTA");
636
637     /*
638      * Make mappings between sequences. The 'aligned cDNA' is playing the role
639      * of what would normally be protein here.
640      */
641     makeMappings(al1, al2);
642
643     ((Alignment) al2).alignAs(al1, false, true);
644     assertEquals("GC-TC--GUC-GTACT", al2.getSequenceAt(0)
645             .getSequenceAsString());
646     assertEquals("-GG-GTC--AGG--CAGT", al2.getSequenceAt(1)
647             .getSequenceAsString());
648   }
649
650   /**
651    * Aligning protein from cDNA.
652    * 
653    * @throws IOException
654    */
655   @Test(groups = { "Functional" })
656   public void testAlignAs_proteinAsCdna() throws IOException
657   {
658     // see also AlignmentUtilsTests
659     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
660     AlignmentI al2 = loadAlignment(AA_SEQS_1, "FASTA");
661     makeMappings(al1, al2);
662
663     // Fudge - alignProteinAsCdna expects mappings to be on protein
664     al2.getCodonFrames().addAll(al1.getCodonFrames());
665
666     ((Alignment) al2).alignAs(al1, false, true);
667     assertEquals("K-Q-Y-L-", al2.getSequenceAt(0).getSequenceAsString());
668     assertEquals("-R-F-P-W", al2.getSequenceAt(1).getSequenceAsString());
669   }
670
671   /**
672    * Test aligning cdna as per protein alignment.
673    * 
674    * @throws IOException
675    */
676   @Test(groups = { "Functional" }, enabled = true)
677   // TODO review / update this test after redesign of alignAs method
678   public void testAlignAs_cdnaAsProtein() throws IOException
679   {
680     /*
681      * Load alignments and add mappings for cDNA to protein
682      */
683     AlignmentI al1 = loadAlignment(CDNA_SEQS_1, "FASTA");
684     AlignmentI al2 = loadAlignment(AA_SEQS_1, "FASTA");
685     makeMappings(al1, al2);
686
687     /*
688      * Realign DNA; currently keeping existing gaps in introns only
689      */
690     ((Alignment) al1).alignAs(al2, false, true);
691     assertEquals("ACG---GCUCCA------ACT---", al1.getSequenceAt(0)
692             .getSequenceAsString());
693     assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
694             .getSequenceAsString());
695   }
696
697   /**
698    * Test aligning cdna as per protein - single sequences
699    * 
700    * @throws IOException
701    */
702   @Test(groups = { "Functional" }, enabled = true)
703   // TODO review / update this test after redesign of alignAs method
704   public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
705   {
706     /*
707      * simple case insert one gap
708      */
709     verifyAlignAs(">dna\nCAAaaa\n", ">protein\nQ-K\n", "CAA---aaa");
710
711     /*
712      * simple case but with sequence offsets
713      */
714     verifyAlignAs(">dna/5-10\nCAAaaa\n", ">protein/20-21\nQ-K\n",
715             "CAA---aaa");
716
717     /*
718      * insert gaps as per protein, drop gaps within codons
719      */
720     verifyAlignAs(">dna/10-18\nCA-Aa-aa--AGA\n", ">aa/6-8\n-Q-K--R\n",
721             "---CAA---aaa------AGA");
722   }
723
724   /**
725    * Helper method that makes mappings and then aligns the first alignment as
726    * the second
727    * 
728    * @param fromSeqs
729    * @param toSeqs
730    * @param expected
731    * @throws IOException
732    */
733   public void verifyAlignAs(String fromSeqs, String toSeqs, String expected)
734           throws IOException
735   {
736     /*
737      * Load alignments and add mappings from nucleotide to protein (or from
738      * first to second if both the same type)
739      */
740     AlignmentI al1 = loadAlignment(fromSeqs, "FASTA");
741     AlignmentI al2 = loadAlignment(toSeqs, "FASTA");
742     makeMappings(al1, al2);
743
744     /*
745      * Realign DNA; currently keeping existing gaps in introns only
746      */
747     ((Alignment) al1).alignAs(al2, false, true);
748     assertEquals(expected, al1.getSequenceAt(0).getSequenceAsString());
749   }
750
751   /**
752    * Helper method to make mappings between sequences, and add the mappings to
753    * the 'mapped from' alignment
754    * 
755    * @param alFrom
756    * @param alTo
757    */
758   public void makeMappings(AlignmentI alFrom, AlignmentI alTo)
759   {
760     int ratio = (alFrom.isNucleotide() == alTo.isNucleotide() ? 1 : 3);
761
762     AlignedCodonFrame acf = new AlignedCodonFrame();
763
764     for (int i = 0; i < alFrom.getHeight(); i++)
765     {
766       SequenceI seqFrom = alFrom.getSequenceAt(i);
767       SequenceI seqTo = alTo.getSequenceAt(i);
768       MapList ml = new MapList(new int[] { seqFrom.getStart(),
769           seqFrom.getEnd() },
770               new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
771       acf.addMap(seqFrom, seqTo, ml);
772     }
773
774     /*
775      * not sure whether mappings 'belong' or protein or nucleotide
776      * alignment, so adding to both ;~)
777      */
778     alFrom.addCodonFrame(acf);
779     alTo.addCodonFrame(acf);
780   }
781
782   /**
783    * Test aligning dna as per protein alignment, for the case where there are
784    * introns (i.e. some dna sites have no mapping from a peptide).
785    * 
786    * @throws IOException
787    */
788   @Test(groups = { "Functional" }, enabled = false)
789   // TODO review / update this test after redesign of alignAs method
790   public void testAlignAs_dnaAsProtein_withIntrons() throws IOException
791   {
792     /*
793      * Load alignments and add mappings for cDNA to protein
794      */
795     String dna1 = "A-Aa-gG-GCC-cT-TT";
796     String dna2 = "c--CCGgg-TT--T-AA-A";
797     AlignmentI al1 = loadAlignment(">Dna1/6-17\n" + dna1
798             + "\n>Dna2/20-31\n" + dna2 + "\n", "FASTA");
799     AlignmentI al2 = loadAlignment(
800             ">Pep1/7-9\n-P--YK\n>Pep2/11-13\nG-T--F\n", "FASTA");
801     AlignedCodonFrame acf = new AlignedCodonFrame();
802     // Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
803     // Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
804     MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
805     { 7, 9 }, 3, 1);
806     acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
807     MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
808         13 }, 3, 1);
809     acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
810     al2.addCodonFrame(acf);
811
812     /*
813      * Align ignoring gaps in dna introns and exons
814      */
815     ((Alignment) al1).alignAs(al2, false, false);
816     assertEquals("---AAagG------GCCcTTT", al1.getSequenceAt(0)
817             .getSequenceAsString());
818     // note 1 gap in protein corresponds to 'gg-' in DNA (3 positions)
819     assertEquals("cCCGgg-TTT------AAA", al1.getSequenceAt(1)
820             .getSequenceAsString());
821
822     /*
823      * Reset and realign, preserving gaps in dna introns and exons
824      */
825     al1.getSequenceAt(0).setSequence(dna1);
826     al1.getSequenceAt(1).setSequence(dna2);
827     ((Alignment) al1).alignAs(al2, true, true);
828     // String dna1 = "A-Aa-gG-GCC-cT-TT";
829     // String dna2 = "c--CCGgg-TT--T-AA-A";
830     // assumption: we include 'the greater of' protein/dna gap lengths, not both
831     assertEquals("---A-Aa-gG------GCC-cT-TT", al1.getSequenceAt(0)
832             .getSequenceAsString());
833     assertEquals("c--CCGgg-TT--T------AA-A", al1.getSequenceAt(1)
834             .getSequenceAsString());
835   }
836
837   @Test(groups = "Functional")
838   public void testCopyConstructor() throws IOException
839   {
840     AlignmentI protein = loadAlignment(AA_SEQS_1, FormatAdapter.PASTE);
841     // create sequence and alignment datasets
842     protein.setDataset(null);
843     AlignedCodonFrame acf = new AlignedCodonFrame();
844     List<AlignedCodonFrame> acfList = Arrays.asList(new AlignedCodonFrame[]
845     { acf });
846     protein.getDataset().setCodonFrames(acfList);
847     AlignmentI copy = new Alignment(protein);
848
849     /*
850      * copy has different aligned sequences but the same dataset sequences
851      */
852     assertFalse(copy.getSequenceAt(0) == protein.getSequenceAt(0));
853     assertFalse(copy.getSequenceAt(1) == protein.getSequenceAt(1));
854     assertSame(copy.getSequenceAt(0).getDatasetSequence(), protein
855             .getSequenceAt(0).getDatasetSequence());
856     assertSame(copy.getSequenceAt(1).getDatasetSequence(), protein
857             .getSequenceAt(1).getDatasetSequence());
858
859     // TODO should the copy constructor copy the dataset?
860     // or make a new one referring to the same dataset sequences??
861     assertNull(copy.getDataset());
862     // TODO test metadata is copied when AlignmentI is a dataset
863
864     // assertArrayEquals(copy.getDataset().getSequencesArray(), protein
865     // .getDataset().getSequencesArray());
866   }
867
868   /**
869    * Test behaviour of createDataset
870    * 
871    * @throws IOException
872    */
873   @Test(groups = "Functional")
874   public void testCreateDatasetAlignment() throws IOException
875   {
876     AlignmentI protein = new FormatAdapter().readFile(AA_SEQS_1,
877             AppletFormatAdapter.PASTE, "FASTA");
878     /*
879      * create a dataset sequence on first sequence
880      * leave the second without one
881      */
882     protein.getSequenceAt(0).createDatasetSequence();
883     assertNotNull(protein.getSequenceAt(0).getDatasetSequence());
884     assertNull(protein.getSequenceAt(1).getDatasetSequence());
885
886     /*
887      * add a mapping to the alignment
888      */
889     AlignedCodonFrame acf = new AlignedCodonFrame();
890     protein.addCodonFrame(acf);
891     assertNull(protein.getDataset());
892     assertTrue(protein.getCodonFrames().contains(acf));
893
894     /*
895      * create the alignment dataset
896      * note this creates sequence datasets where missing
897      * as a side-effect (in this case, on seq2
898      */
899     // TODO promote this method to AlignmentI
900     ((Alignment) protein).createDatasetAlignment();
901
902     AlignmentI ds = protein.getDataset();
903
904     // side-effect: dataset created on second sequence
905     assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
906     // dataset alignment has references to dataset sequences
907     assertEquals(ds.getSequenceAt(0), protein.getSequenceAt(0)
908             .getDatasetSequence());
909     assertEquals(ds.getSequenceAt(1), protein.getSequenceAt(1)
910             .getDatasetSequence());
911
912     // codon frames should have been moved to the dataset
913     // getCodonFrames() should delegate to the dataset:
914     assertTrue(protein.getCodonFrames().contains(acf));
915     // prove the codon frames are indeed on the dataset:
916     assertTrue(ds.getCodonFrames().contains(acf));
917   }
918
919   /**
920    * tests the addition of *all* sequences referred to by a sequence being added
921    * to the dataset
922    */
923   @Test(groups = "Functional")
924   public void testCreateDatasetAlignmentWithMappedToSeqs()
925   {
926     // Alignment with two sequences, gapped.
927     SequenceI sq1 = new Sequence("sq1", "A--SDF");
928     SequenceI sq2 = new Sequence("sq2", "G--TRQ");
929
930     // cross-references to two more sequences.
931     DBRefEntry dbr = new DBRefEntry("SQ1", "", "sq3");
932     SequenceI sq3 = new Sequence("sq3", "VWANG");
933     dbr.setMap(new Mapping(sq3, new MapList(new int[] { 1, 4 }, new int[] {
934         2, 5 }, 1, 1)));
935     sq1.addDBRef(dbr);
936
937     SequenceI sq4 = new Sequence("sq4", "ERKWI");
938     DBRefEntry dbr2 = new DBRefEntry("SQ2", "", "sq4");
939     dbr2.setMap(new Mapping(sq4, new MapList(new int[] { 1, 4 }, new int[] {
940         2, 5 }, 1, 1)));
941     sq2.addDBRef(dbr2);
942     // and a 1:1 codonframe mapping between them.
943     AlignedCodonFrame alc = new AlignedCodonFrame();
944     alc.addMap(sq1, sq2, new MapList(new int[] { 1, 4 },
945             new int[] { 1, 4 }, 1, 1));
946
947     AlignmentI protein = new Alignment(new SequenceI[] { sq1, sq2 });
948
949     /*
950      * create the alignment dataset
951      * note this creates sequence datasets where missing
952      * as a side-effect (in this case, on seq2
953      */
954
955     // TODO promote this method to AlignmentI
956     ((Alignment) protein).createDatasetAlignment();
957
958     AlignmentI ds = protein.getDataset();
959
960     // should be 4 sequences in dataset - two materialised, and two propagated
961     // from dbref
962     assertEquals(4, ds.getHeight());
963     assertTrue(ds.getSequences().contains(sq1.getDatasetSequence()));
964     assertTrue(ds.getSequences().contains(sq2.getDatasetSequence()));
965     assertTrue(ds.getSequences().contains(sq3));
966     assertTrue(ds.getSequences().contains(sq4));
967     // Should have one codon frame mapping between sq1 and sq2 via dataset
968     // sequences
969     assertEquals(ds.getCodonFrame(sq1.getDatasetSequence()),
970             ds.getCodonFrame(sq2.getDatasetSequence()));
971   }
972
973   @Test(groups = "Functional")
974   public void testAddCodonFrame()
975   {
976     AlignmentI align = new Alignment(new SequenceI[] {});
977     AlignedCodonFrame acf = new AlignedCodonFrame();
978     align.addCodonFrame(acf);
979     assertEquals(1, align.getCodonFrames().size());
980     assertTrue(align.getCodonFrames().contains(acf));
981     // can't add the same object twice:
982     align.addCodonFrame(acf);
983     assertEquals(1, align.getCodonFrames().size());
984
985     // create dataset alignment - mappings move to dataset
986     ((Alignment) align).createDatasetAlignment();
987     assertSame(align.getCodonFrames(), align.getDataset().getCodonFrames());
988     assertEquals(1, align.getCodonFrames().size());
989
990     AlignedCodonFrame acf2 = new AlignedCodonFrame();
991     align.addCodonFrame(acf2);
992     assertTrue(align.getDataset().getCodonFrames().contains(acf));
993   }
994
995   @Test(groups = "Functional")
996   public void testAddSequencePreserveDatasetIntegrity()
997   {
998     Sequence seq = new Sequence("testSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
999     Alignment align = new Alignment(new SequenceI[] { seq });
1000     align.createDatasetAlignment();
1001     AlignmentI ds = align.getDataset();
1002     SequenceI copy = new Sequence(seq);
1003     copy.insertCharAt(3, 5, '-');
1004     align.addSequence(copy);
1005     Assert.assertEquals(align.getDataset().getHeight(), 1,
1006             "Dataset shouldn't have more than one sequence.");
1007
1008     Sequence seq2 = new Sequence("newtestSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1009     align.addSequence(seq2);
1010     Assert.assertEquals(align.getDataset().getHeight(), 2,
1011             "Dataset should now have two sequences.");
1012
1013     assertAlignmentDatasetRefs(align,
1014             "addSequence broke dataset reference integrity");
1015   }
1016   @Test(groups = "Functional")
1017   public void getVisibleStartAndEndIndexTest()
1018   {
1019     Sequence seq = new Sequence("testSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1020     AlignmentI align = new Alignment(new SequenceI[] { seq });
1021     ArrayList<int[]> hiddenCols = new ArrayList<int[]>();
1022
1023     int[] startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1024     assertEquals(0, startEnd[0]);
1025     assertEquals(25, startEnd[1]);
1026
1027     hiddenCols.add(new int[] { 0, 0 });
1028     startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1029     assertEquals(1, startEnd[0]);
1030     assertEquals(25, startEnd[1]);
1031
1032     hiddenCols.add(new int[] { 6, 9 });
1033     hiddenCols.add(new int[] { 11, 12 });
1034     startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1035     assertEquals(1, startEnd[0]);
1036     assertEquals(25, startEnd[1]);
1037
1038     hiddenCols.add(new int[] { 24, 25 });
1039     startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1040     System.out.println(startEnd[0] + " : " + startEnd[1]);
1041     assertEquals(1, startEnd[0]);
1042     assertEquals(23, startEnd[1]);
1043   }
1044
1045 }