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