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