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