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