JAL-2210 JAL-2235 fix deriveSequence test for tightened up setDBRefs and addDBRef...
[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     /*
341      * SequenceFeature on sequence and dataset sequence; returns that on
342      * sequence
343      * 
344      * Note JAL-2046: spurious: we have no use case for this at the moment.
345      * This test also buggy - as sf2.equals(sf), no new feature is added
346      */
347     SequenceFeature sf2 = new SequenceFeature();
348     sq.getDatasetSequence().addSequenceFeature(sf2);
349     sfs = sq.getSequenceFeatures();
350     assertEquals(1, sfs.length);
351     assertSame(sf, sfs[0]);
352
353     /*
354      * SequenceFeature on dataset sequence only
355      * Note JAL-2046: spurious: we have no use case for setting a non-dataset sequence's feature array to null at the moment.
356      */
357     sq.setSequenceFeatures(null);
358     assertNull(sq.getDatasetSequence().getSequenceFeatures());
359
360     /*
361      * Corrupt case - no SequenceFeature, dataset's dataset is the original
362      * sequence. Test shows no infinite loop results.
363      */
364     sq.getDatasetSequence().setSequenceFeatures(null);
365     /**
366      * is there a usecase for this ? setDatasetSequence should throw an error if
367      * this actually occurs.
368      */
369     try
370     {
371       sq.getDatasetSequence().setDatasetSequence(sq); // loop!
372       Assert.fail("Expected Error to be raised when calling setDatasetSequence with self reference");
373     } catch (Error e)
374     {
375       // TODO Jalview error/exception class for raising implementation errors
376       assertTrue(e.getMessage().toLowerCase()
377               .contains("implementation error"));
378     }
379     assertNull(sq.getSequenceFeatures());
380   }
381
382   /**
383    * Test the method that returns an array, indexed by sequence position, whose
384    * entries are the residue positions at the sequence position (or to the right
385    * if a gap)
386    */
387   @Test(groups = { "Functional" })
388   public void testFindPositionMap()
389   {
390     /*
391      * Note: Javadoc for findPosition says it returns the residue position to
392      * the left of a gapped position; in fact it returns the position to the
393      * right. Also it returns a non-existent residue position for a gap beyond
394      * the sequence.
395      */
396     Sequence sq = new Sequence("TestSeq", "AB.C-D E.");
397     int[] map = sq.findPositionMap();
398     assertEquals(Arrays.toString(new int[] { 1, 2, 3, 3, 4, 4, 5, 5, 6 }),
399             Arrays.toString(map));
400   }
401
402   /**
403    * Test for getSubsequence
404    */
405   @Test(groups = { "Functional" })
406   public void testGetSubsequence()
407   {
408     SequenceI sq = new Sequence("TestSeq", "ABCDEFG");
409     sq.createDatasetSequence();
410
411     // positions are base 0, end position is exclusive
412     SequenceI subseq = sq.getSubSequence(2, 4);
413
414     assertEquals("CD", subseq.getSequenceAsString());
415     // start/end are base 1 positions
416     assertEquals(3, subseq.getStart());
417     assertEquals(4, subseq.getEnd());
418     // subsequence shares the full dataset sequence
419     assertSame(sq.getDatasetSequence(), subseq.getDatasetSequence());
420   }
421
422   /**
423    * test createDatasetSequence behaves to doc
424    */
425   @Test(groups = { "Functional" })
426   public void testCreateDatasetSequence()
427   {
428     SequenceI sq = new Sequence("my","ASDASD");
429     assertNull(sq.getDatasetSequence());
430     SequenceI rds = sq.createDatasetSequence();
431     assertNotNull(rds);
432     assertNull(rds.getDatasetSequence());
433     assertEquals(sq.getDatasetSequence(), rds);
434   }
435
436   /**
437    * Test for deriveSequence applied to a sequence with a dataset
438    */
439   @Test(groups = { "Functional" })
440   public void testDeriveSequence_existingDataset()
441   {
442     Sequence sq = new Sequence("Seq1", "CD");
443     sq.setDatasetSequence(new Sequence("Seq1", "ABCDEF"));
444     sq.getDatasetSequence().addSequenceFeature(
445             new SequenceFeature("", "", 1, 2, 0f, null));
446     sq.setStart(3);
447     sq.setEnd(4);
448
449     sq.setDescription("Test sequence description..");
450     sq.setVamsasId("TestVamsasId");
451     sq.addDBRef(new DBRefEntry("PDB", "version0", "1TST"));
452
453     sq.addDBRef(new DBRefEntry("PDB", "version1", "1PDB"));
454     sq.addDBRef(new DBRefEntry("PDB", "version2", "2PDB"));
455     sq.addDBRef(new DBRefEntry("PDB", "version3", "3PDB"));
456     sq.addDBRef(new DBRefEntry("PDB", "version4", "4PDB"));
457
458     sq.addPDBId(new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1"));
459     sq.addPDBId(new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1"));
460     sq.addPDBId(new PDBEntry("2PDB", "A", Type.MMCIF, "filePath/test2"));
461     sq.addPDBId(new PDBEntry("2PDB", "B", Type.MMCIF, "filePath/test2"));
462     
463     // these are the same as ones already added
464     DBRefEntry pdb1pdb = new DBRefEntry("PDB", "version1", "1PDB");
465     DBRefEntry pdb2pdb = new DBRefEntry("PDB", "version2", "2PDB");
466
467     
468     List<DBRefEntry> primRefs = Arrays.asList(new DBRefEntry[] { pdb1pdb,
469         pdb2pdb });
470
471     sq.getDatasetSequence().addDBRef(pdb1pdb); // should do nothing
472     sq.getDatasetSequence().addDBRef(pdb2pdb); // should do nothing
473     sq.getDatasetSequence().addDBRef(
474             new DBRefEntry("PDB", "version3", "3PDB")); // should do nothing
475     sq.getDatasetSequence().addDBRef(
476             new DBRefEntry("PDB", "version4", "4PDB")); // should do nothing
477     
478     PDBEntry pdbe1a=new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1");
479     PDBEntry pdbe1b = new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1");
480     PDBEntry pdbe2a=new PDBEntry("2PDB", "A", Type.MMCIF, "filePath/test2");
481     PDBEntry pdbe2b = new PDBEntry("2PDB", "B", Type.MMCIF, "filePath/test2");
482     sq.getDatasetSequence().addPDBId(
483             pdbe1a);
484     sq.getDatasetSequence().addPDBId(
485             pdbe1b);
486     sq.getDatasetSequence().addPDBId(pdbe2a);
487     sq.getDatasetSequence().addPDBId(pdbe2b);
488
489     /*
490      * test we added pdb entries to the dataset sequence
491      */
492     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries(), Arrays
493             .asList(new PDBEntry[] { pdbe1a, pdbe1b, pdbe2a, pdbe2b }),
494             "PDB Entries were not found on dataset sequence.");
495
496     /*
497      * we should recover a pdb entry that is on the dataset sequence via PDBEntry
498      */
499     Assert.assertEquals(pdbe1a,
500             sq.getDatasetSequence().getPDBEntry("1PDB"),
501             "PDB Entry '1PDB' not found on dataset sequence via getPDBEntry.");
502     ArrayList<Annotation> annotsList = new ArrayList<Annotation>();
503     System.out.println(">>>>>> " + sq.getSequenceAsString().length());
504     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
505     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
506     Annotation[] annots = annotsList.toArray(new Annotation[0]);
507     sq.addAlignmentAnnotation(new AlignmentAnnotation("Test annot",
508             "Test annot description", annots));
509     sq.getDatasetSequence().addAlignmentAnnotation(
510             new AlignmentAnnotation("Test annot", "Test annot description",
511                     annots));
512     Assert.assertEquals(sq.getDescription(), "Test sequence description..");
513     Assert.assertEquals(sq.getDBRefs().length, 5); // DBRefs are on dataset
514                                                    // sequence
515     Assert.assertEquals(sq.getAllPDBEntries().size(), 4);
516     Assert.assertNotNull(sq.getAnnotation());
517     Assert.assertEquals(sq.getAnnotation()[0].annotations.length, 2);
518     Assert.assertEquals(sq.getDatasetSequence().getDBRefs().length, 5); // same
519                                                                         // as
520                                                                         // sq.getDBRefs()
521     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries().size(),
522             4);
523     Assert.assertNotNull(sq.getDatasetSequence().getAnnotation());
524
525     Sequence derived = (Sequence) sq.deriveSequence();
526
527     Assert.assertEquals(derived.getDescription(),
528             "Test sequence description..");
529     Assert.assertEquals(derived.getDBRefs().length, 5); // come from dataset
530     Assert.assertEquals(derived.getAllPDBEntries().size(), 4);
531     Assert.assertNotNull(derived.getAnnotation());
532     Assert.assertEquals(derived.getAnnotation()[0].annotations.length, 2);
533     Assert.assertEquals(derived.getDatasetSequence().getDBRefs().length, 5);
534     Assert.assertEquals(derived.getDatasetSequence().getAllPDBEntries()
535             .size(), 4);
536     Assert.assertNotNull(derived.getDatasetSequence().getAnnotation());
537
538     assertEquals("CD", derived.getSequenceAsString());
539     assertSame(sq.getDatasetSequence(), derived.getDatasetSequence());
540
541     assertNull(sq.sequenceFeatures);
542     assertNull(derived.sequenceFeatures);
543     // derived sequence should access dataset sequence features
544     assertNotNull(sq.getSequenceFeatures());
545     assertArrayEquals(sq.getSequenceFeatures(),
546             derived.getSequenceFeatures());
547     
548     /*
549      *  verify we have primary db refs *just* for PDB IDs with associated
550      *  PDBEntry objects
551      */
552
553     assertEquals(primRefs, sq.getPrimaryDBRefs());
554     assertEquals(primRefs, sq.getDatasetSequence().getPrimaryDBRefs());
555
556     assertEquals(sq.getPrimaryDBRefs(), derived.getPrimaryDBRefs());
557
558   }
559
560   /**
561    * Test for deriveSequence applied to an ungapped sequence with no dataset
562    */
563   @Test(groups = { "Functional" })
564   public void testDeriveSequence_noDatasetUngapped()
565   {
566     SequenceI sq = new Sequence("Seq1", "ABCDEF");
567     assertEquals(1, sq.getStart());
568     assertEquals(6, sq.getEnd());
569     SequenceI derived = sq.deriveSequence();
570     assertEquals("ABCDEF", derived.getSequenceAsString());
571     assertEquals("ABCDEF", derived.getDatasetSequence()
572             .getSequenceAsString());
573   }
574
575   /**
576    * Test for deriveSequence applied to a gapped sequence with no dataset
577    */
578   @Test(groups = { "Functional" })
579   public void testDeriveSequence_noDatasetGapped()
580   {
581     SequenceI sq = new Sequence("Seq1", "AB-C.D EF");
582     assertEquals(1, sq.getStart());
583     assertEquals(6, sq.getEnd());
584     assertNull(sq.getDatasetSequence());
585     SequenceI derived = sq.deriveSequence();
586     assertEquals("AB-C.D EF", derived.getSequenceAsString());
587     assertEquals("ABCDEF", derived.getDatasetSequence()
588             .getSequenceAsString());
589   }
590
591   @Test(groups = { "Functional" })
592   public void testCopyConstructor_noDataset()
593   {
594     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
595     seq1.setDescription("description");
596     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
597             1.3d));
598     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
599             12.4f, "group"));
600     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
601     seq1.addDBRef(new DBRefEntry("EMBL", "1.2", "AZ12345"));
602     
603     SequenceI copy = new Sequence(seq1);
604
605     assertNull(copy.getDatasetSequence());
606
607     verifyCopiedSequence(seq1, copy);
608
609     // copy has a copy of the DBRefEntry
610     // this is murky - DBrefs are only copied for dataset sequences
611     // where the test for 'dataset sequence' is 'dataset is null'
612     // but that doesn't distinguish it from an aligned sequence
613     // which has not yet generated a dataset sequence
614     // NB getDBRef looks inside dataset sequence if not null
615     DBRefEntry[] dbrefs = copy.getDBRefs();
616     assertEquals(1, dbrefs.length);
617     assertFalse(dbrefs[0] == seq1.getDBRefs()[0]);
618     assertTrue(dbrefs[0].equals(seq1.getDBRefs()[0]));
619   }
620
621   @Test(groups = { "Functional" })
622   public void testCopyConstructor_withDataset()
623   {
624     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
625     seq1.createDatasetSequence();
626     seq1.setDescription("description");
627     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
628             1.3d));
629     // JAL-2046 - what is the contract for using a derived sequence's
630     // addSequenceFeature ?
631     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
632             12.4f, "group"));
633     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
634     // here we add DBRef to the dataset sequence:
635     seq1.getDatasetSequence().addDBRef(
636             new DBRefEntry("EMBL", "1.2", "AZ12345"));
637
638     SequenceI copy = new Sequence(seq1);
639
640     assertNotNull(copy.getDatasetSequence());
641     assertSame(copy.getDatasetSequence(), seq1.getDatasetSequence());
642
643     verifyCopiedSequence(seq1, copy);
644
645     // getDBRef looks inside dataset sequence and this is shared,
646     // so holds the same dbref objects
647     DBRefEntry[] dbrefs = copy.getDBRefs();
648     assertEquals(1, dbrefs.length);
649     assertSame(dbrefs[0], seq1.getDBRefs()[0]);
650   }
651
652   /**
653    * Helper to make assertions about a copied sequence
654    * 
655    * @param seq1
656    * @param copy
657    */
658   protected void verifyCopiedSequence(SequenceI seq1, SequenceI copy)
659   {
660     // verify basic properties:
661     assertEquals(copy.getName(), seq1.getName());
662     assertEquals(copy.getDescription(), seq1.getDescription());
663     assertEquals(copy.getStart(), seq1.getStart());
664     assertEquals(copy.getEnd(), seq1.getEnd());
665     assertEquals(copy.getSequenceAsString(), seq1.getSequenceAsString());
666
667     // copy has a copy of the annotation:
668     AlignmentAnnotation[] anns = copy.getAnnotation();
669     assertEquals(1, anns.length);
670     assertFalse(anns[0] == seq1.getAnnotation()[0]);
671     assertEquals(anns[0].label, seq1.getAnnotation()[0].label);
672     assertEquals(anns[0].description, seq1.getAnnotation()[0].description);
673     assertEquals(anns[0].score, seq1.getAnnotation()[0].score);
674
675     // copy has a copy of the sequence feature:
676     SequenceFeature[] sfs = copy.getSequenceFeatures();
677     assertEquals(1, sfs.length);
678     if (seq1.getDatasetSequence()!=null && copy.getDatasetSequence()==seq1.getDatasetSequence()) {
679       assertTrue(sfs[0] == seq1.getSequenceFeatures()[0]);
680     } else {
681       assertFalse(sfs[0] == seq1.getSequenceFeatures()[0]);
682     }
683     assertTrue(sfs[0].equals(seq1.getSequenceFeatures()[0]));
684
685     // copy has a copy of the PDB entry
686     Vector<PDBEntry> pdbs = copy.getAllPDBEntries();
687     assertEquals(1, pdbs.size());
688     assertFalse(pdbs.get(0) == seq1.getAllPDBEntries().get(0));
689     assertTrue(pdbs.get(0).equals(seq1.getAllPDBEntries().get(0)));
690   }
691
692   @Test(groups = "Functional")
693   public void testGetCharAt()
694   {
695     SequenceI sq = new Sequence("", "abcde");
696     assertEquals('a', sq.getCharAt(0));
697     assertEquals('e', sq.getCharAt(4));
698     assertEquals(' ', sq.getCharAt(5));
699     assertEquals(' ', sq.getCharAt(-1));
700   }
701
702   /**
703    * Tests for adding (or updating) dbrefs
704    * 
705    * @see DBRefEntry#updateFrom(DBRefEntry)
706    */
707   @Test(groups = { "Functional" })
708   public void testAddDBRef()
709   {
710     SequenceI sq = new Sequence("", "abcde");
711     assertNull(sq.getDBRefs());
712     DBRefEntry dbref = new DBRefEntry("Uniprot", "1", "P00340");
713     sq.addDBRef(dbref);
714     assertEquals(1, sq.getDBRefs().length);
715     assertSame(dbref, sq.getDBRefs()[0]);
716
717     /*
718      * change of version - new entry
719      */
720     DBRefEntry dbref2 = new DBRefEntry("Uniprot", "2", "P00340");
721     sq.addDBRef(dbref2);
722     assertEquals(2, sq.getDBRefs().length);
723     assertSame(dbref, sq.getDBRefs()[0]);
724     assertSame(dbref2, sq.getDBRefs()[1]);
725
726     /*
727      * matches existing entry - not added
728      */
729     sq.addDBRef(new DBRefEntry("UNIPROT", "1", "p00340"));
730     assertEquals(2, sq.getDBRefs().length);
731
732     /*
733      * different source = new entry
734      */
735     DBRefEntry dbref3 = new DBRefEntry("UniRef", "1", "p00340");
736     sq.addDBRef(dbref3);
737     assertEquals(3, sq.getDBRefs().length);
738     assertSame(dbref3, sq.getDBRefs()[2]);
739
740     /*
741      * different ref = new entry
742      */
743     DBRefEntry dbref4 = new DBRefEntry("UniRef", "1", "p00341");
744     sq.addDBRef(dbref4);
745     assertEquals(4, sq.getDBRefs().length);
746     assertSame(dbref4, sq.getDBRefs()[3]);
747
748     /*
749      * matching ref with a mapping - map updated
750      */
751     DBRefEntry dbref5 = new DBRefEntry("UniRef", "1", "p00341");
752     Mapping map = new Mapping(new MapList(new int[] { 1, 3 }, new int[] {
753         1, 1 }, 3, 1));
754     dbref5.setMap(map);
755     sq.addDBRef(dbref5);
756     assertEquals(4, sq.getDBRefs().length);
757     assertSame(dbref4, sq.getDBRefs()[3]);
758     assertSame(map, dbref4.getMap());
759
760     /*
761      * 'real' version replaces "0" version
762      */
763     dbref2.setVersion("0");
764     DBRefEntry dbref6 = new DBRefEntry(dbref2.getSource(), "3",
765             dbref2.getAccessionId());
766     sq.addDBRef(dbref6);
767     assertEquals(4, sq.getDBRefs().length);
768     assertSame(dbref2, sq.getDBRefs()[1]);
769     assertEquals("3", dbref2.getVersion());
770
771     /*
772      * 'real' version replaces "source:0" version
773      */
774     dbref3.setVersion("Uniprot:0");
775     DBRefEntry dbref7 = new DBRefEntry(dbref3.getSource(), "3",
776             dbref3.getAccessionId());
777     sq.addDBRef(dbref7);
778     assertEquals(4, sq.getDBRefs().length);
779     assertSame(dbref3, sq.getDBRefs()[2]);
780     assertEquals("3", dbref2.getVersion());
781   }
782
783   @Test(groups = { "Functional" })
784   public void testGetPrimaryDBRefs_peptide()
785   {
786     SequenceI sq = new Sequence("aseq", "ASDFKYLMQPRST", 10, 22);
787
788     // no dbrefs
789     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
790     assertTrue(primaryDBRefs.isEmpty());
791
792     // empty dbrefs
793     sq.setDBRefs(new DBRefEntry[] {});
794     primaryDBRefs = sq.getPrimaryDBRefs();
795     assertTrue(primaryDBRefs.isEmpty());
796
797     // primary - uniprot
798     DBRefEntry upentry1 = new DBRefEntry("UNIPROT", "0", "Q04760");
799     sq.addDBRef(upentry1);
800
801     // primary - uniprot with congruent map
802     DBRefEntry upentry2 = new DBRefEntry("UNIPROT", "0", "Q04762");
803     upentry2.setMap(new Mapping(null, new MapList(new int[] { 10, 22 },
804             new int[] { 10, 22 }, 1, 1)));
805     sq.addDBRef(upentry2);
806
807     // primary - uniprot with map of enclosing sequence
808     DBRefEntry upentry3 = new DBRefEntry("UNIPROT", "0", "Q04763");
809     upentry3.setMap(new Mapping(null, new MapList(new int[] { 8, 24 },
810             new int[] { 8, 24 }, 1, 1)));
811     sq.addDBRef(upentry3);
812
813     // not primary - uniprot with map of sub-sequence (5')
814     DBRefEntry upentry4 = new DBRefEntry("UNIPROT", "0", "Q04764");
815     upentry4.setMap(new Mapping(null, new MapList(new int[] { 10, 18 },
816             new int[] { 10, 18 }, 1, 1)));
817     sq.addDBRef(upentry4);
818
819     // not primary - uniprot with map that overlaps 3'
820     DBRefEntry upentry5 = new DBRefEntry("UNIPROT", "0", "Q04765");
821     upentry5.setMap(new Mapping(null, new MapList(new int[] { 12, 22 },
822             new int[] { 12, 22 }, 1, 1)));
823     sq.addDBRef(upentry5);
824
825     // not primary - uniprot with map to different coordinates frame
826     DBRefEntry upentry6 = new DBRefEntry("UNIPROT", "0", "Q04766");
827     upentry6.setMap(new Mapping(null, new MapList(new int[] { 12, 18 },
828             new int[] { 112, 118 }, 1, 1)));
829     sq.addDBRef(upentry6);
830
831     // not primary - dbref to 'non-core' database
832     DBRefEntry upentry7 = new DBRefEntry("Pfam", "0", "PF00903");
833     sq.addDBRef(upentry7);
834
835     // primary - type is PDB
836     DBRefEntry pdbentry = new DBRefEntry("PDB", "0", "1qip");
837     sq.addDBRef(pdbentry);
838
839     // not primary - PDBEntry has no file
840     sq.addDBRef(new DBRefEntry("PDB", "0", "1AAA"));
841
842     // not primary - no PDBEntry
843     sq.addDBRef(new DBRefEntry("PDB", "0", "1DDD"));
844
845     // add corroborating PDB entry for primary DBref -
846     // needs to have a file as well as matching ID
847     // note PDB ID is not treated as case sensitive
848     sq.addPDBId(new PDBEntry("1QIP", null, Type.PDB, new File("/blah")
849             .toString()));
850
851     // not valid DBRef - no file..
852     sq.addPDBId(new PDBEntry("1AAA", null, null, null));
853
854     primaryDBRefs = sq.getPrimaryDBRefs();
855     assertEquals(4, primaryDBRefs.size());
856     assertTrue("Couldn't find simple primary reference (UNIPROT)",
857             primaryDBRefs.contains(upentry1));
858     assertTrue("Couldn't find mapped primary reference (UNIPROT)",
859             primaryDBRefs.contains(upentry2));
860     assertTrue("Couldn't find mapped context reference (UNIPROT)",
861             primaryDBRefs.contains(upentry3));
862     assertTrue("Couldn't find expected PDB primary reference",
863             primaryDBRefs.contains(pdbentry));
864   }
865
866   @Test(groups = { "Functional" })
867   public void testGetPrimaryDBRefs_nucleotide()
868   {
869     SequenceI sq = new Sequence("aseq", "TGATCACTCGACTAGCATCAGCATA", 10, 34);
870   
871     // primary - Ensembl
872     DBRefEntry dbr1 = new DBRefEntry("ENSEMBL", "0", "ENSG1234");
873     sq.addDBRef(dbr1);
874   
875     // not primary - Ensembl 'transcript' mapping of sub-sequence
876     DBRefEntry dbr2 = new DBRefEntry("ENSEMBL", "0", "ENST1234");
877     dbr2.setMap(new Mapping(null, new MapList(new int[] { 15, 25 },
878             new int[] { 1, 11 }, 1, 1)));
879     sq.addDBRef(dbr2);
880
881     // primary - EMBL with congruent map
882     DBRefEntry dbr3 = new DBRefEntry("EMBL", "0", "J1234");
883     dbr3.setMap(new Mapping(null, new MapList(new int[] { 10, 34 },
884             new int[] { 10, 34 }, 1, 1)));
885     sq.addDBRef(dbr3);
886
887     // not primary - to non-core database
888     DBRefEntry dbr4 = new DBRefEntry("CCDS", "0", "J1234");
889     sq.addDBRef(dbr4);
890
891     // not primary - to protein
892     DBRefEntry dbr5 = new DBRefEntry("UNIPROT", "0", "Q87654");
893     sq.addDBRef(dbr5);
894   
895     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
896     assertEquals(2, primaryDBRefs.size());
897     assertTrue(primaryDBRefs.contains(dbr1));
898     assertTrue(primaryDBRefs.contains(dbr3));
899   }
900
901   /**
902    * Test the method that updates the list of PDBEntry from any new DBRefEntry
903    * for PDB
904    */
905   @Test(groups = { "Functional" })
906   public void testUpdatePDBIds()
907   {
908     PDBEntry pdbe1 = new PDBEntry("3A6S", null, null, null);
909     seq.addPDBId(pdbe1);
910     seq.addDBRef(new DBRefEntry("Ensembl", "8", "ENST1234"));
911     seq.addDBRef(new DBRefEntry("PDB", "0", "1A70"));
912     seq.addDBRef(new DBRefEntry("PDB", "0", "4BQGa"));
913     seq.addDBRef(new DBRefEntry("PDB", "0", "3a6sB"));
914     // 7 is not a valid chain code:
915     seq.addDBRef(new DBRefEntry("PDB", "0", "2GIS7"));
916     
917     seq.updatePDBIds();
918     List<PDBEntry> pdbIds = seq.getAllPDBEntries();
919     assertEquals(4, pdbIds.size());
920     assertSame(pdbe1, pdbIds.get(0));
921     // chain code got added to 3A6S:
922     assertEquals("B", pdbe1.getChainCode());
923     assertEquals("1A70", pdbIds.get(1).getId());
924     // 4BQGA is parsed into id + chain
925     assertEquals("4BQG", pdbIds.get(2).getId());
926     assertEquals("a", pdbIds.get(2).getChainCode());
927     assertEquals("2GIS7", pdbIds.get(3).getId());
928     assertNull(pdbIds.get(3).getChainCode());
929   }
930
931   /**
932    * Test the method that either adds a pdbid or updates an existing one
933    */
934   @Test(groups = { "Functional" })
935   public void testAddPDBId()
936   {
937     PDBEntry pdbe = new PDBEntry("3A6S", null, null, null);
938     seq.addPDBId(pdbe);
939     assertEquals(1, seq.getAllPDBEntries().size());
940     assertSame(pdbe, seq.getPDBEntry("3A6S"));
941     assertSame(pdbe, seq.getPDBEntry("3a6s")); // case-insensitive
942
943     // add the same entry
944     seq.addPDBId(pdbe);
945     assertEquals(1, seq.getAllPDBEntries().size());
946     assertSame(pdbe, seq.getPDBEntry("3A6S"));
947
948     // add an identical entry
949     seq.addPDBId(new PDBEntry("3A6S", null, null, null));
950     assertEquals(1, seq.getAllPDBEntries().size());
951     assertSame(pdbe, seq.getPDBEntry("3A6S"));
952
953     // add a different entry
954     PDBEntry pdbe2 = new PDBEntry("1A70", null, null, null);
955     seq.addPDBId(pdbe2);
956     assertEquals(2, seq.getAllPDBEntries().size());
957     assertSame(pdbe, seq.getAllPDBEntries().get(0));
958     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
959
960     // update pdbe with chain code, file, type
961     PDBEntry pdbe3 = new PDBEntry("3a6s", "A", Type.PDB, "filepath");
962     seq.addPDBId(pdbe3);
963     assertEquals(2, seq.getAllPDBEntries().size());
964     assertSame(pdbe, seq.getAllPDBEntries().get(0)); // updated in situ
965     assertEquals("3A6S", pdbe.getId()); // unchanged
966     assertEquals("A", pdbe.getChainCode()); // updated
967     assertEquals(Type.PDB.toString(), pdbe.getType()); // updated
968     assertEquals("filepath", pdbe.getFile()); // updated
969     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
970
971     // add with a different file path
972     PDBEntry pdbe4 = new PDBEntry("3a6s", "A", Type.PDB, "filepath2");
973     seq.addPDBId(pdbe4);
974     assertEquals(3, seq.getAllPDBEntries().size());
975     assertSame(pdbe4, seq.getAllPDBEntries().get(2));
976
977     // add with a different chain code
978     PDBEntry pdbe5 = new PDBEntry("3a6s", "B", Type.PDB, "filepath");
979     seq.addPDBId(pdbe5);
980     assertEquals(4, seq.getAllPDBEntries().size());
981     assertSame(pdbe5, seq.getAllPDBEntries().get(3));
982   }
983 }