removed Iterator usage.
[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#clone()
35    */
36   protected Object clone() throws CloneNotSupportedException {
37     // TODO Auto-generated method stub
38     return super.clone();
39   }
40   /* (non-Javadoc)
41    * @see java.lang.Object#equals(java.lang.Object)
42    */
43   public boolean equals(MapList obj) {
44     if (obj==this)
45       return true;
46     if (obj!=null && obj.fromRatio==fromRatio && obj.toRatio==toRatio
47         && obj.fromShifts!=null && obj.toShifts!=null) {
48       int i,iSize=fromShifts.size(),j,jSize=obj.fromShifts.size();
49       if (iSize!=jSize)
50         return false;
51       for (i=0,iSize=fromShifts.size(),j=0, jSize=obj.fromShifts.size(); i<iSize;) {
52         int[] mi=(int[]) fromShifts.elementAt(i++);
53         int[] mj=(int[]) obj.fromShifts.elementAt(j++);
54         if (mi[0]!=mj[0] || mi[1]!=mj[1])
55           return false;
56       }
57       iSize=toShifts.size();
58       jSize=obj.toShifts.size();
59       if (iSize!=jSize)
60         return false;
61       for (i=0,j=0; i<iSize;) {
62         int[] mi=(int[]) toShifts.elementAt(i++);
63         int[] mj=(int[]) obj.toShifts.elementAt(j++);
64         if (mi[0]!=mj[0] || mi[1]!=mj[1])
65           return false;
66       }
67       return true;
68     }
69     return false;
70   }
71   public Vector fromShifts;
72   public Vector toShifts;
73   int fromRatio; // number of steps in fromShifts to one toRatio unit
74   int toRatio; // number of steps in toShifts to one fromRatio
75   /**
76    * lowest and highest value in the from Map
77    */
78   int[] fromRange=null;
79   /**
80    * lowest and highest value in the to Map
81    */
82   int[] toRange=null; 
83   public int getFromRatio()
84   {
85     return fromRatio;
86   }
87   public int getToRatio()
88   {
89     return toRatio;
90   }
91   public int getFromLowest() {
92     return fromRange[0];
93   }
94   public int getFromHighest() {
95     return fromRange[1];
96   }
97   public int getToLowest() {
98     return toRange[0];
99   }
100   public int getToHighest() {
101     return toRange[1];
102   }
103   private void ensureRange(int[] limits, int pos) {
104     if (limits[0]>pos)
105       limits[0]=pos;
106     if (limits[1]<pos)
107       limits[1]=pos;
108   }
109   public MapList(int from[], int to[], int fromRatio, int toRatio)
110   {
111     fromRange=new int[] { from[0],from[1] };
112     toRange=new int[] { to[0],to[1] };
113
114     fromShifts = new Vector();
115     for (int i=0;i<from.length; i+=2)
116     {      
117       ensureRange(fromRange, from[i]);
118       ensureRange(fromRange, from[i+1]);
119
120       fromShifts.add(new int[]
121                              {from[i], from[i + 1]});
122     }
123     toShifts = new Vector();
124     for (int i=0;i<to.length; i+=2)
125     {
126       ensureRange(toRange, to[i]);
127       ensureRange(toRange, to[i+1]);
128       toShifts.add(new int[]
129                            {to[i], to[i + 1]});
130     }
131     this.fromRatio=fromRatio;
132     this.toRatio=toRatio;
133   }
134   /**
135    * get all mapped positions from 'from' to 'to'
136    * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int [fromFinish-fromStart+2] { toStart..toFinish mappings}}
137    */
138   public int[][] makeFromMap()
139   {
140     return posMap(fromShifts, fromRatio, toShifts, toRatio);
141   }
142   /**
143    * get all mapped positions from 'to' to 'from'
144    * @return int[to position]=position mapped in from
145    */
146   public int[][] makeToMap()
147   {
148     return posMap(toShifts,toRatio, fromShifts, fromRatio);
149   }
150   /**
151    * construct an int map for intervals in intVals
152    * @param intVals
153    * @return int[] { from, to pos in range }, int[range.to-range.from+1] returning mapped position
154    */
155   private int[][] posMap(Vector intVals, int ratio, Vector toIntVals,
156       int toRatio)
157   {
158     int iv=0,ivSize = intVals.size();
159     if (iv>=ivSize)
160     {
161       return null;
162     }
163     int[] intv=(int[]) intVals.elementAt(iv++);
164     int from=intv[0],to=intv[1];
165     if (from > to)
166     {
167       from = intv[1];
168       to=intv[0];
169     }
170     while (iv<ivSize)
171     {
172       intv = (int[]) intVals.elementAt(iv++);
173       if (intv[0]<from)
174       {
175         from=intv[0];
176       }
177       if (intv[1]<from)
178       {
179         from=intv[1];
180       }
181       if (intv[0]>to)
182       {
183         to=intv[0];
184       }
185       if (intv[1]>to)
186       {
187         to=intv[1];
188       }
189     }
190     int tF=0,tT=0;
191     int mp[][] = new int[to-from+2][];
192     for (int i = 0; i < mp.length; i++)
193     {
194       int[] m = shift(i+from,intVals,ratio,toIntVals, toRatio);
195       if (m != null)
196       {
197         if (i == 0)
198         {
199           tF=tT=m[0];
200         }
201         else
202         {
203           if (m[0] < tF)
204           {
205             tF=m[0];
206           }
207           if (m[0] > tT)
208           {
209             tT=m[0];
210           }
211         }
212       }
213       mp[i] = m;
214     }
215     int[][] map = new int[][]
216                             {
217         new int[]
218                 {
219             from, to, tF, tT}, new int[to - from + 2]};
220
221     map[0][2] = tF;
222     map[0][3] = tT;
223
224     for (int i = 0; i < mp.length; i++)
225     {
226       if (mp[i] != null)
227       {
228         map[1][i] = mp[i][0]-tF;
229       }
230       else
231       {
232         map[1][i] = -1; // indicates an out of range mapping
233       }
234     }
235     return map;
236   }
237   /**
238    * addShift
239    * @param pos start position for shift (in original reference frame)
240    * @param shift length of shift
241    *
242   public void addShift(int pos, int shift)
243   {
244     int sidx = 0;
245     int[] rshift=null;
246     while (sidx<shifts.size() && (rshift=(int[]) shifts.elementAt(sidx))[0]<pos)
247       sidx++;
248     if (sidx==shifts.size())
249       shifts.insertElementAt(new int[] { pos, shift}, sidx);
250     else
251       rshift[1]+=shift;
252   }
253    */
254   /**
255    * shift from pos to To(pos)
256    *
257    * @param pos int
258    * @return int shifted position in To, frameshift in From, direction of mapped symbol in To
259    */
260   public int[] shiftFrom(int pos)
261   {
262     return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
263   }
264
265   /**
266    * inverse of shiftFrom - maps pos in To to a position in From
267    * @param pos (in To)
268    * @return shifted position in From, frameshift in To, direction of mapped symbol in From
269    */
270   public int[] shiftTo(int pos)
271   {
272     return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
273   }
274   /**
275    * 
276    * @param fromShifts
277    * @param fromRatio
278    * @param toShifts
279    * @param toRatio
280    * @return
281    */
282   private int[] shift(int pos, Vector fromShifts, int fromRatio,
283       Vector toShifts, int toRatio)
284   {
285     int[] fromCount = countPos(fromShifts, pos);
286     if (fromCount==null)
287     {
288       return null;
289     }
290     int fromRemainder=(fromCount[0]-1) % fromRatio;
291     int toCount = 1+(((fromCount[0]-1) / fromRatio) * toRatio);
292     int[] toPos = countToPos(toShifts, toCount);
293     if (toPos==null)
294     {
295       return null; // throw new Error("Bad Mapping!");
296     }
297     //System.out.println(fromCount[0]+" "+fromCount[1]+" "+toCount);
298     return new int[]
299                    {
300         toPos[0], fromRemainder, toPos[1]};
301   }
302   /**
303    * count how many positions pos is along the series of intervals.
304    * @param intVals
305    * @param pos
306    * @return number of positions or null if pos is not within intervals
307    */
308   private int[] countPos(Vector intVals, int pos)
309   {
310     int count=0,intv[],iv=0,ivSize=intVals.size();
311     while (iv<ivSize)
312     {
313       intv = (int[])intVals.elementAt(iv++);
314       if (intv[0] <= intv[1])
315       {
316         if (pos >= intv[0] && pos <= intv[1])
317         {
318           return new int[]
319                          {
320               count + pos - intv[0] + 1, +1};
321         }
322         else
323         {
324           count+=intv[1]-intv[0]+1;
325         }
326       }
327       else
328       {
329         if (pos >= intv[1] && pos <= intv[0])
330         {
331           return new int[]
332                          {
333               count + intv[0] - pos + 1, -1};
334         }
335         else
336         {
337           count+=intv[0]-intv[1]+1;
338         }
339       }
340     }
341     return null;
342   }
343   /**
344    * count out pos positions into a series of intervals and return the position
345    * @param intVals
346    * @param pos
347    * @return position pos in interval set
348    */
349   private int[] countToPos(Vector intVals, int pos)
350   {
351     int count = 0, diff = 0, iv=0,ivSize=intVals.size(), intv[] =
352     {
353         0, 0};
354     while (iv<ivSize)
355     {
356       intv = (int[])intVals.elementAt(iv++);
357       diff = intv[1]-intv[0];
358       if (diff >= 0)
359       {
360         if (pos <= count + 1 + diff)
361         {
362           return new int[]
363                          {
364               pos - count - 1 + intv[0], +1};
365         }
366         else
367         {
368           count+=1+diff;
369         }
370       }
371       else
372       {
373         if (pos <= count + 1 - diff)
374         {
375           return new int[]
376                          {
377               intv[0] - (pos - count - 1), -1};
378         }
379         else
380         {
381           count+=1-diff;
382         }
383       }
384     }
385     return null;//(diff<0) ? (intv[1]-1) : (intv[0]+1);
386   }
387   /**
388    * find series of intervals mapping from start-end in the From map.
389    * @param start position in to map
390    * @param end position in to map
391    * @return series of ranges in from map
392    */
393   public int[] locateInFrom(int start, int end) {
394     // inefficient implementation
395     int fromStart[] = shiftTo(start);
396     int fromEnd[] = shiftTo(end);
397     if (fromStart==null || fromEnd==null)
398       return null;
399     int iv[] = getIntervals(fromShifts, fromStart, fromEnd,fromRatio);
400     return iv;
401   }
402
403   /**
404    * find series of intervals mapping from start-end in the to map.
405    * @param start position in from map
406    * @param end position in from map
407    * @return series of ranges in to map
408    */
409   public int[] locateInTo(int start, int end) {
410     // inefficient implementation
411     int toStart[] = shiftFrom(start);
412     int toEnd[] = shiftFrom(end);
413     if (toStart==null || toEnd==null)
414       return null;
415     int iv[] = getIntervals(toShifts, toStart, toEnd, toRatio);
416     return iv;
417   }
418   /**
419    * like shift - except returns the intervals in the given vector of shifts which were spanned
420    * in traversing fromStart to fromEnd
421    * @param fromShifts2
422    * @param fromStart
423    * @param fromEnd
424    * @param fromRatio2
425    * @return
426    */
427   private int[] getIntervals(Vector fromShifts2, int[] fromStart, int[] fromEnd, int fromRatio2)
428   {
429     // correct for word direction for start and end
430     int startpos = fromStart[0]+fromStart[2]*(fromRatio2-1);
431     int endpos = fromEnd[0]+fromEnd[2]*(fromRatio2-1);
432     int intv=0,intvSize= fromShifts2.size();
433     int iv[],i=0,fs=-1,fe=-1; // containing intervals
434     while (intv<intvSize && (fs==-1 || fe==-1)) {
435       iv = (int[]) fromShifts2.elementAt(intv++);
436       if (iv[0]<=iv[1]) {
437         if (fs==-1 && startpos>=iv[0] && startpos<=iv[1]) {
438           fs = i; 
439         }
440         if (fe==-1 && endpos>=iv[0] && endpos<=iv[1]) {
441           fe = i; 
442         }
443       } else {
444         if (fs==-1 && startpos<=iv[0] && startpos>=iv[1]) {
445           fs = i; 
446         }
447         if (fe==-1 && endpos<=iv[0] && endpos>=iv[1]) {
448           fe = i; 
449         }
450       }
451       i++;
452     }
453     if (fs==fe && fe==-1)
454       return null;
455     Vector ranges=new Vector();
456     if (fs<=fe) {
457       intv = fs;
458       i=fs;
459       // truncate initial interval
460       iv = (int[]) fromShifts2.elementAt(intv++);
461       iv = new int[] { iv[0], iv[1]};// clone
462       if (i==fs)
463         iv[0] = startpos;
464       while (i!=fe) {
465         ranges.addElement(iv); // add initial range
466         iv = (int[]) fromShifts2.elementAt(intv++); // get next interval
467         iv = new int[] { iv[0], iv[1]};// clone
468         i++;
469       }
470       if (i==fe)
471         iv[1] = endpos;
472       ranges.addElement(iv); // add only - or final range
473     } else {
474       // walk from end of interval.
475       i=fromShifts2.size()-1;
476       while (i>fs) {
477         i--;
478       }
479       iv = (int[]) fromShifts2.elementAt(i);
480       iv = new int[] { iv[1], iv[0]};//  reverse and clone
481       // truncate initial interval
482       if (i==fs) 
483       {
484         iv[0] = startpos;
485       }
486       while (i!=fe) {
487         ranges.addElement(iv); // add (truncated) reversed interval
488         iv = (int[]) fromShifts2.elementAt(--i);
489         iv = new int[] { iv[1], iv[0] }; // reverse and clone
490       }
491       if (i==fe) {
492         // interval is already reversed
493         iv[1] = endpos;
494       }
495       ranges.addElement(iv); // add only - or final range
496     }
497     // create array of start end intervals.
498     int[] range = null;
499     if (ranges!=null && ranges.size()>0) 
500     {
501       range = new int[ranges.size()*2];
502       intv = 0;
503       intvSize=ranges.size();
504       i=0; 
505       while (intv<intvSize) 
506       {
507         iv = (int[]) ranges.elementAt(intv);
508         range[i++] = iv[0];
509         range[i++] = iv[1];
510         ranges.setElementAt(null, intv++); // remove
511       }
512     }
513     return range;
514   }
515   /**
516    * test routine. not incremental.
517    * @param ml
518    * @param fromS
519    * @param fromE
520    */
521   public static void testMap(MapList ml, int fromS, int fromE)
522   {
523     for (int from = 1; from <= 25; from++)
524     {
525       int[] too=ml.shiftFrom(from);
526       System.out.print("ShiftFrom("+from+")==");
527       if (too==null)
528       {
529         System.out.print("NaN\n");
530       }
531       else
532       {
533         System.out.print(too[0]+" % "+too[1]+" ("+too[2]+")");
534         System.out.print("\t+--+\t");
535         int[] toofrom=ml.shiftTo(too[0]);
536         if (toofrom != null)
537         {
538           if (toofrom[0]!=from)
539           {
540             System.err.println("Mapping not reflexive:" + from + " " + too[0] +
541                 "->" + toofrom[0]);
542           }
543           System.out.println("ShiftTo(" + too[0] + ")==" + toofrom[0] + " % " +
544               toofrom[1]+" ("+toofrom[2]+")");
545         }
546         else
547         {
548           System.out.println("ShiftTo(" + too[0] + ")==" +
549           "NaN! - not Bijective Mapping!");
550         }
551       }
552     }
553     int mmap[][] = ml.makeFromMap();
554     System.out.println("FromMap : (" + mmap[0][0] + " " + mmap[0][1] + " " +
555         mmap[0][2] + " " + mmap[0][3] + " ");
556     for (int i = 1; i <= mmap[1].length; i++)
557     {
558       if (mmap[1][i - 1] == -1)
559       {
560         System.out.print(i+"=XXX");
561
562       }
563       else
564       {
565         System.out.print(i+"="+(mmap[0][2]+mmap[1][i-1]));
566       }
567       if (i % 20==0)
568       {
569         System.out.print("\n");
570       }
571       else
572       {
573         System.out.print(",");
574       }
575     }
576     //test range function
577     System.out.print("\nTest locateInFrom\n");
578     {
579       int f=mmap[0][2],t=mmap[0][3];
580       while (f<t) {
581         System.out.println("Range "+f+" to "+t);
582         int rng[] = ml.locateInFrom(f,t);
583         if (rng!=null)
584         {
585           for (int i=0; i<rng.length; i++) {
586             System.out.print(rng[i]+((i%2==0) ? "," : ";"));
587           }
588         }
589         else
590         {
591           System.out.println("No range!");
592         }
593         System.out.print("\nReversed\n");
594         rng = ml.locateInFrom(t,f);
595         if (rng!=null)
596         {
597           for (int i=0; i<rng.length; i++) {
598             System.out.print(rng[i]+((i%2==0) ? "," : ";"));
599           }
600         }
601         else
602         {
603           System.out.println("No range!");
604         }
605         System.out.print("\n");
606         f++;t--;
607       }
608     }    
609     System.out.print("\n");
610     mmap = ml.makeToMap();
611     System.out.println("ToMap : (" + mmap[0][0] + " " + mmap[0][1] + " " +
612         mmap[0][2] + " " + mmap[0][3] + " ");
613     for (int i = 1; i <= mmap[1].length; i++)
614     {
615       if (mmap[1][i - 1] == -1)
616       {
617         System.out.print(i+"=XXX");
618
619       }
620       else
621       {
622         System.out.print(i+"="+(mmap[0][2]+mmap[1][i-1]));
623       }
624       if (i % 20==0)
625       {
626         System.out.print("\n");
627       }
628       else
629       {
630         System.out.print(",");
631       }
632     }
633     System.out.print("\n");
634     //test range function
635     System.out.print("\nTest locateInTo\n");
636     {
637       int f=mmap[0][2],t=mmap[0][3];
638       while (f<t) {
639         System.out.println("Range "+f+" to "+t);
640         int rng[] = ml.locateInTo(f,t);
641         if (rng!=null) {
642           for (int i=0; i<rng.length; i++) {
643             System.out.print(rng[i]+((i%2==0) ? "," : ";"));
644           }
645         }
646         else
647         {
648           System.out.println("No range!");
649         }
650         System.out.print("\nReversed\n");
651         rng = ml.locateInTo(t,f);
652         if (rng!=null)
653         {
654           for (int i=0; i<rng.length; i++) {
655             System.out.print(rng[i]+((i%2==0) ? "," : ";"));
656           }
657         }
658         else
659         {
660           System.out.println("No range!");
661         }
662         f++; t--;
663         System.out.print("\n");
664       }
665     }    
666
667   }
668
669   public static void main(String argv[])
670   {
671     MapList ml = new MapList(new int[]
672                                      {1, 5, 10, 15, 25, 20},
673                                      new int[]
674                                              {51, 1}, 1, 3);
675     MapList ml1 = new MapList(new int[]
676                                       {1, 3, 17, 4},
677                                       new int[]
678                                               {51, 1}, 1, 3);
679     MapList ml2 = new MapList(new int[] { 1, 60 },
680         new int[] { 1, 20 }, 3, 1);
681     // test internal consistency
682     int to[] = new int[51];
683     MapList.testMap(ml, 1, 60);
684     /*
685       for (int from=1; from<=51; from++) {
686           int[] too=ml.shiftTo(from);
687           int[] toofrom=ml.shiftFrom(too[0]);
688           System.out.println("ShiftFrom("+from+")=="+too[0]+" % "+too[1]+"\t+-+\tShiftTo("+too[0]+")=="+toofrom[0]+" % "+toofrom[1]);
689       }*/
690     System.out.print("Success?\n"); // if we get here - something must be working!
691   }
692 }