Merge branch 'documentation/JAL-2751patch2102b2' into releases/Release_2_10_2b1_Branch
[jalview.git] / test / jalview / datamodel / SequenceTest.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 import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
30
31 import jalview.datamodel.PDBEntry.Type;
32 import jalview.gui.JvOptionPane;
33 import jalview.util.MapList;
34
35 import java.io.File;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.BitSet;
39 import java.util.List;
40 import java.util.Vector;
41
42 import org.testng.Assert;
43 import org.testng.annotations.BeforeClass;
44 import org.testng.annotations.BeforeMethod;
45 import org.testng.annotations.Test;
46
47 public class SequenceTest
48 {
49
50   @BeforeClass(alwaysRun = true)
51   public void setUpJvOptionPane()
52   {
53     JvOptionPane.setInteractiveMode(false);
54     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
55   }
56
57   Sequence seq;
58
59   @BeforeMethod(alwaysRun = true)
60   public void setUp()
61   {
62     seq = new Sequence("FER1", "AKPNGVL");
63   }
64
65   @Test(groups = { "Functional" })
66   public void testInsertGapsAndGapmaps()
67   {
68     SequenceI aseq = seq.deriveSequence();
69     aseq.insertCharAt(2, 3, '-');
70     aseq.insertCharAt(6, 3, '-');
71     assertEquals("Gap insertions not correct", "AK---P---NGVL",
72             aseq.getSequenceAsString());
73     List<int[]> gapInt = aseq.getInsertions();
74     assertEquals("Gap interval 1 start wrong", 2, gapInt.get(0)[0]);
75     assertEquals("Gap interval 1 end wrong", 4, gapInt.get(0)[1]);
76     assertEquals("Gap interval 2 start wrong", 6, gapInt.get(1)[0]);
77     assertEquals("Gap interval 2 end wrong", 8, gapInt.get(1)[1]);
78
79     BitSet gapfield = aseq.getInsertionsAsBits();
80     BitSet expectedgaps = new BitSet();
81     expectedgaps.set(2, 5);
82     expectedgaps.set(6, 9);
83
84     assertEquals(6, expectedgaps.cardinality());
85
86     assertEquals("getInsertionsAsBits didn't mark expected number of gaps",
87             6, gapfield.cardinality());
88
89     assertEquals("getInsertionsAsBits not correct.", expectedgaps, gapfield);
90   }
91
92   @Test(groups = ("Functional"))
93   public void testIsProtein()
94   {
95     // test Protein
96     assertTrue(new Sequence("prot", "ASDFASDFASDF").isProtein());
97     // test DNA
98     assertFalse(new Sequence("prot", "ACGTACGTACGT").isProtein());
99     // test RNA
100     SequenceI sq = new Sequence("prot", "ACGUACGUACGU");
101     assertFalse(sq.isProtein());
102     // change sequence, should trigger an update of cached result
103     sq.setSequence("ASDFASDFADSF");
104     assertTrue(sq.isProtein());
105     /*
106      * in situ change of sequence doesn't change hashcode :-O
107      * (sequence should not expose internal implementation)
108      */
109     for (int i = 0; i < sq.getSequence().length; i++)
110     {
111       sq.getSequence()[i] = "acgtu".charAt(i % 5);
112     }
113     assertTrue(sq.isProtein()); // but it isn't
114   }
115
116   @Test(groups = { "Functional" })
117   public void testGetAnnotation()
118   {
119     // initial state returns null not an empty array
120     assertNull(seq.getAnnotation());
121     AlignmentAnnotation ann = addAnnotation("label1", "desc1", "calcId1",
122             1f);
123     AlignmentAnnotation[] anns = seq.getAnnotation();
124     assertEquals(1, anns.length);
125     assertSame(ann, anns[0]);
126
127     // removing all annotations reverts array to null
128     seq.removeAlignmentAnnotation(ann);
129     assertNull(seq.getAnnotation());
130   }
131
132   @Test(groups = { "Functional" })
133   public void testGetAnnotation_forLabel()
134   {
135     AlignmentAnnotation ann1 = addAnnotation("label1", "desc1", "calcId1",
136             1f);
137     addAnnotation("label2", "desc2", "calcId2", 1f);
138     AlignmentAnnotation ann3 = addAnnotation("label1", "desc3", "calcId3",
139             1f);
140     AlignmentAnnotation[] anns = seq.getAnnotation("label1");
141     assertEquals(2, anns.length);
142     assertSame(ann1, anns[0]);
143     assertSame(ann3, anns[1]);
144   }
145
146   private AlignmentAnnotation addAnnotation(String label,
147           String description, String calcId, float value)
148   {
149     final AlignmentAnnotation annotation = new AlignmentAnnotation(label,
150             description, value);
151     annotation.setCalcId(calcId);
152     seq.addAlignmentAnnotation(annotation);
153     return annotation;
154   }
155
156   @Test(groups = { "Functional" })
157   public void testGetAlignmentAnnotations_forCalcIdAndLabel()
158   {
159     addAnnotation("label1", "desc1", "calcId1", 1f);
160     AlignmentAnnotation ann2 = addAnnotation("label2", "desc2", "calcId2",
161             1f);
162     addAnnotation("label2", "desc3", "calcId3", 1f);
163     AlignmentAnnotation ann4 = addAnnotation("label2", "desc3", "calcId2",
164             1f);
165     addAnnotation("label5", "desc3", null, 1f);
166     addAnnotation(null, "desc3", "calcId3", 1f);
167
168     List<AlignmentAnnotation> anns = seq.getAlignmentAnnotations("calcId2",
169             "label2");
170     assertEquals(2, anns.size());
171     assertSame(ann2, anns.get(0));
172     assertSame(ann4, anns.get(1));
173
174     assertTrue(seq.getAlignmentAnnotations("calcId2", "label3").isEmpty());
175     assertTrue(seq.getAlignmentAnnotations("calcId3", "label5").isEmpty());
176     assertTrue(seq.getAlignmentAnnotations("calcId2", null).isEmpty());
177     assertTrue(seq.getAlignmentAnnotations(null, "label3").isEmpty());
178     assertTrue(seq.getAlignmentAnnotations(null, null).isEmpty());
179   }
180
181   /**
182    * Tests for addAlignmentAnnotation. Note this method has the side-effect of
183    * setting the sequenceRef on the annotation. Adding the same annotation twice
184    * should be ignored.
185    */
186   @Test(groups = { "Functional" })
187   public void testAddAlignmentAnnotation()
188   {
189     assertNull(seq.getAnnotation());
190     final AlignmentAnnotation annotation = new AlignmentAnnotation("a",
191             "b", 2d);
192     assertNull(annotation.sequenceRef);
193     seq.addAlignmentAnnotation(annotation);
194     assertSame(seq, annotation.sequenceRef);
195     AlignmentAnnotation[] anns = seq.getAnnotation();
196     assertEquals(1, anns.length);
197     assertSame(annotation, anns[0]);
198
199     // re-adding does nothing
200     seq.addAlignmentAnnotation(annotation);
201     anns = seq.getAnnotation();
202     assertEquals(1, anns.length);
203     assertSame(annotation, anns[0]);
204
205     // an identical but different annotation can be added
206     final AlignmentAnnotation annotation2 = new AlignmentAnnotation("a",
207             "b", 2d);
208     seq.addAlignmentAnnotation(annotation2);
209     anns = seq.getAnnotation();
210     assertEquals(2, anns.length);
211     assertSame(annotation, anns[0]);
212     assertSame(annotation2, anns[1]);
213   }
214
215   @Test(groups = { "Functional" })
216   public void testGetStartGetEnd()
217   {
218     SequenceI sq = new Sequence("test", "ABCDEF");
219     assertEquals(1, sq.getStart());
220     assertEquals(6, sq.getEnd());
221
222     sq = new Sequence("test", "--AB-C-DEF--");
223     assertEquals(1, sq.getStart());
224     assertEquals(6, sq.getEnd());
225
226     sq = new Sequence("test", "----");
227     assertEquals(1, sq.getStart());
228     assertEquals(0, sq.getEnd()); // ??
229   }
230
231   /**
232    * Tests for the method that returns an alignment column position (base 1) for
233    * a given sequence position (base 1).
234    */
235   @Test(groups = { "Functional" })
236   public void testFindIndex()
237   {
238     SequenceI sq = new Sequence("test", "ABCDEF");
239     assertEquals(0, sq.findIndex(0));
240     assertEquals(1, sq.findIndex(1));
241     assertEquals(5, sq.findIndex(5));
242     assertEquals(6, sq.findIndex(6));
243     assertEquals(6, sq.findIndex(9));
244
245     sq = new Sequence("test", "-A--B-C-D-E-F--");
246     assertEquals(2, sq.findIndex(1));
247     assertEquals(5, sq.findIndex(2));
248     assertEquals(7, sq.findIndex(3));
249
250     // before start returns 0
251     assertEquals(0, sq.findIndex(0));
252     assertEquals(0, sq.findIndex(-1));
253
254     // beyond end returns last residue column
255     assertEquals(13, sq.findIndex(99));
256
257   }
258
259   /**
260    * Tests for the method that returns a dataset sequence position (base 1) for
261    * an aligned column position (base 0).
262    */
263   @Test(groups = { "Functional" })
264   public void testFindPosition()
265   {
266     SequenceI sq = new Sequence("test", "ABCDEF");
267     assertEquals(1, sq.findPosition(0));
268     assertEquals(6, sq.findPosition(5));
269     // assertEquals(-1, seq.findPosition(6)); // fails
270
271     sq = new Sequence("test", "AB-C-D--");
272     assertEquals(1, sq.findPosition(0));
273     assertEquals(2, sq.findPosition(1));
274     // gap position 'finds' residue to the right (not the left as per javadoc)
275     assertEquals(3, sq.findPosition(2));
276     assertEquals(3, sq.findPosition(3));
277     assertEquals(4, sq.findPosition(4));
278     assertEquals(4, sq.findPosition(5));
279     // returns 1 more than sequence length if off the end ?!?
280     assertEquals(5, sq.findPosition(6));
281     assertEquals(5, sq.findPosition(7));
282
283     sq = new Sequence("test", "--AB-C-DEF--");
284     assertEquals(1, sq.findPosition(0));
285     assertEquals(1, sq.findPosition(1));
286     assertEquals(1, sq.findPosition(2));
287     assertEquals(2, sq.findPosition(3));
288     assertEquals(3, sq.findPosition(4));
289     assertEquals(3, sq.findPosition(5));
290     assertEquals(4, sq.findPosition(6));
291     assertEquals(4, sq.findPosition(7));
292     assertEquals(5, sq.findPosition(8));
293     assertEquals(6, sq.findPosition(9));
294     assertEquals(7, sq.findPosition(10));
295     assertEquals(7, sq.findPosition(11));
296   }
297
298   @Test(groups = { "Functional" })
299   public void testDeleteChars()
300   {
301     SequenceI sq = new Sequence("test", "ABCDEF");
302     assertEquals(1, sq.getStart());
303     assertEquals(6, sq.getEnd());
304     sq.deleteChars(2, 3);
305     assertEquals("ABDEF", sq.getSequenceAsString());
306     assertEquals(1, sq.getStart());
307     assertEquals(5, sq.getEnd());
308
309     sq = new Sequence("test", "ABCDEF");
310     sq.deleteChars(0, 2);
311     assertEquals("CDEF", sq.getSequenceAsString());
312     assertEquals(3, sq.getStart());
313     assertEquals(6, sq.getEnd());
314   }
315
316   @Test(groups = { "Functional" })
317   public void testInsertCharAt()
318   {
319     // non-static methods:
320     SequenceI sq = new Sequence("test", "ABCDEF");
321     sq.insertCharAt(0, 'z');
322     assertEquals("zABCDEF", sq.getSequenceAsString());
323     sq.insertCharAt(2, 2, 'x');
324     assertEquals("zAxxBCDEF", sq.getSequenceAsString());
325
326     // for static method see StringUtilsTest
327   }
328
329   /**
330    * Test the method that returns an array of aligned sequence positions where
331    * the array index is the data sequence position (both base 0).
332    */
333   @Test(groups = { "Functional" })
334   public void testGapMap()
335   {
336     SequenceI sq = new Sequence("test", "-A--B-CD-E--F-");
337     sq.createDatasetSequence();
338     assertEquals("[1, 4, 6, 7, 9, 12]", Arrays.toString(sq.gapMap()));
339   }
340
341   /**
342    * Test the method that gets sequence features, either from the sequence or
343    * its dataset.
344    */
345   @Test(groups = { "Functional" })
346   public void testGetSequenceFeatures()
347   {
348     SequenceI sq = new Sequence("test", "GATCAT");
349     sq.createDatasetSequence();
350
351     assertNull(sq.getSequenceFeatures());
352
353     /*
354      * SequenceFeature on sequence
355      */
356     SequenceFeature sf = new SequenceFeature();
357     sq.addSequenceFeature(sf);
358     SequenceFeature[] sfs = sq.getSequenceFeatures();
359     assertEquals(1, sfs.length);
360     assertSame(sf, sfs[0]);
361
362     /*
363      * SequenceFeature on sequence and dataset sequence; returns that on
364      * sequence
365      * 
366      * Note JAL-2046: spurious: we have no use case for this at the moment.
367      * This test also buggy - as sf2.equals(sf), no new feature is added
368      */
369     SequenceFeature sf2 = new SequenceFeature();
370     sq.getDatasetSequence().addSequenceFeature(sf2);
371     sfs = sq.getSequenceFeatures();
372     assertEquals(1, sfs.length);
373     assertSame(sf, sfs[0]);
374
375     /*
376      * SequenceFeature on dataset sequence only
377      * Note JAL-2046: spurious: we have no use case for setting a non-dataset sequence's feature array to null at the moment.
378      */
379     sq.setSequenceFeatures(null);
380     assertNull(sq.getDatasetSequence().getSequenceFeatures());
381
382     /*
383      * Corrupt case - no SequenceFeature, dataset's dataset is the original
384      * sequence. Test shows no infinite loop results.
385      */
386     sq.getDatasetSequence().setSequenceFeatures(null);
387     /**
388      * is there a usecase for this ? setDatasetSequence should throw an error if
389      * this actually occurs.
390      */
391     try
392     {
393       sq.getDatasetSequence().setDatasetSequence(sq); // loop!
394       Assert.fail("Expected Error to be raised when calling setDatasetSequence with self reference");
395     } catch (IllegalArgumentException e)
396     {
397       // TODO Jalview error/exception class for raising implementation errors
398       assertTrue(e.getMessage().toLowerCase()
399               .contains("implementation error"));
400     }
401     assertNull(sq.getSequenceFeatures());
402   }
403
404   /**
405    * Test the method that returns an array, indexed by sequence position, whose
406    * entries are the residue positions at the sequence position (or to the right
407    * if a gap)
408    */
409   @Test(groups = { "Functional" })
410   public void testFindPositionMap()
411   {
412     /*
413      * Note: Javadoc for findPosition says it returns the residue position to
414      * the left of a gapped position; in fact it returns the position to the
415      * right. Also it returns a non-existent residue position for a gap beyond
416      * the sequence.
417      */
418     Sequence sq = new Sequence("TestSeq", "AB.C-D E.");
419     int[] map = sq.findPositionMap();
420     assertEquals(Arrays.toString(new int[] { 1, 2, 3, 3, 4, 4, 5, 5, 6 }),
421             Arrays.toString(map));
422   }
423
424   /**
425    * Test for getSubsequence
426    */
427   @Test(groups = { "Functional" })
428   public void testGetSubsequence()
429   {
430     SequenceI sq = new Sequence("TestSeq", "ABCDEFG");
431     sq.createDatasetSequence();
432
433     // positions are base 0, end position is exclusive
434     SequenceI subseq = sq.getSubSequence(2, 4);
435
436     assertEquals("CD", subseq.getSequenceAsString());
437     // start/end are base 1 positions
438     assertEquals(3, subseq.getStart());
439     assertEquals(4, subseq.getEnd());
440     // subsequence shares the full dataset sequence
441     assertSame(sq.getDatasetSequence(), subseq.getDatasetSequence());
442   }
443
444   /**
445    * test createDatasetSequence behaves to doc
446    */
447   @Test(groups = { "Functional" })
448   public void testCreateDatasetSequence()
449   {
450     SequenceI sq = new Sequence("my", "ASDASD");
451     assertNull(sq.getDatasetSequence());
452     SequenceI rds = sq.createDatasetSequence();
453     assertNotNull(rds);
454     assertNull(rds.getDatasetSequence());
455     assertEquals(sq.getDatasetSequence(), rds);
456   }
457
458   /**
459    * Test for deriveSequence applied to a sequence with a dataset
460    */
461   @Test(groups = { "Functional" })
462   public void testDeriveSequence_existingDataset()
463   {
464     Sequence sq = new Sequence("Seq1", "CD");
465     sq.setDatasetSequence(new Sequence("Seq1", "ABCDEF"));
466     sq.getDatasetSequence().addSequenceFeature(
467             new SequenceFeature("", "", 1, 2, 0f, null));
468     sq.setStart(3);
469     sq.setEnd(4);
470
471     sq.setDescription("Test sequence description..");
472     sq.setVamsasId("TestVamsasId");
473     sq.addDBRef(new DBRefEntry("PDB", "version0", "1TST"));
474
475     sq.addDBRef(new DBRefEntry("PDB", "version1", "1PDB"));
476     sq.addDBRef(new DBRefEntry("PDB", "version2", "2PDB"));
477     sq.addDBRef(new DBRefEntry("PDB", "version3", "3PDB"));
478     sq.addDBRef(new DBRefEntry("PDB", "version4", "4PDB"));
479
480     sq.addPDBId(new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1"));
481     sq.addPDBId(new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1"));
482     sq.addPDBId(new PDBEntry("2PDB", "A", Type.MMCIF, "filePath/test2"));
483     sq.addPDBId(new PDBEntry("2PDB", "B", Type.MMCIF, "filePath/test2"));
484
485     // these are the same as ones already added
486     DBRefEntry pdb1pdb = new DBRefEntry("PDB", "version1", "1PDB");
487     DBRefEntry pdb2pdb = new DBRefEntry("PDB", "version2", "2PDB");
488
489     List<DBRefEntry> primRefs = Arrays.asList(new DBRefEntry[] { pdb1pdb,
490         pdb2pdb });
491
492     sq.getDatasetSequence().addDBRef(pdb1pdb); // should do nothing
493     sq.getDatasetSequence().addDBRef(pdb2pdb); // should do nothing
494     sq.getDatasetSequence().addDBRef(
495             new DBRefEntry("PDB", "version3", "3PDB")); // should do nothing
496     sq.getDatasetSequence().addDBRef(
497             new DBRefEntry("PDB", "version4", "4PDB")); // should do nothing
498
499     PDBEntry pdbe1a = new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1");
500     PDBEntry pdbe1b = new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1");
501     PDBEntry pdbe2a = new PDBEntry("2PDB", "A", Type.MMCIF,
502             "filePath/test2");
503     PDBEntry pdbe2b = new PDBEntry("2PDB", "B", Type.MMCIF,
504             "filePath/test2");
505     sq.getDatasetSequence().addPDBId(pdbe1a);
506     sq.getDatasetSequence().addPDBId(pdbe1b);
507     sq.getDatasetSequence().addPDBId(pdbe2a);
508     sq.getDatasetSequence().addPDBId(pdbe2b);
509
510     /*
511      * test we added pdb entries to the dataset sequence
512      */
513     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries(), Arrays
514             .asList(new PDBEntry[] { pdbe1a, pdbe1b, pdbe2a, pdbe2b }),
515             "PDB Entries were not found on dataset sequence.");
516
517     /*
518      * we should recover a pdb entry that is on the dataset sequence via PDBEntry
519      */
520     Assert.assertEquals(pdbe1a,
521             sq.getDatasetSequence().getPDBEntry("1PDB"),
522             "PDB Entry '1PDB' not found on dataset sequence via getPDBEntry.");
523     ArrayList<Annotation> annotsList = new ArrayList<Annotation>();
524     System.out.println(">>>>>> " + sq.getSequenceAsString().length());
525     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
526     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
527     Annotation[] annots = annotsList.toArray(new Annotation[0]);
528     sq.addAlignmentAnnotation(new AlignmentAnnotation("Test annot",
529             "Test annot description", annots));
530     sq.getDatasetSequence().addAlignmentAnnotation(
531             new AlignmentAnnotation("Test annot", "Test annot description",
532                     annots));
533     Assert.assertEquals(sq.getDescription(), "Test sequence description..");
534     Assert.assertEquals(sq.getDBRefs().length, 5); // DBRefs are on dataset
535                                                    // sequence
536     Assert.assertEquals(sq.getAllPDBEntries().size(), 4);
537     Assert.assertNotNull(sq.getAnnotation());
538     Assert.assertEquals(sq.getAnnotation()[0].annotations.length, 2);
539     Assert.assertEquals(sq.getDatasetSequence().getDBRefs().length, 5); // same
540                                                                         // as
541                                                                         // sq.getDBRefs()
542     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries().size(),
543             4);
544     Assert.assertNotNull(sq.getDatasetSequence().getAnnotation());
545
546     Sequence derived = (Sequence) sq.deriveSequence();
547
548     Assert.assertEquals(derived.getDescription(),
549             "Test sequence description..");
550     Assert.assertEquals(derived.getDBRefs().length, 5); // come from dataset
551     Assert.assertEquals(derived.getAllPDBEntries().size(), 4);
552     Assert.assertNotNull(derived.getAnnotation());
553     Assert.assertEquals(derived.getAnnotation()[0].annotations.length, 2);
554     Assert.assertEquals(derived.getDatasetSequence().getDBRefs().length, 5);
555     Assert.assertEquals(derived.getDatasetSequence().getAllPDBEntries()
556             .size(), 4);
557     Assert.assertNotNull(derived.getDatasetSequence().getAnnotation());
558
559     assertEquals("CD", derived.getSequenceAsString());
560     assertSame(sq.getDatasetSequence(), derived.getDatasetSequence());
561
562     assertNull(sq.sequenceFeatures);
563     assertNull(derived.sequenceFeatures);
564     // derived sequence should access dataset sequence features
565     assertNotNull(sq.getSequenceFeatures());
566     assertArrayEquals(sq.getSequenceFeatures(),
567             derived.getSequenceFeatures());
568
569     /*
570      *  verify we have primary db refs *just* for PDB IDs with associated
571      *  PDBEntry objects
572      */
573
574     assertEquals(primRefs, sq.getPrimaryDBRefs());
575     assertEquals(primRefs, sq.getDatasetSequence().getPrimaryDBRefs());
576
577     assertEquals(sq.getPrimaryDBRefs(), derived.getPrimaryDBRefs());
578
579   }
580
581   /**
582    * Test for deriveSequence applied to an ungapped sequence with no dataset
583    */
584   @Test(groups = { "Functional" })
585   public void testDeriveSequence_noDatasetUngapped()
586   {
587     SequenceI sq = new Sequence("Seq1", "ABCDEF");
588     assertEquals(1, sq.getStart());
589     assertEquals(6, sq.getEnd());
590     SequenceI derived = sq.deriveSequence();
591     assertEquals("ABCDEF", derived.getSequenceAsString());
592     assertEquals("ABCDEF", derived.getDatasetSequence()
593             .getSequenceAsString());
594   }
595
596   /**
597    * Test for deriveSequence applied to a gapped sequence with no dataset
598    */
599   @Test(groups = { "Functional" })
600   public void testDeriveSequence_noDatasetGapped()
601   {
602     SequenceI sq = new Sequence("Seq1", "AB-C.D EF");
603     assertEquals(1, sq.getStart());
604     assertEquals(6, sq.getEnd());
605     assertNull(sq.getDatasetSequence());
606     SequenceI derived = sq.deriveSequence();
607     assertEquals("AB-C.D EF", derived.getSequenceAsString());
608     assertEquals("ABCDEF", derived.getDatasetSequence()
609             .getSequenceAsString());
610   }
611
612   @Test(groups = { "Functional" })
613   public void testCopyConstructor_noDataset()
614   {
615     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
616     seq1.setDescription("description");
617     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
618             1.3d));
619     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
620             12.4f, "group"));
621     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
622     seq1.addDBRef(new DBRefEntry("EMBL", "1.2", "AZ12345"));
623
624     SequenceI copy = new Sequence(seq1);
625
626     assertNull(copy.getDatasetSequence());
627
628     verifyCopiedSequence(seq1, copy);
629
630     // copy has a copy of the DBRefEntry
631     // this is murky - DBrefs are only copied for dataset sequences
632     // where the test for 'dataset sequence' is 'dataset is null'
633     // but that doesn't distinguish it from an aligned sequence
634     // which has not yet generated a dataset sequence
635     // NB getDBRef looks inside dataset sequence if not null
636     DBRefEntry[] dbrefs = copy.getDBRefs();
637     assertEquals(1, dbrefs.length);
638     assertFalse(dbrefs[0] == seq1.getDBRefs()[0]);
639     assertTrue(dbrefs[0].equals(seq1.getDBRefs()[0]));
640   }
641
642   @Test(groups = { "Functional" })
643   public void testCopyConstructor_withDataset()
644   {
645     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
646     seq1.createDatasetSequence();
647     seq1.setDescription("description");
648     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
649             1.3d));
650     // JAL-2046 - what is the contract for using a derived sequence's
651     // addSequenceFeature ?
652     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
653             12.4f, "group"));
654     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
655     // here we add DBRef to the dataset sequence:
656     seq1.getDatasetSequence().addDBRef(
657             new DBRefEntry("EMBL", "1.2", "AZ12345"));
658
659     SequenceI copy = new Sequence(seq1);
660
661     assertNotNull(copy.getDatasetSequence());
662     assertSame(copy.getDatasetSequence(), seq1.getDatasetSequence());
663
664     verifyCopiedSequence(seq1, copy);
665
666     // getDBRef looks inside dataset sequence and this is shared,
667     // so holds the same dbref objects
668     DBRefEntry[] dbrefs = copy.getDBRefs();
669     assertEquals(1, dbrefs.length);
670     assertSame(dbrefs[0], seq1.getDBRefs()[0]);
671   }
672
673   /**
674    * Helper to make assertions about a copied sequence
675    * 
676    * @param seq1
677    * @param copy
678    */
679   protected void verifyCopiedSequence(SequenceI seq1, SequenceI copy)
680   {
681     // verify basic properties:
682     assertEquals(copy.getName(), seq1.getName());
683     assertEquals(copy.getDescription(), seq1.getDescription());
684     assertEquals(copy.getStart(), seq1.getStart());
685     assertEquals(copy.getEnd(), seq1.getEnd());
686     assertEquals(copy.getSequenceAsString(), seq1.getSequenceAsString());
687
688     // copy has a copy of the annotation:
689     AlignmentAnnotation[] anns = copy.getAnnotation();
690     assertEquals(1, anns.length);
691     assertFalse(anns[0] == seq1.getAnnotation()[0]);
692     assertEquals(anns[0].label, seq1.getAnnotation()[0].label);
693     assertEquals(anns[0].description, seq1.getAnnotation()[0].description);
694     assertEquals(anns[0].score, seq1.getAnnotation()[0].score);
695
696     // copy has a copy of the sequence feature:
697     SequenceFeature[] sfs = copy.getSequenceFeatures();
698     assertEquals(1, sfs.length);
699     if (seq1.getDatasetSequence() != null
700             && copy.getDatasetSequence() == seq1.getDatasetSequence())
701     {
702       assertTrue(sfs[0] == seq1.getSequenceFeatures()[0]);
703     }
704     else
705     {
706       assertFalse(sfs[0] == seq1.getSequenceFeatures()[0]);
707     }
708     assertTrue(sfs[0].equals(seq1.getSequenceFeatures()[0]));
709
710     // copy has a copy of the PDB entry
711     Vector<PDBEntry> pdbs = copy.getAllPDBEntries();
712     assertEquals(1, pdbs.size());
713     assertFalse(pdbs.get(0) == seq1.getAllPDBEntries().get(0));
714     assertTrue(pdbs.get(0).equals(seq1.getAllPDBEntries().get(0)));
715   }
716
717   @Test(groups = "Functional")
718   public void testGetCharAt()
719   {
720     SequenceI sq = new Sequence("", "abcde");
721     assertEquals('a', sq.getCharAt(0));
722     assertEquals('e', sq.getCharAt(4));
723     assertEquals(' ', sq.getCharAt(5));
724     assertEquals(' ', sq.getCharAt(-1));
725   }
726
727   /**
728    * Tests for adding (or updating) dbrefs
729    * 
730    * @see DBRefEntry#updateFrom(DBRefEntry)
731    */
732   @Test(groups = { "Functional" })
733   public void testAddDBRef()
734   {
735     SequenceI sq = new Sequence("", "abcde");
736     assertNull(sq.getDBRefs());
737     DBRefEntry dbref = new DBRefEntry("Uniprot", "1", "P00340");
738     sq.addDBRef(dbref);
739     assertEquals(1, sq.getDBRefs().length);
740     assertSame(dbref, sq.getDBRefs()[0]);
741
742     /*
743      * change of version - new entry
744      */
745     DBRefEntry dbref2 = new DBRefEntry("Uniprot", "2", "P00340");
746     sq.addDBRef(dbref2);
747     assertEquals(2, sq.getDBRefs().length);
748     assertSame(dbref, sq.getDBRefs()[0]);
749     assertSame(dbref2, sq.getDBRefs()[1]);
750
751     /*
752      * matches existing entry - not added
753      */
754     sq.addDBRef(new DBRefEntry("UNIPROT", "1", "p00340"));
755     assertEquals(2, sq.getDBRefs().length);
756
757     /*
758      * different source = new entry
759      */
760     DBRefEntry dbref3 = new DBRefEntry("UniRef", "1", "p00340");
761     sq.addDBRef(dbref3);
762     assertEquals(3, sq.getDBRefs().length);
763     assertSame(dbref3, sq.getDBRefs()[2]);
764
765     /*
766      * different ref = new entry
767      */
768     DBRefEntry dbref4 = new DBRefEntry("UniRef", "1", "p00341");
769     sq.addDBRef(dbref4);
770     assertEquals(4, sq.getDBRefs().length);
771     assertSame(dbref4, sq.getDBRefs()[3]);
772
773     /*
774      * matching ref with a mapping - map updated
775      */
776     DBRefEntry dbref5 = new DBRefEntry("UniRef", "1", "p00341");
777     Mapping map = new Mapping(new MapList(new int[] { 1, 3 }, new int[] {
778         1, 1 }, 3, 1));
779     dbref5.setMap(map);
780     sq.addDBRef(dbref5);
781     assertEquals(4, sq.getDBRefs().length);
782     assertSame(dbref4, sq.getDBRefs()[3]);
783     assertSame(map, dbref4.getMap());
784
785     /*
786      * 'real' version replaces "0" version
787      */
788     dbref2.setVersion("0");
789     DBRefEntry dbref6 = new DBRefEntry(dbref2.getSource(), "3",
790             dbref2.getAccessionId());
791     sq.addDBRef(dbref6);
792     assertEquals(4, sq.getDBRefs().length);
793     assertSame(dbref2, sq.getDBRefs()[1]);
794     assertEquals("3", dbref2.getVersion());
795
796     /*
797      * 'real' version replaces "source:0" version
798      */
799     dbref3.setVersion("Uniprot:0");
800     DBRefEntry dbref7 = new DBRefEntry(dbref3.getSource(), "3",
801             dbref3.getAccessionId());
802     sq.addDBRef(dbref7);
803     assertEquals(4, sq.getDBRefs().length);
804     assertSame(dbref3, sq.getDBRefs()[2]);
805     assertEquals("3", dbref2.getVersion());
806   }
807
808   @Test(groups = { "Functional" })
809   public void testGetPrimaryDBRefs_peptide()
810   {
811     SequenceI sq = new Sequence("aseq", "ASDFKYLMQPRST", 10, 22);
812
813     // no dbrefs
814     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
815     assertTrue(primaryDBRefs.isEmpty());
816
817     // empty dbrefs
818     sq.setDBRefs(new DBRefEntry[] {});
819     primaryDBRefs = sq.getPrimaryDBRefs();
820     assertTrue(primaryDBRefs.isEmpty());
821
822     // primary - uniprot
823     DBRefEntry upentry1 = new DBRefEntry("UNIPROT", "0", "Q04760");
824     sq.addDBRef(upentry1);
825
826     // primary - uniprot with congruent map
827     DBRefEntry upentry2 = new DBRefEntry("UNIPROT", "0", "Q04762");
828     upentry2.setMap(new Mapping(null, new MapList(new int[] { 10, 22 },
829             new int[] { 10, 22 }, 1, 1)));
830     sq.addDBRef(upentry2);
831
832     // primary - uniprot with map of enclosing sequence
833     DBRefEntry upentry3 = new DBRefEntry("UNIPROT", "0", "Q04763");
834     upentry3.setMap(new Mapping(null, new MapList(new int[] { 8, 24 },
835             new int[] { 8, 24 }, 1, 1)));
836     sq.addDBRef(upentry3);
837
838     // not primary - uniprot with map of sub-sequence (5')
839     DBRefEntry upentry4 = new DBRefEntry("UNIPROT", "0", "Q04764");
840     upentry4.setMap(new Mapping(null, new MapList(new int[] { 10, 18 },
841             new int[] { 10, 18 }, 1, 1)));
842     sq.addDBRef(upentry4);
843
844     // not primary - uniprot with map that overlaps 3'
845     DBRefEntry upentry5 = new DBRefEntry("UNIPROT", "0", "Q04765");
846     upentry5.setMap(new Mapping(null, new MapList(new int[] { 12, 22 },
847             new int[] { 12, 22 }, 1, 1)));
848     sq.addDBRef(upentry5);
849
850     // not primary - uniprot with map to different coordinates frame
851     DBRefEntry upentry6 = new DBRefEntry("UNIPROT", "0", "Q04766");
852     upentry6.setMap(new Mapping(null, new MapList(new int[] { 12, 18 },
853             new int[] { 112, 118 }, 1, 1)));
854     sq.addDBRef(upentry6);
855
856     // not primary - dbref to 'non-core' database
857     DBRefEntry upentry7 = new DBRefEntry("Pfam", "0", "PF00903");
858     sq.addDBRef(upentry7);
859
860     // primary - type is PDB
861     DBRefEntry pdbentry = new DBRefEntry("PDB", "0", "1qip");
862     sq.addDBRef(pdbentry);
863
864     // not primary - PDBEntry has no file
865     sq.addDBRef(new DBRefEntry("PDB", "0", "1AAA"));
866
867     // not primary - no PDBEntry
868     sq.addDBRef(new DBRefEntry("PDB", "0", "1DDD"));
869
870     // add corroborating PDB entry for primary DBref -
871     // needs to have a file as well as matching ID
872     // note PDB ID is not treated as case sensitive
873     sq.addPDBId(new PDBEntry("1QIP", null, Type.PDB, new File("/blah")
874             .toString()));
875
876     // not valid DBRef - no file..
877     sq.addPDBId(new PDBEntry("1AAA", null, null, null));
878
879     primaryDBRefs = sq.getPrimaryDBRefs();
880     assertEquals(4, primaryDBRefs.size());
881     assertTrue("Couldn't find simple primary reference (UNIPROT)",
882             primaryDBRefs.contains(upentry1));
883     assertTrue("Couldn't find mapped primary reference (UNIPROT)",
884             primaryDBRefs.contains(upentry2));
885     assertTrue("Couldn't find mapped context reference (UNIPROT)",
886             primaryDBRefs.contains(upentry3));
887     assertTrue("Couldn't find expected PDB primary reference",
888             primaryDBRefs.contains(pdbentry));
889   }
890
891   @Test(groups = { "Functional" })
892   public void testGetPrimaryDBRefs_nucleotide()
893   {
894     SequenceI sq = new Sequence("aseq", "TGATCACTCGACTAGCATCAGCATA", 10, 34);
895
896     // primary - Ensembl
897     DBRefEntry dbr1 = new DBRefEntry("ENSEMBL", "0", "ENSG1234");
898     sq.addDBRef(dbr1);
899
900     // not primary - Ensembl 'transcript' mapping of sub-sequence
901     DBRefEntry dbr2 = new DBRefEntry("ENSEMBL", "0", "ENST1234");
902     dbr2.setMap(new Mapping(null, new MapList(new int[] { 15, 25 },
903             new int[] { 1, 11 }, 1, 1)));
904     sq.addDBRef(dbr2);
905
906     // primary - EMBL with congruent map
907     DBRefEntry dbr3 = new DBRefEntry("EMBL", "0", "J1234");
908     dbr3.setMap(new Mapping(null, new MapList(new int[] { 10, 34 },
909             new int[] { 10, 34 }, 1, 1)));
910     sq.addDBRef(dbr3);
911
912     // not primary - to non-core database
913     DBRefEntry dbr4 = new DBRefEntry("CCDS", "0", "J1234");
914     sq.addDBRef(dbr4);
915
916     // not primary - to protein
917     DBRefEntry dbr5 = new DBRefEntry("UNIPROT", "0", "Q87654");
918     sq.addDBRef(dbr5);
919
920     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
921     assertEquals(2, primaryDBRefs.size());
922     assertTrue(primaryDBRefs.contains(dbr1));
923     assertTrue(primaryDBRefs.contains(dbr3));
924   }
925
926   /**
927    * Test the method that updates the list of PDBEntry from any new DBRefEntry
928    * for PDB
929    */
930   @Test(groups = { "Functional" })
931   public void testUpdatePDBIds()
932   {
933     PDBEntry pdbe1 = new PDBEntry("3A6S", null, null, null);
934     seq.addPDBId(pdbe1);
935     seq.addDBRef(new DBRefEntry("Ensembl", "8", "ENST1234"));
936     seq.addDBRef(new DBRefEntry("PDB", "0", "1A70"));
937     seq.addDBRef(new DBRefEntry("PDB", "0", "4BQGa"));
938     seq.addDBRef(new DBRefEntry("PDB", "0", "3a6sB"));
939     // 7 is not a valid chain code:
940     seq.addDBRef(new DBRefEntry("PDB", "0", "2GIS7"));
941
942     seq.updatePDBIds();
943     List<PDBEntry> pdbIds = seq.getAllPDBEntries();
944     assertEquals(4, pdbIds.size());
945     assertSame(pdbe1, pdbIds.get(0));
946     // chain code got added to 3A6S:
947     assertEquals("B", pdbe1.getChainCode());
948     assertEquals("1A70", pdbIds.get(1).getId());
949     // 4BQGA is parsed into id + chain
950     assertEquals("4BQG", pdbIds.get(2).getId());
951     assertEquals("a", pdbIds.get(2).getChainCode());
952     assertEquals("2GIS7", pdbIds.get(3).getId());
953     assertNull(pdbIds.get(3).getChainCode());
954   }
955
956   /**
957    * Test the method that either adds a pdbid or updates an existing one
958    */
959   @Test(groups = { "Functional" })
960   public void testAddPDBId()
961   {
962     PDBEntry pdbe = new PDBEntry("3A6S", null, null, null);
963     seq.addPDBId(pdbe);
964     assertEquals(1, seq.getAllPDBEntries().size());
965     assertSame(pdbe, seq.getPDBEntry("3A6S"));
966     assertSame(pdbe, seq.getPDBEntry("3a6s")); // case-insensitive
967
968     // add the same entry
969     seq.addPDBId(pdbe);
970     assertEquals(1, seq.getAllPDBEntries().size());
971     assertSame(pdbe, seq.getPDBEntry("3A6S"));
972
973     // add an identical entry
974     seq.addPDBId(new PDBEntry("3A6S", null, null, null));
975     assertEquals(1, seq.getAllPDBEntries().size());
976     assertSame(pdbe, seq.getPDBEntry("3A6S"));
977
978     // add a different entry
979     PDBEntry pdbe2 = new PDBEntry("1A70", null, null, null);
980     seq.addPDBId(pdbe2);
981     assertEquals(2, seq.getAllPDBEntries().size());
982     assertSame(pdbe, seq.getAllPDBEntries().get(0));
983     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
984
985     // update pdbe with chain code, file, type
986     PDBEntry pdbe3 = new PDBEntry("3a6s", "A", Type.PDB, "filepath");
987     seq.addPDBId(pdbe3);
988     assertEquals(2, seq.getAllPDBEntries().size());
989     assertSame(pdbe, seq.getAllPDBEntries().get(0)); // updated in situ
990     assertEquals("3A6S", pdbe.getId()); // unchanged
991     assertEquals("A", pdbe.getChainCode()); // updated
992     assertEquals(Type.PDB.toString(), pdbe.getType()); // updated
993     assertEquals("filepath", pdbe.getFile()); // updated
994     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
995
996     // add with a different file path
997     PDBEntry pdbe4 = new PDBEntry("3a6s", "A", Type.PDB, "filepath2");
998     seq.addPDBId(pdbe4);
999     assertEquals(3, seq.getAllPDBEntries().size());
1000     assertSame(pdbe4, seq.getAllPDBEntries().get(2));
1001
1002     // add with a different chain code
1003     PDBEntry pdbe5 = new PDBEntry("3a6s", "B", Type.PDB, "filepath");
1004     seq.addPDBId(pdbe5);
1005     assertEquals(4, seq.getAllPDBEntries().size());
1006     assertSame(pdbe5, seq.getAllPDBEntries().get(3));
1007   }
1008
1009   @Test(
1010     groups = { "Functional" },
1011     expectedExceptions = { IllegalArgumentException.class })
1012   public void testSetDatasetSequence_toSelf()
1013   {
1014     seq.setDatasetSequence(seq);
1015   }
1016
1017   @Test(
1018     groups = { "Functional" },
1019     expectedExceptions = { IllegalArgumentException.class })
1020   public void testSetDatasetSequence_cascading()
1021   {
1022     SequenceI seq2 = new Sequence("Seq2", "xyz");
1023     seq2.createDatasetSequence();
1024     seq.setDatasetSequence(seq2);
1025   }
1026 }