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