Merge branch 'develop' into feature/JAL-2759
[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 org.testng.Assert;
45 import org.testng.annotations.BeforeClass;
46 import org.testng.annotations.BeforeMethod;
47 import org.testng.annotations.Test;
48
49 import junit.extensions.PA;
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
111   @Test(groups = { "Functional" })
112   public void testGetAnnotation()
113   {
114     // initial state returns null not an empty array
115     assertNull(seq.getAnnotation());
116     AlignmentAnnotation ann = addAnnotation("label1", "desc1", "calcId1",
117             1f);
118     AlignmentAnnotation[] anns = seq.getAnnotation();
119     assertEquals(1, anns.length);
120     assertSame(ann, anns[0]);
121
122     // removing all annotations reverts array to null
123     seq.removeAlignmentAnnotation(ann);
124     assertNull(seq.getAnnotation());
125   }
126
127   @Test(groups = { "Functional" })
128   public void testGetAnnotation_forLabel()
129   {
130     AlignmentAnnotation ann1 = addAnnotation("label1", "desc1", "calcId1",
131             1f);
132     addAnnotation("label2", "desc2", "calcId2", 1f);
133     AlignmentAnnotation ann3 = addAnnotation("label1", "desc3", "calcId3",
134             1f);
135     AlignmentAnnotation[] anns = seq.getAnnotation("label1");
136     assertEquals(2, anns.length);
137     assertSame(ann1, anns[0]);
138     assertSame(ann3, anns[1]);
139   }
140
141   private AlignmentAnnotation addAnnotation(String label,
142           String description, String calcId, float value)
143   {
144     final AlignmentAnnotation annotation = new AlignmentAnnotation(label,
145             description, value);
146     annotation.setCalcId(calcId);
147     seq.addAlignmentAnnotation(annotation);
148     return annotation;
149   }
150
151   @Test(groups = { "Functional" })
152   public void testGetAlignmentAnnotations_forCalcIdAndLabel()
153   {
154     addAnnotation("label1", "desc1", "calcId1", 1f);
155     AlignmentAnnotation ann2 = addAnnotation("label2", "desc2", "calcId2",
156             1f);
157     addAnnotation("label2", "desc3", "calcId3", 1f);
158     AlignmentAnnotation ann4 = addAnnotation("label2", "desc3", "calcId2",
159             1f);
160     addAnnotation("label5", "desc3", null, 1f);
161     addAnnotation(null, "desc3", "calcId3", 1f);
162
163     List<AlignmentAnnotation> anns = seq.getAlignmentAnnotations("calcId2",
164             "label2");
165     assertEquals(2, anns.size());
166     assertSame(ann2, anns.get(0));
167     assertSame(ann4, anns.get(1));
168
169     assertTrue(seq.getAlignmentAnnotations("calcId2", "label3").isEmpty());
170     assertTrue(seq.getAlignmentAnnotations("calcId3", "label5").isEmpty());
171     assertTrue(seq.getAlignmentAnnotations("calcId2", null).isEmpty());
172     assertTrue(seq.getAlignmentAnnotations(null, "label3").isEmpty());
173     assertTrue(seq.getAlignmentAnnotations(null, null).isEmpty());
174   }
175
176   /**
177    * Tests for addAlignmentAnnotation. Note this method has the side-effect of
178    * setting the sequenceRef on the annotation. Adding the same annotation twice
179    * should be ignored.
180    */
181   @Test(groups = { "Functional" })
182   public void testAddAlignmentAnnotation()
183   {
184     assertNull(seq.getAnnotation());
185     final AlignmentAnnotation annotation = new AlignmentAnnotation("a",
186             "b", 2d);
187     assertNull(annotation.sequenceRef);
188     seq.addAlignmentAnnotation(annotation);
189     assertSame(seq, annotation.sequenceRef);
190     AlignmentAnnotation[] anns = seq.getAnnotation();
191     assertEquals(1, anns.length);
192     assertSame(annotation, anns[0]);
193
194     // re-adding does nothing
195     seq.addAlignmentAnnotation(annotation);
196     anns = seq.getAnnotation();
197     assertEquals(1, anns.length);
198     assertSame(annotation, anns[0]);
199
200     // an identical but different annotation can be added
201     final AlignmentAnnotation annotation2 = new AlignmentAnnotation("a",
202             "b", 2d);
203     seq.addAlignmentAnnotation(annotation2);
204     anns = seq.getAnnotation();
205     assertEquals(2, anns.length);
206     assertSame(annotation, anns[0]);
207     assertSame(annotation2, anns[1]);
208   }
209
210   @Test(groups = { "Functional" })
211   public void testGetStartGetEnd()
212   {
213     SequenceI sq = new Sequence("test", "ABCDEF");
214     assertEquals(1, sq.getStart());
215     assertEquals(6, sq.getEnd());
216
217     sq = new Sequence("test", "--AB-C-DEF--");
218     assertEquals(1, sq.getStart());
219     assertEquals(6, sq.getEnd());
220
221     sq = new Sequence("test", "----");
222     assertEquals(1, sq.getStart());
223     assertEquals(0, sq.getEnd()); // ??
224   }
225
226   /**
227    * Tests for the method that returns an alignment column position (base 1) for
228    * a given sequence position (base 1).
229    */
230   @Test(groups = { "Functional" })
231   public void testFindIndex()
232   {
233     /* 
234      * call sequenceChanged() after each test to invalidate any cursor,
235      * forcing the 1-arg findIndex to be executed
236      */
237     SequenceI sq = new Sequence("test", "ABCDEF");
238     assertEquals(0, sq.findIndex(0));
239     sq.sequenceChanged();
240     assertEquals(1, sq.findIndex(1));
241     sq.sequenceChanged();
242     assertEquals(5, sq.findIndex(5));
243     sq.sequenceChanged();
244     assertEquals(6, sq.findIndex(6));
245     sq.sequenceChanged();
246     assertEquals(6, sq.findIndex(9));
247
248     sq = new Sequence("test/8-13", "-A--B-C-D-E-F--");
249     assertEquals(2, sq.findIndex(8));
250     sq.sequenceChanged();
251     assertEquals(5, sq.findIndex(9));
252     sq.sequenceChanged();
253     assertEquals(7, sq.findIndex(10));
254
255     // before start returns 0
256     sq.sequenceChanged();
257     assertEquals(0, sq.findIndex(0));
258     sq.sequenceChanged();
259     assertEquals(0, sq.findIndex(-1));
260
261     // beyond end returns last residue column
262     sq.sequenceChanged();
263     assertEquals(13, sq.findIndex(99));
264   }
265
266   /**
267    * Tests for the method that returns a dataset sequence position (start..) for
268    * an aligned column position (base 0).
269    */
270   @Test(groups = { "Functional" })
271   public void testFindPosition()
272   {
273     /* 
274      * call sequenceChanged() after each test to invalidate any cursor,
275      * forcing the 1-arg findPosition to be executed
276      */
277     SequenceI sq = new Sequence("test/8-13", "ABCDEF");
278     assertEquals(8, sq.findPosition(0));
279     // Sequence should now hold a cursor at [8, 0]
280     assertEquals("test:Pos8:Col1:startCol1:endCol0:tok0",
281             PA.getValue(sq, "cursor").toString());
282     SequenceCursor cursor = (SequenceCursor) PA.getValue(sq, "cursor");
283     int token = (int) PA.getValue(sq, "changeCount");
284     assertEquals(new SequenceCursor(sq, 8, 1, token), cursor);
285
286     sq.sequenceChanged();
287
288     /*
289      * find F13 at column offset 5, cursor should update to [13, 6]
290      * endColumn is found and saved in cursor
291      */
292     assertEquals(13, sq.findPosition(5));
293     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
294     assertEquals(++token, (int) PA.getValue(sq, "changeCount"));
295     assertEquals(new SequenceCursor(sq, 13, 6, token), cursor);
296     assertEquals("test:Pos13:Col6:startCol1:endCol6:tok1",
297             PA.getValue(sq, "cursor").toString());
298
299     // assertEquals(-1, seq.findPosition(6)); // fails
300
301     sq = new Sequence("test/8-11", "AB-C-D--");
302     token = (int) PA.getValue(sq, "changeCount"); // 0
303     assertEquals(8, sq.findPosition(0));
304     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
305     assertEquals(new SequenceCursor(sq, 8, 1, token), cursor);
306     assertEquals("test:Pos8:Col1:startCol1:endCol0:tok0",
307             PA.getValue(sq, "cursor").toString());
308
309     sq.sequenceChanged();
310     assertEquals(9, sq.findPosition(1));
311     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
312     assertEquals(new SequenceCursor(sq, 9, 2, ++token), cursor);
313     assertEquals("test:Pos9:Col2:startCol1:endCol0:tok1",
314             PA.getValue(sq, "cursor").toString());
315
316     sq.sequenceChanged();
317     // gap position 'finds' residue to the right (not the left as per javadoc)
318     // cursor is set to the last residue position found [B 2]
319     assertEquals(10, sq.findPosition(2));
320     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
321     assertEquals(new SequenceCursor(sq, 9, 2, ++token), cursor);
322     assertEquals("test:Pos9:Col2:startCol1:endCol0:tok2",
323             PA.getValue(sq, "cursor").toString());
324
325     sq.sequenceChanged();
326     assertEquals(10, sq.findPosition(3));
327     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
328     assertEquals(new SequenceCursor(sq, 10, 4, ++token), cursor);
329     assertEquals("test:Pos10:Col4:startCol1:endCol0:tok3",
330             PA.getValue(sq, "cursor").toString());
331
332     sq.sequenceChanged();
333     // column[4] is the gap after C - returns D11
334     // cursor is set to [C 4]
335     assertEquals(11, sq.findPosition(4));
336     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
337     assertEquals(new SequenceCursor(sq, 10, 4, ++token), cursor);
338     assertEquals("test:Pos10:Col4:startCol1:endCol0:tok4",
339             PA.getValue(sq, "cursor").toString());
340
341     sq.sequenceChanged();
342     assertEquals(11, sq.findPosition(5)); // D
343     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
344     assertEquals(new SequenceCursor(sq, 11, 6, ++token), cursor);
345     // lastCol has been found and saved in the cursor
346     assertEquals("test:Pos11:Col6:startCol1:endCol6:tok5",
347             PA.getValue(sq, "cursor").toString());
348
349     sq.sequenceChanged();
350     // returns 1 more than sequence length if off the end ?!?
351     assertEquals(12, sq.findPosition(6));
352
353     sq.sequenceChanged();
354     assertEquals(12, sq.findPosition(7));
355
356     /*
357      * first findPosition should also set firstResCol in cursor
358      */
359     sq = new Sequence("test/8-13", "--AB-C-DEF--");
360     assertEquals(8, sq.findPosition(0));
361     assertNull(PA.getValue(sq, "cursor"));
362
363     sq.sequenceChanged();
364     assertEquals(8, sq.findPosition(1));
365     assertNull(PA.getValue(sq, "cursor"));
366
367     sq.sequenceChanged();
368     assertEquals(8, sq.findPosition(2));
369     assertEquals("test:Pos8:Col3:startCol3:endCol0:tok2",
370             PA.getValue(sq, "cursor").toString());
371
372     sq.sequenceChanged();
373     assertEquals(9, sq.findPosition(3));
374     assertEquals("test:Pos9:Col4:startCol3:endCol0:tok3",
375             PA.getValue(sq, "cursor").toString());
376
377     sq.sequenceChanged();
378     // column[4] is a gap, returns next residue pos (C10)
379     // cursor is set to last residue found [B]
380     assertEquals(10, sq.findPosition(4));
381     assertEquals("test:Pos9:Col4:startCol3:endCol0:tok4",
382             PA.getValue(sq, "cursor").toString());
383
384     sq.sequenceChanged();
385     assertEquals(10, sq.findPosition(5));
386     assertEquals("test:Pos10:Col6:startCol3:endCol0:tok5",
387             PA.getValue(sq, "cursor").toString());
388
389     sq.sequenceChanged();
390     // column[6] is a gap, returns next residue pos (D11)
391     // cursor is set to last residue found [C]
392     assertEquals(11, sq.findPosition(6));
393     assertEquals("test:Pos10:Col6:startCol3:endCol0:tok6",
394             PA.getValue(sq, "cursor").toString());
395
396     sq.sequenceChanged();
397     assertEquals(11, sq.findPosition(7));
398     assertEquals("test:Pos11:Col8:startCol3:endCol0:tok7",
399             PA.getValue(sq, "cursor").toString());
400
401     sq.sequenceChanged();
402     assertEquals(12, sq.findPosition(8));
403     assertEquals("test:Pos12:Col9:startCol3:endCol0:tok8",
404             PA.getValue(sq, "cursor").toString());
405
406     /*
407      * when the last residue column is found, it is set in the cursor
408      */
409     sq.sequenceChanged();
410     assertEquals(13, sq.findPosition(9));
411     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok9",
412             PA.getValue(sq, "cursor").toString());
413
414     sq.sequenceChanged();
415     assertEquals(14, sq.findPosition(10));
416     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok10",
417             PA.getValue(sq, "cursor").toString());
418
419     /*
420      * findPosition for column beyond sequence length
421      * returns 1 more than last residue position
422      */
423     sq.sequenceChanged();
424     assertEquals(14, sq.findPosition(11));
425     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok11",
426             PA.getValue(sq, "cursor").toString());
427
428     sq.sequenceChanged();
429     assertEquals(14, sq.findPosition(99));
430     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok12",
431             PA.getValue(sq, "cursor").toString());
432
433     /*
434      * gapped sequence ending in non-gap
435      */
436     sq = new Sequence("test/8-13", "--AB-C-DEF");
437     assertEquals(13, sq.findPosition(9));
438     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok0",
439             PA.getValue(sq, "cursor").toString());
440     sq.sequenceChanged();
441     assertEquals(12, sq.findPosition(8));
442     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
443     // sequenceChanged() invalidates cursor.lastResidueColumn
444     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
445     assertEquals("test:Pos12:Col9:startCol3:endCol0:tok1",
446             cursor.toString());
447     // findPosition with cursor accepts base 1 column values
448     assertEquals(13, ((Sequence) sq).findPosition(10, cursor));
449     assertEquals(13, sq.findPosition(9)); // F13
450     // lastResidueColumn has now been found and saved in cursor
451     assertEquals("test:Pos13:Col10:startCol3:endCol10:tok1",
452             PA.getValue(sq, "cursor").toString());
453   }
454
455   @Test(groups = { "Functional" })
456   public void testDeleteChars()
457   {
458     /*
459      * internal delete
460      */
461     SequenceI sq = new Sequence("test", "ABCDEF");
462     assertNull(PA.getValue(sq, "datasetSequence"));
463     assertEquals(1, sq.getStart());
464     assertEquals(6, sq.getEnd());
465     sq.deleteChars(2, 3);
466     assertEquals("ABDEF", sq.getSequenceAsString());
467     assertEquals(1, sq.getStart());
468     assertEquals(5, sq.getEnd());
469     assertNull(PA.getValue(sq, "datasetSequence"));
470
471     /*
472      * delete at start
473      */
474     sq = new Sequence("test", "ABCDEF");
475     sq.deleteChars(0, 2);
476     assertEquals("CDEF", sq.getSequenceAsString());
477     assertEquals(3, sq.getStart());
478     assertEquals(6, sq.getEnd());
479     assertNull(PA.getValue(sq, "datasetSequence"));
480
481     /*
482      * delete at end
483      */
484     sq = new Sequence("test", "ABCDEF");
485     sq.deleteChars(4, 6);
486     assertEquals("ABCD", sq.getSequenceAsString());
487     assertEquals(1, sq.getStart());
488     assertEquals(4, sq.getEnd());
489     assertNull(PA.getValue(sq, "datasetSequence"));
490   }
491
492   @Test(groups = { "Functional" })
493   public void testDeleteChars_withDbRefsAndFeatures()
494   {
495     /*
496      * internal delete - new dataset sequence created
497      * gets a copy of any dbrefs
498      */
499     SequenceI sq = new Sequence("test", "ABCDEF");
500     sq.createDatasetSequence();
501     DBRefEntry dbr1 = new DBRefEntry("Uniprot", "0", "a123");
502     sq.addDBRef(dbr1);
503     Object ds = PA.getValue(sq, "datasetSequence");
504     assertNotNull(ds);
505     assertEquals(1, sq.getStart());
506     assertEquals(6, sq.getEnd());
507     sq.deleteChars(2, 3);
508     assertEquals("ABDEF", sq.getSequenceAsString());
509     assertEquals(1, sq.getStart());
510     assertEquals(5, sq.getEnd());
511     Object newDs = PA.getValue(sq, "datasetSequence");
512     assertNotNull(newDs);
513     assertNotSame(ds, newDs);
514     assertNotNull(sq.getDBRefs());
515     assertEquals(1, sq.getDBRefs().length);
516     assertNotSame(dbr1, sq.getDBRefs()[0]);
517     assertEquals(dbr1, sq.getDBRefs()[0]);
518
519     /*
520      * internal delete with sequence features
521      * (failure case for JAL-2541)
522      */
523     sq = new Sequence("test", "ABCDEF");
524     sq.createDatasetSequence();
525     SequenceFeature sf1 = new SequenceFeature("Cath", "desc", 2, 4, 2f,
526             "CathGroup");
527     sq.addSequenceFeature(sf1);
528     ds = PA.getValue(sq, "datasetSequence");
529     assertNotNull(ds);
530     assertEquals(1, sq.getStart());
531     assertEquals(6, sq.getEnd());
532     sq.deleteChars(2, 4);
533     assertEquals("ABEF", sq.getSequenceAsString());
534     assertEquals(1, sq.getStart());
535     assertEquals(4, sq.getEnd());
536     newDs = PA.getValue(sq, "datasetSequence");
537     assertNotNull(newDs);
538     assertNotSame(ds, newDs);
539     List<SequenceFeature> sfs = sq.getSequenceFeatures();
540     assertEquals(1, sfs.size());
541     assertNotSame(sf1, sfs.get(0));
542     assertEquals(sf1, sfs.get(0));
543
544     /*
545      * delete at start - no new dataset sequence created
546      * any sequence features remain as before
547      */
548     sq = new Sequence("test", "ABCDEF");
549     sq.createDatasetSequence();
550     ds = PA.getValue(sq, "datasetSequence");
551     sf1 = new SequenceFeature("Cath", "desc", 2, 4, 2f, "CathGroup");
552     sq.addSequenceFeature(sf1);
553     sq.deleteChars(0, 2);
554     assertEquals("CDEF", sq.getSequenceAsString());
555     assertEquals(3, sq.getStart());
556     assertEquals(6, sq.getEnd());
557     assertSame(ds, PA.getValue(sq, "datasetSequence"));
558     sfs = sq.getSequenceFeatures();
559     assertNotNull(sfs);
560     assertEquals(1, sfs.size());
561     assertSame(sf1, sfs.get(0));
562
563     /*
564      * delete at end - no new dataset sequence created
565      * any dbrefs remain as before
566      */
567     sq = new Sequence("test", "ABCDEF");
568     sq.createDatasetSequence();
569     ds = PA.getValue(sq, "datasetSequence");
570     dbr1 = new DBRefEntry("Uniprot", "0", "a123");
571     sq.addDBRef(dbr1);
572     sq.deleteChars(4, 6);
573     assertEquals("ABCD", sq.getSequenceAsString());
574     assertEquals(1, sq.getStart());
575     assertEquals(4, sq.getEnd());
576     assertSame(ds, PA.getValue(sq, "datasetSequence"));
577     assertNotNull(sq.getDBRefs());
578     assertEquals(1, sq.getDBRefs().length);
579     assertSame(dbr1, sq.getDBRefs()[0]);
580   }
581
582   @Test(groups = { "Functional" })
583   public void testInsertCharAt()
584   {
585     // non-static methods:
586     SequenceI sq = new Sequence("test", "ABCDEF");
587     sq.insertCharAt(0, 'z');
588     assertEquals("zABCDEF", sq.getSequenceAsString());
589     sq.insertCharAt(2, 2, 'x');
590     assertEquals("zAxxBCDEF", sq.getSequenceAsString());
591
592     // for static method see StringUtilsTest
593   }
594
595   /**
596    * Test the method that returns an array of aligned sequence positions where
597    * the array index is the data sequence position (both base 0).
598    */
599   @Test(groups = { "Functional" })
600   public void testGapMap()
601   {
602     SequenceI sq = new Sequence("test", "-A--B-CD-E--F-");
603     sq.createDatasetSequence();
604     assertEquals("[1, 4, 6, 7, 9, 12]", Arrays.toString(sq.gapMap()));
605   }
606
607   /**
608    * Test the method that gets sequence features, either from the sequence or
609    * its dataset.
610    */
611   @Test(groups = { "Functional" })
612   public void testGetSequenceFeatures()
613   {
614     SequenceI sq = new Sequence("test", "GATCAT");
615     sq.createDatasetSequence();
616
617     assertTrue(sq.getSequenceFeatures().isEmpty());
618
619     /*
620      * SequenceFeature on sequence
621      */
622     SequenceFeature sf = new SequenceFeature("Cath", "desc", 2, 4, 2f, null);
623     sq.addSequenceFeature(sf);
624     List<SequenceFeature> sfs = sq.getSequenceFeatures();
625     assertEquals(1, sfs.size());
626     assertSame(sf, sfs.get(0));
627
628     /*
629      * SequenceFeature on sequence and dataset sequence; returns that on
630      * sequence
631      * 
632      * Note JAL-2046: spurious: we have no use case for this at the moment.
633      * This test also buggy - as sf2.equals(sf), no new feature is added
634      */
635     SequenceFeature sf2 = new SequenceFeature("Cath", "desc", 2, 4, 2f,
636             null);
637     sq.getDatasetSequence().addSequenceFeature(sf2);
638     sfs = sq.getSequenceFeatures();
639     assertEquals(1, sfs.size());
640     assertSame(sf, sfs.get(0));
641
642     /*
643      * SequenceFeature on dataset sequence only
644      * Note JAL-2046: spurious: we have no use case for setting a non-dataset sequence's feature array to null at the moment.
645      */
646     sq.setSequenceFeatures(null);
647     assertTrue(sq.getDatasetSequence().getSequenceFeatures().isEmpty());
648
649     /*
650      * Corrupt case - no SequenceFeature, dataset's dataset is the original
651      * sequence. Test shows no infinite loop results.
652      */
653     sq.getDatasetSequence().setSequenceFeatures(null);
654     /**
655      * is there a usecase for this ? setDatasetSequence should throw an error if
656      * this actually occurs.
657      */
658     try
659     {
660       sq.getDatasetSequence().setDatasetSequence(sq); // loop!
661       Assert.fail("Expected Error to be raised when calling setDatasetSequence with self reference");
662     } catch (IllegalArgumentException e)
663     {
664       // TODO Jalview error/exception class for raising implementation errors
665       assertTrue(e.getMessage().toLowerCase()
666               .contains("implementation error"));
667     }
668     assertTrue(sq.getSequenceFeatures().isEmpty());
669   }
670
671   /**
672    * Test the method that returns an array, indexed by sequence position, whose
673    * entries are the residue positions at the sequence position (or to the right
674    * if a gap)
675    */
676   @Test(groups = { "Functional" })
677   public void testFindPositionMap()
678   {
679     /*
680      * Note: Javadoc for findPosition says it returns the residue position to
681      * the left of a gapped position; in fact it returns the position to the
682      * right. Also it returns a non-existent residue position for a gap beyond
683      * the sequence.
684      */
685     Sequence sq = new Sequence("TestSeq", "AB.C-D E.");
686     int[] map = sq.findPositionMap();
687     assertEquals(Arrays.toString(new int[] { 1, 2, 3, 3, 4, 4, 5, 5, 6 }),
688             Arrays.toString(map));
689   }
690
691   /**
692    * Test for getSubsequence
693    */
694   @Test(groups = { "Functional" })
695   public void testGetSubsequence()
696   {
697     SequenceI sq = new Sequence("TestSeq", "ABCDEFG");
698     sq.createDatasetSequence();
699
700     // positions are base 0, end position is exclusive
701     SequenceI subseq = sq.getSubSequence(2, 4);
702
703     assertEquals("CD", subseq.getSequenceAsString());
704     // start/end are base 1 positions
705     assertEquals(3, subseq.getStart());
706     assertEquals(4, subseq.getEnd());
707     // subsequence shares the full dataset sequence
708     assertSame(sq.getDatasetSequence(), subseq.getDatasetSequence());
709   }
710
711   /**
712    * test createDatasetSequence behaves to doc
713    */
714   @Test(groups = { "Functional" })
715   public void testCreateDatasetSequence()
716   {
717     SequenceI sq = new Sequence("my", "ASDASD");
718     sq.addSequenceFeature(new SequenceFeature("type", "desc", 1, 10, 1f,
719             "group"));
720     sq.addDBRef(new DBRefEntry("source", "version", "accession"));
721     assertNull(sq.getDatasetSequence());
722     assertNotNull(PA.getValue(sq, "sequenceFeatureStore"));
723     assertNotNull(PA.getValue(sq, "dbrefs"));
724
725     SequenceI rds = sq.createDatasetSequence();
726     assertNotNull(rds);
727     assertNull(rds.getDatasetSequence());
728     assertSame(sq.getDatasetSequence(), rds);
729
730     // sequence features and dbrefs transferred to dataset sequence
731     assertNull(PA.getValue(sq, "sequenceFeatureStore"));
732     assertNull(PA.getValue(sq, "dbrefs"));
733     assertNotNull(PA.getValue(rds, "sequenceFeatureStore"));
734     assertNotNull(PA.getValue(rds, "dbrefs"));
735   }
736
737   /**
738    * Test for deriveSequence applied to a sequence with a dataset
739    */
740   @Test(groups = { "Functional" })
741   public void testDeriveSequence_existingDataset()
742   {
743     Sequence sq = new Sequence("Seq1", "CD");
744     sq.setDatasetSequence(new Sequence("Seq1", "ABCDEF"));
745     sq.getDatasetSequence().addSequenceFeature(
746             new SequenceFeature("", "", 1, 2, 0f, null));
747     sq.setStart(3);
748     sq.setEnd(4);
749
750     sq.setDescription("Test sequence description..");
751     sq.setVamsasId("TestVamsasId");
752     sq.addDBRef(new DBRefEntry("PDB", "version0", "1TST"));
753
754     sq.addDBRef(new DBRefEntry("PDB", "version1", "1PDB"));
755     sq.addDBRef(new DBRefEntry("PDB", "version2", "2PDB"));
756     sq.addDBRef(new DBRefEntry("PDB", "version3", "3PDB"));
757     sq.addDBRef(new DBRefEntry("PDB", "version4", "4PDB"));
758
759     sq.addPDBId(new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1"));
760     sq.addPDBId(new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1"));
761     sq.addPDBId(new PDBEntry("2PDB", "A", Type.MMCIF, "filePath/test2"));
762     sq.addPDBId(new PDBEntry("2PDB", "B", Type.MMCIF, "filePath/test2"));
763
764     // these are the same as ones already added
765     DBRefEntry pdb1pdb = new DBRefEntry("PDB", "version1", "1PDB");
766     DBRefEntry pdb2pdb = new DBRefEntry("PDB", "version2", "2PDB");
767
768     List<DBRefEntry> primRefs = Arrays.asList(new DBRefEntry[] { pdb1pdb,
769         pdb2pdb });
770
771     sq.getDatasetSequence().addDBRef(pdb1pdb); // should do nothing
772     sq.getDatasetSequence().addDBRef(pdb2pdb); // should do nothing
773     sq.getDatasetSequence().addDBRef(
774             new DBRefEntry("PDB", "version3", "3PDB")); // should do nothing
775     sq.getDatasetSequence().addDBRef(
776             new DBRefEntry("PDB", "version4", "4PDB")); // should do nothing
777
778     PDBEntry pdbe1a = new PDBEntry("1PDB", "A", Type.PDB, "filePath/test1");
779     PDBEntry pdbe1b = new PDBEntry("1PDB", "B", Type.PDB, "filePath/test1");
780     PDBEntry pdbe2a = new PDBEntry("2PDB", "A", Type.MMCIF,
781             "filePath/test2");
782     PDBEntry pdbe2b = new PDBEntry("2PDB", "B", Type.MMCIF,
783             "filePath/test2");
784     sq.getDatasetSequence().addPDBId(pdbe1a);
785     sq.getDatasetSequence().addPDBId(pdbe1b);
786     sq.getDatasetSequence().addPDBId(pdbe2a);
787     sq.getDatasetSequence().addPDBId(pdbe2b);
788
789     /*
790      * test we added pdb entries to the dataset sequence
791      */
792     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries(), Arrays
793             .asList(new PDBEntry[] { pdbe1a, pdbe1b, pdbe2a, pdbe2b }),
794             "PDB Entries were not found on dataset sequence.");
795
796     /*
797      * we should recover a pdb entry that is on the dataset sequence via PDBEntry
798      */
799     Assert.assertEquals(pdbe1a,
800             sq.getDatasetSequence().getPDBEntry("1PDB"),
801             "PDB Entry '1PDB' not found on dataset sequence via getPDBEntry.");
802     ArrayList<Annotation> annotsList = new ArrayList<>();
803     System.out.println(">>>>>> " + sq.getSequenceAsString().length());
804     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
805     annotsList.add(new Annotation("A", "A", 'X', 0.1f));
806     Annotation[] annots = annotsList.toArray(new Annotation[0]);
807     sq.addAlignmentAnnotation(new AlignmentAnnotation("Test annot",
808             "Test annot description", annots));
809     sq.getDatasetSequence().addAlignmentAnnotation(
810             new AlignmentAnnotation("Test annot", "Test annot description",
811                     annots));
812     Assert.assertEquals(sq.getDescription(), "Test sequence description..");
813     Assert.assertEquals(sq.getDBRefs().length, 5); // DBRefs are on dataset
814                                                    // sequence
815     Assert.assertEquals(sq.getAllPDBEntries().size(), 4);
816     Assert.assertNotNull(sq.getAnnotation());
817     Assert.assertEquals(sq.getAnnotation()[0].annotations.length, 2);
818     Assert.assertEquals(sq.getDatasetSequence().getDBRefs().length, 5); // same
819                                                                         // as
820                                                                         // sq.getDBRefs()
821     Assert.assertEquals(sq.getDatasetSequence().getAllPDBEntries().size(),
822             4);
823     Assert.assertNotNull(sq.getDatasetSequence().getAnnotation());
824
825     Sequence derived = (Sequence) sq.deriveSequence();
826
827     Assert.assertEquals(derived.getDescription(),
828             "Test sequence description..");
829     Assert.assertEquals(derived.getDBRefs().length, 5); // come from dataset
830     Assert.assertEquals(derived.getAllPDBEntries().size(), 4);
831     Assert.assertNotNull(derived.getAnnotation());
832     Assert.assertEquals(derived.getAnnotation()[0].annotations.length, 2);
833     Assert.assertEquals(derived.getDatasetSequence().getDBRefs().length, 5);
834     Assert.assertEquals(derived.getDatasetSequence().getAllPDBEntries()
835             .size(), 4);
836     Assert.assertNotNull(derived.getDatasetSequence().getAnnotation());
837
838     assertEquals("CD", derived.getSequenceAsString());
839     assertSame(sq.getDatasetSequence(), derived.getDatasetSequence());
840
841     // derived sequence should access dataset sequence features
842     assertNotNull(sq.getSequenceFeatures());
843     assertEquals(sq.getSequenceFeatures(), derived.getSequenceFeatures());
844
845     /*
846      *  verify we have primary db refs *just* for PDB IDs with associated
847      *  PDBEntry objects
848      */
849
850     assertEquals(primRefs, sq.getPrimaryDBRefs());
851     assertEquals(primRefs, sq.getDatasetSequence().getPrimaryDBRefs());
852
853     assertEquals(sq.getPrimaryDBRefs(), derived.getPrimaryDBRefs());
854
855   }
856
857   /**
858    * Test for deriveSequence applied to an ungapped sequence with no dataset
859    */
860   @Test(groups = { "Functional" })
861   public void testDeriveSequence_noDatasetUngapped()
862   {
863     SequenceI sq = new Sequence("Seq1", "ABCDEF");
864     assertEquals(1, sq.getStart());
865     assertEquals(6, sq.getEnd());
866     SequenceI derived = sq.deriveSequence();
867     assertEquals("ABCDEF", derived.getSequenceAsString());
868     assertEquals("ABCDEF", derived.getDatasetSequence()
869             .getSequenceAsString());
870   }
871
872   /**
873    * Test for deriveSequence applied to a gapped sequence with no dataset
874    */
875   @Test(groups = { "Functional" })
876   public void testDeriveSequence_noDatasetGapped()
877   {
878     SequenceI sq = new Sequence("Seq1", "AB-C.D EF");
879     assertEquals(1, sq.getStart());
880     assertEquals(6, sq.getEnd());
881     assertNull(sq.getDatasetSequence());
882     SequenceI derived = sq.deriveSequence();
883     assertEquals("AB-C.D EF", derived.getSequenceAsString());
884     assertEquals("ABCDEF", derived.getDatasetSequence()
885             .getSequenceAsString());
886   }
887
888   @Test(groups = { "Functional" })
889   public void testCopyConstructor_noDataset()
890   {
891     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
892     seq1.setDescription("description");
893     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
894             1.3d));
895     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
896             12.4f, "group"));
897     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
898     seq1.addDBRef(new DBRefEntry("EMBL", "1.2", "AZ12345"));
899
900     SequenceI copy = new Sequence(seq1);
901
902     assertNull(copy.getDatasetSequence());
903
904     verifyCopiedSequence(seq1, copy);
905
906     // copy has a copy of the DBRefEntry
907     // this is murky - DBrefs are only copied for dataset sequences
908     // where the test for 'dataset sequence' is 'dataset is null'
909     // but that doesn't distinguish it from an aligned sequence
910     // which has not yet generated a dataset sequence
911     // NB getDBRef looks inside dataset sequence if not null
912     DBRefEntry[] dbrefs = copy.getDBRefs();
913     assertEquals(1, dbrefs.length);
914     assertFalse(dbrefs[0] == seq1.getDBRefs()[0]);
915     assertTrue(dbrefs[0].equals(seq1.getDBRefs()[0]));
916   }
917
918   @Test(groups = { "Functional" })
919   public void testCopyConstructor_withDataset()
920   {
921     SequenceI seq1 = new Sequence("Seq1", "AB-C.D EF");
922     seq1.createDatasetSequence();
923     seq1.setDescription("description");
924     seq1.addAlignmentAnnotation(new AlignmentAnnotation("label", "desc",
925             1.3d));
926     // JAL-2046 - what is the contract for using a derived sequence's
927     // addSequenceFeature ?
928     seq1.addSequenceFeature(new SequenceFeature("type", "desc", 22, 33,
929             12.4f, "group"));
930     seq1.addPDBId(new PDBEntry("1A70", "B", Type.PDB, "File"));
931     // here we add DBRef to the dataset sequence:
932     seq1.getDatasetSequence().addDBRef(
933             new DBRefEntry("EMBL", "1.2", "AZ12345"));
934
935     SequenceI copy = new Sequence(seq1);
936
937     assertNotNull(copy.getDatasetSequence());
938     assertSame(copy.getDatasetSequence(), seq1.getDatasetSequence());
939
940     verifyCopiedSequence(seq1, copy);
941
942     // getDBRef looks inside dataset sequence and this is shared,
943     // so holds the same dbref objects
944     DBRefEntry[] dbrefs = copy.getDBRefs();
945     assertEquals(1, dbrefs.length);
946     assertSame(dbrefs[0], seq1.getDBRefs()[0]);
947   }
948
949   /**
950    * Helper to make assertions about a copied sequence
951    * 
952    * @param seq1
953    * @param copy
954    */
955   protected void verifyCopiedSequence(SequenceI seq1, SequenceI copy)
956   {
957     // verify basic properties:
958     assertEquals(copy.getName(), seq1.getName());
959     assertEquals(copy.getDescription(), seq1.getDescription());
960     assertEquals(copy.getStart(), seq1.getStart());
961     assertEquals(copy.getEnd(), seq1.getEnd());
962     assertEquals(copy.getSequenceAsString(), seq1.getSequenceAsString());
963
964     // copy has a copy of the annotation:
965     AlignmentAnnotation[] anns = copy.getAnnotation();
966     assertEquals(1, anns.length);
967     assertFalse(anns[0] == seq1.getAnnotation()[0]);
968     assertEquals(anns[0].label, seq1.getAnnotation()[0].label);
969     assertEquals(anns[0].description, seq1.getAnnotation()[0].description);
970     assertEquals(anns[0].score, seq1.getAnnotation()[0].score);
971
972     // copy has a copy of the sequence feature:
973     List<SequenceFeature> sfs = copy.getSequenceFeatures();
974     assertEquals(1, sfs.size());
975     if (seq1.getDatasetSequence() != null
976             && copy.getDatasetSequence() == seq1.getDatasetSequence())
977     {
978       assertSame(sfs.get(0), seq1.getSequenceFeatures().get(0));
979     }
980     else
981     {
982       assertNotSame(sfs.get(0), seq1.getSequenceFeatures().get(0));
983     }
984     assertEquals(sfs.get(0), seq1.getSequenceFeatures().get(0));
985
986     // copy has a copy of the PDB entry
987     Vector<PDBEntry> pdbs = copy.getAllPDBEntries();
988     assertEquals(1, pdbs.size());
989     assertFalse(pdbs.get(0) == seq1.getAllPDBEntries().get(0));
990     assertTrue(pdbs.get(0).equals(seq1.getAllPDBEntries().get(0)));
991   }
992
993   @Test(groups = "Functional")
994   public void testGetCharAt()
995   {
996     SequenceI sq = new Sequence("", "abcde");
997     assertEquals('a', sq.getCharAt(0));
998     assertEquals('e', sq.getCharAt(4));
999     assertEquals(' ', sq.getCharAt(5));
1000     assertEquals(' ', sq.getCharAt(-1));
1001   }
1002
1003   @Test(groups = { "Functional" })
1004   public void testAddSequenceFeatures()
1005   {
1006     SequenceI sq = new Sequence("", "abcde");
1007     // type may not be null
1008     assertFalse(sq.addSequenceFeature(new SequenceFeature(null, "desc", 4,
1009             8, 0f, null)));
1010     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
1011             8, 0f, null)));
1012     // can't add a duplicate feature
1013     assertFalse(sq.addSequenceFeature(new SequenceFeature("Cath", "desc",
1014             4, 8, 0f, null)));
1015     // can add a different feature
1016     assertTrue(sq.addSequenceFeature(new SequenceFeature("Scop", "desc", 4,
1017             8, 0f, null))); // different type
1018     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath",
1019             "description", 4, 8, 0f, null)));// different description
1020     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 3,
1021             8, 0f, null))); // different start position
1022     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
1023             9, 0f, null))); // different end position
1024     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
1025             8, 1f, null))); // different score
1026     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
1027             8, Float.NaN, null))); // score NaN
1028     assertTrue(sq.addSequenceFeature(new SequenceFeature("Cath", "desc", 4,
1029             8, 0f, "Metal"))); // different group
1030     assertEquals(8, sq.getFeatures().getAllFeatures().size());
1031   }
1032
1033   /**
1034    * Tests for adding (or updating) dbrefs
1035    * 
1036    * @see DBRefEntry#updateFrom(DBRefEntry)
1037    */
1038   @Test(groups = { "Functional" })
1039   public void testAddDBRef()
1040   {
1041     SequenceI sq = new Sequence("", "abcde");
1042     assertNull(sq.getDBRefs());
1043     DBRefEntry dbref = new DBRefEntry("Uniprot", "1", "P00340");
1044     sq.addDBRef(dbref);
1045     assertEquals(1, sq.getDBRefs().length);
1046     assertSame(dbref, sq.getDBRefs()[0]);
1047
1048     /*
1049      * change of version - new entry
1050      */
1051     DBRefEntry dbref2 = new DBRefEntry("Uniprot", "2", "P00340");
1052     sq.addDBRef(dbref2);
1053     assertEquals(2, sq.getDBRefs().length);
1054     assertSame(dbref, sq.getDBRefs()[0]);
1055     assertSame(dbref2, sq.getDBRefs()[1]);
1056
1057     /*
1058      * matches existing entry - not added
1059      */
1060     sq.addDBRef(new DBRefEntry("UNIPROT", "1", "p00340"));
1061     assertEquals(2, sq.getDBRefs().length);
1062
1063     /*
1064      * different source = new entry
1065      */
1066     DBRefEntry dbref3 = new DBRefEntry("UniRef", "1", "p00340");
1067     sq.addDBRef(dbref3);
1068     assertEquals(3, sq.getDBRefs().length);
1069     assertSame(dbref3, sq.getDBRefs()[2]);
1070
1071     /*
1072      * different ref = new entry
1073      */
1074     DBRefEntry dbref4 = new DBRefEntry("UniRef", "1", "p00341");
1075     sq.addDBRef(dbref4);
1076     assertEquals(4, sq.getDBRefs().length);
1077     assertSame(dbref4, sq.getDBRefs()[3]);
1078
1079     /*
1080      * matching ref with a mapping - map updated
1081      */
1082     DBRefEntry dbref5 = new DBRefEntry("UniRef", "1", "p00341");
1083     Mapping map = new Mapping(new MapList(new int[] { 1, 3 }, new int[] {
1084         1, 1 }, 3, 1));
1085     dbref5.setMap(map);
1086     sq.addDBRef(dbref5);
1087     assertEquals(4, sq.getDBRefs().length);
1088     assertSame(dbref4, sq.getDBRefs()[3]);
1089     assertSame(map, dbref4.getMap());
1090
1091     /*
1092      * 'real' version replaces "0" version
1093      */
1094     dbref2.setVersion("0");
1095     DBRefEntry dbref6 = new DBRefEntry(dbref2.getSource(), "3",
1096             dbref2.getAccessionId());
1097     sq.addDBRef(dbref6);
1098     assertEquals(4, sq.getDBRefs().length);
1099     assertSame(dbref2, sq.getDBRefs()[1]);
1100     assertEquals("3", dbref2.getVersion());
1101
1102     /*
1103      * 'real' version replaces "source:0" version
1104      */
1105     dbref3.setVersion("Uniprot:0");
1106     DBRefEntry dbref7 = new DBRefEntry(dbref3.getSource(), "3",
1107             dbref3.getAccessionId());
1108     sq.addDBRef(dbref7);
1109     assertEquals(4, sq.getDBRefs().length);
1110     assertSame(dbref3, sq.getDBRefs()[2]);
1111     assertEquals("3", dbref2.getVersion());
1112   }
1113
1114   @Test(groups = { "Functional" })
1115   public void testGetPrimaryDBRefs_peptide()
1116   {
1117     SequenceI sq = new Sequence("aseq", "ASDFKYLMQPRST", 10, 22);
1118
1119     // no dbrefs
1120     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
1121     assertTrue(primaryDBRefs.isEmpty());
1122
1123     // empty dbrefs
1124     sq.setDBRefs(new DBRefEntry[] {});
1125     primaryDBRefs = sq.getPrimaryDBRefs();
1126     assertTrue(primaryDBRefs.isEmpty());
1127
1128     // primary - uniprot
1129     DBRefEntry upentry1 = new DBRefEntry("UNIPROT", "0", "Q04760");
1130     sq.addDBRef(upentry1);
1131
1132     // primary - uniprot with congruent map
1133     DBRefEntry upentry2 = new DBRefEntry("UNIPROT", "0", "Q04762");
1134     upentry2.setMap(new Mapping(null, new MapList(new int[] { 10, 22 },
1135             new int[] { 10, 22 }, 1, 1)));
1136     sq.addDBRef(upentry2);
1137
1138     // primary - uniprot with map of enclosing sequence
1139     DBRefEntry upentry3 = new DBRefEntry("UNIPROT", "0", "Q04763");
1140     upentry3.setMap(new Mapping(null, new MapList(new int[] { 8, 24 },
1141             new int[] { 8, 24 }, 1, 1)));
1142     sq.addDBRef(upentry3);
1143
1144     // not primary - uniprot with map of sub-sequence (5')
1145     DBRefEntry upentry4 = new DBRefEntry("UNIPROT", "0", "Q04764");
1146     upentry4.setMap(new Mapping(null, new MapList(new int[] { 10, 18 },
1147             new int[] { 10, 18 }, 1, 1)));
1148     sq.addDBRef(upentry4);
1149
1150     // not primary - uniprot with map that overlaps 3'
1151     DBRefEntry upentry5 = new DBRefEntry("UNIPROT", "0", "Q04765");
1152     upentry5.setMap(new Mapping(null, new MapList(new int[] { 12, 22 },
1153             new int[] { 12, 22 }, 1, 1)));
1154     sq.addDBRef(upentry5);
1155
1156     // not primary - uniprot with map to different coordinates frame
1157     DBRefEntry upentry6 = new DBRefEntry("UNIPROT", "0", "Q04766");
1158     upentry6.setMap(new Mapping(null, new MapList(new int[] { 12, 18 },
1159             new int[] { 112, 118 }, 1, 1)));
1160     sq.addDBRef(upentry6);
1161
1162     // not primary - dbref to 'non-core' database
1163     DBRefEntry upentry7 = new DBRefEntry("Pfam", "0", "PF00903");
1164     sq.addDBRef(upentry7);
1165
1166     // primary - type is PDB
1167     DBRefEntry pdbentry = new DBRefEntry("PDB", "0", "1qip");
1168     sq.addDBRef(pdbentry);
1169
1170     // not primary - PDBEntry has no file
1171     sq.addDBRef(new DBRefEntry("PDB", "0", "1AAA"));
1172
1173     // not primary - no PDBEntry
1174     sq.addDBRef(new DBRefEntry("PDB", "0", "1DDD"));
1175
1176     // add corroborating PDB entry for primary DBref -
1177     // needs to have a file as well as matching ID
1178     // note PDB ID is not treated as case sensitive
1179     sq.addPDBId(new PDBEntry("1QIP", null, Type.PDB, new File("/blah")
1180             .toString()));
1181
1182     // not valid DBRef - no file..
1183     sq.addPDBId(new PDBEntry("1AAA", null, null, null));
1184
1185     primaryDBRefs = sq.getPrimaryDBRefs();
1186     assertEquals(4, primaryDBRefs.size());
1187     assertTrue("Couldn't find simple primary reference (UNIPROT)",
1188             primaryDBRefs.contains(upentry1));
1189     assertTrue("Couldn't find mapped primary reference (UNIPROT)",
1190             primaryDBRefs.contains(upentry2));
1191     assertTrue("Couldn't find mapped context reference (UNIPROT)",
1192             primaryDBRefs.contains(upentry3));
1193     assertTrue("Couldn't find expected PDB primary reference",
1194             primaryDBRefs.contains(pdbentry));
1195   }
1196
1197   @Test(groups = { "Functional" })
1198   public void testGetPrimaryDBRefs_nucleotide()
1199   {
1200     SequenceI sq = new Sequence("aseq", "TGATCACTCGACTAGCATCAGCATA", 10, 34);
1201
1202     // primary - Ensembl
1203     DBRefEntry dbr1 = new DBRefEntry("ENSEMBL", "0", "ENSG1234");
1204     sq.addDBRef(dbr1);
1205
1206     // not primary - Ensembl 'transcript' mapping of sub-sequence
1207     DBRefEntry dbr2 = new DBRefEntry("ENSEMBL", "0", "ENST1234");
1208     dbr2.setMap(new Mapping(null, new MapList(new int[] { 15, 25 },
1209             new int[] { 1, 11 }, 1, 1)));
1210     sq.addDBRef(dbr2);
1211
1212     // primary - EMBL with congruent map
1213     DBRefEntry dbr3 = new DBRefEntry("EMBL", "0", "J1234");
1214     dbr3.setMap(new Mapping(null, new MapList(new int[] { 10, 34 },
1215             new int[] { 10, 34 }, 1, 1)));
1216     sq.addDBRef(dbr3);
1217
1218     // not primary - to non-core database
1219     DBRefEntry dbr4 = new DBRefEntry("CCDS", "0", "J1234");
1220     sq.addDBRef(dbr4);
1221
1222     // not primary - to protein
1223     DBRefEntry dbr5 = new DBRefEntry("UNIPROT", "0", "Q87654");
1224     sq.addDBRef(dbr5);
1225
1226     List<DBRefEntry> primaryDBRefs = sq.getPrimaryDBRefs();
1227     assertEquals(2, primaryDBRefs.size());
1228     assertTrue(primaryDBRefs.contains(dbr1));
1229     assertTrue(primaryDBRefs.contains(dbr3));
1230   }
1231
1232   /**
1233    * Test the method that updates the list of PDBEntry from any new DBRefEntry
1234    * for PDB
1235    */
1236   @Test(groups = { "Functional" })
1237   public void testUpdatePDBIds()
1238   {
1239     PDBEntry pdbe1 = new PDBEntry("3A6S", null, null, null);
1240     seq.addPDBId(pdbe1);
1241     seq.addDBRef(new DBRefEntry("Ensembl", "8", "ENST1234"));
1242     seq.addDBRef(new DBRefEntry("PDB", "0", "1A70"));
1243     seq.addDBRef(new DBRefEntry("PDB", "0", "4BQGa"));
1244     seq.addDBRef(new DBRefEntry("PDB", "0", "3a6sB"));
1245     // 7 is not a valid chain code:
1246     seq.addDBRef(new DBRefEntry("PDB", "0", "2GIS7"));
1247
1248     seq.updatePDBIds();
1249     List<PDBEntry> pdbIds = seq.getAllPDBEntries();
1250     assertEquals(4, pdbIds.size());
1251     assertSame(pdbe1, pdbIds.get(0));
1252     // chain code got added to 3A6S:
1253     assertEquals("B", pdbe1.getChainCode());
1254     assertEquals("1A70", pdbIds.get(1).getId());
1255     // 4BQGA is parsed into id + chain
1256     assertEquals("4BQG", pdbIds.get(2).getId());
1257     assertEquals("a", pdbIds.get(2).getChainCode());
1258     assertEquals("2GIS7", pdbIds.get(3).getId());
1259     assertNull(pdbIds.get(3).getChainCode());
1260   }
1261
1262   /**
1263    * Test the method that either adds a pdbid or updates an existing one
1264    */
1265   @Test(groups = { "Functional" })
1266   public void testAddPDBId()
1267   {
1268     PDBEntry pdbe = new PDBEntry("3A6S", null, null, null);
1269     seq.addPDBId(pdbe);
1270     assertEquals(1, seq.getAllPDBEntries().size());
1271     assertSame(pdbe, seq.getPDBEntry("3A6S"));
1272     assertSame(pdbe, seq.getPDBEntry("3a6s")); // case-insensitive
1273
1274     // add the same entry
1275     seq.addPDBId(pdbe);
1276     assertEquals(1, seq.getAllPDBEntries().size());
1277     assertSame(pdbe, seq.getPDBEntry("3A6S"));
1278
1279     // add an identical entry
1280     seq.addPDBId(new PDBEntry("3A6S", null, null, null));
1281     assertEquals(1, seq.getAllPDBEntries().size());
1282     assertSame(pdbe, seq.getPDBEntry("3A6S"));
1283
1284     // add a different entry
1285     PDBEntry pdbe2 = new PDBEntry("1A70", null, null, null);
1286     seq.addPDBId(pdbe2);
1287     assertEquals(2, seq.getAllPDBEntries().size());
1288     assertSame(pdbe, seq.getAllPDBEntries().get(0));
1289     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
1290
1291     // update pdbe with chain code, file, type
1292     PDBEntry pdbe3 = new PDBEntry("3a6s", "A", Type.PDB, "filepath");
1293     seq.addPDBId(pdbe3);
1294     assertEquals(2, seq.getAllPDBEntries().size());
1295     assertSame(pdbe, seq.getAllPDBEntries().get(0)); // updated in situ
1296     assertEquals("3A6S", pdbe.getId()); // unchanged
1297     assertEquals("A", pdbe.getChainCode()); // updated
1298     assertEquals(Type.PDB.toString(), pdbe.getType()); // updated
1299     assertEquals("filepath", pdbe.getFile()); // updated
1300     assertSame(pdbe2, seq.getAllPDBEntries().get(1));
1301
1302     // add with a different file path
1303     PDBEntry pdbe4 = new PDBEntry("3a6s", "A", Type.PDB, "filepath2");
1304     seq.addPDBId(pdbe4);
1305     assertEquals(3, seq.getAllPDBEntries().size());
1306     assertSame(pdbe4, seq.getAllPDBEntries().get(2));
1307
1308     // add with a different chain code
1309     PDBEntry pdbe5 = new PDBEntry("3a6s", "B", Type.PDB, "filepath");
1310     seq.addPDBId(pdbe5);
1311     assertEquals(4, seq.getAllPDBEntries().size());
1312     assertSame(pdbe5, seq.getAllPDBEntries().get(3));
1313   }
1314
1315   @Test(
1316     groups = { "Functional" },
1317     expectedExceptions = { IllegalArgumentException.class })
1318   public void testSetDatasetSequence_toSelf()
1319   {
1320     seq.setDatasetSequence(seq);
1321   }
1322
1323   @Test(
1324     groups = { "Functional" },
1325     expectedExceptions = { IllegalArgumentException.class })
1326   public void testSetDatasetSequence_cascading()
1327   {
1328     SequenceI seq2 = new Sequence("Seq2", "xyz");
1329     seq2.createDatasetSequence();
1330     seq.setDatasetSequence(seq2);
1331   }
1332
1333   @Test(groups = { "Functional" })
1334   public void testFindFeatures()
1335   {
1336     SequenceI sq = new Sequence("test/8-16", "-ABC--DEF--GHI--");
1337     sq.createDatasetSequence();
1338
1339     assertTrue(sq.findFeatures(1, 99).isEmpty());
1340
1341     // add non-positional feature
1342     SequenceFeature sf0 = new SequenceFeature("Cath", "desc", 0, 0, 2f,
1343             null);
1344     sq.addSequenceFeature(sf0);
1345     // add feature on BCD
1346     SequenceFeature sfBCD = new SequenceFeature("Cath", "desc", 9, 11, 2f,
1347             null);
1348     sq.addSequenceFeature(sfBCD);
1349     // add feature on DE
1350     SequenceFeature sfDE = new SequenceFeature("Cath", "desc", 11, 12, 2f,
1351             null);
1352     sq.addSequenceFeature(sfDE);
1353     // add contact feature at [B, H]
1354     SequenceFeature sfContactBH = new SequenceFeature("Disulphide bond",
1355             "desc", 9, 15, 2f, null);
1356     sq.addSequenceFeature(sfContactBH);
1357     // add contact feature at [F, G]
1358     SequenceFeature sfContactFG = new SequenceFeature("Disulfide Bond",
1359             "desc", 13, 14, 2f, null);
1360     sq.addSequenceFeature(sfContactFG);
1361     // add single position feature at [I]
1362     SequenceFeature sfI = new SequenceFeature("Disulfide Bond",
1363             "desc", 16, 16, null);
1364     sq.addSequenceFeature(sfI);
1365
1366     // no features in columns 1-2 (-A)
1367     List<SequenceFeature> found = sq.findFeatures(1, 2);
1368     assertTrue(found.isEmpty());
1369
1370     // columns 1-6 (-ABC--) includes BCD and B/H feature but not DE
1371     found = sq.findFeatures(1, 6);
1372     assertEquals(2, found.size());
1373     assertTrue(found.contains(sfBCD));
1374     assertTrue(found.contains(sfContactBH));
1375
1376     // columns 5-6 (--) includes (enclosing) BCD but not (contact) B/H feature
1377     found = sq.findFeatures(5, 6);
1378     assertEquals(1, found.size());
1379     assertTrue(found.contains(sfBCD));
1380
1381     // columns 7-10 (DEF-) includes BCD, DE, F/G but not B/H feature
1382     found = sq.findFeatures(7, 10);
1383     assertEquals(3, found.size());
1384     assertTrue(found.contains(sfBCD));
1385     assertTrue(found.contains(sfDE));
1386     assertTrue(found.contains(sfContactFG));
1387
1388     // columns 10-11 (--) should find nothing
1389     found = sq.findFeatures(10, 11);
1390     assertEquals(0, found.size());
1391
1392     // columns 14-14 (I) should find variant feature
1393     found = sq.findFeatures(14, 14);
1394     assertEquals(1, found.size());
1395     assertTrue(found.contains(sfI));
1396   }
1397
1398   @Test(groups = { "Functional" })
1399   public void testFindIndex_withCursor()
1400   {
1401     Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
1402
1403     // find F given A
1404     assertEquals(10, sq.findIndex(13, new SequenceCursor(sq, 8, 2, 0)));
1405
1406     // find A given F
1407     assertEquals(2, sq.findIndex(8, new SequenceCursor(sq, 13, 10, 0)));
1408
1409     // find C given C
1410     assertEquals(6, sq.findIndex(10, new SequenceCursor(sq, 10, 6, 0)));
1411   }
1412
1413   @Test(groups = { "Functional" })
1414   public void testFindPosition_withCursor()
1415   {
1416     Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
1417   
1418     // find F pos given A - lastCol gets set in cursor
1419     assertEquals(13, sq.findPosition(10, new SequenceCursor(sq, 8, 2, 0)));
1420     assertEquals("test:Pos13:Col10:startCol0:endCol10:tok0",
1421             PA.getValue(sq, "cursor").toString());
1422
1423     // find A pos given F - first residue column is saved in cursor
1424     assertEquals(8, sq.findPosition(2, new SequenceCursor(sq, 13, 10, 0)));
1425     assertEquals("test:Pos8:Col2:startCol2:endCol10:tok0",
1426             PA.getValue(sq, "cursor").toString());
1427   
1428     // find C pos given C (neither startCol nor endCol is set)
1429     assertEquals(10, sq.findPosition(6, new SequenceCursor(sq, 10, 6, 0)));
1430     assertEquals("test:Pos10:Col6:startCol0:endCol0:tok0",
1431             PA.getValue(sq, "cursor").toString());
1432
1433     // now the grey area - what residue position for a gapped column? JAL-2562
1434
1435     // find 'residue' for column 3 given cursor for D (so working left)
1436     // returns B9; cursor is updated to [B 5]
1437     assertEquals(9, sq.findPosition(3, new SequenceCursor(sq, 11, 7, 0)));
1438     assertEquals("test:Pos9:Col5:startCol0:endCol0:tok0",
1439             PA.getValue(sq, "cursor").toString());
1440
1441     // find 'residue' for column 8 given cursor for D (so working right)
1442     // returns E12; cursor is updated to [D 7]
1443     assertEquals(12, sq.findPosition(8, new SequenceCursor(sq, 11, 7, 0)));
1444     assertEquals("test:Pos11:Col7:startCol0:endCol0:tok0",
1445             PA.getValue(sq, "cursor").toString());
1446
1447     // find 'residue' for column 12 given cursor for B
1448     // returns 1 more than last residue position; cursor is updated to [F 10]
1449     // lastCol position is saved in cursor
1450     assertEquals(14, sq.findPosition(12, new SequenceCursor(sq, 9, 5, 0)));
1451     assertEquals("test:Pos13:Col10:startCol0:endCol10:tok0",
1452             PA.getValue(sq, "cursor").toString());
1453
1454     /*
1455      * findPosition for column beyond length of sequence
1456      * returns 1 more than the last residue position
1457      * cursor is set to last real residue position [F 10]
1458      */
1459     assertEquals(14, sq.findPosition(99, new SequenceCursor(sq, 8, 2, 0)));
1460     assertEquals("test:Pos13:Col10:startCol0:endCol10:tok0",
1461             PA.getValue(sq, "cursor").toString());
1462
1463     /*
1464      * and the case without a trailing gap
1465      */
1466     sq = new Sequence("test/8-13", "-A--BCD-EF");
1467     // first find C from A
1468     assertEquals(10, sq.findPosition(6, new SequenceCursor(sq, 8, 2, 0)));
1469     SequenceCursor cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1470     assertEquals("test:Pos10:Col6:startCol0:endCol0:tok0",
1471             cursor.toString());
1472     // now 'find' 99 from C
1473     // cursor is set to [F 10] and saved lastCol
1474     assertEquals(14, sq.findPosition(99, cursor));
1475     assertEquals("test:Pos13:Col10:startCol0:endCol10:tok0",
1476             PA.getValue(sq, "cursor").toString());
1477   }
1478
1479   @Test
1480   public void testIsValidCursor()
1481   {
1482     Sequence sq = new Sequence("Seq", "ABC--DE-F", 8, 13);
1483     assertFalse(sq.isValidCursor(null));
1484
1485     /*
1486      * cursor is valid if it has valid sequence ref and changeCount token
1487      * and positions within the range of the sequence
1488      */
1489     int changeCount = (int) PA.getValue(sq, "changeCount");
1490     SequenceCursor cursor = new SequenceCursor(sq, 13, 1, changeCount);
1491     assertTrue(sq.isValidCursor(cursor));
1492
1493     /*
1494      * column position outside [0 - length] is rejected
1495      */
1496     cursor = new SequenceCursor(sq, 13, -1, changeCount);
1497     assertFalse(sq.isValidCursor(cursor));
1498     cursor = new SequenceCursor(sq, 13, 10, changeCount);
1499     assertFalse(sq.isValidCursor(cursor));
1500     cursor = new SequenceCursor(sq, 7, 8, changeCount);
1501     assertFalse(sq.isValidCursor(cursor));
1502     cursor = new SequenceCursor(sq, 14, 2, changeCount);
1503     assertFalse(sq.isValidCursor(cursor));
1504
1505     /*
1506      * wrong sequence is rejected
1507      */
1508     cursor = new SequenceCursor(null, 13, 1, changeCount);
1509     assertFalse(sq.isValidCursor(cursor));
1510     cursor = new SequenceCursor(new Sequence("Seq", "abc"), 13, 1,
1511             changeCount);
1512     assertFalse(sq.isValidCursor(cursor));
1513
1514     /*
1515      * wrong token value is rejected
1516      */
1517     cursor = new SequenceCursor(sq, 13, 1, changeCount + 1);
1518     assertFalse(sq.isValidCursor(cursor));
1519     cursor = new SequenceCursor(sq, 13, 1, changeCount - 1);
1520     assertFalse(sq.isValidCursor(cursor));
1521   }
1522
1523   @Test(groups = { "Functional" })
1524   public void testFindPosition_withCursorAndEdits()
1525   {
1526     Sequence sq = new Sequence("test/8-13", "-A--BCD-EF--");
1527   
1528     // find F pos given A
1529     assertEquals(13, sq.findPosition(10, new SequenceCursor(sq, 8, 2, 0)));
1530     int token = (int) PA.getValue(sq, "changeCount"); // 0
1531     SequenceCursor cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1532     assertEquals(new SequenceCursor(sq, 13, 10, token), cursor);
1533
1534     /*
1535      * setSequence should invalidate the cursor cached by the sequence
1536      */
1537     sq.setSequence("-A-BCD-EF---"); // one gap removed
1538     assertEquals(8, sq.getStart()); // sanity check
1539     assertEquals(11, sq.findPosition(5)); // D11
1540     // cursor should now be at [D 6]
1541     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1542     assertEquals(new SequenceCursor(sq, 11, 6, ++token), cursor);
1543
1544     /*
1545      * deleteChars should invalidate the cached cursor
1546      */
1547     sq.deleteChars(2, 5); // delete -BC
1548     assertEquals("-AD-EF---", sq.getSequenceAsString());
1549     assertEquals(8, sq.getStart()); // sanity check
1550     assertEquals(10, sq.findPosition(4)); // E10
1551     // cursor should now be at [E 5]
1552     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1553     assertEquals(new SequenceCursor(sq, 10, 5, ++token), cursor);
1554
1555     /*
1556      * Edit to insert gaps should invalidate the cached cursor
1557      * insert 2 gaps at column[3] to make -AD---EF---
1558      */
1559     SequenceI[] seqs = new SequenceI[] { sq };
1560     AlignmentI al = new Alignment(seqs);
1561     new EditCommand().appendEdit(Action.INSERT_GAP, seqs, 3, 2, al, true);
1562     assertEquals("-AD---EF---", sq.getSequenceAsString());
1563     assertEquals(10, sq.findPosition(4)); // E10
1564     // cursor should now be at [D 3]
1565     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1566     assertEquals(new SequenceCursor(sq, 9, 3, ++token), cursor);
1567
1568     /*
1569      * insertCharAt should invalidate the cached cursor
1570      * insert CC at column[4] to make -AD-CC--EF---
1571      */
1572     sq.insertCharAt(4, 2, 'C');
1573     assertEquals("-AD-CC--EF---", sq.getSequenceAsString());
1574     assertEquals(13, sq.findPosition(9)); // F13
1575     // cursor should now be at [F 10]
1576     cursor = (SequenceCursor) PA.getValue(sq, "cursor");
1577     assertEquals(new SequenceCursor(sq, 13, 10, ++token), cursor);
1578   }
1579
1580   @Test(groups = { "Functional" })
1581   public void testGetSequence()
1582   {
1583     String seqstring = "-A--BCD-EF--";
1584     Sequence sq = new Sequence("test/8-13", seqstring);
1585     sq.createDatasetSequence();
1586     assertTrue(Arrays.equals(sq.getSequence(), seqstring.toCharArray()));
1587     assertTrue(Arrays.equals(sq.getDatasetSequence().getSequence(),
1588             "ABCDEF".toCharArray()));
1589
1590     // verify a copy of the sequence array is returned
1591     char[] theSeq = (char[]) PA.getValue(sq, "sequence");
1592     assertNotSame(theSeq, sq.getSequence());
1593     theSeq = (char[]) PA.getValue(sq.getDatasetSequence(), "sequence");
1594     assertNotSame(theSeq, sq.getDatasetSequence().getSequence());
1595   }
1596
1597   @Test(groups = { "Functional" })
1598   public void testReplace()
1599   {
1600     String seqstring = "-A--BCD-EF--";
1601     SequenceI sq = new Sequence("test/8-13", seqstring);
1602     assertEquals(0, PA.getValue(sq, "changeCount"));
1603
1604     assertEquals(0, sq.replace('A', 'A')); // same char
1605     assertEquals(seqstring, sq.getSequenceAsString());
1606     assertEquals(0, PA.getValue(sq, "changeCount"));
1607
1608     assertEquals(0, sq.replace('X', 'Y')); // not there
1609     assertEquals(seqstring, sq.getSequenceAsString());
1610     assertEquals(0, PA.getValue(sq, "changeCount"));
1611
1612     assertEquals(1, sq.replace('A', 'K'));
1613     assertEquals("-K--BCD-EF--", sq.getSequenceAsString());
1614     assertEquals(1, PA.getValue(sq, "changeCount"));
1615
1616     assertEquals(6, sq.replace('-', '.'));
1617     assertEquals(".K..BCD.EF..", sq.getSequenceAsString());
1618     assertEquals(2, PA.getValue(sq, "changeCount"));
1619   }
1620
1621   @Test(groups = { "Functional" })
1622   public void testFindPositions()
1623   {
1624     SequenceI sq = new Sequence("test/8-13", "-ABC---DE-F--");
1625
1626     /*
1627      * invalid inputs
1628      */
1629     assertNull(sq.findPositions(6, 5));
1630     assertNull(sq.findPositions(0, 5));
1631     assertNull(sq.findPositions(-1, 5));
1632
1633     /*
1634      * all gapped ranges
1635      */
1636     assertNull(sq.findPositions(1, 1)); // 1-based columns
1637     assertNull(sq.findPositions(5, 5));
1638     assertNull(sq.findPositions(5, 6));
1639     assertNull(sq.findPositions(5, 7));
1640
1641     /*
1642      * all ungapped ranges
1643      */
1644     assertEquals(new Range(8, 8), sq.findPositions(2, 2)); // A
1645     assertEquals(new Range(8, 9), sq.findPositions(2, 3)); // AB
1646     assertEquals(new Range(8, 10), sq.findPositions(2, 4)); // ABC
1647     assertEquals(new Range(9, 10), sq.findPositions(3, 4)); // BC
1648
1649     /*
1650      * gap to ungapped range
1651      */
1652     assertEquals(new Range(8, 10), sq.findPositions(1, 4)); // ABC
1653     assertEquals(new Range(11, 12), sq.findPositions(6, 9)); // DE
1654
1655     /*
1656      * ungapped to gapped range
1657      */
1658     assertEquals(new Range(10, 10), sq.findPositions(4, 5)); // C
1659     assertEquals(new Range(9, 13), sq.findPositions(3, 11)); // BCDEF
1660
1661     /*
1662      * ungapped to ungapped enclosing gaps
1663      */
1664     assertEquals(new Range(10, 11), sq.findPositions(4, 8)); // CD
1665     assertEquals(new Range(8, 13), sq.findPositions(2, 11)); // ABCDEF
1666
1667     /*
1668      * gapped to gapped enclosing ungapped
1669      */
1670     assertEquals(new Range(8, 10), sq.findPositions(1, 5)); // ABC
1671     assertEquals(new Range(11, 12), sq.findPositions(5, 10)); // DE
1672     assertEquals(new Range(8, 13), sq.findPositions(1, 13)); // the lot
1673     assertEquals(new Range(8, 13), sq.findPositions(1, 99));
1674   }
1675
1676   @Test(groups = { "Functional" })
1677   public void testGapBitset()
1678   {
1679     SequenceI sq = new Sequence("test/8-13", "-ABC---DE-F--");
1680     BitSet bs = sq.gapBitset();
1681     BitSet expected = new BitSet();
1682     expected.set(0);
1683     expected.set(4, 7);
1684     expected.set(9);
1685     expected.set(11, 13);
1686
1687     assertTrue(bs.equals(expected));
1688
1689   }
1690
1691   public void testFindFeatures_largeEndPos()
1692   {
1693     /*
1694      * imitate a PDB sequence where end is larger than end position
1695      */
1696     SequenceI sq = new Sequence("test", "-ABC--DEF--", 1, 20);
1697     sq.createDatasetSequence();
1698   
1699     assertTrue(sq.findFeatures(1, 9).isEmpty());
1700     // should be no array bounds exception - JAL-2772
1701     assertTrue(sq.findFeatures(1, 15).isEmpty());
1702   
1703     // add feature on BCD
1704     SequenceFeature sfBCD = new SequenceFeature("Cath", "desc", 2, 4, 2f,
1705             null);
1706     sq.addSequenceFeature(sfBCD);
1707   
1708     // no features in columns 1-2 (-A)
1709     List<SequenceFeature> found = sq.findFeatures(1, 2);
1710     assertTrue(found.isEmpty());
1711   
1712     // columns 1-6 (-ABC--) includes BCD
1713     found = sq.findFeatures(1, 6);
1714     assertEquals(1, found.size());
1715     assertTrue(found.contains(sfBCD));
1716
1717     // columns 10-11 (--) should find nothing
1718     found = sq.findFeatures(10, 11);
1719     assertEquals(0, found.size());
1720   }
1721
1722   @Test(groups = { "Functional" })
1723   public void testSetName()
1724   {
1725     SequenceI sq = new Sequence("test", "-ABC---DE-F--");
1726     assertEquals("test", sq.getName());
1727     assertEquals(1, sq.getStart());
1728     assertEquals(6, sq.getEnd());
1729
1730     sq.setName("testing");
1731     assertEquals("testing", sq.getName());
1732
1733     sq.setName("test/8-10");
1734     assertEquals("test", sq.getName());
1735     assertEquals(8, sq.getStart());
1736     assertEquals(13, sq.getEnd()); // note end is recomputed
1737
1738     sq.setName("testing/7-99");
1739     assertEquals("testing", sq.getName());
1740     assertEquals(7, sq.getStart());
1741     assertEquals(99, sq.getEnd()); // end may be beyond physical end
1742
1743     sq.setName("/2-3");
1744     assertEquals("", sq.getName());
1745     assertEquals(2, sq.getStart());
1746     assertEquals(7, sq.getEnd());
1747
1748     sq.setName("test/"); // invalid
1749     assertEquals("test/", sq.getName());
1750     assertEquals(2, sq.getStart());
1751     assertEquals(7, sq.getEnd());
1752
1753     sq.setName("test/6-13/7-99");
1754     assertEquals("test/6-13", sq.getName());
1755     assertEquals(7, sq.getStart());
1756     assertEquals(99, sq.getEnd());
1757
1758     sq.setName("test/0-5"); // 0 is invalid - ignored
1759     assertEquals("test/0-5", sq.getName());
1760     assertEquals(7, sq.getStart());
1761     assertEquals(99, sq.getEnd());
1762
1763     sq.setName("test/a-5"); // a is invalid - ignored
1764     assertEquals("test/a-5", sq.getName());
1765     assertEquals(7, sq.getStart());
1766     assertEquals(99, sq.getEnd());
1767
1768     sq.setName("test/6-5"); // start > end is invalid - ignored
1769     assertEquals("test/6-5", sq.getName());
1770     assertEquals(7, sq.getStart());
1771     assertEquals(99, sq.getEnd());
1772
1773     sq.setName("test/5"); // invalid - ignored
1774     assertEquals("test/5", sq.getName());
1775     assertEquals(7, sq.getStart());
1776     assertEquals(99, sq.getEnd());
1777
1778     sq.setName("test/-5"); // invalid - ignored
1779     assertEquals("test/-5", sq.getName());
1780     assertEquals(7, sq.getStart());
1781     assertEquals(99, sq.getEnd());
1782
1783     sq.setName("test/5-"); // invalid - ignored
1784     assertEquals("test/5-", sq.getName());
1785     assertEquals(7, sq.getStart());
1786     assertEquals(99, sq.getEnd());
1787
1788     sq.setName("test/5-6-7"); // invalid - ignored
1789     assertEquals("test/5-6-7", sq.getName());
1790     assertEquals(7, sq.getStart());
1791     assertEquals(99, sq.getEnd());
1792
1793     sq.setName(null); // invalid, gets converted to space
1794     assertEquals("", sq.getName());
1795     assertEquals(7, sq.getStart());
1796     assertEquals(99, sq.getEnd());
1797   }
1798
1799   @Test(groups = { "Functional" })
1800   public void testCheckValidRange()
1801   {
1802     Sequence sq = new Sequence("test/7-12", "-ABC---DE-F--");
1803     assertEquals(7, sq.getStart());
1804     assertEquals(12, sq.getEnd());
1805
1806     /*
1807      * checkValidRange ensures end is at least the last residue position
1808      */
1809     PA.setValue(sq, "end", 2);
1810     sq.checkValidRange();
1811     assertEquals(12, sq.getEnd());
1812
1813     /*
1814      * end may be beyond the last residue position
1815      */
1816     PA.setValue(sq, "end", 22);
1817     sq.checkValidRange();
1818     assertEquals(22, sq.getEnd());
1819   }
1820
1821   @Test(groups = { "Functional" })
1822   public void testDeleteChars_withGaps()
1823   {
1824     /*
1825      * delete gaps only
1826      */
1827     SequenceI sq = new Sequence("test/8-10", "A-B-C");
1828     sq.createDatasetSequence();
1829     assertEquals("ABC", sq.getDatasetSequence().getSequenceAsString());
1830     sq.deleteChars(1, 2); // delete first gap
1831     assertEquals("AB-C", sq.getSequenceAsString());
1832     assertEquals(8, sq.getStart());
1833     assertEquals(10, sq.getEnd());
1834     assertEquals("ABC", sq.getDatasetSequence().getSequenceAsString());
1835
1836     /*
1837      * delete gaps and residues at start (no new dataset sequence)
1838      */
1839     sq = new Sequence("test/8-10", "A-B-C");
1840     sq.createDatasetSequence();
1841     sq.deleteChars(0, 3); // delete A-B
1842     assertEquals("-C", sq.getSequenceAsString());
1843     assertEquals(10, sq.getStart());
1844     assertEquals(10, sq.getEnd());
1845     assertEquals("ABC", sq.getDatasetSequence().getSequenceAsString());
1846
1847     /*
1848      * delete gaps and residues at end (no new dataset sequence)
1849      */
1850     sq = new Sequence("test/8-10", "A-B-C");
1851     sq.createDatasetSequence();
1852     sq.deleteChars(2, 5); // delete B-C
1853     assertEquals("A-", sq.getSequenceAsString());
1854     assertEquals(8, sq.getStart());
1855     assertEquals(8, sq.getEnd());
1856     assertEquals("ABC", sq.getDatasetSequence().getSequenceAsString());
1857
1858     /*
1859      * delete gaps and residues internally (new dataset sequence)
1860      * first delete from gap to residue
1861      */
1862     sq = new Sequence("test/8-10", "A-B-C");
1863     sq.createDatasetSequence();
1864     sq.deleteChars(1, 3); // delete -B
1865     assertEquals("A-C", sq.getSequenceAsString());
1866     assertEquals(8, sq.getStart());
1867     assertEquals(9, sq.getEnd());
1868     assertEquals("AC", sq.getDatasetSequence().getSequenceAsString());
1869     assertEquals(8, sq.getDatasetSequence().getStart());
1870     assertEquals(9, sq.getDatasetSequence().getEnd());
1871
1872     /*
1873      * internal delete from gap to gap
1874      */
1875     sq = new Sequence("test/8-10", "A-B-C");
1876     sq.createDatasetSequence();
1877     sq.deleteChars(1, 4); // delete -B-
1878     assertEquals("AC", sq.getSequenceAsString());
1879     assertEquals(8, sq.getStart());
1880     assertEquals(9, sq.getEnd());
1881     assertEquals("AC", sq.getDatasetSequence().getSequenceAsString());
1882     assertEquals(8, sq.getDatasetSequence().getStart());
1883     assertEquals(9, sq.getDatasetSequence().getEnd());
1884
1885     /*
1886      * internal delete from residue to residue
1887      */
1888     sq = new Sequence("test/8-10", "A-B-C");
1889     sq.createDatasetSequence();
1890     sq.deleteChars(2, 3); // delete B
1891     assertEquals("A--C", sq.getSequenceAsString());
1892     assertEquals(8, sq.getStart());
1893     assertEquals(9, sq.getEnd());
1894     assertEquals("AC", sq.getDatasetSequence().getSequenceAsString());
1895     assertEquals(8, sq.getDatasetSequence().getStart());
1896     assertEquals(9, sq.getDatasetSequence().getEnd());
1897   }
1898 }