bugfix and comments
[jalview.git] / src / jalview / util / MapList.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.util;
20
21 import java.util.*;
22
23 /**
24  * MapList
25  * Simple way of bijectively mapping a non-contiguous linear range to another non-contiguous linear range
26  * Use at your own risk!
27  * TODO: efficient implementation of private posMap method
28  * TODO: test/ensure that sense of from and to ratio start position is conserved (codon start position recovery)
29  * TODO: optimize to use int[][] arrays rather than vectors.
30  */
31 public class MapList
32 {
33   /* (non-Javadoc)
34    * @see java.lang.Object#equals(java.lang.Object)
35    */
36   public boolean equals(MapList obj) {
37     if (obj==this)
38       return true;
39     if (obj!=null && obj.fromRatio==fromRatio && obj.toRatio==toRatio
40         && obj.fromShifts!=null && obj.toShifts!=null) {
41       int i,iSize=fromShifts.size(),j,jSize=obj.fromShifts.size();
42       if (iSize!=jSize)
43         return false;
44       for (i=0,iSize=fromShifts.size(),j=0, jSize=obj.fromShifts.size(); i<iSize;) {
45         int[] mi=(int[]) fromShifts.elementAt(i++);
46         int[] mj=(int[]) obj.fromShifts.elementAt(j++);
47         if (mi[0]!=mj[0] || mi[1]!=mj[1])
48           return false;
49       }
50       iSize=toShifts.size();
51       jSize=obj.toShifts.size();
52       if (iSize!=jSize)
53         return false;
54       for (i=0,j=0; i<iSize;) {
55         int[] mi=(int[]) toShifts.elementAt(i++);
56         int[] mj=(int[]) obj.toShifts.elementAt(j++);
57         if (mi[0]!=mj[0] || mi[1]!=mj[1])
58           return false;
59       }
60       return true;
61     }
62     return false;
63   }
64   public Vector fromShifts;
65   public Vector toShifts;
66   int fromRatio; // number of steps in fromShifts to one toRatio unit
67   int toRatio; // number of steps in toShifts to one fromRatio
68   
69   /**
70    * 
71    * @return series of intervals mapped in from
72    */
73   public int[] getFromRanges()
74   {
75     return getRanges(fromShifts);
76   }
77   public int[] getToRanges()
78   {
79     return getRanges(toShifts);
80   }
81   
82   private int[] getRanges(Vector shifts)
83   {
84     int[] rnges = new int[2*shifts.size()];
85     Enumeration e = shifts.elements();
86     int i=0;
87     while (e.hasMoreElements())
88     {
89       int r[] = (int[]) e.nextElement();
90       rnges[i++] = r[0];
91       rnges[i++] = r[1];
92     }
93     return rnges;
94   }
95   /**
96    * lowest and highest value in the from Map
97    */
98   int[] fromRange=null;
99   /**
100    * lowest and highest value in the to Map
101    */
102   int[] toRange=null;
103   /**
104    * 
105    * @return length of mapped phrase in from
106    */
107   public int getFromRatio()
108   {
109     return fromRatio;
110   }
111   /**
112    * 
113    * @return length of mapped phrase in to
114    */
115   public int getToRatio()
116   {
117     return toRatio;
118   }
119   public int getFromLowest() {
120     return fromRange[0];
121   }
122   public int getFromHighest() {
123     return fromRange[1];
124   }
125   public int getToLowest() {
126     return toRange[0];
127   }
128   public int getToHighest() {
129     return toRange[1];
130   }
131   private void ensureRange(int[] limits, int pos) {
132     if (limits[0]>pos)
133       limits[0]=pos;
134     if (limits[1]<pos)
135       limits[1]=pos;
136   }
137   public MapList(int from[], int to[], int fromRatio, int toRatio)
138   {
139     fromRange=new int[] { from[0],from[1] };
140     toRange=new int[] { to[0],to[1] };
141
142     fromShifts = new Vector();
143     for (int i=0;i<from.length; i+=2)
144     {
145       ensureRange(fromRange, from[i]);
146       ensureRange(fromRange, from[i+1]);
147
148       fromShifts.addElement(new int[]
149                              {from[i], from[i + 1]});
150     }
151     toShifts = new Vector();
152     for (int i=0;i<to.length; i+=2)
153     {
154       ensureRange(toRange, to[i]);
155       ensureRange(toRange, to[i+1]);
156       toShifts.addElement(new int[]
157                            {to[i], to[i + 1]});
158     }
159     this.fromRatio=fromRatio;
160     this.toRatio=toRatio;
161   }
162   public MapList(MapList map)
163   {
164     this.fromRange = new int[]
165     { map.fromRange[0], map.fromRange[1] };
166     this.toRange = new int[]
167     { map.toRange[0], map.toRange[1] };
168     this.fromRatio = map.fromRatio;
169     this.toRatio = map.toRatio;
170     if (map.fromShifts != null)
171     {
172       this.fromShifts = new Vector();
173       Enumeration e = map.fromShifts.elements();
174       while (e.hasMoreElements())
175       {
176         int[] el = (int[]) e.nextElement();
177         fromShifts.addElement(new int[]
178         { el[0], el[1] });
179       }
180     }
181     if (map.toShifts != null)
182     {
183       this.toShifts = new Vector();
184       Enumeration e = map.toShifts.elements();
185       while (e.hasMoreElements())
186       {
187         int[] el = (int[]) e.nextElement();
188         toShifts.addElement(new int[]
189         { el[0], el[1] });
190       }
191     }
192   }
193   /**
194    * get all mapped positions from 'from' to 'to'
195    * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int [fromFinish-fromStart+2] { toStart..toFinish mappings}}
196    */
197   public int[][] makeFromMap()
198   {
199     return posMap(fromShifts, fromRatio, toShifts, toRatio);
200   }
201   /**
202    * get all mapped positions from 'to' to 'from'
203    * @return int[to position]=position mapped in from
204    */
205   public int[][] makeToMap()
206   {
207     return posMap(toShifts,toRatio, fromShifts, fromRatio);
208   }
209   /**
210    * construct an int map for intervals in intVals
211    * @param intVals
212    * @return int[] { from, to pos in range }, int[range.to-range.from+1] returning mapped position
213    */
214   private int[][] posMap(Vector intVals, int ratio, Vector toIntVals,
215       int toRatio)
216   {
217     int iv=0,ivSize = intVals.size();
218     if (iv>=ivSize)
219     {
220       return null;
221     }
222     int[] intv=(int[]) intVals.elementAt(iv++);
223     int from=intv[0],to=intv[1];
224     if (from > to)
225     {
226       from = intv[1];
227       to=intv[0];
228     }
229     while (iv<ivSize)
230     {
231       intv = (int[]) intVals.elementAt(iv++);
232       if (intv[0]<from)
233       {
234         from=intv[0];
235       }
236       if (intv[1]<from)
237       {
238         from=intv[1];
239       }
240       if (intv[0]>to)
241       {
242         to=intv[0];
243       }
244       if (intv[1]>to)
245       {
246         to=intv[1];
247       }
248     }
249     int tF=0,tT=0;
250     int mp[][] = new int[to-from+2][];
251     for (int i = 0; i < mp.length; i++)
252     {
253       int[] m = shift(i+from,intVals,ratio,toIntVals, toRatio);
254       if (m != null)
255       {
256         if (i == 0)
257         {
258           tF=tT=m[0];
259         }
260         else
261         {
262           if (m[0] < tF)
263           {
264             tF=m[0];
265           }
266           if (m[0] > tT)
267           {
268             tT=m[0];
269           }
270         }
271       }
272       mp[i] = m;
273     }
274     int[][] map = new int[][]
275                             {
276         new int[]
277                 {
278             from, to, tF, tT}, new int[to - from + 2]};
279
280     map[0][2] = tF;
281     map[0][3] = tT;
282
283     for (int i = 0; i < mp.length; i++)
284     {
285       if (mp[i] != null)
286       {
287         map[1][i] = mp[i][0]-tF;
288       }
289       else
290       {
291         map[1][i] = -1; // indicates an out of range mapping
292       }
293     }
294     return map;
295   }
296   /**
297    * addShift
298    * @param pos start position for shift (in original reference frame)
299    * @param shift length of shift
300    *
301   public void addShift(int pos, int shift)
302   {
303     int sidx = 0;
304     int[] rshift=null;
305     while (sidx<shifts.size() && (rshift=(int[]) shifts.elementAt(sidx))[0]<pos)
306       sidx++;
307     if (sidx==shifts.size())
308       shifts.insertElementAt(new int[] { pos, shift}, sidx);
309     else
310       rshift[1]+=shift;
311   }
312    */
313   /**
314    * shift from pos to To(pos)
315    *
316    * @param pos int
317    * @return int shifted position in To, frameshift in From, direction of mapped symbol in To
318    */
319   public int[] shiftFrom(int pos)
320   {
321     return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
322   }
323
324   /**
325    * inverse of shiftFrom - maps pos in To to a position in From
326    * @param pos (in To)
327    * @return shifted position in From, frameshift in To, direction of mapped symbol in From
328    */
329   public int[] shiftTo(int pos)
330   {
331     return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
332   }
333   /**
334    *
335    * @param fromShifts
336    * @param fromRatio
337    * @param toShifts
338    * @param toRatio
339    * @return
340    */
341   private int[] shift(int pos, Vector fromShifts, int fromRatio,
342       Vector toShifts, int toRatio)
343   {
344     int[] fromCount = countPos(fromShifts, pos);
345     if (fromCount==null)
346     {
347       return null;
348     }
349     int fromRemainder=(fromCount[0]-1) % fromRatio;
350     int toCount = 1+(((fromCount[0]-1) / fromRatio) * toRatio);
351     int[] toPos = countToPos(toShifts, toCount);
352     if (toPos==null)
353     {
354       return null; // throw new Error("Bad Mapping!");
355     }
356     //System.out.println(fromCount[0]+" "+fromCount[1]+" "+toCount);
357     return new int[]
358                    {
359         toPos[0], fromRemainder, toPos[1]};
360   }
361   /**
362    * count how many positions pos is along the series of intervals.
363    * @param intVals
364    * @param pos
365    * @return number of positions or null if pos is not within intervals
366    */
367   private int[] countPos(Vector intVals, int pos)
368   {
369     int count=0,intv[],iv=0,ivSize=intVals.size();
370     while (iv<ivSize)
371     {
372       intv = (int[])intVals.elementAt(iv++);
373       if (intv[0] <= intv[1])
374       {
375         if (pos >= intv[0] && pos <= intv[1])
376         {
377           return new int[]
378                          {
379               count + pos - intv[0] + 1, +1};
380         }
381         else
382         {
383           count+=intv[1]-intv[0]+1;
384         }
385       }
386       else
387       {
388         if (pos >= intv[1] && pos <= intv[0])
389         {
390           return new int[]
391                          {
392               count + intv[0] - pos + 1, -1};
393         }
394         else
395         {
396           count+=intv[0]-intv[1]+1;
397         }
398       }
399     }
400     return null;
401   }
402   /**
403    * count out pos positions into a series of intervals and return the position
404    * @param intVals
405    * @param pos
406    * @return position pos in interval set
407    */
408   private int[] countToPos(Vector intVals, int pos)
409   {
410     int count = 0, diff = 0, iv=0,ivSize=intVals.size(), intv[] =
411     {
412         0, 0};
413     while (iv<ivSize)
414     {
415       intv = (int[])intVals.elementAt(iv++);
416       diff = intv[1]-intv[0];
417       if (diff >= 0)
418       {
419         if (pos <= count + 1 + diff)
420         {
421           return new int[]
422                          {
423               pos - count - 1 + intv[0], +1};
424         }
425         else
426         {
427           count+=1+diff;
428         }
429       }
430       else
431       {
432         if (pos <= count + 1 - diff)
433         {
434           return new int[]
435                          {
436               intv[0] - (pos - count - 1), -1};
437         }
438         else
439         {
440           count+=1-diff;
441         }
442       }
443     }
444     return null;//(diff<0) ? (intv[1]-1) : (intv[0]+1);
445   }
446   /**
447    * find series of intervals mapping from start-end in the From map.
448    * @param start position in to map
449    * @param end position in to map
450    * @return series of ranges in from map
451    */
452   public int[] locateInFrom(int start, int end) {
453     // inefficient implementation
454     int fromStart[] = shiftTo(start);
455     int fromEnd[] = shiftTo(end); // needs to be inclusive of end of symbol position
456     if (fromStart==null || fromEnd==null)
457       return null;
458     int iv[] = getIntervals(fromShifts, fromStart, fromEnd,fromRatio);
459     return iv;
460   }
461
462   /**
463    * find series of intervals mapping from start-end in the to map.
464    * @param start position in from map
465    * @param end position in from map
466    * @return series of ranges in to map
467    */
468   public int[] locateInTo(int start, int end) {
469     // inefficient implementation
470     int toStart[] = shiftFrom(start);
471     int toEnd[] = shiftFrom(end);
472     if (toStart==null || toEnd==null)
473       return null;
474     int iv[] = getIntervals(toShifts, toStart, toEnd, toRatio);
475     return iv;
476   }
477   /**
478    * like shift - except returns the intervals in the given vector of shifts which were spanned
479    * in traversing fromStart to fromEnd
480    * @param fromShifts2
481    * @param fromStart
482    * @param fromEnd
483    * @param fromRatio2
484    * @return series of from,to intervals from from first position of starting region to final position of ending region inclusive
485    */
486   private int[] getIntervals(Vector fromShifts2, int[] fromStart, int[] fromEnd, int fromRatio2)
487   {
488     int startpos,endpos;
489     startpos = fromStart[0]; // first position in fromStart 
490     endpos = fromEnd[0]+fromEnd[2]*(fromRatio2-1); // last position in fromEnd
491     int intv=0,intvSize= fromShifts2.size();
492     int iv[],i=0,fs=-1,fe=-1; // containing intervals
493     while (intv<intvSize && (fs==-1 || fe==-1)) {
494       iv = (int[]) fromShifts2.elementAt(intv++);
495       if (iv[0]<=iv[1]) {
496         if (fs==-1 && startpos>=iv[0] && startpos<=iv[1]) {
497           fs = i;
498         }
499         if (fe==-1 && endpos>=iv[0] && endpos<=iv[1]) {
500           fe = i;
501         }
502       } else {
503         if (fs==-1 && startpos<=iv[0] && startpos>=iv[1]) {
504           fs = i;
505         }
506         if (fe==-1 && endpos<=iv[0] && endpos>=iv[1]) {
507           fe = i;
508         }
509       }
510       i++;
511     }
512     if (fs==fe && fe==-1)
513       return null;
514     Vector ranges=new Vector();
515     if (fs<=fe) {
516       intv = fs;
517       i=fs;
518       // truncate initial interval
519       iv = (int[]) fromShifts2.elementAt(intv++);
520       iv = new int[] { iv[0], iv[1]};// clone
521       if (i==fs)
522         iv[0] = startpos;
523       while (i!=fe) {
524         ranges.addElement(iv); // add initial range
525         iv = (int[]) fromShifts2.elementAt(intv++); // get next interval
526         iv = new int[] { iv[0], iv[1]};// clone
527         i++;
528       }
529       if (i==fe)
530         iv[1] = endpos;
531       ranges.addElement(iv); // add only - or final range
532     } else {
533       // walk from end of interval.
534       i=fromShifts2.size()-1;
535       while (i>fs) {
536         i--;
537       }
538       iv = (int[]) fromShifts2.elementAt(i);
539       iv = new int[] { iv[1], iv[0]};//  reverse and clone
540       // truncate initial interval
541       if (i==fs)
542       {
543         iv[0] = startpos;
544       }
545       while (--i!=fe) { // fix apparent logic bug when fe==-1
546         ranges.addElement(iv); // add (truncated) reversed interval
547         iv = (int[]) fromShifts2.elementAt(i);
548         iv = new int[] { iv[1], iv[0] }; // reverse and clone
549       }
550       if (i==fe) {
551         // interval is already reversed
552         iv[1] = endpos;
553       }
554       ranges.addElement(iv); // add only - or final range
555     }
556     // create array of start end intervals.
557     int[] range = null;
558     if (ranges!=null && ranges.size()>0)
559     {
560       range = new int[ranges.size()*2];
561       intv = 0;
562       intvSize=ranges.size();
563       i=0;
564       while (intv<intvSize)
565       {
566         iv = (int[]) ranges.elementAt(intv);
567         range[i++] = iv[0];
568         range[i++] = iv[1];
569         ranges.setElementAt(null, intv++); // remove
570       }
571     }
572     return range;
573   }
574   /**
575  * get the 'initial' position of mpos in To
576  * @param mpos position in from
577  * @return position of first word in to reference frame
578  */
579 public int getToPosition(int mpos)
580 {
581   int[] mp = shiftTo(mpos);
582   if (mp!=null)
583   {
584     return mp[0];
585   }
586   return mpos;
587 }
588 /**
589  * get range of positions in To frame for the mpos word in From
590  * @param mpos position in From
591  * @return null or int[] first position in To for mpos, last position in to for Mpos
592  */
593 public int[] getToWord(int mpos) {
594   int[] mp=shiftTo(mpos);
595   if (mp!=null) {
596       return new int[] {mp[0], mp[0]+mp[2]*(getFromRatio()-1)};
597   }
598   return null;
599 }
600 /**
601  * get From position in the associated
602  * reference frame for position pos in the
603  * associated sequence.
604  * @param pos
605  * @return
606  */
607 public int getMappedPosition(int pos) {
608   int[] mp = shiftFrom(pos);
609   if (mp!=null)
610   {
611     return mp[0];
612   }
613   return pos;
614 }
615 public int[] getMappedWord(int pos) {
616   int[] mp = shiftFrom(pos);
617   if (mp!=null)
618   {
619     return new int[] { mp[0], mp[0]+mp[2]*(getToRatio()-1)};
620   }
621   return null;
622 }
623
624   /**
625    * test routine. not incremental.
626    * @param ml
627    * @param fromS
628    * @param fromE
629    */
630   public static void testMap(MapList ml, int fromS, int fromE)
631   {
632     for (int from = 1; from <= 25; from++)
633     {
634       int[] too=ml.shiftFrom(from);
635       System.out.print("ShiftFrom("+from+")==");
636       if (too==null)
637       {
638         System.out.print("NaN\n");
639       }
640       else
641       {
642         System.out.print(too[0]+" % "+too[1]+" ("+too[2]+")");
643         System.out.print("\t+--+\t");
644         int[] toofrom=ml.shiftTo(too[0]);
645         if (toofrom != null)
646         {
647           if (toofrom[0]!=from)
648           {
649             System.err.println("Mapping not reflexive:" + from + " " + too[0] +
650                 "->" + toofrom[0]);
651           }
652           System.out.println("ShiftTo(" + too[0] + ")==" + toofrom[0] + " % " +
653               toofrom[1]+" ("+toofrom[2]+")");
654         }
655         else
656         {
657           System.out.println("ShiftTo(" + too[0] + ")==" +
658           "NaN! - not Bijective Mapping!");
659         }
660       }
661     }
662     int mmap[][] = ml.makeFromMap();
663     System.out.println("FromMap : (" + mmap[0][0] + " " + mmap[0][1] + " " +
664         mmap[0][2] + " " + mmap[0][3] + " ");
665     for (int i = 1; i <= mmap[1].length; i++)
666     {
667       if (mmap[1][i - 1] == -1)
668       {
669         System.out.print(i+"=XXX");
670
671       }
672       else
673       {
674         System.out.print(i+"="+(mmap[0][2]+mmap[1][i-1]));
675       }
676       if (i % 20==0)
677       {
678         System.out.print("\n");
679       }
680       else
681       {
682         System.out.print(",");
683       }
684     }
685     //test range function
686     System.out.print("\nTest locateInFrom\n");
687     {
688       int f=mmap[0][2],t=mmap[0][3];
689       while (f<=t) {
690         System.out.println("Range "+f+" to "+t);
691         int rng[] = ml.locateInFrom(f,t);
692         if (rng!=null)
693         {
694           for (int i=0; i<rng.length; i++) {
695             System.out.print(rng[i]+((i%2==0) ? "," : ";"));
696           }
697         }
698         else
699         {
700           System.out.println("No range!");
701         }
702         System.out.print("\nReversed\n");
703         rng = ml.locateInFrom(t,f);
704         if (rng!=null)
705         {
706           for (int i=0; i<rng.length; i++) {
707             System.out.print(rng[i]+((i%2==0) ? "," : ";"));
708           }
709         }
710         else
711         {
712           System.out.println("No range!");
713         }
714         System.out.print("\n");
715         f++;t--;
716       }
717     }
718     System.out.print("\n");
719     mmap = ml.makeToMap();
720     System.out.println("ToMap : (" + mmap[0][0] + " " + mmap[0][1] + " " +
721         mmap[0][2] + " " + mmap[0][3] + " ");
722     for (int i = 1; i <= mmap[1].length; i++)
723     {
724       if (mmap[1][i - 1] == -1)
725       {
726         System.out.print(i+"=XXX");
727
728       }
729       else
730       {
731         System.out.print(i+"="+(mmap[0][2]+mmap[1][i-1]));
732       }
733       if (i % 20==0)
734       {
735         System.out.print("\n");
736       }
737       else
738       {
739         System.out.print(",");
740       }
741     }
742     System.out.print("\n");
743     //test range function
744     System.out.print("\nTest locateInTo\n");
745     {
746       int f=mmap[0][2],t=mmap[0][3];
747       while (f<=t) {
748         System.out.println("Range "+f+" to "+t);
749         int rng[] = ml.locateInTo(f,t);
750         if (rng!=null) {
751           for (int i=0; i<rng.length; i++) {
752             System.out.print(rng[i]+((i%2==0) ? "," : ";"));
753           }
754         }
755         else
756         {
757           System.out.println("No range!");
758         }
759         System.out.print("\nReversed\n");
760         rng = ml.locateInTo(t,f);
761         if (rng!=null)
762         {
763           for (int i=0; i<rng.length; i++) {
764             System.out.print(rng[i]+((i%2==0) ? "," : ";"));
765           }
766         }
767         else
768         {
769           System.out.println("No range!");
770         }
771         f++; t--;
772         System.out.print("\n");
773       }
774     }
775
776   }
777
778   public static void main(String argv[])
779   {
780     MapList ml = new MapList(new int[]
781                                      {1, 5, 10, 15, 25, 20},
782                                      new int[]
783                                              {51, 1}, 1, 3);
784     MapList ml1 = new MapList(new int[]
785                                       {1, 3, 17, 4},
786                                       new int[]
787                                               {51, 1}, 1, 3);
788     MapList ml2 = new MapList(new int[] { 1, 60 },
789         new int[] { 1, 20 }, 3, 1);
790     // test internal consistency
791     int to[] = new int[51];
792     MapList.testMap(ml, 1, 60);
793     /*
794       for (int from=1; from<=51; from++) {
795           int[] too=ml.shiftTo(from);
796           int[] toofrom=ml.shiftFrom(too[0]);
797           System.out.println("ShiftFrom("+from+")=="+too[0]+" % "+too[1]+"\t+-+\tShiftTo("+too[0]+")=="+toofrom[0]+" % "+toofrom[1]);
798       }*/
799     System.out.print("Success?\n"); // if we get here - something must be working!
800   }
801   /**
802    * 
803    * @return a MapList whose From range is this maplist's To Range, and vice versa
804    */
805   public MapList getInverse()
806   {
807     return new MapList(getToRanges(), getFromRanges(), getToRatio(), getFromRatio());
808   }
809 }