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