Merge branch 'features/JAL-2526sequenceCursor' into
[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
31 import jalview.commands.EditCommand;
32 import jalview.commands.EditCommand.Action;
33 import jalview.datamodel.PDBEntry.Type;
34 import jalview.gui.JvOptionPane;
35 import jalview.util.MapList;
36
37 import java.io.File;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.BitSet;
41 import java.util.List;
42 import java.util.Vector;
43
44 import junit.extensions.PA;
45
46 import org.testng.Assert;
47 import org.testng.annotations.BeforeClass;
48 import org.testng.annotations.BeforeMethod;
49 import org.testng.annotations.Test;
50
51 public class SequenceTest
52 {
53
54   @BeforeClass(alwaysRun = true)
55   public void setUpJvOptionPane()
56   {
57     JvOptionPane.setInteractiveMode(false);
58     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
59   }
60
61   Sequence seq;
62
63   @BeforeMethod(alwaysRun = true)
64   public void setUp()
65   {
66     seq = new Sequence("FER1", "AKPNGVL");
67   }
68
69   @Test(groups = { "Functional" })
70   public void testInsertGapsAndGapmaps()
71   {
72     SequenceI aseq = seq.deriveSequence();
73     aseq.insertCharAt(2, 3, '-');
74     aseq.insertCharAt(6, 3, '-');
75     assertEquals("Gap insertions not correct", "AK---P---NGVL",
76             aseq.getSequenceAsString());
77     List<int[]> gapInt = aseq.getInsertions();
78     assertEquals("Gap interval 1 start wrong", 2, gapInt.get(0)[0]);
79     assertEquals("Gap interval 1 end wrong", 4, gapInt.get(0)[1]);
80     assertEquals("Gap interval 2 start wrong", 6, gapInt.get(1)[0]);
81     assertEquals("Gap interval 2 end wrong", 8, gapInt.get(1)[1]);
82
83     BitSet gapfield = aseq.getInsertionsAsBits();
84     BitSet expectedgaps = new BitSet();
85     expectedgaps.set(2, 5);
86     expectedgaps.set(6, 9);
87
88     assertEquals(6, expectedgaps.cardinality());
89
90     assertEquals("getInsertionsAsBits didn't mark expected number of gaps",
91             6, gapfield.cardinality());
92
93     assertEquals("getInsertionsAsBits not correct.", expectedgaps, gapfield);
94   }
95
96   @Test(groups = ("Functional"))
97   public void testIsProtein()
98   {
99     // test Protein
100     assertTrue(new Sequence("prot", "ASDFASDFASDF").isProtein());
101     // test DNA
102     assertFalse(new Sequence("prot", "ACGTACGTACGT").isProtein());
103     // test RNA
104     SequenceI sq = new Sequence("prot", "ACGUACGUACGU");
105     assertFalse(sq.isProtein());
106     // change sequence, should trigger an update of cached result
107     sq.setSequence("ASDFASDFADSF");
108     assertTrue(sq.isProtein());
109     /*
110      * in situ change of sequence doesn't change hashcode :-O
111      * (sequence should not expose internal implementation)
112      */
113     for (int i = 0; i < sq.getSequence().length; i++)
114     {
115       sq.getSequence()[i] = "acgtu".charAt(i % 5);
116     }
117     assertTrue(sq.isProtein()); // but it isn't
118   }
119
120   @Test(groups = { "Functional" })
121   public void testGetAnnotation()
122   {
123     // initial state returns null not an empty array
124     assertNull(seq.getAnnotation());
125     AlignmentAnnotation ann = addAnnotation("label1", "desc1", "calcId1",
126             1f);
127     AlignmentAnnotation[] anns = seq.getAnnotation();
128     assertEquals(1, anns.length);
129     assertSame(ann, anns[0]);
130
131     // removing all annotations reverts array to null
132     seq.removeAlignmentAnnotation(ann);
133     assertNull(seq.getAnnotation());
134   }
135
136   @Test(groups = { "Functional" })
137   public void testGetAnnotation_forLabel()
138   {
139     AlignmentAnnotation ann1 = addAnnotation("label1", "desc1", "calcId1",
140             1f);
141     addAnnotation("label2", "desc2", "calcId2", 1f);
142     AlignmentAnnotation ann3 = addAnnotation("label1", "desc3", "calcId3",
143             1f);
144     AlignmentAnnotation[] anns = seq.getAnnotation("label1");
145     assertEquals(2, anns.length);
146     assertSame(ann1, anns[0]);
147     assertSame(ann3, anns[1]);
148   }
149
150   private AlignmentAnnotation addAnnotation(String label,
151           String description, String calcId, float value)
152   {
153     final AlignmentAnnotation annotation = new AlignmentAnnotation(label,
154             description, value);
155     annotation.setCalcId(calcId);
156     seq.addAlignmentAnnotation(annotation);
157     return annotation;
158   }
159
160   @Test(groups = { "Functional" })
161   public void testGetAlignmentAnnotations_forCalcIdAndLabel()
162   {
163     addAnnotation("label1", "desc1", "calcId1", 1f);
164     AlignmentAnnotation ann2 = addAnnotation("label2", "desc2", "calcId2",
165             1f);
166     addAnnotation("label2", "desc3", "calcId3", 1f);
167     AlignmentAnnotation ann4 = addAnnotation("label2", "desc3", "calcId2",
168             1f);
169     addAnnotation("label5", "desc3", null, 1f);
170     addAnnotation(null, "desc3", "calcId3", 1f);
171
172     List<AlignmentAnnotation> anns = seq.getAlignmentAnnotations("calcId2",
173             "label2");
174     assertEquals(2, anns.size());
175     assertSame(ann2, anns.get(0));
176     assertSame(ann4, anns.get(1));
177
178     assertTrue(seq.getAlignmentAnnotations("calcId2", "label3").isEmpty());
179     assertTrue(seq.getAlignmentAnnotations("calcId3", "label5").isEmpty());
180     assertTrue(seq.getAlignmentAnnotations("calcId2", null).isEmpty());
181     assertTrue(seq.getAlignmentAnnotations(null, "label3").isEmpty());
182     assertTrue(seq.getAlignmentAnnotations(null, null).isEmpty());
183   }
184
185   /**
186    * Tests for addAlignmentAnnotation. Note this method has the side-effect of
187    * setting the sequenceRef on the annotation. Adding the same annotation twice
188    * should be ignored.
189    */
190   @Test(groups = { "Functional" })
191   public void testAddAlignmentAnnotation()
192   {
193     assertNull(seq.getAnnotation());
194     final AlignmentAnnotation annotation = new AlignmentAnnotation("a",
195             "b", 2d);
196     assertNull(annotation.sequenceRef);
197     seq.addAlignmentAnnotation(annotation);
198     assertSame(seq, annotation.sequenceRef);
199     AlignmentAnnotation[] anns = seq.getAnnotation();
200     assertEquals(1, anns.length);
201     assertSame(annotation, anns[0]);
202
203     // re-adding does nothing
204     seq.addAlignmentAnnotation(annotation);
205     anns = seq.getAnnotation();
206     assertEquals(1, anns.length);
207     assertSame(annotation, anns[0]);
208
209     // an identical but different annotation can be added
210     final AlignmentAnnotation annotation2 = new AlignmentAnnotation("a",
211             "b", 2d);
212     seq.addAlignmentAnnotation(annotation2);
213     anns = seq.getAnnotation();
214     assertEquals(2, anns.length);
215     assertSame(annotation, anns[0]);
216     assertSame(annotation2, anns[1]);
217   }
218
219   @Test(groups = { "Functional" })
220   public void testGetStartGetEnd()
221   {
222     SequenceI sq = new Sequence("test", "ABCDEF");
223     assertEquals(1, sq.getStart());
224     assertEquals(6, sq.getEnd());
225
226     sq = new Sequence("test", "--AB-C-DEF--");
227     assertEquals(1, sq.getStart());
228     assertEquals(6, sq.getEnd());
229
230     sq = new Sequence("test", "----");
231     assertEquals(1, sq.getStart());
232     assertEquals(0, sq.getEnd()); // ??
233   }
234
235   /**
236    * Tests for the method that returns an alignment column position (base 1) for
237    * a given sequence position (base 1).
238    */
239   @Test(groups = { "Functional" })
240   public void testFindIndex()
241   {
242     /* 
243      * call sequenceChanged() after each test to invalidate any cursor,
244      * forcing the 1-arg findIndex to be executed
245      */
246     SequenceI sq = new Sequence("test", "ABCDEF");
247     assertEquals(0, sq.findIndex(0));
248     sq.sequenceChanged();
249     assertEquals(1, sq.findIndex(1));
250     sq.sequenceChanged();
251     assertEquals(5, sq.findIndex(5));
252     sq.sequenceChanged();
253     assertEquals(6, sq.findIndex(6));
254     sq.sequenceChanged();
255     assertEquals(6, sq.findIndex(9));
256
257     sq = new Sequence("test/8-13", "-A--B-C-D-E-F--");
258     assertEquals(2, sq.findIndex(8));
259     sq.sequenceChanged();
260     assertEquals(5, sq.findIndex(9));
261     sq.sequenceChanged();
262     assertEquals(7, sq.findIndex(10));
263
264     // before start returns 0
265     sq.sequenceChanged();
266     assertEquals(0, sq.findIndex(0));
267     sq.sequenceChanged();
268     assertEquals(0, sq.findIndex(-1));
269
270     // beyond end returns last residue column
271     sq.sequenceChanged();
272     assertEquals(13, sq.findIndex(99));
273   }
274
275   /**
276    * Tests for the method that returns a dataset sequence position (start..) for
277    * an aligned column position (base 0).
278    */
279   @Test(groups = { "Functional" })
280   public void testFindPosition()
281   {
282     /* 
283      * call sequenceChanged() after each test to invalidate any cursor,
284      * forcing the 1-arg findPosition to be executed
285      */
286     SequenceI sq = new Sequence("test/8-13", "ABCDEF");
287     assertEquals(8, sq.findPosition(0));
288     // Sequence should now hold a cursor at [8, 0]
289     SequenceCursor cursor = (SequenceCursor) PA.getValue(sq, "cursor");
290     int token = (int) PA.getValue(sq, "changeCount");
291     assertEquals(new SequenceCursor(sq, 8, 1, token), cursor);
292
293     sq.sequenceChanged();
294
295     /*
296      * find F13 at column offset 5, cursor should update to [13, 6]
297      */
298     assertEquals(13, sq.findPosition(5));
299     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
300     assertEquals(++token, (int) PA.getValue(sq, "changeCount"));
301     assertEquals(new SequenceCursor(sq, 13, 6, token), cursor);
302
303     // assertEquals(-1, seq.findPosition(6)); // fails
304
305     sq = new Sequence("test/8-11", "AB-C-D--");
306     token = (int) PA.getValue(sq, "changeCount"); // 0
307     assertEquals(8, sq.findPosition(0));
308     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
309     assertEquals(new SequenceCursor(sq, 8, 1, token), cursor);
310
311     sq.sequenceChanged();
312     assertEquals(9, sq.findPosition(1));
313     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
314     assertEquals(new SequenceCursor(sq, 9, 2, ++token), cursor);
315
316     sq.sequenceChanged();
317     // gap position 'finds' residue to the right (not the left as per javadoc)
318     // cursor is set to the last residue position found [B 2]
319     assertEquals(10, sq.findPosition(2));
320     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
321     assertEquals(new SequenceCursor(sq, 9, 2, ++token), cursor);
322
323     sq.sequenceChanged();
324     assertEquals(10, sq.findPosition(3));
325     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
326     assertEquals(new SequenceCursor(sq, 10, 4, ++token), cursor);
327
328     sq.sequenceChanged();
329     // column[4] is the gap after C - returns D11
330     // cursor is set to [C 4]
331     assertEquals(11, sq.findPosition(4));
332     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
333     assertEquals(new SequenceCursor(sq, 10, 4, ++token), cursor);
334
335     sq.sequenceChanged();
336     assertEquals(11, sq.findPosition(5)); // D
337     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
338     assertEquals(new SequenceCursor(sq, 11, 6, ++token), cursor);
339
340     sq.sequenceChanged();
341     // returns 1 more than sequence length if off the end ?!?
342     assertEquals(12, sq.findPosition(6));
343
344     sq.sequenceChanged();
345     assertEquals(12, sq.findPosition(7));
346
347     sq = new Sequence("test/8-13", "--AB-C-DEF--");
348     assertEquals(8, sq.findPosition(0));
349
350     sq.sequenceChanged();
351     assertEquals(8, sq.findPosition(1));
352
353     sq.sequenceChanged();
354     assertEquals(8, sq.findPosition(2));
355
356     sq.sequenceChanged();
357     assertEquals(9, sq.findPosition(3));
358
359     sq.sequenceChanged();
360     assertEquals(10, sq.findPosition(4));
361
362     sq.sequenceChanged();
363     assertEquals(10, sq.findPosition(5));
364
365     sq.sequenceChanged();
366     assertEquals(11, sq.findPosition(6));
367
368     sq.sequenceChanged();
369     assertEquals(11, sq.findPosition(7));
370
371     sq.sequenceChanged();
372     assertEquals(12, sq.findPosition(8));
373
374     sq.sequenceChanged();
375     assertEquals(13, sq.findPosition(9));
376
377     sq.sequenceChanged();
378     assertEquals(14, sq.findPosition(10));
379
380     /*
381      * findPosition for column beyond sequence length
382      * returns 1 more than last residue position
383      */
384     sq.sequenceChanged();
385     assertEquals(14, sq.findPosition(11));
386     sq.sequenceChanged();
387     assertEquals(14, sq.findPosition(99));
388   }
389
390   @Test(groups = { "Functional" })
391   public void testDeleteChars()
392   {
393     /*
394      * internal delete
395      */
396     SequenceI sq = new Sequence("test", "ABCDEF");
397     assertNull(PA.getValue(sq, "datasetSequence"));
398     assertEquals(1, sq.getStart());
399     assertEquals(6, sq.getEnd());
400     sq.deleteChars(2, 3);
401     assertEquals("ABDEF", sq.getSequenceAsString());
402     assertEquals(1, sq.getStart());
403     assertEquals(5, sq.getEnd());
404     assertNull(PA.getValue(sq, "datasetSequence"));
405
406     /*
407      * delete at start
408      */
409     sq = new Sequence("test", "ABCDEF");
410     sq.deleteChars(0, 2);
411     assertEquals("CDEF", sq.getSequenceAsString());
412     assertEquals(3, sq.getStart());
413     assertEquals(6, sq.getEnd());
414     assertNull(PA.getValue(sq, "datasetSequence"));
415
416     /*
417      * delete at end
418      */
419     sq = new Sequence("test", "ABCDEF");
420     sq.deleteChars(4, 6);
421     assertEquals("ABCD", sq.getSequenceAsString());
422     assertEquals(1, sq.getStart());
423     assertEquals(4, sq.getEnd());
424     assertNull(PA.getValue(sq, "datasetSequence"));
425   }
426
427   @Test(groups = { "Functional" })
428   public void testDeleteChars_withDbRefsAndFeatures()
429   {
430     /*
431      * internal delete - new dataset sequence created
432      * gets a copy of any dbrefs
433      */
434     SequenceI sq = new Sequence("test", "ABCDEF");
435     sq.createDatasetSequence();
436     DBRefEntry dbr1 = new DBRefEntry("Uniprot", "0", "a123");
437     sq.addDBRef(dbr1);
438     Object ds = PA.getValue(sq, "datasetSequence");
439     assertNotNull(ds);
440     assertEquals(1, sq.getStart());
441     assertEquals(6, sq.getEnd());
442     sq.deleteChars(2, 3);
443     assertEquals("ABDEF", sq.getSequenceAsString());
444     assertEquals(1, sq.getStart());
445     assertEquals(5, sq.getEnd());
446     Object newDs = PA.getValue(sq, "datasetSequence");
447     assertNotNull(newDs);
448     assertNotSame(ds, newDs);
449     assertNotNull(sq.getDBRefs());
450     assertEquals(1, sq.getDBRefs().length);
451     assertNotSame(dbr1, sq.getDBRefs()[0]);
452     assertEquals(dbr1, sq.getDBRefs()[0]);
453
454     /*
455      * internal delete with sequence features
456      * (failure case for JAL-2541)
457      */
458     sq = new Sequence("test", "ABCDEF");
459     sq.createDatasetSequence();
460     SequenceFeature sf1 = new SequenceFeature("Cath", "desc", 2, 4, 2f,
461             "CathGroup");
462     sq.addSequenceFeature(sf1);
463     ds = PA.getValue(sq, "datasetSequence");
464     assertNotNull(ds);
465     assertEquals(1, sq.getStart());
466     assertEquals(6, sq.getEnd());
467     sq.deleteChars(2, 4);
468     assertEquals("ABEF", sq.getSequenceAsString());
469     assertEquals(1, sq.getStart());
470     assertEquals(4, sq.getEnd());
471     newDs = PA.getValue(sq, "datasetSequence");
472     assertNotNull(newDs);
473     assertNotSame(ds, newDs);
474     List<SequenceFeature> sfs = sq.getSequenceFeatures();
475     assertEquals(1, sfs.size());
476     assertNotSame(sf1, sfs.get(0));
477     assertEquals(sf1, sfs.get(0));
478
479     /*
480      * delete at start - no new dataset sequence created
481      * any sequence features remain as before
482      */
483     sq = new Sequence("test", "ABCDEF");
484     sq.createDatasetSequence();
485     ds = PA.getValue(sq, "datasetSequence");
486     sf1 = new SequenceFeature("Cath", "desc", 2, 4, 2f, "CathGroup");
487     sq.addSequenceFeature(sf1);
488     sq.deleteChars(0, 2);
489     assertEquals("CDEF", sq.getSequenceAsString());
490     assertEquals(3, sq.getStart());
491     assertEquals(6, sq.getEnd());
492     assertSame(ds, PA.getValue(sq, "datasetSequence"));
493     sfs = sq.getSequenceFeatures();
494     assertNotNull(sfs);
495     assertEquals(1, sfs.size());
496     assertSame(sf1, sfs.get(0));
497
498     /*
499      * delete at end - no new dataset sequence created
500      * any dbrefs remain as before
501      */
502     sq = new Sequence("test", "ABCDEF");
503     sq.createDatasetSequence();
504     ds = PA.getValue(sq, "datasetSequence");
505     dbr1 = new DBRefEntry("Uniprot", "0", "a123");
506     sq.addDBRef(dbr1);
507     sq.deleteChars(4, 6);
508     assertEquals("ABCD", sq.getSequenceAsString());
509     assertEquals(1, sq.getStart());
510     assertEquals(4, sq.getEnd());
511     assertSame(ds, PA.getValue(sq, "datasetSequence"));
512     assertNotNull(sq.getDBRefs());
513     assertEquals(1, sq.getDBRefs().length);
514     assertSame(dbr1, sq.getDBRefs()[0]);
515   }
516
517   @Test(groups = { "Functional" })
518   public void testInsertCharAt()
519   {
520     // non-static methods:
521     SequenceI sq = new Sequence("test", "ABCDEF");
522     sq.insertCharAt(0, 'z');
523     assertEquals("zABCDEF", sq.getSequenceAsString());
524     sq.insertCharAt(2, 2, 'x');
525     assertEquals("zAxxBCDEF", sq.getSequenceAsString());
526
527     // for static method see StringUtilsTest
528   }
529
530   /**
531    * Test the method that returns an array of aligned sequence positions where
532    * the array index is the data sequence position (both base 0).
533    */
534   @Test(groups = { "Functional" })
535   public void testGapMap()
536   {
537     SequenceI sq = new Sequence("test", "-A--B-CD-E--F-");
538     sq.createDatasetSequence();
539     assertEquals("[1, 4, 6, 7, 9, 12]", Arrays.toString(sq.gapMap()));
540   }
541
542   /**
543    * Test the method that gets sequence features, either from the sequence or
544    * its dataset.
545    */
546   @Test(groups = { "Functional" })
547   public void testGetSequenceFeatures()
548   {
549     SequenceI sq = new Sequence("test", "GATCAT");
550     sq.createDatasetSequence();
551
552     assertTrue(sq.getSequenceFeatures().isEmpty());
553
554     /*
555      * SequenceFeature on sequence
556      */
557     SequenceFeature sf = new SequenceFeature("Cath", "desc", 2, 4, 2f, null);
558     sq.addSequenceFeature(sf);
559     List<SequenceFeature> sfs = sq.getSequenceFeatures();
560     assertEquals(1, sfs.size());
561     assertSame(sf, sfs.get(0));
562
563     /*
564      * SequenceFeature on sequence and dataset sequence; returns that on
565      * sequence
566      * 
567      * Note JAL-2046: spurious: we have no use case for this at the moment.
568      * This test also buggy - as sf2.equals(sf), no new feature is added
569      */
570     SequenceFeature sf2 = new SequenceFeature("Cath", "desc", 2, 4, 2f,
571             null);
572     sq.getDatasetSequence().addSequenceFeature(sf2);
573     sfs = sq.getSequenceFeatures();
574     assertEquals(1, sfs.size());
575     assertSame(sf, sfs.get(0));
576
577     /*
578      * SequenceFeature on dataset sequence only
579      * Note JAL-2046: spurious: we have no use case for setting a non-dataset sequence's feature array to null at the moment.
580      */
581     sq.setSequenceFeatures(null);
582     assertTrue(sq.getDatasetSequence().getSequenceFeatures().isEmpty());
583
584     /*
585      * Corrupt case - no SequenceFeature, dataset's dataset is the original
586      * sequence. Test shows no infinite loop results.
587      */
588     sq.getDatasetSequence().setSequenceFeatures(null);
589     /**
590      * is there a usecase for this ? setDatasetSequence should throw an error if
591      * this actually occurs.
592      */
593     try
594     {
595       sq.getDatasetSequence().setDatasetSequence(sq); // loop!
596       Assert.fail("Expected Error to be raised when calling setDatasetSequence with self reference");
597     } catch (IllegalArgumentException e)
598     {
599       // TODO Jalview error/exception class for raising implementation errors
600       assertTrue(e.getMessage().toLowerCase()
601               .contains("implementation error"));
602     }
603     assertTrue(sq.getSequenceFeatures().isEmpty());
604   }
605
606   /**
607    * Test the method that returns an array, indexed by sequence position, whose
608    * entries are the residue positions at the sequence position (or to the right
609    * if a gap)
610    */
611   @Test(groups = { "Functional" })
612   public void testFindPositionMap()
613   {
614     /*
615      * Note: Javadoc for findPosition says it returns the residue position to
616      * the left of a gapped position; in fact it returns the position to the
617      * right. Also it returns a non-existent residue position for a gap beyond
618      * the sequence.
619      */
620     Sequence sq = new Sequence("TestSeq", "AB.C-D E.");
621     int[] map = sq.findPositionMap();
622     assertEquals(Arrays.toString(new int[] { 1, 2, 3, 3, 4, 4, 5, 5, 6 }),
623             Arrays.toString(map));
624   }
625
626   /**
627    * Test for getSubsequence
628    */
629   @Test(groups = { "Functional" })
630   public void testGetSubsequence()
631   {
632     SequenceI sq = new Sequence("TestSeq", "ABCDEFG");
633     sq.createDatasetSequence();
634
635     // positions are base 0, end position is exclusive
636     SequenceI subseq = sq.getSubSequence(2, 4);
637
638     assertEquals("CD", subseq.getSequenceAsString());
639     // start/end are base 1 positions
640     assertEquals(3, subseq.getStart());
641     assertEquals(4, subseq.getEnd());
642     // subsequence shares the full dataset sequence
643     assertSame(sq.getDatasetSequence(), subseq.getDatasetSequence());
644   }
645
646   /**
647    * test createDatasetSequence behaves to doc
648    */
649   @Test(groups = { "Functional" })
650   public void testCreateDatasetSequence()
651   {
652     SequenceI sq = new Sequence("my", "ASDASD");
653     sq.addSequenceFeature(new SequenceFeature("type", "desc", 1, 10, 1f,
654             "group"));
655     sq.addDBRef(new DBRefEntry("source", "version", "accession"));
656     assertNull(sq.getDatasetSequence());
657     assertNotNull(PA.getValue(sq, "sequenceFeatureStore"));
658     assertNotNull(PA.getValue(sq, "dbrefs"));
659
660     SequenceI rds = sq.createDatasetSequence();
661     assertNotNull(rds);
662     assertNull(rds.getDatasetSequence());
663     assertSame(sq.getDatasetSequence(), rds);
664
665     // sequence features and dbrefs transferred to dataset sequence
666     assertNull(PA.getValue(sq, "sequenceFeatureStore"));
667     assertNull(PA.getValue(sq, "dbrefs"));
668     assertNotNull(PA.getValue(rds, "sequenceFeatureStore"));
669     assertNotNull(PA.getValue(rds, "dbrefs"));
670   }
671
672   /**
673    * Test for deriveSequence applied to a sequence with a dataset
674    */
675   @Test(groups = { "Functional" })
676   public void testDeriveSequence_existingDataset()
677   {
678     Sequence sq = new Sequence("Seq1", "CD");
679     sq.setDatasetSequence(new Sequence("Seq1", "ABCDEF"));
680     sq.getDatasetSequence().addSequenceFeature(
681             new SequenceFeature("", "", 1, 2, 0f, null));
682     sq.setStart(3);
683     sq.setEnd(4);
684
685     sq.setDescription("Test sequence description..");
686     sq.setVamsasId("TestVamsasId");
687     sq.addDBRef(new DBRefEntry("PDB", "version0", "1TST"));
688
689     sq.addDBRef(new DBRefEntry("PDB", "version1", "1PDB"));
690     sq.addDBRef(new DBRefEntry("PDB", "version2", "2PDB"));
691     sq.addDBRef(new DBRefEntry("PDB", "version3", "3PDB"));
692     sq.addDBRef(new DBRefEntry("PDB", "version4", "4PDB"));
693
694     sq.addPDBId(new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1"));
695     sq.addPDBId(new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1"));
696     sq.addPDBId(new PDBEntry("2PDB", "A", Type.MMCIF, "filePath/test2"));
697     sq.addPDBId(new PDBEntry("2PDB", "B", Type.MMCIF, "filePath/test2"));
698
699     // these are the same as ones already added
700     DBRefEntry pdb1pdb = new DBRefEntry("PDB", "version1", "1PDB");
701     DBRefEntry pdb2pdb = new DBRefEntry("PDB", "version2", "2PDB");
702
703     List<DBRefEntry> primRefs = Arrays.asList(new DBRefEntry[] { pdb1pdb,
704         pdb2pdb });
705
706     sq.getDatasetSequence().addDBRef(pdb1pdb); // should do nothing
707     sq.getDatasetSequence().addDBRef(pdb2pdb); // should do nothing
708     sq.getDatasetSequence().addDBRef(
709             new DBRefEntry("PDB", "version3", "3PDB")); // should do nothing
710     sq.getDatasetSequence().addDBRef(
711             new DBRefEntry("PDB", "version4", "4PDB")); // should do nothing
712
713     PDBEntry pdbe1a = new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1");
714     PDBEntry pdbe1b = new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1");
715     PDBEntry pdbe2a = new PDBEntry("2PDB", "A", Type.MMCIF,
716             "filePath/test2");
717     PDBEntry pdbe2b = new PDBEntry("2PDB", "B", Type.MMCIF,
718             "filePath/test2");
719     sq.getDatasetSequence().addPDBId(pdbe1a);
720     sq.getDatasetSequence().addPDBId(pdbe1b);
721     sq.getDatasetSequence().addPDBId(pdbe2a);
722     sq.getDatasetSequence().addPDBId(pdbe2b);
723
724     /*
725      * test we added pdb entries to the dataset sequence
726      */
727     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries(), Arrays
728             .asList(new PDBEntry[] { pdbe1a, pdbe1b, pdbe2a, pdbe2b }),
729             "PDB Entries were not found on dataset sequence.");
730
731     /*
732      * we should recover a pdb entry that is on the dataset sequence via PDBEntry
733      */
734     Assert.assertEquals(pdbe1a,
735             sq.getDatasetSequence().getPDBEntry("1PDB"),
736             "PDB Entry '1PDB' not found on dataset sequence via getPDBEntry.");
737     ArrayList<Annotation> annotsList = new ArrayList<Annotation>();
738     System.out.println(">>>>>> " + sq.getSequenceAsString().length());
739     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
740     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
741     Annotation[] annots = annotsList.toArray(new Annotation[0]);
742     sq.addAlignmentAnnotation(new AlignmentAnnotation("Test annot",
743             "Test annot description", annots));
744     sq.getDatasetSequence().addAlignmentAnnotation(
745             new AlignmentAnnotation("Test annot", "Test annot description",
746                     annots));
747     Assert.assertEquals(sq.getDescription(), "Test sequence description..");
748     Assert.assertEquals(sq.getDBRefs().length, 5); // DBRefs are on dataset
749                                                    // sequence
750     Assert.assertEquals(sq.getAllPDBEntries().size(), 4);
751     Assert.assertNotNull(sq.getAnnotation());
752     Assert.assertEquals(sq.getAnnotation()[0].annotations.length, 2);
753     Assert.assertEquals(sq.getDatasetSequence().getDBRefs().length, 5); // same
754                                                                         // as
755                                                                         // sq.getDBRefs()
756     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries().size(),
757             4);
758     Assert.assertNotNull(sq.getDatasetSequence().getAnnotation());
759
760     Sequence derived = (Sequence) sq.deriveSequence();
761
762     Assert.assertEquals(derived.getDescription(),
763             "Test sequence description..");
764     Assert.assertEquals(derived.getDBRefs().length, 5); // come from dataset
765     Assert.assertEquals(derived.getAllPDBEntries().size(), 4);
766     Assert.assertNotNull(derived.getAnnotation());
767     Assert.assertEquals(derived.getAnnotation()[0].annotations.length, 2);
768     Assert.assertEquals(derived.getDatasetSequence().getDBRefs().length, 5);
769     Assert.assertEquals(derived.getDatasetSequence().getAllPDBEntries()
770             .size(), 4);
771     Assert.assertNotNull(derived.getDatasetSequence().getAnnotation());
772
773     assertEquals("CD", derived.getSequenceAsString());
774     assertSame(sq.getDatasetSequence(), derived.getDatasetSequence());
775
776     // derived sequence should access dataset sequence features
777     assertNotNull(sq.getSequenceFeatures());
778     assertEquals(sq.getSequenceFeatures(), derived.getSequenceFeatures());
779
780     /*
781      *  verify we have primary db refs *just* for PDB IDs with associated
782      *  PDBEntry objects
783      */
784
785     assertEquals(primRefs, sq.getPrimaryDBRefs());
786     assertEquals(primRefs, sq.getDatasetSequence().getPrimaryDBRefs());
787
788     assertEquals(sq.getPrimaryDBRefs(), derived.getPrimaryDBRefs());
789
790   }
791
792   /**
793    * Test for deriveSequence applied to an ungapped sequence with no dataset
794    */
795   @Test(groups = { "Functional" })
796   public void testDeriveSequence_noDatasetUngapped()
797   {
798     SequenceI sq = new Sequence("Seq1", "ABCDEF");
799     assertEquals(1, sq.getStart());
800     assertEquals(6, sq.getEnd());
801     SequenceI derived = sq.deriveSequence();
802     assertEquals("ABCDEF", derived.getSequenceAsString());
803     assertEquals("ABCDEF", derived.getDatasetSequence()
804             .getSequenceAsString());
805   }
806
807   /**
808    * Test for deriveSequence applied to a gapped sequence with no dataset
809    */
810   @Test(groups = { "Functional" })
811   public void testDeriveSequence_noDatasetGapped()
812   {
813     SequenceI sq = new Sequence("Seq1", "AB-C.D EF");
814     assertEquals(1, sq.getStart());
815     assertEquals(6, sq.getEnd());
816     assertNull(sq.getDatasetSequence());
817     SequenceI derived = sq.deriveSequence();
818     assertEquals("AB-C.D EF", derived.getSequenceAsString());
819     assertEquals("ABCDEF", derived.getDatasetSequence()
820             .getSequenceAsString());
821   }
822
823   @Test(groups = { "Functional" })
824   public void testCopyConstructor_noDataset()
825   {
826     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
827     seq1.setDescription("description");
828     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
829             1.3d));
830     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
831             12.4f, "group"));
832     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
833     seq1.addDBRef(new DBRefEntry("EMBL", "1.2", "AZ12345"));
834
835     SequenceI copy = new Sequence(seq1);
836
837     assertNull(copy.getDatasetSequence());
838
839     verifyCopiedSequence(seq1, copy);
840
841     // copy has a copy of the DBRefEntry
842     // this is murky - DBrefs are only copied for dataset sequences
843     // where the test for 'dataset sequence' is 'dataset is null'
844     // but that doesn't distinguish it from an aligned sequence
845     // which has not yet generated a dataset sequence
846     // NB getDBRef looks inside dataset sequence if not null
847     DBRefEntry[] dbrefs = copy.getDBRefs();
848     assertEquals(1, dbrefs.length);
849     assertFalse(dbrefs[0] == seq1.getDBRefs()[0]);
850     assertTrue(dbrefs[0].equals(seq1.getDBRefs()[0]));
851   }
852
853   @Test(groups = { "Functional" })
854   public void testCopyConstructor_withDataset()
855   {
856     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
857     seq1.createDatasetSequence();
858     seq1.setDescription("description");
859     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
860             1.3d));
861     // JAL-2046 - what is the contract for using a derived sequence's
862     // addSequenceFeature ?
863     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
864             12.4f, "group"));
865     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
866     // here we add DBRef to the dataset sequence:
867     seq1.getDatasetSequence().addDBRef(
868             new DBRefEntry("EMBL", "1.2", "AZ12345"));
869
870     SequenceI copy = new Sequence(seq1);
871
872     assertNotNull(copy.getDatasetSequence());
873     assertSame(copy.getDatasetSequence(), seq1.getDatasetSequence());
874
875     verifyCopiedSequence(seq1, copy);
876
877     // getDBRef looks inside dataset sequence and this is shared,
878     // so holds the same dbref objects
879     DBRefEntry[] dbrefs = copy.getDBRefs();
880     assertEquals(1, dbrefs.length);
881     assertSame(dbrefs[0], seq1.getDBRefs()[0]);
882   }
883
884   /**
885    * Helper to make assertions about a copied sequence
886    * 
887    * @param seq1
888    * @param copy
889    */
890   protected void verifyCopiedSequence(SequenceI seq1, SequenceI copy)
891   {
892     // verify basic properties:
893     assertEquals(copy.getName(), seq1.getName());
894     assertEquals(copy.getDescription(), seq1.getDescription());
895     assertEquals(copy.getStart(), seq1.getStart());
896     assertEquals(copy.getEnd(), seq1.getEnd());
897     assertEquals(copy.getSequenceAsString(), seq1.getSequenceAsString());
898
899     // copy has a copy of the annotation:
900     AlignmentAnnotation[] anns = copy.getAnnotation();
901     assertEquals(1, anns.length);
902     assertFalse(anns[0] == seq1.getAnnotation()[0]);
903     assertEquals(anns[0].label, seq1.getAnnotation()[0].label);
904     assertEquals(anns[0].description, seq1.getAnnotation()[0].description);
905     assertEquals(anns[0].score, seq1.getAnnotation()[0].score);
906
907     // copy has a copy of the sequence feature:
908     List<SequenceFeature> sfs = copy.getSequenceFeatures();
909     assertEquals(1, sfs.size());
910     if (seq1.getDatasetSequence() != null
911             && copy.getDatasetSequence() == seq1.getDatasetSequence())
912     {
913       assertSame(sfs.get(0), seq1.getSequenceFeatures().get(0));
914     }
915     else
916     {
917       assertNotSame(sfs.get(0), seq1.getSequenceFeatures().get(0));
918     }
919     assertEquals(sfs.get(0), seq1.getSequenceFeatures().get(0));
920
921     // copy has a copy of the PDB entry
922     Vector<PDBEntry> pdbs = copy.getAllPDBEntries();
923     assertEquals(1, pdbs.size());
924     assertFalse(pdbs.get(0) == seq1.getAllPDBEntries().get(0));
925     assertTrue(pdbs.get(0).equals(seq1.getAllPDBEntries().get(0)));
926   }
927
928   @Test(groups = "Functional")
929   public void testGetCharAt()
930   {
931     SequenceI sq = new Sequence("", "abcde");
932     assertEquals('a', sq.getCharAt(0));
933     assertEquals('e', sq.getCharAt(4));
934     assertEquals(' ', sq.getCharAt(5));
935     assertEquals(' ', sq.getCharAt(-1));
936   }
937
938   @Test(groups = { "Functional" })
939   public void testAddSequenceFeatures()
940   {
941     SequenceI sq = new Sequence("", "abcde");
942     // type may not be null
943     assertFalse(sq.addSequenceFeature(new SequenceFeature(null, "desc", 4,
944             8, 0f, null)));
945     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
946             8, 0f, null)));
947     // can't add a duplicate feature
948     assertFalse(sq.addSequenceFeature(new SequenceFeature("Cath", "desc",
949             4, 8, 0f, null)));
950     // can add a different feature
951     assertTrue(sq.addSequenceFeature(new SequenceFeature("Scop", "desc", 4,
952             8, 0f, null))); // different type
953     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath",
954             "description", 4, 8, 0f, null)));// different description
955     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 3,
956             8, 0f, null))); // different start position
957     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
958             9, 0f, null))); // different end position
959     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
960             8, 1f, null))); // different score
961     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
962             8, Float.NaN, null))); // score NaN
963     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
964             8, 0f, "Metal"))); // different group
965     assertEquals(8, sq.getFeatures().getAllFeatures().size());
966   }
967
968   /**
969    * Tests for adding (or updating) dbrefs
970    * 
971    * @see DBRefEntry#updateFrom(DBRefEntry)
972    */
973   @Test(groups = { "Functional" })
974   public void testAddDBRef()
975   {
976     SequenceI sq = new Sequence("", "abcde");
977     assertNull(sq.getDBRefs());
978     DBRefEntry dbref = new DBRefEntry("Uniprot", "1", "P00340");
979     sq.addDBRef(dbref);
980     assertEquals(1, sq.getDBRefs().length);
981     assertSame(dbref, sq.getDBRefs()[0]);
982
983     /*
984      * change of version - new entry
985      */
986     DBRefEntry dbref2 = new DBRefEntry("Uniprot", "2", "P00340");
987     sq.addDBRef(dbref2);
988     assertEquals(2, sq.getDBRefs().length);
989     assertSame(dbref, sq.getDBRefs()[0]);
990     assertSame(dbref2, sq.getDBRefs()[1]);
991
992     /*
993      * matches existing entry - not added
994      */
995     sq.addDBRef(new DBRefEntry("UNIPROT", "1", "p00340"));
996     assertEquals(2, sq.getDBRefs().length);
997
998     /*
999      * different source = new entry
1000      */
1001     DBRefEntry dbref3 = new DBRefEntry("UniRef", "1", "p00340");
1002     sq.addDBRef(dbref3);
1003     assertEquals(3, sq.getDBRefs().length);
1004     assertSame(dbref3, sq.getDBRefs()[2]);
1005
1006     /*
1007      * different ref = new entry
1008      */
1009     DBRefEntry dbref4 = new DBRefEntry("UniRef", "1", "p00341");
1010     sq.addDBRef(dbref4);
1011     assertEquals(4, sq.getDBRefs().length);
1012     assertSame(dbref4, sq.getDBRefs()[3]);
1013
1014     /*
1015      * matching ref with a mapping - map updated
1016      */
1017     DBRefEntry dbref5 = new DBRefEntry("UniRef", "1", "p00341");
1018     Mapping map = new Mapping(new MapList(new int[] { 1, 3 }, new int[] {
1019         1, 1 }, 3, 1));
1020     dbref5.setMap(map);
1021     sq.addDBRef(dbref5);
1022     assertEquals(4, sq.getDBRefs().length);
1023     assertSame(dbref4, sq.getDBRefs()[3]);
1024     assertSame(map, dbref4.getMap());
1025
1026     /*
1027      * 'real' version replaces "0" version
1028      */
1029     dbref2.setVersion("0");
1030     DBRefEntry dbref6 = new DBRefEntry(dbref2.getSource(), "3",
1031             dbref2.getAccessionId());
1032     sq.addDBRef(dbref6);
1033     assertEquals(4, sq.getDBRefs().length);
1034     assertSame(dbref2, sq.getDBRefs()[1]);
1035     assertEquals("3", dbref2.getVersion());
1036
1037     /*
1038      * 'real' version replaces "source:0" version
1039      */
1040     dbref3.setVersion("Uniprot:0");
1041     DBRefEntry dbref7 = new DBRefEntry(dbref3.getSource(), "3",
1042             dbref3.getAccessionId());
1043     sq.addDBRef(dbref7);
1044     assertEquals(4, sq.getDBRefs().length);
1045     assertSame(dbref3, sq.getDBRefs()[2]);
1046     assertEquals("3", dbref2.getVersion());
1047   }
1048
1049   @Test(groups = { "Functional" })
1050   public void testGetPrimaryDBRefs_peptide()
1051   {
1052     SequenceI sq = new Sequence("aseq", "ASDFKYLMQPRST", 10, 22);
1053
1054     // no dbrefs
1055     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
1056     assertTrue(primaryDBRefs.isEmpty());
1057
1058     // empty dbrefs
1059     sq.setDBRefs(new DBRefEntry[] {});
1060     primaryDBRefs = sq.getPrimaryDBRefs();
1061     assertTrue(primaryDBRefs.isEmpty());
1062
1063     // primary - uniprot
1064     DBRefEntry upentry1 = new DBRefEntry("UNIPROT", "0", "Q04760");
1065     sq.addDBRef(upentry1);
1066
1067     // primary - uniprot with congruent map
1068     DBRefEntry upentry2 = new DBRefEntry("UNIPROT", "0", "Q04762");
1069     upentry2.setMap(new Mapping(null, new MapList(new int[] { 10, 22 },
1070             new int[] { 10, 22 }, 1, 1)));
1071     sq.addDBRef(upentry2);
1072
1073     // primary - uniprot with map of enclosing sequence
1074     DBRefEntry upentry3 = new DBRefEntry("UNIPROT", "0", "Q04763");
1075     upentry3.setMap(new Mapping(null, new MapList(new int[] { 8, 24 },
1076             new int[] { 8, 24 }, 1, 1)));
1077     sq.addDBRef(upentry3);
1078
1079     // not primary - uniprot with map of sub-sequence (5')
1080     DBRefEntry upentry4 = new DBRefEntry("UNIPROT", "0", "Q04764");
1081     upentry4.setMap(new Mapping(null, new MapList(new int[] { 10, 18 },
1082             new int[] { 10, 18 }, 1, 1)));
1083     sq.addDBRef(upentry4);
1084
1085     // not primary - uniprot with map that overlaps 3'
1086     DBRefEntry upentry5 = new DBRefEntry("UNIPROT", "0", "Q04765");
1087     upentry5.setMap(new Mapping(null, new MapList(new int[] { 12, 22 },
1088             new int[] { 12, 22 }, 1, 1)));
1089     sq.addDBRef(upentry5);
1090
1091     // not primary - uniprot with map to different coordinates frame
1092     DBRefEntry upentry6 = new DBRefEntry("UNIPROT", "0", "Q04766");
1093     upentry6.setMap(new Mapping(null, new MapList(new int[] { 12, 18 },
1094             new int[] { 112, 118 }, 1, 1)));
1095     sq.addDBRef(upentry6);
1096
1097     // not primary - dbref to 'non-core' database
1098     DBRefEntry upentry7 = new DBRefEntry("Pfam", "0", "PF00903");
1099     sq.addDBRef(upentry7);
1100
1101     // primary - type is PDB
1102     DBRefEntry pdbentry = new DBRefEntry("PDB", "0", "1qip");
1103     sq.addDBRef(pdbentry);
1104
1105     // not primary - PDBEntry has no file
1106     sq.addDBRef(new DBRefEntry("PDB", "0", "1AAA"));
1107
1108     // not primary - no PDBEntry
1109     sq.addDBRef(new DBRefEntry("PDB", "0", "1DDD"));
1110
1111     // add corroborating PDB entry for primary DBref -
1112     // needs to have a file as well as matching ID
1113     // note PDB ID is not treated as case sensitive
1114     sq.addPDBId(new PDBEntry("1QIP", null, Type.PDB, new File("/blah")
1115             .toString()));
1116
1117     // not valid DBRef - no file..
1118     sq.addPDBId(new PDBEntry("1AAA", null, null, null));
1119
1120     primaryDBRefs = sq.getPrimaryDBRefs();
1121     assertEquals(4, primaryDBRefs.size());
1122     assertTrue("Couldn't find simple primary reference (UNIPROT)",
1123             primaryDBRefs.contains(upentry1));
1124     assertTrue("Couldn't find mapped primary reference (UNIPROT)",
1125             primaryDBRefs.contains(upentry2));
1126     assertTrue("Couldn't find mapped context reference (UNIPROT)",
1127             primaryDBRefs.contains(upentry3));
1128     assertTrue("Couldn't find expected PDB primary reference",
1129             primaryDBRefs.contains(pdbentry));
1130   }
1131
1132   @Test(groups = { "Functional" })
1133   public void testGetPrimaryDBRefs_nucleotide()
1134   {
1135     SequenceI sq = new Sequence("aseq", "TGATCACTCGACTAGCATCAGCATA", 10, 34);
1136
1137     // primary - Ensembl
1138     DBRefEntry dbr1 = new DBRefEntry("ENSEMBL", "0", "ENSG1234");
1139     sq.addDBRef(dbr1);
1140
1141     // not primary - Ensembl 'transcript' mapping of sub-sequence
1142     DBRefEntry dbr2 = new DBRefEntry("ENSEMBL", "0", "ENST1234");
1143     dbr2.setMap(new Mapping(null, new MapList(new int[] { 15, 25 },
1144             new int[] { 1, 11 }, 1, 1)));
1145     sq.addDBRef(dbr2);
1146
1147     // primary - EMBL with congruent map
1148     DBRefEntry dbr3 = new DBRefEntry("EMBL", "0", "J1234");
1149     dbr3.setMap(new Mapping(null, new MapList(new int[] { 10, 34 },
1150             new int[] { 10, 34 }, 1, 1)));
1151     sq.addDBRef(dbr3);
1152
1153     // not primary - to non-core database
1154     DBRefEntry dbr4 = new DBRefEntry("CCDS", "0", "J1234");
1155     sq.addDBRef(dbr4);
1156
1157     // not primary - to protein
1158     DBRefEntry dbr5 = new DBRefEntry("UNIPROT", "0", "Q87654");
1159     sq.addDBRef(dbr5);
1160
1161     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
1162     assertEquals(2, primaryDBRefs.size());
1163     assertTrue(primaryDBRefs.contains(dbr1));
1164     assertTrue(primaryDBRefs.contains(dbr3));
1165   }
1166
1167   /**
1168    * Test the method that updates the list of PDBEntry from any new DBRefEntry
1169    * for PDB
1170    */
1171   @Test(groups = { "Functional" })
1172   public void testUpdatePDBIds()
1173   {
1174     PDBEntry pdbe1 = new PDBEntry("3A6S", null, null, null);
1175     seq.addPDBId(pdbe1);
1176     seq.addDBRef(new DBRefEntry("Ensembl", "8", "ENST1234"));
1177     seq.addDBRef(new DBRefEntry("PDB", "0", "1A70"));
1178     seq.addDBRef(new DBRefEntry("PDB", "0", "4BQGa"));
1179     seq.addDBRef(new DBRefEntry("PDB", "0", "3a6sB"));
1180     // 7 is not a valid chain code:
1181     seq.addDBRef(new DBRefEntry("PDB", "0", "2GIS7"));
1182
1183     seq.updatePDBIds();
1184     List<PDBEntry> pdbIds = seq.getAllPDBEntries();
1185     assertEquals(4, pdbIds.size());
1186     assertSame(pdbe1, pdbIds.get(0));
1187     // chain code got added to 3A6S:
1188     assertEquals("B", pdbe1.getChainCode());
1189     assertEquals("1A70", pdbIds.get(1).getId());
1190     // 4BQGA is parsed into id + chain
1191     assertEquals("4BQG", pdbIds.get(2).getId());
1192     assertEquals("a", pdbIds.get(2).getChainCode());
1193     assertEquals("2GIS7", pdbIds.get(3).getId());
1194     assertNull(pdbIds.get(3).getChainCode());
1195   }
1196
1197   /**
1198    * Test the method that either adds a pdbid or updates an existing one
1199    */
1200   @Test(groups = { "Functional" })
1201   public void testAddPDBId()
1202   {
1203     PDBEntry pdbe = new PDBEntry("3A6S", null, null, null);
1204     seq.addPDBId(pdbe);
1205     assertEquals(1, seq.getAllPDBEntries().size());
1206     assertSame(pdbe, seq.getPDBEntry("3A6S"));
1207     assertSame(pdbe, seq.getPDBEntry("3a6s")); // case-insensitive
1208
1209     // add the same entry
1210     seq.addPDBId(pdbe);
1211     assertEquals(1, seq.getAllPDBEntries().size());
1212     assertSame(pdbe, seq.getPDBEntry("3A6S"));
1213
1214     // add an identical entry
1215     seq.addPDBId(new PDBEntry("3A6S", null, null, null));
1216     assertEquals(1, seq.getAllPDBEntries().size());
1217     assertSame(pdbe, seq.getPDBEntry("3A6S"));
1218
1219     // add a different entry
1220     PDBEntry pdbe2 = new PDBEntry("1A70", null, null, null);
1221     seq.addPDBId(pdbe2);
1222     assertEquals(2, seq.getAllPDBEntries().size());
1223     assertSame(pdbe, seq.getAllPDBEntries().get(0));
1224     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
1225
1226     // update pdbe with chain code, file, type
1227     PDBEntry pdbe3 = new PDBEntry("3a6s", "A", Type.PDB, "filepath");
1228     seq.addPDBId(pdbe3);
1229     assertEquals(2, seq.getAllPDBEntries().size());
1230     assertSame(pdbe, seq.getAllPDBEntries().get(0)); // updated in situ
1231     assertEquals("3A6S", pdbe.getId()); // unchanged
1232     assertEquals("A", pdbe.getChainCode()); // updated
1233     assertEquals(Type.PDB.toString(), pdbe.getType()); // updated
1234     assertEquals("filepath", pdbe.getFile()); // updated
1235     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
1236
1237     // add with a different file path
1238     PDBEntry pdbe4 = new PDBEntry("3a6s", "A", Type.PDB, "filepath2");
1239     seq.addPDBId(pdbe4);
1240     assertEquals(3, seq.getAllPDBEntries().size());
1241     assertSame(pdbe4, seq.getAllPDBEntries().get(2));
1242
1243     // add with a different chain code
1244     PDBEntry pdbe5 = new PDBEntry("3a6s", "B", Type.PDB, "filepath");
1245     seq.addPDBId(pdbe5);
1246     assertEquals(4, seq.getAllPDBEntries().size());
1247     assertSame(pdbe5, seq.getAllPDBEntries().get(3));
1248   }
1249
1250   @Test(
1251     groups = { "Functional" },
1252     expectedExceptions = { IllegalArgumentException.class })
1253   public void testSetDatasetSequence_toSelf()
1254   {
1255     seq.setDatasetSequence(seq);
1256   }
1257
1258   @Test(
1259     groups = { "Functional" },
1260     expectedExceptions = { IllegalArgumentException.class })
1261   public void testSetDatasetSequence_cascading()
1262   {
1263     SequenceI seq2 = new Sequence("Seq2", "xyz");
1264     seq2.createDatasetSequence();
1265     seq.setDatasetSequence(seq2);
1266   }
1267
1268   @Test(groups = { "Functional" })
1269   public void testFindFeatures()
1270   {
1271     SequenceI sq = new Sequence("test/8-16", "-ABC--DEF--GHI--");
1272     sq.createDatasetSequence();
1273
1274     assertTrue(sq.findFeatures(1, 99).isEmpty());
1275
1276     // add non-positional feature
1277     SequenceFeature sf0 = new SequenceFeature("Cath", "desc", 0, 0, 2f,
1278             null);
1279     sq.addSequenceFeature(sf0);
1280     // add feature on BCD
1281     SequenceFeature sf1 = new SequenceFeature("Cath", "desc", 9, 11, 2f,
1282             null);
1283     sq.addSequenceFeature(sf1);
1284     // add feature on DE
1285     SequenceFeature sf2 = new SequenceFeature("Cath", "desc", 11, 12, 2f,
1286             null);
1287     sq.addSequenceFeature(sf2);
1288     // add contact feature at [B, H]
1289     SequenceFeature sf3 = new SequenceFeature("Disulphide bond", "desc", 9,
1290             15, 2f,
1291             null);
1292     sq.addSequenceFeature(sf3);
1293     // add contact feature at [F, G]
1294     SequenceFeature sf4 = new SequenceFeature("Disulfide Bond", "desc", 13,
1295             14, 2f,
1296             null);
1297     sq.addSequenceFeature(sf4);
1298
1299     // no features in columns 1-2 (-A)
1300     List<SequenceFeature> found = sq.findFeatures(1, 2);
1301     assertTrue(found.isEmpty());
1302
1303     // columns 1-6 (-ABC--) includes BCD and B/H feature but not DE
1304     found = sq.findFeatures(1, 6);
1305     assertEquals(2, found.size());
1306     assertTrue(found.contains(sf1));
1307     assertTrue(found.contains(sf3));
1308
1309     // columns 5-6 (--) includes (enclosing) BCD but not (contact) B/H feature
1310     found = sq.findFeatures(5, 6);
1311     assertEquals(1, found.size());
1312     assertTrue(found.contains(sf1));
1313
1314     // columns 7-10 (DEF-) includes BCD, DE, F/G but not B/H feature
1315     found = sq.findFeatures(7, 10);
1316     assertEquals(3, found.size());
1317     assertTrue(found.contains(sf1));
1318     assertTrue(found.contains(sf2));
1319     assertTrue(found.contains(sf4));
1320   }
1321
1322   @Test(groups = { "Functional" })
1323   public void testFindIndex_withCursor()
1324   {
1325     Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
1326
1327     // find F given A
1328     assertEquals(10, sq.findIndex(13, new SequenceCursor(sq, 8, 2, 0)));
1329
1330     // find A given F
1331     assertEquals(2, sq.findIndex(8, new SequenceCursor(sq, 13, 10, 0)));
1332
1333     // find C given C
1334     assertEquals(6, sq.findIndex(10, new SequenceCursor(sq, 10, 6, 0)));
1335   }
1336
1337   @Test(groups = { "Functional" })
1338   public void testFindPosition_withCursor()
1339   {
1340     Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
1341   
1342     // find F pos given A
1343     assertEquals(13, sq.findPosition(10, new SequenceCursor(sq, 8, 2, 0)));
1344     int token = (int) PA.getValue(sq, "changeCount"); // 0
1345     SequenceCursor cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1346     assertEquals(new SequenceCursor(sq, 13, 10, token), cursor);
1347
1348     // find A pos given F
1349     assertEquals(8, sq.findPosition(2, new SequenceCursor(sq, 13, 10, 0)));
1350     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1351     assertEquals(new SequenceCursor(sq, 8, 2, token), cursor);
1352   
1353     // find C pos given C
1354     assertEquals(10, sq.findPosition(6, new SequenceCursor(sq, 10, 6, 0)));
1355     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1356     assertEquals(new SequenceCursor(sq, 10, 6, token), cursor);
1357
1358     // now the grey area - what residue position for a gapped column? JAL-2562
1359
1360     // find 'residue' for column 3 given cursor for D (so working left)
1361     // returns B9; cursor is updated to [B 5]
1362     assertEquals(9, sq.findPosition(3, new SequenceCursor(sq, 11, 7, 0)));
1363     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1364     assertEquals(new SequenceCursor(sq, 9, 5, token), cursor);
1365
1366     // find 'residue' for column 8 given cursor for D (so working right)
1367     // returns E12; cursor is updated to [D 7]
1368     assertEquals(12, sq.findPosition(8, new SequenceCursor(sq, 11, 7, 0)));
1369     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1370     assertEquals(new SequenceCursor(sq, 11, 7, token), cursor);
1371
1372     // find 'residue' for column 12 given cursor for B
1373     // returns 1 more than last residue position; cursor is updated to [F 10]
1374     assertEquals(14, sq.findPosition(12, new SequenceCursor(sq, 9, 5, 0)));
1375     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1376     assertEquals(new SequenceCursor(sq, 13, 10, token), cursor);
1377
1378     /*
1379      * findPosition for column beyond length of sequence
1380      * returns 1 more than the last residue position
1381      * cursor is set to last real residue position [F 10]
1382      */
1383     assertEquals(14, sq.findPosition(99, new SequenceCursor(sq, 8, 2, 0)));
1384     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1385     assertEquals(new SequenceCursor(sq, 13, 10, token), cursor);
1386
1387     /*
1388      * and the case without a trailing gap
1389      */
1390     sq = new Sequence("test/8-13", "-A--BCD-EF");
1391     // first find C from A
1392     assertEquals(10, sq.findPosition(6, new SequenceCursor(sq, 8, 2, 0)));
1393     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1394     assertEquals(new SequenceCursor(sq, 10, 6, token), cursor);
1395     // now 'find' 99 from C
1396     // cursor is set to [F 10]
1397     assertEquals(14, sq.findPosition(99, cursor));
1398     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1399     assertEquals(new SequenceCursor(sq, 13, 10, token), cursor);
1400   }
1401
1402   @Test
1403   public void testIsValidCursor()
1404   {
1405     Sequence sq = new Sequence("Seq", "ABC--DE-F", 8, 13);
1406     assertFalse(sq.isValidCursor(null));
1407
1408     /*
1409      * cursor is valid if it has valid sequence ref and changeCount token
1410      * and positions within the range of the sequence
1411      */
1412     int changeCount = (int) PA.getValue(sq, "changeCount");
1413     SequenceCursor cursor = new SequenceCursor(sq, 13, 1, changeCount);
1414     assertTrue(sq.isValidCursor(cursor));
1415
1416     /*
1417      * column position outside [0 - length-1] is rejected
1418      */
1419     cursor = new SequenceCursor(sq, 13, -1, changeCount);
1420     assertFalse(sq.isValidCursor(cursor));
1421     cursor = new SequenceCursor(sq, 13, 9, changeCount);
1422     assertFalse(sq.isValidCursor(cursor));
1423     cursor = new SequenceCursor(sq, 7, 8, changeCount);
1424     assertFalse(sq.isValidCursor(cursor));
1425     cursor = new SequenceCursor(sq, 14, 2, changeCount);
1426     assertFalse(sq.isValidCursor(cursor));
1427
1428     /*
1429      * wrong sequence is rejected
1430      */
1431     cursor = new SequenceCursor(null, 13, 1, changeCount);
1432     assertFalse(sq.isValidCursor(cursor));
1433     cursor = new SequenceCursor(new Sequence("Seq", "abc"), 13, 1,
1434             changeCount);
1435     assertFalse(sq.isValidCursor(cursor));
1436
1437     /*
1438      * wrong token value is rejected
1439      */
1440     cursor = new SequenceCursor(sq, 13, 1, changeCount + 1);
1441     assertFalse(sq.isValidCursor(cursor));
1442     cursor = new SequenceCursor(sq, 13, 1, changeCount - 1);
1443     assertFalse(sq.isValidCursor(cursor));
1444   }
1445
1446   @Test(groups = { "Functional" })
1447   public void testFindPosition_withCursorAndEdits()
1448   {
1449     Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
1450   
1451     // find F pos given A
1452     assertEquals(13, sq.findPosition(10, new SequenceCursor(sq, 8, 2, 0)));
1453     int token = (int) PA.getValue(sq, "changeCount"); // 0
1454     SequenceCursor cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1455     assertEquals(new SequenceCursor(sq, 13, 10, token), cursor);
1456
1457     /*
1458      * setSequence should invalidate the cursor cached by the sequence
1459      */
1460     sq.setSequence("-A-BCD-EF---"); // one gap removed
1461     assertEquals(8, sq.getStart()); // sanity check
1462     assertEquals(11, sq.findPosition(5)); // D11
1463     // cursor should now be at [D 6]
1464     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1465     assertEquals(new SequenceCursor(sq, 11, 6, ++token), cursor);
1466
1467     /*
1468      * deleteChars should invalidate the cached cursor
1469      */
1470     sq.deleteChars(2, 5); // delete -BC
1471     assertEquals("-AD-EF---", sq.getSequenceAsString());
1472     assertEquals(8, sq.getStart()); // sanity check
1473     assertEquals(10, sq.findPosition(4)); // E10
1474     // cursor should now be at [E 5]
1475     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1476     assertEquals(new SequenceCursor(sq, 10, 5, ++token), cursor);
1477
1478     /*
1479      * Edit to insert gaps should invalidate the cached cursor
1480      * insert 2 gaps at column[3] to make -AD---EF---
1481      */
1482     SequenceI[] seqs = new SequenceI[] { sq };
1483     AlignmentI al = new Alignment(seqs);
1484     new EditCommand().appendEdit(Action.INSERT_GAP, seqs, 3, 2, al, true);
1485     assertEquals("-AD---EF---", sq.getSequenceAsString());
1486     assertEquals(10, sq.findPosition(4)); // E10
1487     // cursor should now be at [D 3]
1488     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1489     assertEquals(new SequenceCursor(sq, 9, 3, ++token), cursor);
1490
1491     /*
1492      * insertCharAt should invalidate the cached cursor
1493      * insert CC at column[4] to make -AD-CC--EF---
1494      */
1495     sq.insertCharAt(4, 2, 'C');
1496     assertEquals("-AD-CC--EF---", sq.getSequenceAsString());
1497     assertEquals(13, sq.findPosition(9)); // F13
1498     // cursor should now be at [F 10]
1499     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1500     assertEquals(new SequenceCursor(sq, 13, 10, ++token), cursor);
1501   }
1502 }