JAL-2526 cache first/last residue column positions in cursor
[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     assertEquals("test:Pos8:Col1:startCol1:endCol0:tok0",
290             PA.getValue(sq, "cursor").toString());
291     SequenceCursor cursor = (SequenceCursor) PA.getValue(sq, "cursor");
292     int token = (int) PA.getValue(sq, "changeCount");
293     assertEquals(new SequenceCursor(sq, 8, 1, token), cursor);
294
295     sq.sequenceChanged();
296
297     /*
298      * find F13 at column offset 5, cursor should update to [13, 6]
299      * endColumn is found and saved in cursor
300      */
301     assertEquals(13, sq.findPosition(5));
302     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
303     assertEquals(++token, (int) PA.getValue(sq, "changeCount"));
304     assertEquals(new SequenceCursor(sq, 13, 6, token), cursor);
305     assertEquals("test:Pos13:Col6:startCol1:endCol6:tok1",
306             PA.getValue(sq, "cursor").toString());
307
308     // assertEquals(-1, seq.findPosition(6)); // fails
309
310     sq = new Sequence("test/8-11", "AB-C-D--");
311     token = (int) PA.getValue(sq, "changeCount"); // 0
312     assertEquals(8, sq.findPosition(0));
313     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
314     assertEquals(new SequenceCursor(sq, 8, 1, token), cursor);
315     assertEquals("test:Pos8:Col1:startCol1:endCol0:tok0",
316             PA.getValue(sq, "cursor").toString());
317
318     sq.sequenceChanged();
319     assertEquals(9, sq.findPosition(1));
320     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
321     assertEquals(new SequenceCursor(sq, 9, 2, ++token), cursor);
322     assertEquals("test:Pos9:Col2:startCol1:endCol0:tok1",
323             PA.getValue(sq, "cursor").toString());
324
325     sq.sequenceChanged();
326     // gap position 'finds' residue to the right (not the left as per javadoc)
327     // cursor is set to the last residue position found [B 2]
328     assertEquals(10, sq.findPosition(2));
329     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
330     assertEquals(new SequenceCursor(sq, 9, 2, ++token), cursor);
331     assertEquals("test:Pos9:Col2:startCol1:endCol0:tok2",
332             PA.getValue(sq, "cursor").toString());
333
334     sq.sequenceChanged();
335     assertEquals(10, sq.findPosition(3));
336     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
337     assertEquals(new SequenceCursor(sq, 10, 4, ++token), cursor);
338     assertEquals("test:Pos10:Col4:startCol1:endCol0:tok3",
339             PA.getValue(sq, "cursor").toString());
340
341     sq.sequenceChanged();
342     // column[4] is the gap after C - returns D11
343     // cursor is set to [C 4]
344     assertEquals(11, sq.findPosition(4));
345     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
346     assertEquals(new SequenceCursor(sq, 10, 4, ++token), cursor);
347     assertEquals("test:Pos10:Col4:startCol1:endCol0:tok4",
348             PA.getValue(sq, "cursor").toString());
349
350     sq.sequenceChanged();
351     assertEquals(11, sq.findPosition(5)); // D
352     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
353     assertEquals(new SequenceCursor(sq, 11, 6, ++token), cursor);
354     // lastCol has been found and saved in the cursor
355     assertEquals("test:Pos11:Col6:startCol1:endCol6:tok5",
356             PA.getValue(sq, "cursor").toString());
357
358     sq.sequenceChanged();
359     // returns 1 more than sequence length if off the end ?!?
360     assertEquals(12, sq.findPosition(6));
361
362     sq.sequenceChanged();
363     assertEquals(12, sq.findPosition(7));
364
365     /*
366      * first findPosition should also set firstResCol in cursor
367      */
368     sq = new Sequence("test/8-13", "--AB-C-DEF--");
369     assertEquals(8, sq.findPosition(0));
370     assertNull(PA.getValue(sq, "cursor"));
371
372     sq.sequenceChanged();
373     assertEquals(8, sq.findPosition(1));
374     assertNull(PA.getValue(sq, "cursor"));
375
376     sq.sequenceChanged();
377     assertEquals(8, sq.findPosition(2));
378     assertEquals("test:Pos8:Col3:startCol3:endCol0:tok2",
379             PA.getValue(sq, "cursor").toString());
380
381     sq.sequenceChanged();
382     assertEquals(9, sq.findPosition(3));
383     assertEquals("test:Pos9:Col4:startCol3:endCol0:tok3",
384             PA.getValue(sq, "cursor").toString());
385
386     sq.sequenceChanged();
387     // column[4] is a gap, returns next residue pos (C10)
388     // cursor is set to last residue found [B]
389     assertEquals(10, sq.findPosition(4));
390     assertEquals("test:Pos9:Col4:startCol3:endCol0:tok4",
391             PA.getValue(sq, "cursor").toString());
392
393     sq.sequenceChanged();
394     assertEquals(10, sq.findPosition(5));
395     assertEquals("test:Pos10:Col6:startCol3:endCol0:tok5",
396             PA.getValue(sq, "cursor").toString());
397
398     sq.sequenceChanged();
399     // column[6] is a gap, returns next residue pos (D11)
400     // cursor is set to last residue found [C]
401     assertEquals(11, sq.findPosition(6));
402     assertEquals("test:Pos10:Col6:startCol3:endCol0:tok6",
403             PA.getValue(sq, "cursor").toString());
404
405     sq.sequenceChanged();
406     assertEquals(11, sq.findPosition(7));
407     assertEquals("test:Pos11:Col8:startCol3:endCol0:tok7",
408             PA.getValue(sq, "cursor").toString());
409
410     sq.sequenceChanged();
411     assertEquals(12, sq.findPosition(8));
412     assertEquals("test:Pos12:Col9:startCol3:endCol0:tok8",
413             PA.getValue(sq, "cursor").toString());
414
415     /*
416      * when the last residue column is found, it is set in the cursor
417      */
418     sq.sequenceChanged();
419     assertEquals(13, sq.findPosition(9));
420     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok9",
421             PA.getValue(sq, "cursor").toString());
422
423     sq.sequenceChanged();
424     assertEquals(14, sq.findPosition(10));
425     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok10",
426             PA.getValue(sq, "cursor").toString());
427
428     /*
429      * findPosition for column beyond sequence length
430      * returns 1 more than last residue position
431      */
432     sq.sequenceChanged();
433     assertEquals(14, sq.findPosition(11));
434     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok11",
435             PA.getValue(sq, "cursor").toString());
436
437     sq.sequenceChanged();
438     assertEquals(14, sq.findPosition(99));
439     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok12",
440             PA.getValue(sq, "cursor").toString());
441   }
442
443   @Test(groups = { "Functional" })
444   public void testDeleteChars()
445   {
446     /*
447      * internal delete
448      */
449     SequenceI sq = new Sequence("test", "ABCDEF");
450     assertNull(PA.getValue(sq, "datasetSequence"));
451     assertEquals(1, sq.getStart());
452     assertEquals(6, sq.getEnd());
453     sq.deleteChars(2, 3);
454     assertEquals("ABDEF", sq.getSequenceAsString());
455     assertEquals(1, sq.getStart());
456     assertEquals(5, sq.getEnd());
457     assertNull(PA.getValue(sq, "datasetSequence"));
458
459     /*
460      * delete at start
461      */
462     sq = new Sequence("test", "ABCDEF");
463     sq.deleteChars(0, 2);
464     assertEquals("CDEF", sq.getSequenceAsString());
465     assertEquals(3, sq.getStart());
466     assertEquals(6, sq.getEnd());
467     assertNull(PA.getValue(sq, "datasetSequence"));
468
469     /*
470      * delete at end
471      */
472     sq = new Sequence("test", "ABCDEF");
473     sq.deleteChars(4, 6);
474     assertEquals("ABCD", sq.getSequenceAsString());
475     assertEquals(1, sq.getStart());
476     assertEquals(4, sq.getEnd());
477     assertNull(PA.getValue(sq, "datasetSequence"));
478   }
479
480   @Test(groups = { "Functional" })
481   public void testDeleteChars_withDbRefsAndFeatures()
482   {
483     /*
484      * internal delete - new dataset sequence created
485      * gets a copy of any dbrefs
486      */
487     SequenceI sq = new Sequence("test", "ABCDEF");
488     sq.createDatasetSequence();
489     DBRefEntry dbr1 = new DBRefEntry("Uniprot", "0", "a123");
490     sq.addDBRef(dbr1);
491     Object ds = PA.getValue(sq, "datasetSequence");
492     assertNotNull(ds);
493     assertEquals(1, sq.getStart());
494     assertEquals(6, sq.getEnd());
495     sq.deleteChars(2, 3);
496     assertEquals("ABDEF", sq.getSequenceAsString());
497     assertEquals(1, sq.getStart());
498     assertEquals(5, sq.getEnd());
499     Object newDs = PA.getValue(sq, "datasetSequence");
500     assertNotNull(newDs);
501     assertNotSame(ds, newDs);
502     assertNotNull(sq.getDBRefs());
503     assertEquals(1, sq.getDBRefs().length);
504     assertNotSame(dbr1, sq.getDBRefs()[0]);
505     assertEquals(dbr1, sq.getDBRefs()[0]);
506
507     /*
508      * internal delete with sequence features
509      * (failure case for JAL-2541)
510      */
511     sq = new Sequence("test", "ABCDEF");
512     sq.createDatasetSequence();
513     SequenceFeature sf1 = new SequenceFeature("Cath", "desc", 2, 4, 2f,
514             "CathGroup");
515     sq.addSequenceFeature(sf1);
516     ds = PA.getValue(sq, "datasetSequence");
517     assertNotNull(ds);
518     assertEquals(1, sq.getStart());
519     assertEquals(6, sq.getEnd());
520     sq.deleteChars(2, 4);
521     assertEquals("ABEF", sq.getSequenceAsString());
522     assertEquals(1, sq.getStart());
523     assertEquals(4, sq.getEnd());
524     newDs = PA.getValue(sq, "datasetSequence");
525     assertNotNull(newDs);
526     assertNotSame(ds, newDs);
527     List<SequenceFeature> sfs = sq.getSequenceFeatures();
528     assertEquals(1, sfs.size());
529     assertNotSame(sf1, sfs.get(0));
530     assertEquals(sf1, sfs.get(0));
531
532     /*
533      * delete at start - no new dataset sequence created
534      * any sequence features remain as before
535      */
536     sq = new Sequence("test", "ABCDEF");
537     sq.createDatasetSequence();
538     ds = PA.getValue(sq, "datasetSequence");
539     sf1 = new SequenceFeature("Cath", "desc", 2, 4, 2f, "CathGroup");
540     sq.addSequenceFeature(sf1);
541     sq.deleteChars(0, 2);
542     assertEquals("CDEF", sq.getSequenceAsString());
543     assertEquals(3, sq.getStart());
544     assertEquals(6, sq.getEnd());
545     assertSame(ds, PA.getValue(sq, "datasetSequence"));
546     sfs = sq.getSequenceFeatures();
547     assertNotNull(sfs);
548     assertEquals(1, sfs.size());
549     assertSame(sf1, sfs.get(0));
550
551     /*
552      * delete at end - no new dataset sequence created
553      * any dbrefs remain as before
554      */
555     sq = new Sequence("test", "ABCDEF");
556     sq.createDatasetSequence();
557     ds = PA.getValue(sq, "datasetSequence");
558     dbr1 = new DBRefEntry("Uniprot", "0", "a123");
559     sq.addDBRef(dbr1);
560     sq.deleteChars(4, 6);
561     assertEquals("ABCD", sq.getSequenceAsString());
562     assertEquals(1, sq.getStart());
563     assertEquals(4, sq.getEnd());
564     assertSame(ds, PA.getValue(sq, "datasetSequence"));
565     assertNotNull(sq.getDBRefs());
566     assertEquals(1, sq.getDBRefs().length);
567     assertSame(dbr1, sq.getDBRefs()[0]);
568   }
569
570   @Test(groups = { "Functional" })
571   public void testInsertCharAt()
572   {
573     // non-static methods:
574     SequenceI sq = new Sequence("test", "ABCDEF");
575     sq.insertCharAt(0, 'z');
576     assertEquals("zABCDEF", sq.getSequenceAsString());
577     sq.insertCharAt(2, 2, 'x');
578     assertEquals("zAxxBCDEF", sq.getSequenceAsString());
579
580     // for static method see StringUtilsTest
581   }
582
583   /**
584    * Test the method that returns an array of aligned sequence positions where
585    * the array index is the data sequence position (both base 0).
586    */
587   @Test(groups = { "Functional" })
588   public void testGapMap()
589   {
590     SequenceI sq = new Sequence("test", "-A--B-CD-E--F-");
591     sq.createDatasetSequence();
592     assertEquals("[1, 4, 6, 7, 9, 12]", Arrays.toString(sq.gapMap()));
593   }
594
595   /**
596    * Test the method that gets sequence features, either from the sequence or
597    * its dataset.
598    */
599   @Test(groups = { "Functional" })
600   public void testGetSequenceFeatures()
601   {
602     SequenceI sq = new Sequence("test", "GATCAT");
603     sq.createDatasetSequence();
604
605     assertTrue(sq.getSequenceFeatures().isEmpty());
606
607     /*
608      * SequenceFeature on sequence
609      */
610     SequenceFeature sf = new SequenceFeature("Cath", "desc", 2, 4, 2f, null);
611     sq.addSequenceFeature(sf);
612     List<SequenceFeature> sfs = sq.getSequenceFeatures();
613     assertEquals(1, sfs.size());
614     assertSame(sf, sfs.get(0));
615
616     /*
617      * SequenceFeature on sequence and dataset sequence; returns that on
618      * sequence
619      * 
620      * Note JAL-2046: spurious: we have no use case for this at the moment.
621      * This test also buggy - as sf2.equals(sf), no new feature is added
622      */
623     SequenceFeature sf2 = new SequenceFeature("Cath", "desc", 2, 4, 2f,
624             null);
625     sq.getDatasetSequence().addSequenceFeature(sf2);
626     sfs = sq.getSequenceFeatures();
627     assertEquals(1, sfs.size());
628     assertSame(sf, sfs.get(0));
629
630     /*
631      * SequenceFeature on dataset sequence only
632      * Note JAL-2046: spurious: we have no use case for setting a non-dataset sequence's feature array to null at the moment.
633      */
634     sq.setSequenceFeatures(null);
635     assertTrue(sq.getDatasetSequence().getSequenceFeatures().isEmpty());
636
637     /*
638      * Corrupt case - no SequenceFeature, dataset's dataset is the original
639      * sequence. Test shows no infinite loop results.
640      */
641     sq.getDatasetSequence().setSequenceFeatures(null);
642     /**
643      * is there a usecase for this ? setDatasetSequence should throw an error if
644      * this actually occurs.
645      */
646     try
647     {
648       sq.getDatasetSequence().setDatasetSequence(sq); // loop!
649       Assert.fail("Expected Error to be raised when calling setDatasetSequence with self reference");
650     } catch (IllegalArgumentException e)
651     {
652       // TODO Jalview error/exception class for raising implementation errors
653       assertTrue(e.getMessage().toLowerCase()
654               .contains("implementation error"));
655     }
656     assertTrue(sq.getSequenceFeatures().isEmpty());
657   }
658
659   /**
660    * Test the method that returns an array, indexed by sequence position, whose
661    * entries are the residue positions at the sequence position (or to the right
662    * if a gap)
663    */
664   @Test(groups = { "Functional" })
665   public void testFindPositionMap()
666   {
667     /*
668      * Note: Javadoc for findPosition says it returns the residue position to
669      * the left of a gapped position; in fact it returns the position to the
670      * right. Also it returns a non-existent residue position for a gap beyond
671      * the sequence.
672      */
673     Sequence sq = new Sequence("TestSeq", "AB.C-D E.");
674     int[] map = sq.findPositionMap();
675     assertEquals(Arrays.toString(new int[] { 1, 2, 3, 3, 4, 4, 5, 5, 6 }),
676             Arrays.toString(map));
677   }
678
679   /**
680    * Test for getSubsequence
681    */
682   @Test(groups = { "Functional" })
683   public void testGetSubsequence()
684   {
685     SequenceI sq = new Sequence("TestSeq", "ABCDEFG");
686     sq.createDatasetSequence();
687
688     // positions are base 0, end position is exclusive
689     SequenceI subseq = sq.getSubSequence(2, 4);
690
691     assertEquals("CD", subseq.getSequenceAsString());
692     // start/end are base 1 positions
693     assertEquals(3, subseq.getStart());
694     assertEquals(4, subseq.getEnd());
695     // subsequence shares the full dataset sequence
696     assertSame(sq.getDatasetSequence(), subseq.getDatasetSequence());
697   }
698
699   /**
700    * test createDatasetSequence behaves to doc
701    */
702   @Test(groups = { "Functional" })
703   public void testCreateDatasetSequence()
704   {
705     SequenceI sq = new Sequence("my", "ASDASD");
706     sq.addSequenceFeature(new SequenceFeature("type", "desc", 1, 10, 1f,
707             "group"));
708     sq.addDBRef(new DBRefEntry("source", "version", "accession"));
709     assertNull(sq.getDatasetSequence());
710     assertNotNull(PA.getValue(sq, "sequenceFeatureStore"));
711     assertNotNull(PA.getValue(sq, "dbrefs"));
712
713     SequenceI rds = sq.createDatasetSequence();
714     assertNotNull(rds);
715     assertNull(rds.getDatasetSequence());
716     assertSame(sq.getDatasetSequence(), rds);
717
718     // sequence features and dbrefs transferred to dataset sequence
719     assertNull(PA.getValue(sq, "sequenceFeatureStore"));
720     assertNull(PA.getValue(sq, "dbrefs"));
721     assertNotNull(PA.getValue(rds, "sequenceFeatureStore"));
722     assertNotNull(PA.getValue(rds, "dbrefs"));
723   }
724
725   /**
726    * Test for deriveSequence applied to a sequence with a dataset
727    */
728   @Test(groups = { "Functional" })
729   public void testDeriveSequence_existingDataset()
730   {
731     Sequence sq = new Sequence("Seq1", "CD");
732     sq.setDatasetSequence(new Sequence("Seq1", "ABCDEF"));
733     sq.getDatasetSequence().addSequenceFeature(
734             new SequenceFeature("", "", 1, 2, 0f, null));
735     sq.setStart(3);
736     sq.setEnd(4);
737
738     sq.setDescription("Test sequence description..");
739     sq.setVamsasId("TestVamsasId");
740     sq.addDBRef(new DBRefEntry("PDB", "version0", "1TST"));
741
742     sq.addDBRef(new DBRefEntry("PDB", "version1", "1PDB"));
743     sq.addDBRef(new DBRefEntry("PDB", "version2", "2PDB"));
744     sq.addDBRef(new DBRefEntry("PDB", "version3", "3PDB"));
745     sq.addDBRef(new DBRefEntry("PDB", "version4", "4PDB"));
746
747     sq.addPDBId(new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1"));
748     sq.addPDBId(new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1"));
749     sq.addPDBId(new PDBEntry("2PDB", "A", Type.MMCIF, "filePath/test2"));
750     sq.addPDBId(new PDBEntry("2PDB", "B", Type.MMCIF, "filePath/test2"));
751
752     // these are the same as ones already added
753     DBRefEntry pdb1pdb = new DBRefEntry("PDB", "version1", "1PDB");
754     DBRefEntry pdb2pdb = new DBRefEntry("PDB", "version2", "2PDB");
755
756     List<DBRefEntry> primRefs = Arrays.asList(new DBRefEntry[] { pdb1pdb,
757         pdb2pdb });
758
759     sq.getDatasetSequence().addDBRef(pdb1pdb); // should do nothing
760     sq.getDatasetSequence().addDBRef(pdb2pdb); // should do nothing
761     sq.getDatasetSequence().addDBRef(
762             new DBRefEntry("PDB", "version3", "3PDB")); // should do nothing
763     sq.getDatasetSequence().addDBRef(
764             new DBRefEntry("PDB", "version4", "4PDB")); // should do nothing
765
766     PDBEntry pdbe1a = new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1");
767     PDBEntry pdbe1b = new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1");
768     PDBEntry pdbe2a = new PDBEntry("2PDB", "A", Type.MMCIF,
769             "filePath/test2");
770     PDBEntry pdbe2b = new PDBEntry("2PDB", "B", Type.MMCIF,
771             "filePath/test2");
772     sq.getDatasetSequence().addPDBId(pdbe1a);
773     sq.getDatasetSequence().addPDBId(pdbe1b);
774     sq.getDatasetSequence().addPDBId(pdbe2a);
775     sq.getDatasetSequence().addPDBId(pdbe2b);
776
777     /*
778      * test we added pdb entries to the dataset sequence
779      */
780     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries(), Arrays
781             .asList(new PDBEntry[] { pdbe1a, pdbe1b, pdbe2a, pdbe2b }),
782             "PDB Entries were not found on dataset sequence.");
783
784     /*
785      * we should recover a pdb entry that is on the dataset sequence via PDBEntry
786      */
787     Assert.assertEquals(pdbe1a,
788             sq.getDatasetSequence().getPDBEntry("1PDB"),
789             "PDB Entry '1PDB' not found on dataset sequence via getPDBEntry.");
790     ArrayList<Annotation> annotsList = new ArrayList<Annotation>();
791     System.out.println(">>>>>> " + sq.getSequenceAsString().length());
792     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
793     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
794     Annotation[] annots = annotsList.toArray(new Annotation[0]);
795     sq.addAlignmentAnnotation(new AlignmentAnnotation("Test annot",
796             "Test annot description", annots));
797     sq.getDatasetSequence().addAlignmentAnnotation(
798             new AlignmentAnnotation("Test annot", "Test annot description",
799                     annots));
800     Assert.assertEquals(sq.getDescription(), "Test sequence description..");
801     Assert.assertEquals(sq.getDBRefs().length, 5); // DBRefs are on dataset
802                                                    // sequence
803     Assert.assertEquals(sq.getAllPDBEntries().size(), 4);
804     Assert.assertNotNull(sq.getAnnotation());
805     Assert.assertEquals(sq.getAnnotation()[0].annotations.length, 2);
806     Assert.assertEquals(sq.getDatasetSequence().getDBRefs().length, 5); // same
807                                                                         // as
808                                                                         // sq.getDBRefs()
809     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries().size(),
810             4);
811     Assert.assertNotNull(sq.getDatasetSequence().getAnnotation());
812
813     Sequence derived = (Sequence) sq.deriveSequence();
814
815     Assert.assertEquals(derived.getDescription(),
816             "Test sequence description..");
817     Assert.assertEquals(derived.getDBRefs().length, 5); // come from dataset
818     Assert.assertEquals(derived.getAllPDBEntries().size(), 4);
819     Assert.assertNotNull(derived.getAnnotation());
820     Assert.assertEquals(derived.getAnnotation()[0].annotations.length, 2);
821     Assert.assertEquals(derived.getDatasetSequence().getDBRefs().length, 5);
822     Assert.assertEquals(derived.getDatasetSequence().getAllPDBEntries()
823             .size(), 4);
824     Assert.assertNotNull(derived.getDatasetSequence().getAnnotation());
825
826     assertEquals("CD", derived.getSequenceAsString());
827     assertSame(sq.getDatasetSequence(), derived.getDatasetSequence());
828
829     // derived sequence should access dataset sequence features
830     assertNotNull(sq.getSequenceFeatures());
831     assertEquals(sq.getSequenceFeatures(), derived.getSequenceFeatures());
832
833     /*
834      *  verify we have primary db refs *just* for PDB IDs with associated
835      *  PDBEntry objects
836      */
837
838     assertEquals(primRefs, sq.getPrimaryDBRefs());
839     assertEquals(primRefs, sq.getDatasetSequence().getPrimaryDBRefs());
840
841     assertEquals(sq.getPrimaryDBRefs(), derived.getPrimaryDBRefs());
842
843   }
844
845   /**
846    * Test for deriveSequence applied to an ungapped sequence with no dataset
847    */
848   @Test(groups = { "Functional" })
849   public void testDeriveSequence_noDatasetUngapped()
850   {
851     SequenceI sq = new Sequence("Seq1", "ABCDEF");
852     assertEquals(1, sq.getStart());
853     assertEquals(6, sq.getEnd());
854     SequenceI derived = sq.deriveSequence();
855     assertEquals("ABCDEF", derived.getSequenceAsString());
856     assertEquals("ABCDEF", derived.getDatasetSequence()
857             .getSequenceAsString());
858   }
859
860   /**
861    * Test for deriveSequence applied to a gapped sequence with no dataset
862    */
863   @Test(groups = { "Functional" })
864   public void testDeriveSequence_noDatasetGapped()
865   {
866     SequenceI sq = new Sequence("Seq1", "AB-C.D EF");
867     assertEquals(1, sq.getStart());
868     assertEquals(6, sq.getEnd());
869     assertNull(sq.getDatasetSequence());
870     SequenceI derived = sq.deriveSequence();
871     assertEquals("AB-C.D EF", derived.getSequenceAsString());
872     assertEquals("ABCDEF", derived.getDatasetSequence()
873             .getSequenceAsString());
874   }
875
876   @Test(groups = { "Functional" })
877   public void testCopyConstructor_noDataset()
878   {
879     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
880     seq1.setDescription("description");
881     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
882             1.3d));
883     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
884             12.4f, "group"));
885     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
886     seq1.addDBRef(new DBRefEntry("EMBL", "1.2", "AZ12345"));
887
888     SequenceI copy = new Sequence(seq1);
889
890     assertNull(copy.getDatasetSequence());
891
892     verifyCopiedSequence(seq1, copy);
893
894     // copy has a copy of the DBRefEntry
895     // this is murky - DBrefs are only copied for dataset sequences
896     // where the test for 'dataset sequence' is 'dataset is null'
897     // but that doesn't distinguish it from an aligned sequence
898     // which has not yet generated a dataset sequence
899     // NB getDBRef looks inside dataset sequence if not null
900     DBRefEntry[] dbrefs = copy.getDBRefs();
901     assertEquals(1, dbrefs.length);
902     assertFalse(dbrefs[0] == seq1.getDBRefs()[0]);
903     assertTrue(dbrefs[0].equals(seq1.getDBRefs()[0]));
904   }
905
906   @Test(groups = { "Functional" })
907   public void testCopyConstructor_withDataset()
908   {
909     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
910     seq1.createDatasetSequence();
911     seq1.setDescription("description");
912     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
913             1.3d));
914     // JAL-2046 - what is the contract for using a derived sequence's
915     // addSequenceFeature ?
916     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
917             12.4f, "group"));
918     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
919     // here we add DBRef to the dataset sequence:
920     seq1.getDatasetSequence().addDBRef(
921             new DBRefEntry("EMBL", "1.2", "AZ12345"));
922
923     SequenceI copy = new Sequence(seq1);
924
925     assertNotNull(copy.getDatasetSequence());
926     assertSame(copy.getDatasetSequence(), seq1.getDatasetSequence());
927
928     verifyCopiedSequence(seq1, copy);
929
930     // getDBRef looks inside dataset sequence and this is shared,
931     // so holds the same dbref objects
932     DBRefEntry[] dbrefs = copy.getDBRefs();
933     assertEquals(1, dbrefs.length);
934     assertSame(dbrefs[0], seq1.getDBRefs()[0]);
935   }
936
937   /**
938    * Helper to make assertions about a copied sequence
939    * 
940    * @param seq1
941    * @param copy
942    */
943   protected void verifyCopiedSequence(SequenceI seq1, SequenceI copy)
944   {
945     // verify basic properties:
946     assertEquals(copy.getName(), seq1.getName());
947     assertEquals(copy.getDescription(), seq1.getDescription());
948     assertEquals(copy.getStart(), seq1.getStart());
949     assertEquals(copy.getEnd(), seq1.getEnd());
950     assertEquals(copy.getSequenceAsString(), seq1.getSequenceAsString());
951
952     // copy has a copy of the annotation:
953     AlignmentAnnotation[] anns = copy.getAnnotation();
954     assertEquals(1, anns.length);
955     assertFalse(anns[0] == seq1.getAnnotation()[0]);
956     assertEquals(anns[0].label, seq1.getAnnotation()[0].label);
957     assertEquals(anns[0].description, seq1.getAnnotation()[0].description);
958     assertEquals(anns[0].score, seq1.getAnnotation()[0].score);
959
960     // copy has a copy of the sequence feature:
961     List<SequenceFeature> sfs = copy.getSequenceFeatures();
962     assertEquals(1, sfs.size());
963     if (seq1.getDatasetSequence() != null
964             && copy.getDatasetSequence() == seq1.getDatasetSequence())
965     {
966       assertSame(sfs.get(0), seq1.getSequenceFeatures().get(0));
967     }
968     else
969     {
970       assertNotSame(sfs.get(0), seq1.getSequenceFeatures().get(0));
971     }
972     assertEquals(sfs.get(0), seq1.getSequenceFeatures().get(0));
973
974     // copy has a copy of the PDB entry
975     Vector<PDBEntry> pdbs = copy.getAllPDBEntries();
976     assertEquals(1, pdbs.size());
977     assertFalse(pdbs.get(0) == seq1.getAllPDBEntries().get(0));
978     assertTrue(pdbs.get(0).equals(seq1.getAllPDBEntries().get(0)));
979   }
980
981   @Test(groups = "Functional")
982   public void testGetCharAt()
983   {
984     SequenceI sq = new Sequence("", "abcde");
985     assertEquals('a', sq.getCharAt(0));
986     assertEquals('e', sq.getCharAt(4));
987     assertEquals(' ', sq.getCharAt(5));
988     assertEquals(' ', sq.getCharAt(-1));
989   }
990
991   @Test(groups = { "Functional" })
992   public void testAddSequenceFeatures()
993   {
994     SequenceI sq = new Sequence("", "abcde");
995     // type may not be null
996     assertFalse(sq.addSequenceFeature(new SequenceFeature(null, "desc", 4,
997             8, 0f, null)));
998     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
999             8, 0f, null)));
1000     // can't add a duplicate feature
1001     assertFalse(sq.addSequenceFeature(new SequenceFeature("Cath", "desc",
1002             4, 8, 0f, null)));
1003     // can add a different feature
1004     assertTrue(sq.addSequenceFeature(new SequenceFeature("Scop", "desc", 4,
1005             8, 0f, null))); // different type
1006     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath",
1007             "description", 4, 8, 0f, null)));// different description
1008     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 3,
1009             8, 0f, null))); // different start position
1010     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
1011             9, 0f, null))); // different end position
1012     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
1013             8, 1f, null))); // different score
1014     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
1015             8, Float.NaN, null))); // score NaN
1016     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
1017             8, 0f, "Metal"))); // different group
1018     assertEquals(8, sq.getFeatures().getAllFeatures().size());
1019   }
1020
1021   /**
1022    * Tests for adding (or updating) dbrefs
1023    * 
1024    * @see DBRefEntry#updateFrom(DBRefEntry)
1025    */
1026   @Test(groups = { "Functional" })
1027   public void testAddDBRef()
1028   {
1029     SequenceI sq = new Sequence("", "abcde");
1030     assertNull(sq.getDBRefs());
1031     DBRefEntry dbref = new DBRefEntry("Uniprot", "1", "P00340");
1032     sq.addDBRef(dbref);
1033     assertEquals(1, sq.getDBRefs().length);
1034     assertSame(dbref, sq.getDBRefs()[0]);
1035
1036     /*
1037      * change of version - new entry
1038      */
1039     DBRefEntry dbref2 = new DBRefEntry("Uniprot", "2", "P00340");
1040     sq.addDBRef(dbref2);
1041     assertEquals(2, sq.getDBRefs().length);
1042     assertSame(dbref, sq.getDBRefs()[0]);
1043     assertSame(dbref2, sq.getDBRefs()[1]);
1044
1045     /*
1046      * matches existing entry - not added
1047      */
1048     sq.addDBRef(new DBRefEntry("UNIPROT", "1", "p00340"));
1049     assertEquals(2, sq.getDBRefs().length);
1050
1051     /*
1052      * different source = new entry
1053      */
1054     DBRefEntry dbref3 = new DBRefEntry("UniRef", "1", "p00340");
1055     sq.addDBRef(dbref3);
1056     assertEquals(3, sq.getDBRefs().length);
1057     assertSame(dbref3, sq.getDBRefs()[2]);
1058
1059     /*
1060      * different ref = new entry
1061      */
1062     DBRefEntry dbref4 = new DBRefEntry("UniRef", "1", "p00341");
1063     sq.addDBRef(dbref4);
1064     assertEquals(4, sq.getDBRefs().length);
1065     assertSame(dbref4, sq.getDBRefs()[3]);
1066
1067     /*
1068      * matching ref with a mapping - map updated
1069      */
1070     DBRefEntry dbref5 = new DBRefEntry("UniRef", "1", "p00341");
1071     Mapping map = new Mapping(new MapList(new int[] { 1, 3 }, new int[] {
1072         1, 1 }, 3, 1));
1073     dbref5.setMap(map);
1074     sq.addDBRef(dbref5);
1075     assertEquals(4, sq.getDBRefs().length);
1076     assertSame(dbref4, sq.getDBRefs()[3]);
1077     assertSame(map, dbref4.getMap());
1078
1079     /*
1080      * 'real' version replaces "0" version
1081      */
1082     dbref2.setVersion("0");
1083     DBRefEntry dbref6 = new DBRefEntry(dbref2.getSource(), "3",
1084             dbref2.getAccessionId());
1085     sq.addDBRef(dbref6);
1086     assertEquals(4, sq.getDBRefs().length);
1087     assertSame(dbref2, sq.getDBRefs()[1]);
1088     assertEquals("3", dbref2.getVersion());
1089
1090     /*
1091      * 'real' version replaces "source:0" version
1092      */
1093     dbref3.setVersion("Uniprot:0");
1094     DBRefEntry dbref7 = new DBRefEntry(dbref3.getSource(), "3",
1095             dbref3.getAccessionId());
1096     sq.addDBRef(dbref7);
1097     assertEquals(4, sq.getDBRefs().length);
1098     assertSame(dbref3, sq.getDBRefs()[2]);
1099     assertEquals("3", dbref2.getVersion());
1100   }
1101
1102   @Test(groups = { "Functional" })
1103   public void testGetPrimaryDBRefs_peptide()
1104   {
1105     SequenceI sq = new Sequence("aseq", "ASDFKYLMQPRST", 10, 22);
1106
1107     // no dbrefs
1108     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
1109     assertTrue(primaryDBRefs.isEmpty());
1110
1111     // empty dbrefs
1112     sq.setDBRefs(new DBRefEntry[] {});
1113     primaryDBRefs = sq.getPrimaryDBRefs();
1114     assertTrue(primaryDBRefs.isEmpty());
1115
1116     // primary - uniprot
1117     DBRefEntry upentry1 = new DBRefEntry("UNIPROT", "0", "Q04760");
1118     sq.addDBRef(upentry1);
1119
1120     // primary - uniprot with congruent map
1121     DBRefEntry upentry2 = new DBRefEntry("UNIPROT", "0", "Q04762");
1122     upentry2.setMap(new Mapping(null, new MapList(new int[] { 10, 22 },
1123             new int[] { 10, 22 }, 1, 1)));
1124     sq.addDBRef(upentry2);
1125
1126     // primary - uniprot with map of enclosing sequence
1127     DBRefEntry upentry3 = new DBRefEntry("UNIPROT", "0", "Q04763");
1128     upentry3.setMap(new Mapping(null, new MapList(new int[] { 8, 24 },
1129             new int[] { 8, 24 }, 1, 1)));
1130     sq.addDBRef(upentry3);
1131
1132     // not primary - uniprot with map of sub-sequence (5')
1133     DBRefEntry upentry4 = new DBRefEntry("UNIPROT", "0", "Q04764");
1134     upentry4.setMap(new Mapping(null, new MapList(new int[] { 10, 18 },
1135             new int[] { 10, 18 }, 1, 1)));
1136     sq.addDBRef(upentry4);
1137
1138     // not primary - uniprot with map that overlaps 3'
1139     DBRefEntry upentry5 = new DBRefEntry("UNIPROT", "0", "Q04765");
1140     upentry5.setMap(new Mapping(null, new MapList(new int[] { 12, 22 },
1141             new int[] { 12, 22 }, 1, 1)));
1142     sq.addDBRef(upentry5);
1143
1144     // not primary - uniprot with map to different coordinates frame
1145     DBRefEntry upentry6 = new DBRefEntry("UNIPROT", "0", "Q04766");
1146     upentry6.setMap(new Mapping(null, new MapList(new int[] { 12, 18 },
1147             new int[] { 112, 118 }, 1, 1)));
1148     sq.addDBRef(upentry6);
1149
1150     // not primary - dbref to 'non-core' database
1151     DBRefEntry upentry7 = new DBRefEntry("Pfam", "0", "PF00903");
1152     sq.addDBRef(upentry7);
1153
1154     // primary - type is PDB
1155     DBRefEntry pdbentry = new DBRefEntry("PDB", "0", "1qip");
1156     sq.addDBRef(pdbentry);
1157
1158     // not primary - PDBEntry has no file
1159     sq.addDBRef(new DBRefEntry("PDB", "0", "1AAA"));
1160
1161     // not primary - no PDBEntry
1162     sq.addDBRef(new DBRefEntry("PDB", "0", "1DDD"));
1163
1164     // add corroborating PDB entry for primary DBref -
1165     // needs to have a file as well as matching ID
1166     // note PDB ID is not treated as case sensitive
1167     sq.addPDBId(new PDBEntry("1QIP", null, Type.PDB, new File("/blah")
1168             .toString()));
1169
1170     // not valid DBRef - no file..
1171     sq.addPDBId(new PDBEntry("1AAA", null, null, null));
1172
1173     primaryDBRefs = sq.getPrimaryDBRefs();
1174     assertEquals(4, primaryDBRefs.size());
1175     assertTrue("Couldn't find simple primary reference (UNIPROT)",
1176             primaryDBRefs.contains(upentry1));
1177     assertTrue("Couldn't find mapped primary reference (UNIPROT)",
1178             primaryDBRefs.contains(upentry2));
1179     assertTrue("Couldn't find mapped context reference (UNIPROT)",
1180             primaryDBRefs.contains(upentry3));
1181     assertTrue("Couldn't find expected PDB primary reference",
1182             primaryDBRefs.contains(pdbentry));
1183   }
1184
1185   @Test(groups = { "Functional" })
1186   public void testGetPrimaryDBRefs_nucleotide()
1187   {
1188     SequenceI sq = new Sequence("aseq", "TGATCACTCGACTAGCATCAGCATA", 10, 34);
1189
1190     // primary - Ensembl
1191     DBRefEntry dbr1 = new DBRefEntry("ENSEMBL", "0", "ENSG1234");
1192     sq.addDBRef(dbr1);
1193
1194     // not primary - Ensembl 'transcript' mapping of sub-sequence
1195     DBRefEntry dbr2 = new DBRefEntry("ENSEMBL", "0", "ENST1234");
1196     dbr2.setMap(new Mapping(null, new MapList(new int[] { 15, 25 },
1197             new int[] { 1, 11 }, 1, 1)));
1198     sq.addDBRef(dbr2);
1199
1200     // primary - EMBL with congruent map
1201     DBRefEntry dbr3 = new DBRefEntry("EMBL", "0", "J1234");
1202     dbr3.setMap(new Mapping(null, new MapList(new int[] { 10, 34 },
1203             new int[] { 10, 34 }, 1, 1)));
1204     sq.addDBRef(dbr3);
1205
1206     // not primary - to non-core database
1207     DBRefEntry dbr4 = new DBRefEntry("CCDS", "0", "J1234");
1208     sq.addDBRef(dbr4);
1209
1210     // not primary - to protein
1211     DBRefEntry dbr5 = new DBRefEntry("UNIPROT", "0", "Q87654");
1212     sq.addDBRef(dbr5);
1213
1214     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
1215     assertEquals(2, primaryDBRefs.size());
1216     assertTrue(primaryDBRefs.contains(dbr1));
1217     assertTrue(primaryDBRefs.contains(dbr3));
1218   }
1219
1220   /**
1221    * Test the method that updates the list of PDBEntry from any new DBRefEntry
1222    * for PDB
1223    */
1224   @Test(groups = { "Functional" })
1225   public void testUpdatePDBIds()
1226   {
1227     PDBEntry pdbe1 = new PDBEntry("3A6S", null, null, null);
1228     seq.addPDBId(pdbe1);
1229     seq.addDBRef(new DBRefEntry("Ensembl", "8", "ENST1234"));
1230     seq.addDBRef(new DBRefEntry("PDB", "0", "1A70"));
1231     seq.addDBRef(new DBRefEntry("PDB", "0", "4BQGa"));
1232     seq.addDBRef(new DBRefEntry("PDB", "0", "3a6sB"));
1233     // 7 is not a valid chain code:
1234     seq.addDBRef(new DBRefEntry("PDB", "0", "2GIS7"));
1235
1236     seq.updatePDBIds();
1237     List<PDBEntry> pdbIds = seq.getAllPDBEntries();
1238     assertEquals(4, pdbIds.size());
1239     assertSame(pdbe1, pdbIds.get(0));
1240     // chain code got added to 3A6S:
1241     assertEquals("B", pdbe1.getChainCode());
1242     assertEquals("1A70", pdbIds.get(1).getId());
1243     // 4BQGA is parsed into id + chain
1244     assertEquals("4BQG", pdbIds.get(2).getId());
1245     assertEquals("a", pdbIds.get(2).getChainCode());
1246     assertEquals("2GIS7", pdbIds.get(3).getId());
1247     assertNull(pdbIds.get(3).getChainCode());
1248   }
1249
1250   /**
1251    * Test the method that either adds a pdbid or updates an existing one
1252    */
1253   @Test(groups = { "Functional" })
1254   public void testAddPDBId()
1255   {
1256     PDBEntry pdbe = new PDBEntry("3A6S", null, null, null);
1257     seq.addPDBId(pdbe);
1258     assertEquals(1, seq.getAllPDBEntries().size());
1259     assertSame(pdbe, seq.getPDBEntry("3A6S"));
1260     assertSame(pdbe, seq.getPDBEntry("3a6s")); // case-insensitive
1261
1262     // add the same entry
1263     seq.addPDBId(pdbe);
1264     assertEquals(1, seq.getAllPDBEntries().size());
1265     assertSame(pdbe, seq.getPDBEntry("3A6S"));
1266
1267     // add an identical entry
1268     seq.addPDBId(new PDBEntry("3A6S", null, null, null));
1269     assertEquals(1, seq.getAllPDBEntries().size());
1270     assertSame(pdbe, seq.getPDBEntry("3A6S"));
1271
1272     // add a different entry
1273     PDBEntry pdbe2 = new PDBEntry("1A70", null, null, null);
1274     seq.addPDBId(pdbe2);
1275     assertEquals(2, seq.getAllPDBEntries().size());
1276     assertSame(pdbe, seq.getAllPDBEntries().get(0));
1277     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
1278
1279     // update pdbe with chain code, file, type
1280     PDBEntry pdbe3 = new PDBEntry("3a6s", "A", Type.PDB, "filepath");
1281     seq.addPDBId(pdbe3);
1282     assertEquals(2, seq.getAllPDBEntries().size());
1283     assertSame(pdbe, seq.getAllPDBEntries().get(0)); // updated in situ
1284     assertEquals("3A6S", pdbe.getId()); // unchanged
1285     assertEquals("A", pdbe.getChainCode()); // updated
1286     assertEquals(Type.PDB.toString(), pdbe.getType()); // updated
1287     assertEquals("filepath", pdbe.getFile()); // updated
1288     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
1289
1290     // add with a different file path
1291     PDBEntry pdbe4 = new PDBEntry("3a6s", "A", Type.PDB, "filepath2");
1292     seq.addPDBId(pdbe4);
1293     assertEquals(3, seq.getAllPDBEntries().size());
1294     assertSame(pdbe4, seq.getAllPDBEntries().get(2));
1295
1296     // add with a different chain code
1297     PDBEntry pdbe5 = new PDBEntry("3a6s", "B", Type.PDB, "filepath");
1298     seq.addPDBId(pdbe5);
1299     assertEquals(4, seq.getAllPDBEntries().size());
1300     assertSame(pdbe5, seq.getAllPDBEntries().get(3));
1301   }
1302
1303   @Test(
1304     groups = { "Functional" },
1305     expectedExceptions = { IllegalArgumentException.class })
1306   public void testSetDatasetSequence_toSelf()
1307   {
1308     seq.setDatasetSequence(seq);
1309   }
1310
1311   @Test(
1312     groups = { "Functional" },
1313     expectedExceptions = { IllegalArgumentException.class })
1314   public void testSetDatasetSequence_cascading()
1315   {
1316     SequenceI seq2 = new Sequence("Seq2", "xyz");
1317     seq2.createDatasetSequence();
1318     seq.setDatasetSequence(seq2);
1319   }
1320
1321   @Test(groups = { "Functional" })
1322   public void testFindFeatures()
1323   {
1324     SequenceI sq = new Sequence("test/8-16", "-ABC--DEF--GHI--");
1325     sq.createDatasetSequence();
1326
1327     assertTrue(sq.findFeatures(1, 99).isEmpty());
1328
1329     // add non-positional feature
1330     SequenceFeature sf0 = new SequenceFeature("Cath", "desc", 0, 0, 2f,
1331             null);
1332     sq.addSequenceFeature(sf0);
1333     // add feature on BCD
1334     SequenceFeature sf1 = new SequenceFeature("Cath", "desc", 9, 11, 2f,
1335             null);
1336     sq.addSequenceFeature(sf1);
1337     // add feature on DE
1338     SequenceFeature sf2 = new SequenceFeature("Cath", "desc", 11, 12, 2f,
1339             null);
1340     sq.addSequenceFeature(sf2);
1341     // add contact feature at [B, H]
1342     SequenceFeature sf3 = new SequenceFeature("Disulphide bond", "desc", 9,
1343             15, 2f,
1344             null);
1345     sq.addSequenceFeature(sf3);
1346     // add contact feature at [F, G]
1347     SequenceFeature sf4 = new SequenceFeature("Disulfide Bond", "desc", 13,
1348             14, 2f,
1349             null);
1350     sq.addSequenceFeature(sf4);
1351
1352     // no features in columns 1-2 (-A)
1353     List<SequenceFeature> found = sq.findFeatures(1, 2);
1354     assertTrue(found.isEmpty());
1355
1356     // columns 1-6 (-ABC--) includes BCD and B/H feature but not DE
1357     found = sq.findFeatures(1, 6);
1358     assertEquals(2, found.size());
1359     assertTrue(found.contains(sf1));
1360     assertTrue(found.contains(sf3));
1361
1362     // columns 5-6 (--) includes (enclosing) BCD but not (contact) B/H feature
1363     found = sq.findFeatures(5, 6);
1364     assertEquals(1, found.size());
1365     assertTrue(found.contains(sf1));
1366
1367     // columns 7-10 (DEF-) includes BCD, DE, F/G but not B/H feature
1368     found = sq.findFeatures(7, 10);
1369     assertEquals(3, found.size());
1370     assertTrue(found.contains(sf1));
1371     assertTrue(found.contains(sf2));
1372     assertTrue(found.contains(sf4));
1373   }
1374
1375   @Test(groups = { "Functional" })
1376   public void testFindIndex_withCursor()
1377   {
1378     Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
1379
1380     // find F given A
1381     assertEquals(10, sq.findIndex(13, new SequenceCursor(sq, 8, 2, 0)));
1382
1383     // find A given F
1384     assertEquals(2, sq.findIndex(8, new SequenceCursor(sq, 13, 10, 0)));
1385
1386     // find C given C
1387     assertEquals(6, sq.findIndex(10, new SequenceCursor(sq, 10, 6, 0)));
1388   }
1389
1390   @Test(groups = { "Functional" })
1391   public void testFindPosition_withCursor()
1392   {
1393     Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
1394   
1395     // find F pos given A - lastCol gets set in cursor
1396     assertEquals(13, sq.findPosition(10, new SequenceCursor(sq, 8, 2, 0)));
1397     assertEquals("test:Pos13:Col10:startCol0:endCol10:tok0",
1398             PA.getValue(sq, "cursor").toString());
1399
1400     // find A pos given F - first residue column is saved in cursor
1401     assertEquals(8, sq.findPosition(2, new SequenceCursor(sq, 13, 10, 0)));
1402     assertEquals("test:Pos8:Col2:startCol2:endCol10:tok0",
1403             PA.getValue(sq, "cursor").toString());
1404   
1405     // find C pos given C (neither startCol nor endCol is set)
1406     assertEquals(10, sq.findPosition(6, new SequenceCursor(sq, 10, 6, 0)));
1407     assertEquals("test:Pos10:Col6:startCol0:endCol0:tok0",
1408             PA.getValue(sq, "cursor").toString());
1409
1410     // now the grey area - what residue position for a gapped column? JAL-2562
1411
1412     // find 'residue' for column 3 given cursor for D (so working left)
1413     // returns B9; cursor is updated to [B 5]
1414     assertEquals(9, sq.findPosition(3, new SequenceCursor(sq, 11, 7, 0)));
1415     assertEquals("test:Pos9:Col5:startCol0:endCol0:tok0",
1416             PA.getValue(sq, "cursor").toString());
1417
1418     // find 'residue' for column 8 given cursor for D (so working right)
1419     // returns E12; cursor is updated to [D 7]
1420     assertEquals(12, sq.findPosition(8, new SequenceCursor(sq, 11, 7, 0)));
1421     assertEquals("test:Pos11:Col7:startCol0:endCol0:tok0",
1422             PA.getValue(sq, "cursor").toString());
1423
1424     // find 'residue' for column 12 given cursor for B
1425     // returns 1 more than last residue position; cursor is updated to [F 10]
1426     // lastCol position is saved in cursor
1427     assertEquals(14, sq.findPosition(12, new SequenceCursor(sq, 9, 5, 0)));
1428     assertEquals("test:Pos13:Col10:startCol0:endCol10:tok0",
1429             PA.getValue(sq, "cursor").toString());
1430
1431     /*
1432      * findPosition for column beyond length of sequence
1433      * returns 1 more than the last residue position
1434      * cursor is set to last real residue position [F 10]
1435      */
1436     assertEquals(14, sq.findPosition(99, new SequenceCursor(sq, 8, 2, 0)));
1437     assertEquals("test:Pos13:Col10:startCol0:endCol10:tok0",
1438             PA.getValue(sq, "cursor").toString());
1439
1440     /*
1441      * and the case without a trailing gap
1442      */
1443     sq = new Sequence("test/8-13", "-A--BCD-EF");
1444     // first find C from A
1445     assertEquals(10, sq.findPosition(6, new SequenceCursor(sq, 8, 2, 0)));
1446     SequenceCursor cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1447     assertEquals("test:Pos10:Col6:startCol0:endCol0:tok0",
1448             cursor.toString());
1449     // now 'find' 99 from C
1450     // cursor is set to [F 10] and saved lastCol
1451     assertEquals(14, sq.findPosition(99, cursor));
1452     assertEquals("test:Pos13:Col10:startCol0:endCol10:tok0",
1453             PA.getValue(sq, "cursor").toString());
1454   }
1455
1456   @Test
1457   public void testIsValidCursor()
1458   {
1459     Sequence sq = new Sequence("Seq", "ABC--DE-F", 8, 13);
1460     assertFalse(sq.isValidCursor(null));
1461
1462     /*
1463      * cursor is valid if it has valid sequence ref and changeCount token
1464      * and positions within the range of the sequence
1465      */
1466     int changeCount = (int) PA.getValue(sq, "changeCount");
1467     SequenceCursor cursor = new SequenceCursor(sq, 13, 1, changeCount);
1468     assertTrue(sq.isValidCursor(cursor));
1469
1470     /*
1471      * column position outside [0 - length] is rejected
1472      */
1473     cursor = new SequenceCursor(sq, 13, -1, changeCount);
1474     assertFalse(sq.isValidCursor(cursor));
1475     cursor = new SequenceCursor(sq, 13, 10, changeCount);
1476     assertFalse(sq.isValidCursor(cursor));
1477     cursor = new SequenceCursor(sq, 7, 8, changeCount);
1478     assertFalse(sq.isValidCursor(cursor));
1479     cursor = new SequenceCursor(sq, 14, 2, changeCount);
1480     assertFalse(sq.isValidCursor(cursor));
1481
1482     /*
1483      * wrong sequence is rejected
1484      */
1485     cursor = new SequenceCursor(null, 13, 1, changeCount);
1486     assertFalse(sq.isValidCursor(cursor));
1487     cursor = new SequenceCursor(new Sequence("Seq", "abc"), 13, 1,
1488             changeCount);
1489     assertFalse(sq.isValidCursor(cursor));
1490
1491     /*
1492      * wrong token value is rejected
1493      */
1494     cursor = new SequenceCursor(sq, 13, 1, changeCount + 1);
1495     assertFalse(sq.isValidCursor(cursor));
1496     cursor = new SequenceCursor(sq, 13, 1, changeCount - 1);
1497     assertFalse(sq.isValidCursor(cursor));
1498   }
1499
1500   @Test(groups = { "Functional" })
1501   public void testFindPosition_withCursorAndEdits()
1502   {
1503     Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
1504   
1505     // find F pos given A
1506     assertEquals(13, sq.findPosition(10, new SequenceCursor(sq, 8, 2, 0)));
1507     int token = (int) PA.getValue(sq, "changeCount"); // 0
1508     SequenceCursor cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1509     assertEquals(new SequenceCursor(sq, 13, 10, token), cursor);
1510
1511     /*
1512      * setSequence should invalidate the cursor cached by the sequence
1513      */
1514     sq.setSequence("-A-BCD-EF---"); // one gap removed
1515     assertEquals(8, sq.getStart()); // sanity check
1516     assertEquals(11, sq.findPosition(5)); // D11
1517     // cursor should now be at [D 6]
1518     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1519     assertEquals(new SequenceCursor(sq, 11, 6, ++token), cursor);
1520
1521     /*
1522      * deleteChars should invalidate the cached cursor
1523      */
1524     sq.deleteChars(2, 5); // delete -BC
1525     assertEquals("-AD-EF---", sq.getSequenceAsString());
1526     assertEquals(8, sq.getStart()); // sanity check
1527     assertEquals(10, sq.findPosition(4)); // E10
1528     // cursor should now be at [E 5]
1529     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1530     assertEquals(new SequenceCursor(sq, 10, 5, ++token), cursor);
1531
1532     /*
1533      * Edit to insert gaps should invalidate the cached cursor
1534      * insert 2 gaps at column[3] to make -AD---EF---
1535      */
1536     SequenceI[] seqs = new SequenceI[] { sq };
1537     AlignmentI al = new Alignment(seqs);
1538     new EditCommand().appendEdit(Action.INSERT_GAP, seqs, 3, 2, al, true);
1539     assertEquals("-AD---EF---", sq.getSequenceAsString());
1540     assertEquals(10, sq.findPosition(4)); // E10
1541     // cursor should now be at [D 3]
1542     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1543     assertEquals(new SequenceCursor(sq, 9, 3, ++token), cursor);
1544
1545     /*
1546      * insertCharAt should invalidate the cached cursor
1547      * insert CC at column[4] to make -AD-CC--EF---
1548      */
1549     sq.insertCharAt(4, 2, 'C');
1550     assertEquals("-AD-CC--EF---", sq.getSequenceAsString());
1551     assertEquals(13, sq.findPosition(9)); // F13
1552     // cursor should now be at [F 10]
1553     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1554     assertEquals(new SequenceCursor(sq, 13, 10, ++token), cursor);
1555   }
1556 }