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