7792287b12e2a095ef83d00f774ae07e521717e1
[jalview.git] / src / jalview / util / ShiftList.java
1 package jalview.util;\r
2 \r
3 import jalview.datamodel.SequenceI;\r
4 \r
5 import java.util.*;\r
6 \r
7 /**\r
8  * ShiftList\r
9  * Simple way of mapping a linear series to a new linear range with new points introduced.\r
10  * Use at your own risk!\r
11  * <p>Title: ShiftList</p>\r
12  *\r
13  * <p>Description: </p>\r
14  *\r
15  * <p>Copyright: Copyright (c) 2004</p>\r
16  *\r
17  * <p>Company: Dundee University</p>\r
18  *\r
19  * @author not attributable\r
20  * @version 1.0\r
21  */\r
22 public class ShiftList\r
23 {\r
24     public Vector shifts;\r
25   public ShiftList()\r
26   {\r
27     shifts = new Vector();\r
28   }\r
29 \r
30   /**\r
31    * addShift\r
32    * @param pos start position for shift (in original reference frame)\r
33    * @param shift length of shift\r
34    */\r
35   public void addShift(int pos, int shift)\r
36   {\r
37     int sidx = 0;\r
38     int[] rshift=null;\r
39     while (sidx<shifts.size() && (rshift=(int[]) shifts.elementAt(sidx))[0]<pos)\r
40       sidx++;\r
41     if (sidx==shifts.size())\r
42       shifts.insertElementAt(new int[] { pos, shift}, sidx);\r
43     else\r
44       rshift[1]+=shift;\r
45   }\r
46 \r
47   /**\r
48    * shift\r
49    *\r
50    * @param pos int\r
51    * @return int shifted position\r
52    */\r
53   public int shift(int pos)\r
54   {\r
55     if (shifts.size()==0)\r
56       return pos;\r
57     int shifted=pos;\r
58     int sidx=0;\r
59     int rshift[];\r
60     while (sidx<shifts.size()\r
61            &&\r
62            (rshift=((int[]) shifts.elementAt(sidx++)))[0]<=pos) {\r
63       shifted += rshift[1];\r
64     }\r
65     return shifted;\r
66   }\r
67 \r
68   /**\r
69    * clear all shifts\r
70    */\r
71   public void clear()\r
72   {\r
73     shifts.removeAllElements();\r
74   }\r
75   /**\r
76    * invert the shifts\r
77    * @return ShiftList with inverse shift operations\r
78    */\r
79   public ShiftList getInverse() {\r
80     ShiftList inverse=new ShiftList();\r
81     if (shifts!=null) {\r
82       for (int i=0,j=shifts.size(); i<j; i++) {\r
83         int[] sh=(int[]) shifts.elementAt(i);\r
84         if (sh!=null)\r
85           inverse.shifts.addElement(new int[] {sh[0], -sh[1]});\r
86       }\r
87     }\r
88     return inverse;\r
89   }\r
90 \r
91   /**\r
92    * parse a 1d map of position 1<i<n to L<pos[i]<N\r
93    * such as that returned from SequenceI.gapMap()\r
94    * @param gapMap\r
95    * @return\r
96    */\r
97   public static ShiftList parseMap(int[] gapMap) {\r
98     ShiftList shiftList = null;\r
99     if (gapMap!=null && gapMap.length>0) {\r
100       shiftList=new ShiftList();\r
101 \r
102       for (int i=0,p=0; i<gapMap.length; p++,i++) {\r
103         if (p!=gapMap[i]) {\r
104           shiftList.addShift(p, gapMap[i]-p);\r
105           p=gapMap[i];\r
106         }\r
107       }\r
108     }\r
109     return shiftList;\r
110   }\r
111 }\r