2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.datamodel;
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;
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;
39 import java.io.IOException;
40 import java.util.Arrays;
41 import java.util.Iterator;
42 import java.util.List;
44 import org.testng.Assert;
45 import org.testng.annotations.BeforeClass;
46 import org.testng.annotations.BeforeMethod;
47 import org.testng.annotations.Test;
50 * Unit tests for Alignment datamodel.
55 public class AlignmentTest
58 @BeforeClass(alwaysRun = true)
59 public void setUpJvOptionPane()
61 JvOptionPane.setInteractiveMode(false);
62 JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
66 private static final String TEST_DATA =
68 "#=GS D.melanogaster.1 AC AY119185.1/838-902\n" +
69 "#=GS D.melanogaster.2 AC AC092237.1/57223-57161\n" +
70 "#=GS D.melanogaster.3 AC AY060611.1/560-627\n" +
71 "D.melanogaster.1 G.AGCC.CU...AUGAUCGA\n" +
72 "#=GR D.melanogaster.1 SS ................((((\n" +
73 "D.melanogaster.2 C.AUUCAACU.UAUGAGGAU\n" +
74 "#=GR D.melanogaster.2 SS ................((((\n" +
75 "D.melanogaster.3 G.UGGCGCU..UAUGACGCA\n" +
76 "#=GR D.melanogaster.3 SS (.(((...(....(((((((\n" +
79 private static final String AA_SEQS_1 =
85 private static final String CDNA_SEQS_1 =
86 ">Seq1Name/100-111\n" +
87 "AC-GG--CUC-CAA-CT\n" +
88 ">Seq2Name/200-211\n" +
89 "-CG-TTA--ACG---AAGT\n";
91 private static final String CDNA_SEQS_2 =
98 private AlignmentI al;
101 * Helper method to load an alignment and ensure dataset sequences are set up.
107 * @throws IOException
109 protected AlignmentI loadAlignment(final String data, FileFormatI format)
112 AlignmentI a = new FormatAdapter().readFile(data, DataSourceType.PASTE,
119 * assert wrapper: tests all references in the given alignment are consistent
123 public static void assertAlignmentDatasetRefs(AlignmentI alignment)
125 verifyAlignmentDatasetRefs(alignment, true, null);
129 * assert wrapper: tests all references in the given alignment are consistent
133 * - prefixed to any assert failed messages
135 public static void assertAlignmentDatasetRefs(AlignmentI alignment,
138 verifyAlignmentDatasetRefs(alignment, true, message);
142 * verify sequence and dataset references are properly contained within
146 * - the alignmentI object to verify (either alignment or dataset)
148 * - when set, testng assertions are raised.
150 * - null or a string message to prepend to the assert failed
152 * @return true if alignment references were in order, otherwise false.
154 public static boolean verifyAlignmentDatasetRefs(AlignmentI alignment,
155 boolean raiseAssert, String message)
161 if (alignment == null)
165 Assert.fail(message + "Alignment for verification was null.");
169 if (alignment.getDataset() != null)
171 AlignmentI dataset = alignment.getDataset();
172 // check all alignment sequences have their dataset within the dataset
173 for (SequenceI seq : alignment.getSequences())
175 SequenceI seqds = seq.getDatasetSequence();
176 if (seqds.getDatasetSequence() != null)
181 + " Alignment contained a sequence who's dataset sequence has a second dataset reference.");
185 if (dataset.findIndex(seqds) == -1)
190 + " Alignment contained a sequence who's dataset sequence was not in the dataset.");
195 return verifyAlignmentDatasetRefs(alignment.getDataset(),
196 raiseAssert, message);
201 // verify all dataset sequences
202 for (SequenceI seqds : alignment.getSequences())
205 if (seqds.getDatasetSequence() != null)
210 + " Dataset contained a sequence with non-null dataset reference (ie not a dataset sequence!)");
214 int foundp = alignment.findIndex(seqds);
220 + " Dataset sequence array contains a reference at "
221 + dsp + " to a sequence first seen at " + foundp + " ("
222 + seqds.toString() + ")");
226 if (seqds.getDBRefs() != null)
228 for (DBRefEntry dbr : seqds.getDBRefs())
230 if (dbr.getMap() != null)
232 SequenceI seqdbrmapto = dbr.getMap().getTo();
233 if (seqdbrmapto != null)
235 if (seqdbrmapto.getDatasetSequence() != null)
240 + " DBRefEntry for sequence in alignment had map to sequence which was not a dataset sequence");
245 if (alignment.findIndex(dbr.getMap().getTo()) == -1)
250 + " DBRefEntry for sequence in alignment had map to sequence not in dataset");
259 // finally, verify codonmappings involve only dataset sequences.
260 if (alignment.getCodonFrames() != null)
262 for (AlignedCodonFrame alc : alignment.getCodonFrames())
264 for (SequenceToSequenceMapping ssm : alc.getMappings())
266 if (ssm.getFromSeq().getDatasetSequence() != null)
271 + " CodonFrame-SSM-FromSeq is not a dataset sequence");
275 if (alignment.findIndex(ssm.getFromSeq()) == -1)
281 + " CodonFrame-SSM-FromSeq is not contained in dataset");
285 if (ssm.getMapping().getTo().getDatasetSequence() != null)
290 + " CodonFrame-SSM-Mapping-ToSeq is not a dataset sequence");
294 if (alignment.findIndex(ssm.getMapping().getTo()) == -1)
300 + " CodonFrame-SSM-Mapping-ToSeq is not contained in dataset");
308 return true; // all relationships verified!
312 * call verifyAlignmentDatasetRefs with and without assertion raising enabled,
313 * to check expected pass/fail actually occurs in both conditions
319 private void assertVerifyAlignment(AlignmentI al, boolean expected,
327 Assert.assertTrue(verifyAlignmentDatasetRefs(al, true, null),
328 "Valid test alignment failed when raiseAsserts enabled:"
330 } catch (AssertionError ae)
332 ae.printStackTrace();
334 "Valid test alignment raised assertion errors when raiseAsserts enabled: "
337 // also check validation passes with asserts disabled
338 Assert.assertTrue(verifyAlignmentDatasetRefs(al, false, null),
339 "Valid test alignment tested false when raiseAsserts disabled:"
344 boolean assertRaised = false;
347 verifyAlignmentDatasetRefs(al, true, null);
348 } catch (AssertionError ae)
350 // expected behaviour
355 Assert.fail("Invalid test alignment passed when raiseAsserts enabled:"
358 // also check validation passes with asserts disabled
359 Assert.assertFalse(verifyAlignmentDatasetRefs(al, false, null),
360 "Invalid test alignment tested true when raiseAsserts disabled:"
365 @Test(groups = { "Functional" })
366 public void testVerifyAlignmentDatasetRefs()
368 SequenceI sq1 = new Sequence("sq1", "ASFDD"), sq2 = new Sequence("sq2",
371 // construct simple valid alignment dataset
372 Alignment al = new Alignment(new SequenceI[] { sq1, sq2 });
373 // expect this to pass
374 assertVerifyAlignment(al, true, "Simple valid alignment didn't verify");
376 // check test for sequence->datasetSequence validity
377 sq1.setDatasetSequence(sq2);
378 assertVerifyAlignment(al, false,
379 "didn't detect dataset sequence with a dataset sequence reference.");
381 sq1.setDatasetSequence(null);
382 assertVerifyAlignment(
385 "didn't reinstate validity after nulling dataset sequence dataset reference");
387 // now create dataset and check again
388 al.createDatasetAlignment();
389 assertNotNull(al.getDataset());
391 assertVerifyAlignment(al, true,
392 "verify failed after createDatasetAlignment");
394 // create a dbref on sq1 with a sequence ref to sq2
395 DBRefEntry dbrs1tos2 = new DBRefEntry("UNIPROT", "1", "Q111111");
396 dbrs1tos2.setMap(new Mapping(sq2.getDatasetSequence(),
397 new int[] { 1, 5 }, new int[] { 2, 6 }, 1, 1));
398 sq1.getDatasetSequence().addDBRef(dbrs1tos2);
399 assertVerifyAlignment(al, true,
400 "verify failed after addition of valid DBRefEntry/map");
401 // now create a dbref on a new sequence which maps to another sequence
402 // outside of the dataset
403 SequenceI sqout = new Sequence("sqout", "ututututucagcagcag"), sqnew = new Sequence(
405 DBRefEntry sqnewsqout = new DBRefEntry("ENAFOO", "1", "R000001");
406 sqnewsqout.setMap(new Mapping(sqout, new int[] { 1, 6 }, new int[] { 1,
408 al.getDataset().addSequence(sqnew);
410 assertVerifyAlignment(al, true,
411 "verify failed after addition of new sequence to dataset");
412 // now start checking exception conditions
413 sqnew.addDBRef(sqnewsqout);
414 assertVerifyAlignment(
417 "verify passed when a dbref with map to sequence outside of dataset was added");
418 // make the verify pass by adding the outsider back in
419 al.getDataset().addSequence(sqout);
420 assertVerifyAlignment(al, true,
421 "verify should have passed after adding dbref->to sequence in to dataset");
422 // and now the same for a codon mapping...
423 SequenceI sqanotherout = new Sequence("sqanotherout",
424 "aggtutaggcagcagcag");
426 AlignedCodonFrame alc = new AlignedCodonFrame();
427 alc.addMap(sqanotherout, sqnew, new MapList(new int[] { 1, 6 },
428 new int[] { 1, 18 }, 3, 1));
430 al.addCodonFrame(alc);
431 Assert.assertEquals(al.getDataset().getCodonFrames().size(), 1);
433 assertVerifyAlignment(
436 "verify passed when alCodonFrame mapping to sequence outside of dataset was added");
437 // make the verify pass by adding the outsider back in
438 al.getDataset().addSequence(sqanotherout);
439 assertVerifyAlignment(
442 "verify should have passed once all sequences involved in alCodonFrame were added to dataset");
443 al.getDataset().addSequence(sqanotherout);
444 assertVerifyAlignment(al, false,
445 "verify should have failed when a sequence was added twice to the dataset");
446 al.getDataset().deleteSequence(sqanotherout);
447 assertVerifyAlignment(al, true,
448 "verify should have passed after duplicate entry for sequence was removed");
452 * checks that the sequence data for an alignment's dataset is non-redundant.
453 * Fails if there are sequences with same id, sequence, start, and.
456 public static void assertDatasetIsNormalised(AlignmentI al)
458 assertDatasetIsNormalised(al, null);
462 * checks that the sequence data for an alignment's dataset is non-redundant.
463 * Fails if there are sequences with same id, sequence, start, and.
466 * - alignment to verify
468 * - null or message prepended to exception message.
470 public static void assertDatasetIsNormalised(AlignmentI al, String message)
472 if (al.getDataset() != null)
474 assertDatasetIsNormalised(al.getDataset(), message);
478 * look for pairs of sequences with same ID, start, end, and sequence
480 List<SequenceI> seqSet = al.getSequences();
481 for (int p = 0; p < seqSet.size(); p++)
483 SequenceI pSeq = seqSet.get(p);
484 for (int q = p + 1; q < seqSet.size(); q++)
486 SequenceI qSeq = seqSet.get(q);
487 if (pSeq.getStart() != qSeq.getStart())
491 if (pSeq.getEnd() != qSeq.getEnd())
495 if (!pSeq.getName().equals(qSeq.getName()))
499 if (!Arrays.equals(pSeq.getSequence(), qSeq.getSequence()))
503 Assert.fail((message == null ? "" : message + " :")
504 + "Found similar sequences at position " + p + " and " + q
505 + "\n" + pSeq.toString());
510 @Test(groups = { "Functional", "Asserts" })
511 public void testAssertDatasetIsNormalised()
513 Sequence sq1 = new Sequence("s1/1-4", "asdf");
514 Sequence sq1shift = new Sequence("s1/2-5", "asdf");
515 Sequence sq1seqd = new Sequence("s1/1-4", "asdt");
516 Sequence sq2 = new Sequence("s2/1-4", "asdf");
517 Sequence sq1dup = new Sequence("s1/1-4", "asdf");
519 Alignment al = new Alignment(new SequenceI[] { sq1 });
524 assertDatasetIsNormalised(al);
525 } catch (AssertionError ae)
527 Assert.fail("Single sequence should be valid normalised dataset.");
532 assertDatasetIsNormalised(al);
533 } catch (AssertionError ae)
535 Assert.fail("Two different sequences should be valid normalised dataset.");
538 * now change sq2's name in the alignment. should still be valid
540 al.findName(sq2.getName()).setName("sq1");
543 assertDatasetIsNormalised(al);
544 } catch (AssertionError ae)
546 Assert.fail("Two different sequences in dataset, but same name in alignment, should be valid normalised dataset.");
549 al.addSequence(sq1seqd);
552 assertDatasetIsNormalised(al);
553 } catch (AssertionError ae)
555 Assert.fail("sq1 and sq1 with different sequence should be distinct.");
558 al.addSequence(sq1shift);
561 assertDatasetIsNormalised(al);
562 } catch (AssertionError ae)
564 Assert.fail("sq1 and sq1 with different start/end should be distinct.");
567 * finally, the failure case
569 al.addSequence(sq1dup);
570 boolean ssertRaised = false;
573 assertDatasetIsNormalised(al);
575 } catch (AssertionError ae)
581 Assert.fail("Expected identical sequence to raise exception.");
586 * Read in Stockholm format test data including secondary structure
589 @BeforeMethod(alwaysRun = true)
590 public void setUp() throws IOException
592 al = loadAlignment(TEST_DATA, FileFormat.Stockholm);
594 for (AlignmentAnnotation ann : al.getAlignmentAnnotation())
596 ann.setCalcId("CalcIdFor" + al.getSequenceAt(i).getName());
602 * Test method that returns annotations that match on calcId.
604 @Test(groups = { "Functional" })
605 public void testFindAnnotation_byCalcId()
607 Iterable<AlignmentAnnotation> anns = al
608 .findAnnotation("CalcIdForD.melanogaster.2");
609 Iterator<AlignmentAnnotation> iter = anns.iterator();
610 assertTrue(iter.hasNext());
611 AlignmentAnnotation ann = iter.next();
612 assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
613 assertFalse(iter.hasNext());
616 anns = al.findAnnotation("CalcIdForD.melanogaster.?");
617 assertFalse(iter.hasNext());
618 anns = al.findAnnotation(null);
619 assertFalse(iter.hasNext());
623 * Test method that returns annotations that match on reference sequence,
626 @Test(groups = { "Functional" })
627 public void testFindAnnotations_bySeqLabelandorCalcId()
629 // TODO: finish testFindAnnotations_bySeqLabelandorCalcId test
630 /* Note - this is an incomplete test - need to check null or
631 * non-null [ matches, not matches ] behaviour for each of the three
634 // search for a single, unique calcId with wildcards on other params
635 Iterable<AlignmentAnnotation> anns = al.findAnnotations(null,
636 "CalcIdForD.melanogaster.2", null);
637 Iterator<AlignmentAnnotation> iter = anns.iterator();
638 assertTrue(iter.hasNext());
639 AlignmentAnnotation ann = iter.next();
640 assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
641 assertFalse(iter.hasNext());
643 // save reference to test sequence reference parameter
644 SequenceI rseq = ann.sequenceRef;
646 // search for annotation associated with a single sequence
647 anns = al.findAnnotations(rseq, null, null);
648 iter = anns.iterator();
649 assertTrue(iter.hasNext());
651 assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
652 assertFalse(iter.hasNext());
654 // search for annotation with a non-existant calcId
655 anns = al.findAnnotations(null, "CalcIdForD.melanogaster.?", null);
656 iter = anns.iterator();
657 assertFalse(iter.hasNext());
659 // search for annotation with a particular label - expect three
660 anns = al.findAnnotations(null, null, "Secondary Structure");
661 iter = anns.iterator();
662 assertTrue(iter.hasNext());
664 assertTrue(iter.hasNext());
666 assertTrue(iter.hasNext());
669 assertFalse(iter.hasNext());
671 // null on all parameters == find all annotations
672 anns = al.findAnnotations(null, null, null);
673 iter = anns.iterator();
674 int n = al.getAlignmentAnnotation().length;
675 while (iter.hasNext())
680 assertTrue("Found " + n + " fewer annotations from search.", n == 0);
683 @Test(groups = { "Functional" })
684 public void testDeleteAllAnnotations_includingAutocalculated()
686 AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
688 aa.autoCalculated = true;
689 al.addAnnotation(aa);
690 AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
691 assertEquals("Wrong number of annotations before deleting", 4,
693 al.deleteAllAnnotations(true);
694 assertEquals("Not all deleted", 0, al.getAlignmentAnnotation().length);
697 @Test(groups = { "Functional" })
698 public void testDeleteAllAnnotations_excludingAutocalculated()
700 AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
702 aa.autoCalculated = true;
703 al.addAnnotation(aa);
704 AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
705 assertEquals("Wrong number of annotations before deleting", 4,
707 al.deleteAllAnnotations(false);
708 assertEquals("Not just one annotation left", 1,
709 al.getAlignmentAnnotation().length);
713 * Tests for realigning as per a supplied alignment: Dna as Dna.
715 * Note: AlignedCodonFrame's state variables are named for protein-to-cDNA
716 * mapping, but can be exploited for a general 'sequence-to-sequence' mapping
719 * @throws IOException
721 @Test(groups = { "Functional" })
722 public void testAlignAs_dnaAsDna() throws IOException
725 AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
727 AlignmentI al2 = loadAlignment(CDNA_SEQS_2, FileFormat.Fasta);
730 * Make mappings between sequences. The 'aligned cDNA' is playing the role
731 * of what would normally be protein here.
733 makeMappings(al1, al2);
735 ((Alignment) al2).alignAs(al1, false, true);
736 assertEquals("GC-TC--GUC-GTACT", al2.getSequenceAt(0)
737 .getSequenceAsString());
738 assertEquals("-GG-GTC--AGG--CAGT", al2.getSequenceAt(1)
739 .getSequenceAsString());
743 * Aligning protein from cDNA.
745 * @throws IOException
747 @Test(groups = { "Functional" })
748 public void testAlignAs_proteinAsCdna() throws IOException
750 // see also AlignmentUtilsTests
751 AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
752 AlignmentI al2 = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
753 makeMappings(al1, al2);
755 // Fudge - alignProteinAsCdna expects mappings to be on protein
756 al2.getCodonFrames().addAll(al1.getCodonFrames());
758 ((Alignment) al2).alignAs(al1, false, true);
759 assertEquals("K-Q-Y-L-", al2.getSequenceAt(0).getSequenceAsString());
760 assertEquals("-R-F-P-W", al2.getSequenceAt(1).getSequenceAsString());
764 * Test aligning cdna as per protein alignment.
766 * @throws IOException
768 @Test(groups = { "Functional" }, enabled = true)
769 // TODO review / update this test after redesign of alignAs method
770 public void testAlignAs_cdnaAsProtein() throws IOException
773 * Load alignments and add mappings for cDNA to protein
775 AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
776 AlignmentI al2 = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
777 makeMappings(al1, al2);
780 * Realign DNA; currently keeping existing gaps in introns only
782 ((Alignment) al1).alignAs(al2, false, true);
783 assertEquals("ACG---GCUCCA------ACT---", al1.getSequenceAt(0)
784 .getSequenceAsString());
785 assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
786 .getSequenceAsString());
790 * Test aligning cdna as per protein - single sequences
792 * @throws IOException
794 @Test(groups = { "Functional" }, enabled = true)
795 // TODO review / update this test after redesign of alignAs method
796 public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
799 * simple case insert one gap
801 verifyAlignAs(">dna\nCAAaaa\n", ">protein\nQ-K\n", "CAA---aaa");
804 * simple case but with sequence offsets
806 verifyAlignAs(">dna/5-10\nCAAaaa\n", ">protein/20-21\nQ-K\n",
810 * insert gaps as per protein, drop gaps within codons
812 verifyAlignAs(">dna/10-18\nCA-Aa-aa--AGA\n", ">aa/6-8\n-Q-K--R\n",
813 "---CAA---aaa------AGA");
817 * Helper method that makes mappings and then aligns the first alignment as
823 * @throws IOException
825 public void verifyAlignAs(String fromSeqs, String toSeqs, String expected)
829 * Load alignments and add mappings from nucleotide to protein (or from
830 * first to second if both the same type)
832 AlignmentI al1 = loadAlignment(fromSeqs, FileFormat.Fasta);
833 AlignmentI al2 = loadAlignment(toSeqs, FileFormat.Fasta);
834 makeMappings(al1, al2);
837 * Realign DNA; currently keeping existing gaps in introns only
839 ((Alignment) al1).alignAs(al2, false, true);
840 assertEquals(expected, al1.getSequenceAt(0).getSequenceAsString());
844 * Helper method to make mappings between sequences, and add the mappings to
845 * the 'mapped from' alignment
850 public void makeMappings(AlignmentI alFrom, AlignmentI alTo)
852 int ratio = (alFrom.isNucleotide() == alTo.isNucleotide() ? 1 : 3);
854 AlignedCodonFrame acf = new AlignedCodonFrame();
856 for (int i = 0; i < alFrom.getHeight(); i++)
858 SequenceI seqFrom = alFrom.getSequenceAt(i);
859 SequenceI seqTo = alTo.getSequenceAt(i);
860 MapList ml = new MapList(new int[] { seqFrom.getStart(),
862 new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
863 acf.addMap(seqFrom, seqTo, ml);
867 * not sure whether mappings 'belong' or protein or nucleotide
868 * alignment, so adding to both ;~)
870 alFrom.addCodonFrame(acf);
871 alTo.addCodonFrame(acf);
875 * Test aligning dna as per protein alignment, for the case where there are
876 * introns (i.e. some dna sites have no mapping from a peptide).
878 * @throws IOException
880 @Test(groups = { "Functional" }, enabled = false)
881 // TODO review / update this test after redesign of alignAs method
882 public void testAlignAs_dnaAsProtein_withIntrons() throws IOException
885 * Load alignments and add mappings for cDNA to protein
887 String dna1 = "A-Aa-gG-GCC-cT-TT";
888 String dna2 = "c--CCGgg-TT--T-AA-A";
889 AlignmentI al1 = loadAlignment(">Dna1/6-17\n" + dna1
890 + "\n>Dna2/20-31\n" + dna2 + "\n", FileFormat.Fasta);
891 AlignmentI al2 = loadAlignment(
892 ">Pep1/7-9\n-P--YK\n>Pep2/11-13\nG-T--F\n", FileFormat.Fasta);
893 AlignedCodonFrame acf = new AlignedCodonFrame();
894 // Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
895 // Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
896 MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
898 acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
899 MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
901 acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
902 al2.addCodonFrame(acf);
905 * Align ignoring gaps in dna introns and exons
907 ((Alignment) al1).alignAs(al2, false, false);
908 assertEquals("---AAagG------GCCcTTT", al1.getSequenceAt(0)
909 .getSequenceAsString());
910 // note 1 gap in protein corresponds to 'gg-' in DNA (3 positions)
911 assertEquals("cCCGgg-TTT------AAA", al1.getSequenceAt(1)
912 .getSequenceAsString());
915 * Reset and realign, preserving gaps in dna introns and exons
917 al1.getSequenceAt(0).setSequence(dna1);
918 al1.getSequenceAt(1).setSequence(dna2);
919 ((Alignment) al1).alignAs(al2, true, true);
920 // String dna1 = "A-Aa-gG-GCC-cT-TT";
921 // String dna2 = "c--CCGgg-TT--T-AA-A";
922 // assumption: we include 'the greater of' protein/dna gap lengths, not both
923 assertEquals("---A-Aa-gG------GCC-cT-TT", al1.getSequenceAt(0)
924 .getSequenceAsString());
925 assertEquals("c--CCGgg-TT--T------AA-A", al1.getSequenceAt(1)
926 .getSequenceAsString());
929 @Test(groups = "Functional")
930 public void testCopyConstructor() throws IOException
932 AlignmentI protein = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
933 // create sequence and alignment datasets
934 protein.setDataset(null);
935 AlignedCodonFrame acf = new AlignedCodonFrame();
936 List<AlignedCodonFrame> acfList = Arrays.asList(new AlignedCodonFrame[]
938 protein.getDataset().setCodonFrames(acfList);
939 AlignmentI copy = new Alignment(protein);
942 * copy has different aligned sequences but the same dataset sequences
944 assertFalse(copy.getSequenceAt(0) == protein.getSequenceAt(0));
945 assertFalse(copy.getSequenceAt(1) == protein.getSequenceAt(1));
946 assertSame(copy.getSequenceAt(0).getDatasetSequence(), protein
947 .getSequenceAt(0).getDatasetSequence());
948 assertSame(copy.getSequenceAt(1).getDatasetSequence(), protein
949 .getSequenceAt(1).getDatasetSequence());
951 // TODO should the copy constructor copy the dataset?
952 // or make a new one referring to the same dataset sequences??
953 assertNull(copy.getDataset());
954 // TODO test metadata is copied when AlignmentI is a dataset
956 // assertArrayEquals(copy.getDataset().getSequencesArray(), protein
957 // .getDataset().getSequencesArray());
961 * Test behaviour of createDataset
963 * @throws IOException
965 @Test(groups = "Functional")
966 public void testCreateDatasetAlignment() throws IOException
968 AlignmentI protein = new FormatAdapter().readFile(AA_SEQS_1,
969 DataSourceType.PASTE, FileFormat.Fasta);
971 * create a dataset sequence on first sequence
972 * leave the second without one
974 protein.getSequenceAt(0).createDatasetSequence();
975 assertNotNull(protein.getSequenceAt(0).getDatasetSequence());
976 assertNull(protein.getSequenceAt(1).getDatasetSequence());
979 * add a mapping to the alignment
981 AlignedCodonFrame acf = new AlignedCodonFrame();
982 protein.addCodonFrame(acf);
983 assertNull(protein.getDataset());
984 assertTrue(protein.getCodonFrames().contains(acf));
987 * create the alignment dataset
988 * note this creates sequence datasets where missing
989 * as a side-effect (in this case, on seq2
991 // TODO promote this method to AlignmentI
992 ((Alignment) protein).createDatasetAlignment();
994 AlignmentI ds = protein.getDataset();
996 // side-effect: dataset created on second sequence
997 assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
998 // dataset alignment has references to dataset sequences
999 assertEquals(ds.getSequenceAt(0), protein.getSequenceAt(0)
1000 .getDatasetSequence());
1001 assertEquals(ds.getSequenceAt(1), protein.getSequenceAt(1)
1002 .getDatasetSequence());
1004 // codon frames should have been moved to the dataset
1005 // getCodonFrames() should delegate to the dataset:
1006 assertTrue(protein.getCodonFrames().contains(acf));
1007 // prove the codon frames are indeed on the dataset:
1008 assertTrue(ds.getCodonFrames().contains(acf));
1012 * tests the addition of *all* sequences referred to by a sequence being added
1015 @Test(groups = "Functional")
1016 public void testCreateDatasetAlignmentWithMappedToSeqs()
1018 // Alignment with two sequences, gapped.
1019 SequenceI sq1 = new Sequence("sq1", "A--SDF");
1020 SequenceI sq2 = new Sequence("sq2", "G--TRQ");
1022 // cross-references to two more sequences.
1023 DBRefEntry dbr = new DBRefEntry("SQ1", "", "sq3");
1024 SequenceI sq3 = new Sequence("sq3", "VWANG");
1025 dbr.setMap(new Mapping(sq3, new MapList(new int[] { 1, 4 }, new int[] {
1029 SequenceI sq4 = new Sequence("sq4", "ERKWI");
1030 DBRefEntry dbr2 = new DBRefEntry("SQ2", "", "sq4");
1031 dbr2.setMap(new Mapping(sq4, new MapList(new int[] { 1, 4 }, new int[] {
1034 // and a 1:1 codonframe mapping between them.
1035 AlignedCodonFrame alc = new AlignedCodonFrame();
1036 alc.addMap(sq1, sq2, new MapList(new int[] { 1, 4 },
1037 new int[] { 1, 4 }, 1, 1));
1039 AlignmentI protein = new Alignment(new SequenceI[] { sq1, sq2 });
1042 * create the alignment dataset
1043 * note this creates sequence datasets where missing
1044 * as a side-effect (in this case, on seq2
1047 // TODO promote this method to AlignmentI
1048 ((Alignment) protein).createDatasetAlignment();
1050 AlignmentI ds = protein.getDataset();
1052 // should be 4 sequences in dataset - two materialised, and two propagated
1054 assertEquals(4, ds.getHeight());
1055 assertTrue(ds.getSequences().contains(sq1.getDatasetSequence()));
1056 assertTrue(ds.getSequences().contains(sq2.getDatasetSequence()));
1057 assertTrue(ds.getSequences().contains(sq3));
1058 assertTrue(ds.getSequences().contains(sq4));
1059 // Should have one codon frame mapping between sq1 and sq2 via dataset
1061 assertEquals(ds.getCodonFrame(sq1.getDatasetSequence()),
1062 ds.getCodonFrame(sq2.getDatasetSequence()));
1065 @Test(groups = "Functional")
1066 public void testAddCodonFrame()
1068 AlignmentI align = new Alignment(new SequenceI[] {});
1069 AlignedCodonFrame acf = new AlignedCodonFrame();
1070 align.addCodonFrame(acf);
1071 assertEquals(1, align.getCodonFrames().size());
1072 assertTrue(align.getCodonFrames().contains(acf));
1073 // can't add the same object twice:
1074 align.addCodonFrame(acf);
1075 assertEquals(1, align.getCodonFrames().size());
1077 // create dataset alignment - mappings move to dataset
1078 ((Alignment) align).createDatasetAlignment();
1079 assertSame(align.getCodonFrames(), align.getDataset().getCodonFrames());
1080 assertEquals(1, align.getCodonFrames().size());
1082 AlignedCodonFrame acf2 = new AlignedCodonFrame();
1083 align.addCodonFrame(acf2);
1084 assertTrue(align.getDataset().getCodonFrames().contains(acf));
1087 @Test(groups = "Functional")
1088 public void testAddSequencePreserveDatasetIntegrity()
1090 Sequence seq = new Sequence("testSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1091 Alignment align = new Alignment(new SequenceI[] { seq });
1092 align.createDatasetAlignment();
1093 AlignmentI ds = align.getDataset();
1094 SequenceI copy = new Sequence(seq);
1095 copy.insertCharAt(3, 5, '-');
1096 align.addSequence(copy);
1097 Assert.assertEquals(align.getDataset().getHeight(), 1,
1098 "Dataset shouldn't have more than one sequence.");
1100 Sequence seq2 = new Sequence("newtestSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1101 align.addSequence(seq2);
1102 Assert.assertEquals(align.getDataset().getHeight(), 2,
1103 "Dataset should now have two sequences.");
1105 assertAlignmentDatasetRefs(align,
1106 "addSequence broke dataset reference integrity");
1110 * Tests that dbrefs with mappings to sequence get updated if the sequence
1111 * acquires a dataset sequence
1113 @Test(groups = "Functional")
1114 public void testCreateDataset_updateDbrefMappings()
1116 SequenceI pep = new Sequence("pep", "ASD");
1117 SequenceI dna = new Sequence("dna", "aaaGCCTCGGATggg");
1118 SequenceI cds = new Sequence("cds", "GCCTCGGAT");
1120 // add dbref from dna to peptide
1121 DBRefEntry dbr = new DBRefEntry("UNIPROT", "", "pep");
1122 dbr.setMap(new Mapping(pep, new MapList(new int[] { 4, 15 }, new int[] {
1126 // add dbref from dna to peptide
1127 DBRefEntry dbr2 = new DBRefEntry("UNIPROT", "", "pep");
1128 dbr2.setMap(new Mapping(pep, new MapList(new int[] { 1, 12 }, new int[]
1132 // add dbref from peptide to dna
1133 DBRefEntry dbr3 = new DBRefEntry("EMBL", "", "dna");
1134 dbr3.setMap(new Mapping(dna, new MapList(new int[] { 1, 4 }, new int[] {
1138 // add dbref from peptide to cds
1139 DBRefEntry dbr4 = new DBRefEntry("EMBLCDS", "", "cds");
1140 dbr4.setMap(new Mapping(cds, new MapList(new int[] { 1, 4 }, new int[] {
1144 AlignmentI protein = new Alignment(new SequenceI[] { pep });
1147 * create the alignment dataset
1149 ((Alignment) protein).createDatasetAlignment();
1151 AlignmentI ds = protein.getDataset();
1153 // should be 3 sequences in dataset
1154 assertEquals(3, ds.getHeight());
1155 assertTrue(ds.getSequences().contains(pep.getDatasetSequence()));
1156 assertTrue(ds.getSequences().contains(dna));
1157 assertTrue(ds.getSequences().contains(cds));
1160 * verify peptide.cdsdbref.peptidedbref is now mapped to peptide dataset
1162 DBRefEntry[] dbRefs = pep.getDBRefs();
1163 assertEquals(2, dbRefs.length);
1164 assertSame(dna, dbRefs[0].map.to);
1165 assertSame(cds, dbRefs[1].map.to);
1166 assertEquals(1, dna.getDBRefs().length);
1167 assertSame(pep.getDatasetSequence(), dna.getDBRefs()[0].map.to);
1168 assertEquals(1, cds.getDBRefs().length);
1169 assertSame(pep.getDatasetSequence(), cds.getDBRefs()[0].map.to);
1172 @Test(groups = { "Functional" })
1173 public void testFindGroup()
1175 SequenceI seq1 = new Sequence("seq1", "ABCDEF---GHI");
1176 SequenceI seq2 = new Sequence("seq2", "---JKLMNO---");
1177 AlignmentI a = new Alignment(new SequenceI[] { seq1, seq2 });
1179 assertNull(a.findGroup(null, 0));
1180 assertNull(a.findGroup(seq1, 1));
1181 assertNull(a.findGroup(seq1, -1));
1184 * add a group consisting of just "DEF"
1186 SequenceGroup sg1 = new SequenceGroup();
1187 sg1.addSequence(seq1, false);
1192 assertNull(a.findGroup(seq1, 2)); // position not in group
1193 assertNull(a.findGroup(seq1, 6)); // position not in group
1194 assertNull(a.findGroup(seq2, 5)); // sequence not in group
1195 assertSame(a.findGroup(seq1, 3), sg1); // yes
1196 assertSame(a.findGroup(seq1, 4), sg1);
1197 assertSame(a.findGroup(seq1, 5), sg1);
1200 * add a group consisting of
1204 SequenceGroup sg2 = new SequenceGroup();
1205 sg2.addSequence(seq1, false);
1206 sg2.addSequence(seq2, false);
1211 assertNull(a.findGroup(seq1, 2)); // unchanged
1212 assertSame(a.findGroup(seq1, 3), sg1); // unchanged
1214 * if a residue is in more than one group, method returns
1215 * the first found (in order groups were added)
1217 assertSame(a.findGroup(seq1, 4), sg1);
1218 assertSame(a.findGroup(seq1, 5), sg1);
1221 * seq2 only belongs to the second group
1223 assertSame(a.findGroup(seq2, 4), sg2);
1224 assertSame(a.findGroup(seq2, 5), sg2);
1225 assertSame(a.findGroup(seq2, 6), sg2);
1226 assertSame(a.findGroup(seq2, 7), sg2);
1227 assertNull(a.findGroup(seq2, 3));
1228 assertNull(a.findGroup(seq2, 8));
1231 @Test(groups = { "Functional" })
1232 public void testDeleteSequenceByIndex()
1234 // create random alignment
1235 AlignmentGenerator gen = new AlignmentGenerator(false);
1236 AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1238 // delete sequence 10, alignment reduced by 1
1239 int height = a.getAbsoluteHeight();
1240 a.deleteSequence(10);
1241 assertEquals(a.getAbsoluteHeight(), height - 1);
1243 // try to delete -ve index, nothing happens
1244 a.deleteSequence(-1);
1245 assertEquals(a.getAbsoluteHeight(), height - 1);
1247 // try to delete beyond end of alignment, nothing happens
1248 a.deleteSequence(14);
1249 assertEquals(a.getAbsoluteHeight(), height - 1);
1252 @Test(groups = { "Functional" })
1253 public void testDeleteSequenceBySeq()
1255 // create random alignment
1256 AlignmentGenerator gen = new AlignmentGenerator(false);
1257 AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1259 // delete sequence 10, alignment reduced by 1
1260 int height = a.getAbsoluteHeight();
1261 SequenceI seq = a.getSequenceAt(10);
1262 a.deleteSequence(seq);
1263 assertEquals(a.getAbsoluteHeight(), height - 1);
1265 // try to delete non-existent sequence, nothing happens
1266 seq = new Sequence("cds", "GCCTCGGAT");
1267 assertEquals(a.getAbsoluteHeight(), height - 1);
1270 @Test(groups = { "Functional" })
1271 public void testDeleteHiddenSequence()
1273 // create random alignment
1274 AlignmentGenerator gen = new AlignmentGenerator(false);
1275 AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1277 // delete a sequence which is hidden, check it is NOT removed from hidden
1279 int height = a.getAbsoluteHeight();
1280 SequenceI seq = a.getSequenceAt(2);
1281 a.getHiddenSequences().hideSequence(seq);
1282 assertEquals(a.getHiddenSequences().getSize(), 1);
1283 a.deleteSequence(2);
1284 assertEquals(a.getAbsoluteHeight(), height - 1);
1285 assertEquals(a.getHiddenSequences().getSize(), 1);
1287 // delete a sequence which is not hidden, check hiddenSequences are not
1289 a.deleteSequence(10);
1290 assertEquals(a.getAbsoluteHeight(), height - 2);
1291 assertEquals(a.getHiddenSequences().getSize(), 1);
1295 groups = "Functional",
1296 expectedExceptions = { IllegalArgumentException.class })
1297 public void testSetDataset_selfReference()
1299 SequenceI seq = new Sequence("a", "a");
1300 AlignmentI alignment = new Alignment(new SequenceI[] { seq });
1301 alignment.setDataset(alignment);
1304 @Test(groups = "Functional")
1305 public void testAppend()
1307 SequenceI seq = new Sequence("seq1", "FRMLPSRT-A--L-");
1308 AlignmentI alignment = new Alignment(new SequenceI[] { seq });
1309 alignment.setGapCharacter('-');
1310 SequenceI seq2 = new Sequence("seq1", "KP..L.FQII.");
1311 AlignmentI alignment2 = new Alignment(new SequenceI[] { seq2 });
1312 alignment2.setGapCharacter('.');
1314 alignment.append(alignment2);
1316 assertEquals('-', alignment.getGapCharacter());
1317 assertSame(seq, alignment.getSequenceAt(0));
1318 assertEquals("KP--L-FQII-", alignment.getSequenceAt(1)
1319 .getSequenceAsString());
1321 // todo test coverage for annotations, mappings, groups,
1322 // hidden sequences, properties