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