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