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