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.ArrayList;
41 import java.util.Arrays;
42 import java.util.Iterator;
43 import java.util.List;
45 import org.testng.Assert;
46 import org.testng.annotations.BeforeClass;
47 import org.testng.annotations.BeforeMethod;
48 import org.testng.annotations.Test;
51 * Unit tests for Alignment datamodel.
56 public class AlignmentTest
59 @BeforeClass(alwaysRun = true)
60 public void setUpJvOptionPane()
62 JvOptionPane.setInteractiveMode(false);
63 JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
67 private static final String TEST_DATA =
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" +
80 private static final String AA_SEQS_1 =
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";
92 private static final String CDNA_SEQS_2 =
99 private AlignmentI al;
102 * Helper method to load an alignment and ensure dataset sequences are set up.
108 * @throws IOException
110 protected AlignmentI loadAlignment(final String data, FileFormatI format)
113 AlignmentI a = new FormatAdapter().readFile(data, DataSourceType.PASTE,
120 * assert wrapper: tests all references in the given alignment are consistent
124 public static void assertAlignmentDatasetRefs(AlignmentI alignment)
126 verifyAlignmentDatasetRefs(alignment, true, null);
130 * assert wrapper: tests all references in the given alignment are consistent
134 * - prefixed to any assert failed messages
136 public static void assertAlignmentDatasetRefs(AlignmentI alignment,
139 verifyAlignmentDatasetRefs(alignment, true, message);
143 * verify sequence and dataset references are properly contained within
147 * - the alignmentI object to verify (either alignment or dataset)
149 * - when set, testng assertions are raised.
151 * - null or a string message to prepend to the assert failed
153 * @return true if alignment references were in order, otherwise false.
155 public static boolean verifyAlignmentDatasetRefs(AlignmentI alignment,
156 boolean raiseAssert, String message)
162 if (alignment == null)
166 Assert.fail(message + "Alignment for verification was null.");
170 if (alignment.getDataset() != null)
172 AlignmentI dataset = alignment.getDataset();
173 // check all alignment sequences have their dataset within the dataset
174 for (SequenceI seq : alignment.getSequences())
176 SequenceI seqds = seq.getDatasetSequence();
177 if (seqds.getDatasetSequence() != null)
182 + " Alignment contained a sequence who's dataset sequence has a second dataset reference.");
186 if (dataset.findIndex(seqds) == -1)
191 + " Alignment contained a sequence who's dataset sequence was not in the dataset.");
196 return verifyAlignmentDatasetRefs(alignment.getDataset(),
197 raiseAssert, message);
202 // verify all dataset sequences
203 for (SequenceI seqds : alignment.getSequences())
206 if (seqds.getDatasetSequence() != null)
211 + " Dataset contained a sequence with non-null dataset reference (ie not a dataset sequence!)");
215 int foundp = alignment.findIndex(seqds);
221 + " Dataset sequence array contains a reference at "
222 + dsp + " to a sequence first seen at " + foundp + " ("
223 + seqds.toString() + ")");
227 if (seqds.getDBRefs() != null)
229 for (DBRefEntry dbr : seqds.getDBRefs())
231 if (dbr.getMap() != null)
233 SequenceI seqdbrmapto = dbr.getMap().getTo();
234 if (seqdbrmapto != null)
236 if (seqdbrmapto.getDatasetSequence() != null)
241 + " DBRefEntry for sequence in alignment had map to sequence which was not a dataset sequence");
246 if (alignment.findIndex(dbr.getMap().getTo()) == -1)
251 + " DBRefEntry for sequence in alignment had map to sequence not in dataset");
260 // finally, verify codonmappings involve only dataset sequences.
261 if (alignment.getCodonFrames() != null)
263 for (AlignedCodonFrame alc : alignment.getCodonFrames())
265 for (SequenceToSequenceMapping ssm : alc.getMappings())
267 if (ssm.getFromSeq().getDatasetSequence() != null)
272 + " CodonFrame-SSM-FromSeq is not a dataset sequence");
276 if (alignment.findIndex(ssm.getFromSeq()) == -1)
282 + " CodonFrame-SSM-FromSeq is not contained in dataset");
286 if (ssm.getMapping().getTo().getDatasetSequence() != null)
291 + " CodonFrame-SSM-Mapping-ToSeq is not a dataset sequence");
295 if (alignment.findIndex(ssm.getMapping().getTo()) == -1)
301 + " CodonFrame-SSM-Mapping-ToSeq is not contained in dataset");
309 return true; // all relationships verified!
313 * call verifyAlignmentDatasetRefs with and without assertion raising enabled,
314 * to check expected pass/fail actually occurs in both conditions
320 private void assertVerifyAlignment(AlignmentI al, boolean expected,
328 Assert.assertTrue(verifyAlignmentDatasetRefs(al, true, null),
329 "Valid test alignment failed when raiseAsserts enabled:"
331 } catch (AssertionError ae)
333 ae.printStackTrace();
335 "Valid test alignment raised assertion errors when raiseAsserts enabled: "
338 // also check validation passes with asserts disabled
339 Assert.assertTrue(verifyAlignmentDatasetRefs(al, false, null),
340 "Valid test alignment tested false when raiseAsserts disabled:"
345 boolean assertRaised = false;
348 verifyAlignmentDatasetRefs(al, true, null);
349 } catch (AssertionError ae)
351 // expected behaviour
356 Assert.fail("Invalid test alignment passed when raiseAsserts enabled:"
359 // also check validation passes with asserts disabled
360 Assert.assertFalse(verifyAlignmentDatasetRefs(al, false, null),
361 "Invalid test alignment tested true when raiseAsserts disabled:"
366 @Test(groups = { "Functional" })
367 public void testVerifyAlignmentDatasetRefs()
369 SequenceI sq1 = new Sequence("sq1", "ASFDD"), sq2 = new Sequence("sq2",
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");
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.");
382 sq1.setDatasetSequence(null);
383 assertVerifyAlignment(
386 "didn't reinstate validity after nulling dataset sequence dataset reference");
388 // now create dataset and check again
389 al.createDatasetAlignment();
390 assertNotNull(al.getDataset());
392 assertVerifyAlignment(al, true,
393 "verify failed after createDatasetAlignment");
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(
406 DBRefEntry sqnewsqout = new DBRefEntry("ENAFOO", "1", "R000001");
407 sqnewsqout.setMap(new Mapping(sqout, new int[] { 1, 6 }, new int[] { 1,
409 al.getDataset().addSequence(sqnew);
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(
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");
427 AlignedCodonFrame alc = new AlignedCodonFrame();
428 alc.addMap(sqanotherout, sqnew, new MapList(new int[] { 1, 6 },
429 new int[] { 1, 18 }, 3, 1));
431 al.addCodonFrame(alc);
432 Assert.assertEquals(al.getDataset().getCodonFrames().size(), 1);
434 assertVerifyAlignment(
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(
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");
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.
457 public static void assertDatasetIsNormalised(AlignmentI al)
459 assertDatasetIsNormalised(al, null);
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.
467 * - alignment to verify
469 * - null or message prepended to exception message.
471 public static void assertDatasetIsNormalised(AlignmentI al, String message)
473 if (al.getDataset() != null)
475 assertDatasetIsNormalised(al.getDataset(), message);
479 * look for pairs of sequences with same ID, start, end, and sequence
481 List<SequenceI> seqSet = al.getSequences();
482 for (int p = 0; p < seqSet.size(); p++)
484 SequenceI pSeq = seqSet.get(p);
485 for (int q = p + 1; q < seqSet.size(); q++)
487 SequenceI qSeq = seqSet.get(q);
488 if (pSeq.getStart() != qSeq.getStart())
492 if (pSeq.getEnd() != qSeq.getEnd())
496 if (!pSeq.getName().equals(qSeq.getName()))
500 if (!Arrays.equals(pSeq.getSequence(), qSeq.getSequence()))
504 Assert.fail((message == null ? "" : message + " :")
505 + "Found similar sequences at position " + p + " and " + q
506 + "\n" + pSeq.toString());
511 @Test(groups = { "Functional", "Asserts" })
512 public void testAssertDatasetIsNormalised()
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");
520 Alignment al = new Alignment(new SequenceI[] { sq1 });
525 assertDatasetIsNormalised(al);
526 } catch (AssertionError ae)
528 Assert.fail("Single sequence should be valid normalised dataset.");
533 assertDatasetIsNormalised(al);
534 } catch (AssertionError ae)
536 Assert.fail("Two different sequences should be valid normalised dataset.");
539 * now change sq2's name in the alignment. should still be valid
541 al.findName(sq2.getName()).setName("sq1");
544 assertDatasetIsNormalised(al);
545 } catch (AssertionError ae)
547 Assert.fail("Two different sequences in dataset, but same name in alignment, should be valid normalised dataset.");
550 al.addSequence(sq1seqd);
553 assertDatasetIsNormalised(al);
554 } catch (AssertionError ae)
556 Assert.fail("sq1 and sq1 with different sequence should be distinct.");
559 al.addSequence(sq1shift);
562 assertDatasetIsNormalised(al);
563 } catch (AssertionError ae)
565 Assert.fail("sq1 and sq1 with different start/end should be distinct.");
568 * finally, the failure case
570 al.addSequence(sq1dup);
571 boolean ssertRaised = false;
574 assertDatasetIsNormalised(al);
576 } catch (AssertionError ae)
582 Assert.fail("Expected identical sequence to raise exception.");
587 * Read in Stockholm format test data including secondary structure
590 @BeforeMethod(alwaysRun = true)
591 public void setUp() throws IOException
593 al = loadAlignment(TEST_DATA, FileFormat.Stockholm);
595 for (AlignmentAnnotation ann : al.getAlignmentAnnotation())
597 ann.setCalcId("CalcIdFor" + al.getSequenceAt(i).getName());
603 * Test method that returns annotations that match on calcId.
605 @Test(groups = { "Functional" })
606 public void testFindAnnotation_byCalcId()
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());
617 anns = al.findAnnotation("CalcIdForD.melanogaster.?");
618 assertFalse(iter.hasNext());
619 anns = al.findAnnotation(null);
620 assertFalse(iter.hasNext());
624 * Test method that returns annotations that match on reference sequence,
627 @Test(groups = { "Functional" })
628 public void testFindAnnotations_bySeqLabelandorCalcId()
630 // TODO: finish testFindAnnotations_bySeqLabelandorCalcId test
631 /* Note - this is an incomplete test - need to check null or
632 * non-null [ matches, not matches ] behaviour for each of the three
635 // search for a single, unique calcId with wildcards on other params
636 Iterable<AlignmentAnnotation> anns = al.findAnnotations(null,
637 "CalcIdForD.melanogaster.2", null);
638 Iterator<AlignmentAnnotation> iter = anns.iterator();
639 assertTrue(iter.hasNext());
640 AlignmentAnnotation ann = iter.next();
641 assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
642 assertFalse(iter.hasNext());
644 // save reference to test sequence reference parameter
645 SequenceI rseq = ann.sequenceRef;
647 // search for annotation associated with a single sequence
648 anns = al.findAnnotations(rseq, null, null);
649 iter = anns.iterator();
650 assertTrue(iter.hasNext());
652 assertEquals("D.melanogaster.2", ann.sequenceRef.getName());
653 assertFalse(iter.hasNext());
655 // search for annotation with a non-existant calcId
656 anns = al.findAnnotations(null, "CalcIdForD.melanogaster.?", null);
657 iter = anns.iterator();
658 assertFalse(iter.hasNext());
660 // search for annotation with a particular label - expect three
661 anns = al.findAnnotations(null, null, "Secondary Structure");
662 iter = anns.iterator();
663 assertTrue(iter.hasNext());
665 assertTrue(iter.hasNext());
667 assertTrue(iter.hasNext());
670 assertFalse(iter.hasNext());
672 // null on all parameters == find all annotations
673 anns = al.findAnnotations(null, null, null);
674 iter = anns.iterator();
675 int n = al.getAlignmentAnnotation().length;
676 while (iter.hasNext())
681 assertTrue("Found " + n + " fewer annotations from search.", n == 0);
684 @Test(groups = { "Functional" })
685 public void testDeleteAllAnnotations_includingAutocalculated()
687 AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
689 aa.autoCalculated = true;
690 al.addAnnotation(aa);
691 AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
692 assertEquals("Wrong number of annotations before deleting", 4,
694 al.deleteAllAnnotations(true);
695 assertEquals("Not all deleted", 0, al.getAlignmentAnnotation().length);
698 @Test(groups = { "Functional" })
699 public void testDeleteAllAnnotations_excludingAutocalculated()
701 AlignmentAnnotation aa = new AlignmentAnnotation("Consensus",
703 aa.autoCalculated = true;
704 al.addAnnotation(aa);
705 AlignmentAnnotation[] anns = al.getAlignmentAnnotation();
706 assertEquals("Wrong number of annotations before deleting", 4,
708 al.deleteAllAnnotations(false);
709 assertEquals("Not just one annotation left", 1,
710 al.getAlignmentAnnotation().length);
714 * Tests for realigning as per a supplied alignment: Dna as Dna.
716 * Note: AlignedCodonFrame's state variables are named for protein-to-cDNA
717 * mapping, but can be exploited for a general 'sequence-to-sequence' mapping
720 * @throws IOException
722 @Test(groups = { "Functional" })
723 public void testAlignAs_dnaAsDna() throws IOException
726 AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
728 AlignmentI al2 = loadAlignment(CDNA_SEQS_2, FileFormat.Fasta);
731 * Make mappings between sequences. The 'aligned cDNA' is playing the role
732 * of what would normally be protein here.
734 makeMappings(al1, al2);
736 ((Alignment) al2).alignAs(al1, false, true);
737 assertEquals("GC-TC--GUC-GTACT", al2.getSequenceAt(0)
738 .getSequenceAsString());
739 assertEquals("-GG-GTC--AGG--CAGT", al2.getSequenceAt(1)
740 .getSequenceAsString());
744 * Aligning protein from cDNA.
746 * @throws IOException
748 @Test(groups = { "Functional" })
749 public void testAlignAs_proteinAsCdna() throws IOException
751 // see also AlignmentUtilsTests
752 AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
753 AlignmentI al2 = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
754 makeMappings(al1, al2);
756 // Fudge - alignProteinAsCdna expects mappings to be on protein
757 al2.getCodonFrames().addAll(al1.getCodonFrames());
759 ((Alignment) al2).alignAs(al1, false, true);
760 assertEquals("K-Q-Y-L-", al2.getSequenceAt(0).getSequenceAsString());
761 assertEquals("-R-F-P-W", al2.getSequenceAt(1).getSequenceAsString());
765 * Test aligning cdna as per protein alignment.
767 * @throws IOException
769 @Test(groups = { "Functional" }, enabled = true)
770 // TODO review / update this test after redesign of alignAs method
771 public void testAlignAs_cdnaAsProtein() throws IOException
774 * Load alignments and add mappings for cDNA to protein
776 AlignmentI al1 = loadAlignment(CDNA_SEQS_1, FileFormat.Fasta);
777 AlignmentI al2 = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
778 makeMappings(al1, al2);
781 * Realign DNA; currently keeping existing gaps in introns only
783 ((Alignment) al1).alignAs(al2, false, true);
784 assertEquals("ACG---GCUCCA------ACT---", al1.getSequenceAt(0)
785 .getSequenceAsString());
786 assertEquals("---CGT---TAACGA---AGT---", al1.getSequenceAt(1)
787 .getSequenceAsString());
791 * Test aligning cdna as per protein - single sequences
793 * @throws IOException
795 @Test(groups = { "Functional" }, enabled = true)
796 // TODO review / update this test after redesign of alignAs method
797 public void testAlignAs_cdnaAsProtein_singleSequence() throws IOException
800 * simple case insert one gap
802 verifyAlignAs(">dna\nCAAaaa\n", ">protein\nQ-K\n", "CAA---aaa");
805 * simple case but with sequence offsets
807 verifyAlignAs(">dna/5-10\nCAAaaa\n", ">protein/20-21\nQ-K\n",
811 * insert gaps as per protein, drop gaps within codons
813 verifyAlignAs(">dna/10-18\nCA-Aa-aa--AGA\n", ">aa/6-8\n-Q-K--R\n",
814 "---CAA---aaa------AGA");
818 * Helper method that makes mappings and then aligns the first alignment as
824 * @throws IOException
826 public void verifyAlignAs(String fromSeqs, String toSeqs, String expected)
830 * Load alignments and add mappings from nucleotide to protein (or from
831 * first to second if both the same type)
833 AlignmentI al1 = loadAlignment(fromSeqs, FileFormat.Fasta);
834 AlignmentI al2 = loadAlignment(toSeqs, FileFormat.Fasta);
835 makeMappings(al1, al2);
838 * Realign DNA; currently keeping existing gaps in introns only
840 ((Alignment) al1).alignAs(al2, false, true);
841 assertEquals(expected, al1.getSequenceAt(0).getSequenceAsString());
845 * Helper method to make mappings between sequences, and add the mappings to
846 * the 'mapped from' alignment
851 public void makeMappings(AlignmentI alFrom, AlignmentI alTo)
853 int ratio = (alFrom.isNucleotide() == alTo.isNucleotide() ? 1 : 3);
855 AlignedCodonFrame acf = new AlignedCodonFrame();
857 for (int i = 0; i < alFrom.getHeight(); i++)
859 SequenceI seqFrom = alFrom.getSequenceAt(i);
860 SequenceI seqTo = alTo.getSequenceAt(i);
861 MapList ml = new MapList(new int[] { seqFrom.getStart(),
863 new int[] { seqTo.getStart(), seqTo.getEnd() }, ratio, 1);
864 acf.addMap(seqFrom, seqTo, ml);
868 * not sure whether mappings 'belong' or protein or nucleotide
869 * alignment, so adding to both ;~)
871 alFrom.addCodonFrame(acf);
872 alTo.addCodonFrame(acf);
876 * Test aligning dna as per protein alignment, for the case where there are
877 * introns (i.e. some dna sites have no mapping from a peptide).
879 * @throws IOException
881 @Test(groups = { "Functional" }, enabled = false)
882 // TODO review / update this test after redesign of alignAs method
883 public void testAlignAs_dnaAsProtein_withIntrons() throws IOException
886 * Load alignments and add mappings for cDNA to protein
888 String dna1 = "A-Aa-gG-GCC-cT-TT";
889 String dna2 = "c--CCGgg-TT--T-AA-A";
890 AlignmentI al1 = loadAlignment(">Dna1/6-17\n" + dna1
891 + "\n>Dna2/20-31\n" + dna2 + "\n", FileFormat.Fasta);
892 AlignmentI al2 = loadAlignment(
893 ">Pep1/7-9\n-P--YK\n>Pep2/11-13\nG-T--F\n", FileFormat.Fasta);
894 AlignedCodonFrame acf = new AlignedCodonFrame();
895 // Seq1 has intron at dna positions 3,4,9 so splice is AAG GCC TTT
896 // Seq2 has intron at dna positions 1,5,6 so splice is CCG TTT AAA
897 MapList ml1 = new MapList(new int[] { 6, 7, 10, 13, 15, 17 }, new int[]
899 acf.addMap(al1.getSequenceAt(0), al2.getSequenceAt(0), ml1);
900 MapList ml2 = new MapList(new int[] { 21, 23, 26, 31 }, new int[] { 11,
902 acf.addMap(al1.getSequenceAt(1), al2.getSequenceAt(1), ml2);
903 al2.addCodonFrame(acf);
906 * Align ignoring gaps in dna introns and exons
908 ((Alignment) al1).alignAs(al2, false, false);
909 assertEquals("---AAagG------GCCcTTT", al1.getSequenceAt(0)
910 .getSequenceAsString());
911 // note 1 gap in protein corresponds to 'gg-' in DNA (3 positions)
912 assertEquals("cCCGgg-TTT------AAA", al1.getSequenceAt(1)
913 .getSequenceAsString());
916 * Reset and realign, preserving gaps in dna introns and exons
918 al1.getSequenceAt(0).setSequence(dna1);
919 al1.getSequenceAt(1).setSequence(dna2);
920 ((Alignment) al1).alignAs(al2, true, true);
921 // String dna1 = "A-Aa-gG-GCC-cT-TT";
922 // String dna2 = "c--CCGgg-TT--T-AA-A";
923 // assumption: we include 'the greater of' protein/dna gap lengths, not both
924 assertEquals("---A-Aa-gG------GCC-cT-TT", al1.getSequenceAt(0)
925 .getSequenceAsString());
926 assertEquals("c--CCGgg-TT--T------AA-A", al1.getSequenceAt(1)
927 .getSequenceAsString());
930 @Test(groups = "Functional")
931 public void testCopyConstructor() throws IOException
933 AlignmentI protein = loadAlignment(AA_SEQS_1, FileFormat.Fasta);
934 // create sequence and alignment datasets
935 protein.setDataset(null);
936 AlignedCodonFrame acf = new AlignedCodonFrame();
937 List<AlignedCodonFrame> acfList = Arrays.asList(new AlignedCodonFrame[]
939 protein.getDataset().setCodonFrames(acfList);
940 AlignmentI copy = new Alignment(protein);
943 * copy has different aligned sequences but the same dataset sequences
945 assertFalse(copy.getSequenceAt(0) == protein.getSequenceAt(0));
946 assertFalse(copy.getSequenceAt(1) == protein.getSequenceAt(1));
947 assertSame(copy.getSequenceAt(0).getDatasetSequence(), protein
948 .getSequenceAt(0).getDatasetSequence());
949 assertSame(copy.getSequenceAt(1).getDatasetSequence(), protein
950 .getSequenceAt(1).getDatasetSequence());
952 // TODO should the copy constructor copy the dataset?
953 // or make a new one referring to the same dataset sequences??
954 assertNull(copy.getDataset());
955 // TODO test metadata is copied when AlignmentI is a dataset
957 // assertArrayEquals(copy.getDataset().getSequencesArray(), protein
958 // .getDataset().getSequencesArray());
962 * Test behaviour of createDataset
964 * @throws IOException
966 @Test(groups = "Functional")
967 public void testCreateDatasetAlignment() throws IOException
969 AlignmentI protein = new FormatAdapter().readFile(AA_SEQS_1,
970 DataSourceType.PASTE, FileFormat.Fasta);
972 * create a dataset sequence on first sequence
973 * leave the second without one
975 protein.getSequenceAt(0).createDatasetSequence();
976 assertNotNull(protein.getSequenceAt(0).getDatasetSequence());
977 assertNull(protein.getSequenceAt(1).getDatasetSequence());
980 * add a mapping to the alignment
982 AlignedCodonFrame acf = new AlignedCodonFrame();
983 protein.addCodonFrame(acf);
984 assertNull(protein.getDataset());
985 assertTrue(protein.getCodonFrames().contains(acf));
988 * create the alignment dataset
989 * note this creates sequence datasets where missing
990 * as a side-effect (in this case, on seq2
992 // TODO promote this method to AlignmentI
993 ((Alignment) protein).createDatasetAlignment();
995 AlignmentI ds = protein.getDataset();
997 // side-effect: dataset created on second sequence
998 assertNotNull(protein.getSequenceAt(1).getDatasetSequence());
999 // dataset alignment has references to dataset sequences
1000 assertEquals(ds.getSequenceAt(0), protein.getSequenceAt(0)
1001 .getDatasetSequence());
1002 assertEquals(ds.getSequenceAt(1), protein.getSequenceAt(1)
1003 .getDatasetSequence());
1005 // codon frames should have been moved to the dataset
1006 // getCodonFrames() should delegate to the dataset:
1007 assertTrue(protein.getCodonFrames().contains(acf));
1008 // prove the codon frames are indeed on the dataset:
1009 assertTrue(ds.getCodonFrames().contains(acf));
1013 * tests the addition of *all* sequences referred to by a sequence being added
1016 @Test(groups = "Functional")
1017 public void testCreateDatasetAlignmentWithMappedToSeqs()
1019 // Alignment with two sequences, gapped.
1020 SequenceI sq1 = new Sequence("sq1", "A--SDF");
1021 SequenceI sq2 = new Sequence("sq2", "G--TRQ");
1023 // cross-references to two more sequences.
1024 DBRefEntry dbr = new DBRefEntry("SQ1", "", "sq3");
1025 SequenceI sq3 = new Sequence("sq3", "VWANG");
1026 dbr.setMap(new Mapping(sq3, new MapList(new int[] { 1, 4 }, new int[] {
1030 SequenceI sq4 = new Sequence("sq4", "ERKWI");
1031 DBRefEntry dbr2 = new DBRefEntry("SQ2", "", "sq4");
1032 dbr2.setMap(new Mapping(sq4, new MapList(new int[] { 1, 4 }, new int[] {
1035 // and a 1:1 codonframe mapping between them.
1036 AlignedCodonFrame alc = new AlignedCodonFrame();
1037 alc.addMap(sq1, sq2, new MapList(new int[] { 1, 4 },
1038 new int[] { 1, 4 }, 1, 1));
1040 AlignmentI protein = new Alignment(new SequenceI[] { sq1, sq2 });
1043 * create the alignment dataset
1044 * note this creates sequence datasets where missing
1045 * as a side-effect (in this case, on seq2
1048 // TODO promote this method to AlignmentI
1049 ((Alignment) protein).createDatasetAlignment();
1051 AlignmentI ds = protein.getDataset();
1053 // should be 4 sequences in dataset - two materialised, and two propagated
1055 assertEquals(4, ds.getHeight());
1056 assertTrue(ds.getSequences().contains(sq1.getDatasetSequence()));
1057 assertTrue(ds.getSequences().contains(sq2.getDatasetSequence()));
1058 assertTrue(ds.getSequences().contains(sq3));
1059 assertTrue(ds.getSequences().contains(sq4));
1060 // Should have one codon frame mapping between sq1 and sq2 via dataset
1062 assertEquals(ds.getCodonFrame(sq1.getDatasetSequence()),
1063 ds.getCodonFrame(sq2.getDatasetSequence()));
1066 @Test(groups = "Functional")
1067 public void testAddCodonFrame()
1069 AlignmentI align = new Alignment(new SequenceI[] {});
1070 AlignedCodonFrame acf = new AlignedCodonFrame();
1071 align.addCodonFrame(acf);
1072 assertEquals(1, align.getCodonFrames().size());
1073 assertTrue(align.getCodonFrames().contains(acf));
1074 // can't add the same object twice:
1075 align.addCodonFrame(acf);
1076 assertEquals(1, align.getCodonFrames().size());
1078 // create dataset alignment - mappings move to dataset
1079 ((Alignment) align).createDatasetAlignment();
1080 assertSame(align.getCodonFrames(), align.getDataset().getCodonFrames());
1081 assertEquals(1, align.getCodonFrames().size());
1083 AlignedCodonFrame acf2 = new AlignedCodonFrame();
1084 align.addCodonFrame(acf2);
1085 assertTrue(align.getDataset().getCodonFrames().contains(acf));
1088 @Test(groups = "Functional")
1089 public void testAddSequencePreserveDatasetIntegrity()
1091 Sequence seq = new Sequence("testSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1092 Alignment align = new Alignment(new SequenceI[] { seq });
1093 align.createDatasetAlignment();
1094 AlignmentI ds = align.getDataset();
1095 SequenceI copy = new Sequence(seq);
1096 copy.insertCharAt(3, 5, '-');
1097 align.addSequence(copy);
1098 Assert.assertEquals(align.getDataset().getHeight(), 1,
1099 "Dataset shouldn't have more than one sequence.");
1101 Sequence seq2 = new Sequence("newtestSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1102 align.addSequence(seq2);
1103 Assert.assertEquals(align.getDataset().getHeight(), 2,
1104 "Dataset should now have two sequences.");
1106 assertAlignmentDatasetRefs(align,
1107 "addSequence broke dataset reference integrity");
1110 @Test(groups = "Functional")
1111 public void getVisibleStartAndEndIndexTest()
1113 Sequence seq = new Sequence("testSeq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1114 AlignmentI align = new Alignment(new SequenceI[] { seq });
1115 ArrayList<int[]> hiddenCols = new ArrayList<int[]>();
1117 int[] startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1118 assertEquals(0, startEnd[0]);
1119 assertEquals(25, startEnd[1]);
1121 hiddenCols.add(new int[] { 0, 0 });
1122 startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1123 assertEquals(1, startEnd[0]);
1124 assertEquals(25, startEnd[1]);
1126 hiddenCols.add(new int[] { 6, 9 });
1127 hiddenCols.add(new int[] { 11, 12 });
1128 startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1129 assertEquals(1, startEnd[0]);
1130 assertEquals(25, startEnd[1]);
1132 hiddenCols.add(new int[] { 24, 25 });
1133 startEnd = align.getVisibleStartAndEndIndex(hiddenCols);
1134 System.out.println(startEnd[0] + " : " + startEnd[1]);
1135 assertEquals(1, startEnd[0]);
1136 assertEquals(23, startEnd[1]);
1140 * Tests that dbrefs with mappings to sequence get updated if the sequence
1141 * acquires a dataset sequence
1143 @Test(groups = "Functional")
1144 public void testCreateDataset_updateDbrefMappings()
1146 SequenceI pep = new Sequence("pep", "ASD");
1147 SequenceI dna = new Sequence("dna", "aaaGCCTCGGATggg");
1148 SequenceI cds = new Sequence("cds", "GCCTCGGAT");
1150 // add dbref from dna to peptide
1151 DBRefEntry dbr = new DBRefEntry("UNIPROT", "", "pep");
1152 dbr.setMap(new Mapping(pep, new MapList(new int[] { 4, 15 }, new int[] {
1156 // add dbref from dna to peptide
1157 DBRefEntry dbr2 = new DBRefEntry("UNIPROT", "", "pep");
1158 dbr2.setMap(new Mapping(pep, new MapList(new int[] { 1, 12 }, new int[]
1162 // add dbref from peptide to dna
1163 DBRefEntry dbr3 = new DBRefEntry("EMBL", "", "dna");
1164 dbr3.setMap(new Mapping(dna, new MapList(new int[] { 1, 4 }, new int[] {
1168 // add dbref from peptide to cds
1169 DBRefEntry dbr4 = new DBRefEntry("EMBLCDS", "", "cds");
1170 dbr4.setMap(new Mapping(cds, new MapList(new int[] { 1, 4 }, new int[] {
1174 AlignmentI protein = new Alignment(new SequenceI[] { pep });
1177 * create the alignment dataset
1179 ((Alignment) protein).createDatasetAlignment();
1181 AlignmentI ds = protein.getDataset();
1183 // should be 3 sequences in dataset
1184 assertEquals(3, ds.getHeight());
1185 assertTrue(ds.getSequences().contains(pep.getDatasetSequence()));
1186 assertTrue(ds.getSequences().contains(dna));
1187 assertTrue(ds.getSequences().contains(cds));
1190 * verify peptide.cdsdbref.peptidedbref is now mapped to peptide dataset
1192 DBRefEntry[] dbRefs = pep.getDBRefs();
1193 assertEquals(2, dbRefs.length);
1194 assertSame(dna, dbRefs[0].map.to);
1195 assertSame(cds, dbRefs[1].map.to);
1196 assertEquals(1, dna.getDBRefs().length);
1197 assertSame(pep.getDatasetSequence(), dna.getDBRefs()[0].map.to);
1198 assertEquals(1, cds.getDBRefs().length);
1199 assertSame(pep.getDatasetSequence(), cds.getDBRefs()[0].map.to);
1202 @Test(groups = { "Functional" })
1203 public void testFindGroup()
1205 SequenceI seq1 = new Sequence("seq1", "ABCDEF---GHI");
1206 SequenceI seq2 = new Sequence("seq2", "---JKLMNO---");
1207 AlignmentI a = new Alignment(new SequenceI[] { seq1, seq2 });
1209 assertNull(a.findGroup(null, 0));
1210 assertNull(a.findGroup(seq1, 1));
1211 assertNull(a.findGroup(seq1, -1));
1214 * add a group consisting of just "DEF"
1216 SequenceGroup sg1 = new SequenceGroup();
1217 sg1.addSequence(seq1, false);
1222 assertNull(a.findGroup(seq1, 2)); // position not in group
1223 assertNull(a.findGroup(seq1, 6)); // position not in group
1224 assertNull(a.findGroup(seq2, 5)); // sequence not in group
1225 assertSame(a.findGroup(seq1, 3), sg1); // yes
1226 assertSame(a.findGroup(seq1, 4), sg1);
1227 assertSame(a.findGroup(seq1, 5), sg1);
1230 * add a group consisting of
1234 SequenceGroup sg2 = new SequenceGroup();
1235 sg2.addSequence(seq1, false);
1236 sg2.addSequence(seq2, false);
1241 assertNull(a.findGroup(seq1, 2)); // unchanged
1242 assertSame(a.findGroup(seq1, 3), sg1); // unchanged
1244 * if a residue is in more than one group, method returns
1245 * the first found (in order groups were added)
1247 assertSame(a.findGroup(seq1, 4), sg1);
1248 assertSame(a.findGroup(seq1, 5), sg1);
1251 * seq2 only belongs to the second group
1253 assertSame(a.findGroup(seq2, 4), sg2);
1254 assertSame(a.findGroup(seq2, 5), sg2);
1255 assertSame(a.findGroup(seq2, 6), sg2);
1256 assertSame(a.findGroup(seq2, 7), sg2);
1257 assertNull(a.findGroup(seq2, 3));
1258 assertNull(a.findGroup(seq2, 8));
1261 @Test(groups = { "Functional" })
1262 public void testDeleteSequenceByIndex()
1264 // create random alignment
1265 AlignmentGenerator gen = new AlignmentGenerator(false);
1266 AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1268 // delete sequence 10, alignment reduced by 1
1269 int height = a.getAbsoluteHeight();
1270 a.deleteSequence(10);
1271 assertEquals(a.getAbsoluteHeight(), height - 1);
1273 // try to delete -ve index, nothing happens
1274 a.deleteSequence(-1);
1275 assertEquals(a.getAbsoluteHeight(), height - 1);
1277 // try to delete beyond end of alignment, nothing happens
1278 a.deleteSequence(14);
1279 assertEquals(a.getAbsoluteHeight(), height - 1);
1282 @Test(groups = { "Functional" })
1283 public void testDeleteSequenceBySeq()
1285 // create random alignment
1286 AlignmentGenerator gen = new AlignmentGenerator(false);
1287 AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1289 // delete sequence 10, alignment reduced by 1
1290 int height = a.getAbsoluteHeight();
1291 SequenceI seq = a.getSequenceAt(10);
1292 a.deleteSequence(seq);
1293 assertEquals(a.getAbsoluteHeight(), height - 1);
1295 // try to delete non-existent sequence, nothing happens
1296 seq = new Sequence("cds", "GCCTCGGAT");
1297 assertEquals(a.getAbsoluteHeight(), height - 1);
1300 @Test(groups = { "Functional" })
1301 public void testDeleteHiddenSequence()
1303 // create random alignment
1304 AlignmentGenerator gen = new AlignmentGenerator(false);
1305 AlignmentI a = gen.generate(20, 15, 123, 5, 5);
1307 // delete a sequence which is hidden, check it is NOT removed from hidden
1309 int height = a.getAbsoluteHeight();
1310 SequenceI seq = a.getSequenceAt(2);
1311 a.getHiddenSequences().hideSequence(seq);
1312 assertEquals(a.getHiddenSequences().getSize(), 1);
1313 a.deleteSequence(2);
1314 assertEquals(a.getAbsoluteHeight(), height - 1);
1315 assertEquals(a.getHiddenSequences().getSize(), 1);
1317 // delete a sequence which is not hidden, check hiddenSequences are not
1319 a.deleteSequence(10);
1320 assertEquals(a.getAbsoluteHeight(), height - 2);
1321 assertEquals(a.getHiddenSequences().getSize(), 1);
1325 groups = "Functional",
1326 expectedExceptions = { IllegalArgumentException.class })
1327 public void testSetDataset_selfReference()
1329 SequenceI seq = new Sequence("a", "a");
1330 AlignmentI alignment = new Alignment(new SequenceI[] { seq });
1331 alignment.setDataset(alignment);