JAL-3761 debugged and working (but not tidied) locateInFrom2/To2
[jalview.git] / src / jalview / util / MapList.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.util;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
26
27 /**
28  * A simple way of bijectively mapping a non-contiguous linear range to another
29  * non-contiguous linear range.
30  * 
31  * Use at your own risk!
32  * 
33  * TODO: efficient implementation of private posMap method
34  * 
35  * TODO: test/ensure that sense of from and to ratio start position is conserved
36  * (codon start position recovery)
37  */
38 public class MapList
39 {
40
41   /*
42    * Subregions (base 1) described as { [start1, end1], [start2, end2], ...}
43    */
44   private List<int[]> fromShifts;
45
46   /*
47    * Same format as fromShifts, for the 'mapped to' sequence
48    */
49   private List<int[]> toShifts;
50
51   /*
52    * number of steps in fromShifts to one toRatio unit
53    */
54   private int fromRatio;
55
56   /*
57    * number of steps in toShifts to one fromRatio
58    */
59   private int toRatio;
60
61   /*
62    * lowest and highest value in the from Map
63    */
64   private int fromLowest;
65
66   private int fromHighest;
67
68   /*
69    * lowest and highest value in the to Map
70    */
71   private int toLowest;
72
73   private int toHighest;
74
75   /**
76    * Constructor
77    */
78   public MapList()
79   {
80     fromShifts = new ArrayList<>();
81     toShifts = new ArrayList<>();
82   }
83
84   /**
85    * Two MapList objects are equal if they are the same object, or they both
86    * have populated shift ranges and all values are the same.
87    */
88   @Override
89   public boolean equals(Object o)
90   {
91     if (o == null || !(o instanceof MapList))
92     {
93       return false;
94     }
95
96     MapList obj = (MapList) o;
97     if (obj == this)
98     {
99       return true;
100     }
101     if (obj.fromRatio != fromRatio || obj.toRatio != toRatio
102             || obj.fromShifts == null || obj.toShifts == null)
103     {
104       return false;
105     }
106     return Arrays.deepEquals(fromShifts.toArray(), obj.fromShifts.toArray())
107             && Arrays.deepEquals(toShifts.toArray(),
108                     obj.toShifts.toArray());
109   }
110
111   /**
112    * Returns a hashcode made from the fromRatio, toRatio, and from/to ranges
113    */
114   @Override
115   public int hashCode()
116   {
117     int hashCode = 31 * fromRatio;
118     hashCode = 31 * hashCode + toRatio;
119     for (int[] shift : fromShifts)
120     {
121       hashCode = 31 * hashCode + shift[0];
122       hashCode = 31 * hashCode + shift[1];
123     }
124     for (int[] shift : toShifts)
125     {
126       hashCode = 31 * hashCode + shift[0];
127       hashCode = 31 * hashCode + shift[1];
128     }
129
130     return hashCode;
131   }
132
133   /**
134    * Returns the 'from' ranges as {[start1, end1], [start2, end2], ...}
135    * 
136    * @return
137    */
138   public List<int[]> getFromRanges()
139   {
140     return fromShifts;
141   }
142
143   /**
144    * Returns the 'to' ranges as {[start1, end1], [start2, end2], ...}
145    * 
146    * @return
147    */
148   public List<int[]> getToRanges()
149   {
150     return toShifts;
151   }
152
153   /**
154    * Flattens a list of [start, end] into a single [start1, end1, start2,
155    * end2,...] array.
156    * 
157    * @param shifts
158    * @return
159    */
160   protected static int[] getRanges(List<int[]> shifts)
161   {
162     int[] rnges = new int[2 * shifts.size()];
163     int i = 0;
164     for (int[] r : shifts)
165     {
166       rnges[i++] = r[0];
167       rnges[i++] = r[1];
168     }
169     return rnges;
170   }
171
172   /**
173    * 
174    * @return length of mapped phrase in from
175    */
176   public int getFromRatio()
177   {
178     return fromRatio;
179   }
180
181   /**
182    * 
183    * @return length of mapped phrase in to
184    */
185   public int getToRatio()
186   {
187     return toRatio;
188   }
189
190   public int getFromLowest()
191   {
192     return fromLowest;
193   }
194
195   public int getFromHighest()
196   {
197     return fromHighest;
198   }
199
200   public int getToLowest()
201   {
202     return toLowest;
203   }
204
205   public int getToHighest()
206   {
207     return toHighest;
208   }
209
210   /**
211    * Constructor given from and to ranges as [start1, end1, start2, end2,...].
212    * There is no validation check that the ranges do not overlap each other.
213    * 
214    * @param from
215    *          contiguous regions as [start1, end1, start2, end2, ...]
216    * @param to
217    *          same format as 'from'
218    * @param fromRatio
219    *          phrase length in 'from' (e.g. 3 for dna)
220    * @param toRatio
221    *          phrase length in 'to' (e.g. 1 for protein)
222    */
223   public MapList(int from[], int to[], int fromRatio, int toRatio)
224   {
225     this();
226     this.fromRatio = fromRatio;
227     this.toRatio = toRatio;
228     fromLowest = Integer.MAX_VALUE;
229     fromHighest = Integer.MIN_VALUE;
230
231     for (int i = 0; i < from.length; i += 2)
232     {
233       /*
234        * note lowest and highest values - bearing in mind the
235        * direction may be reversed
236        */
237       fromLowest = Math.min(fromLowest, Math.min(from[i], from[i + 1]));
238       fromHighest = Math.max(fromHighest, Math.max(from[i], from[i + 1]));
239       fromShifts.add(new int[] { from[i], from[i + 1] });
240     }
241
242     toLowest = Integer.MAX_VALUE;
243     toHighest = Integer.MIN_VALUE;
244     for (int i = 0; i < to.length; i += 2)
245     {
246       toLowest = Math.min(toLowest, Math.min(to[i], to[i + 1]));
247       toHighest = Math.max(toHighest, Math.max(to[i], to[i + 1]));
248       toShifts.add(new int[] { to[i], to[i + 1] });
249     }
250   }
251
252   /**
253    * Copy constructor. Creates an identical mapping.
254    * 
255    * @param map
256    */
257   public MapList(MapList map)
258   {
259     this();
260     // TODO not used - remove?
261     this.fromLowest = map.fromLowest;
262     this.fromHighest = map.fromHighest;
263     this.toLowest = map.toLowest;
264     this.toHighest = map.toHighest;
265
266     this.fromRatio = map.fromRatio;
267     this.toRatio = map.toRatio;
268     if (map.fromShifts != null)
269     {
270       for (int[] r : map.fromShifts)
271       {
272         fromShifts.add(new int[] { r[0], r[1] });
273       }
274     }
275     if (map.toShifts != null)
276     {
277       for (int[] r : map.toShifts)
278       {
279         toShifts.add(new int[] { r[0], r[1] });
280       }
281     }
282   }
283
284   /**
285    * Constructor given ranges as lists of [start, end] positions. There is no
286    * validation check that the ranges do not overlap each other.
287    * 
288    * @param fromRange
289    * @param toRange
290    * @param fromRatio
291    * @param toRatio
292    */
293   public MapList(List<int[]> fromRange, List<int[]> toRange, int fromRatio,
294           int toRatio)
295   {
296     this();
297     fromRange = coalesceRanges(fromRange);
298     toRange = coalesceRanges(toRange);
299     this.fromShifts = fromRange;
300     this.toShifts = toRange;
301     this.fromRatio = fromRatio;
302     this.toRatio = toRatio;
303
304     fromLowest = Integer.MAX_VALUE;
305     fromHighest = Integer.MIN_VALUE;
306     for (int[] range : fromRange)
307     {
308       if (range.length != 2)
309       {
310         // throw new IllegalArgumentException(range);
311         System.err.println("Invalid format for fromRange "
312                 + Arrays.toString(range) + " may cause errors");
313       }
314       fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
315       fromHighest = Math.max(fromHighest, Math.max(range[0], range[1]));
316     }
317
318     toLowest = Integer.MAX_VALUE;
319     toHighest = Integer.MIN_VALUE;
320     for (int[] range : toRange)
321     {
322       if (range.length != 2)
323       {
324         // throw new IllegalArgumentException(range);
325         System.err.println("Invalid format for toRange "
326                 + Arrays.toString(range) + " may cause errors");
327       }
328       toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
329       toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
330     }
331   }
332
333   /**
334    * Consolidates a list of ranges so that any contiguous ranges are merged.
335    * This assumes the ranges are already in start order (does not sort them).
336    * <p>
337    * The main use case for this method is when mapping cDNA sequence to its
338    * protein product, based on CDS feature ranges which derive from spliced
339    * exons, but are contiguous on the cDNA sequence. For example
340    * 
341    * <pre>
342    *   CDS 1-20  // from exon1
343    *   CDS 21-35 // from exon2
344    *   CDS 36-71 // from exon3
345    * 'coalesce' to range 1-71
346    * </pre>
347    * 
348    * @param ranges
349    * @return the same list (if unchanged), else a new merged list, leaving the
350    *         input list unchanged
351    */
352   public static List<int[]> coalesceRanges(final List<int[]> ranges)
353   {
354     if (ranges == null || ranges.size() < 2)
355     {
356       return ranges;
357     }
358
359     boolean changed = false;
360     List<int[]> merged = new ArrayList<>();
361     int[] lastRange = ranges.get(0);
362     int lastDirection = lastRange[1] >= lastRange[0] ? 1 : -1;
363     lastRange = new int[] { lastRange[0], lastRange[1] };
364     merged.add(lastRange);
365     boolean first = true;
366
367     for (final int[] range : ranges)
368     {
369       if (first)
370       {
371         first = false;
372         continue;
373       }
374
375       int direction = range[1] >= range[0] ? 1 : -1;
376
377       /*
378        * if next range is in the same direction as last and contiguous,
379        * just update the end position of the last range
380        */
381       boolean sameDirection = range[1] == range[0]
382               || direction == lastDirection;
383       boolean extending = range[0] == lastRange[1] + lastDirection;
384       if (sameDirection && extending)
385       {
386         lastRange[1] = range[1];
387         changed = true;
388       }
389       else
390       {
391         lastRange = new int[] { range[0], range[1] };
392         merged.add(lastRange);
393         // careful: merging [5, 5] after [7, 6] should keep negative direction
394         lastDirection = (range[1] == range[0]) ? lastDirection : direction;
395       }
396     }
397
398     return changed ? merged : ranges;
399   }
400
401   /**
402    * get all mapped positions from 'from' to 'to'
403    * 
404    * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int
405    *         [fromFinish-fromStart+2] { toStart..toFinish mappings}}
406    */
407   protected int[][] makeFromMap()
408   {
409     // TODO not used - remove??
410     return posMap(fromShifts, fromRatio, toShifts, toRatio);
411   }
412
413   /**
414    * get all mapped positions from 'to' to 'from'
415    * 
416    * @return int[to position]=position mapped in from
417    */
418   protected int[][] makeToMap()
419   {
420     // TODO not used - remove??
421     return posMap(toShifts, toRatio, fromShifts, fromRatio);
422   }
423
424   /**
425    * construct an int map for intervals in intVals
426    * 
427    * @param shiftTo
428    * @return int[] { from, to pos in range }, int[range.to-range.from+1]
429    *         returning mapped position
430    */
431   private int[][] posMap(List<int[]> shiftTo, int ratio,
432           List<int[]> shiftFrom, int toRatio)
433   {
434     // TODO not used - remove??
435     int iv = 0, ivSize = shiftTo.size();
436     if (iv >= ivSize)
437     {
438       return null;
439     }
440     int[] intv = shiftTo.get(iv++);
441     int from = intv[0], to = intv[1];
442     if (from > to)
443     {
444       from = intv[1];
445       to = intv[0];
446     }
447     while (iv < ivSize)
448     {
449       intv = shiftTo.get(iv++);
450       if (intv[0] < from)
451       {
452         from = intv[0];
453       }
454       if (intv[1] < from)
455       {
456         from = intv[1];
457       }
458       if (intv[0] > to)
459       {
460         to = intv[0];
461       }
462       if (intv[1] > to)
463       {
464         to = intv[1];
465       }
466     }
467     int tF = 0, tT = 0;
468     int mp[][] = new int[to - from + 2][];
469     for (int i = 0; i < mp.length; i++)
470     {
471       int[] m = shift(i + from, shiftTo, ratio, shiftFrom, toRatio);
472       if (m != null)
473       {
474         if (i == 0)
475         {
476           tF = tT = m[0];
477         }
478         else
479         {
480           if (m[0] < tF)
481           {
482             tF = m[0];
483           }
484           if (m[0] > tT)
485           {
486             tT = m[0];
487           }
488         }
489       }
490       mp[i] = m;
491     }
492     int[][] map = new int[][] { new int[] { from, to, tF, tT },
493         new int[to - from + 2] };
494
495     map[0][2] = tF;
496     map[0][3] = tT;
497
498     for (int i = 0; i < mp.length; i++)
499     {
500       if (mp[i] != null)
501       {
502         map[1][i] = mp[i][0] - tF;
503       }
504       else
505       {
506         map[1][i] = -1; // indicates an out of range mapping
507       }
508     }
509     return map;
510   }
511
512   /**
513    * addShift
514    * 
515    * @param pos
516    *          start position for shift (in original reference frame)
517    * @param shift
518    *          length of shift
519    * 
520    *          public void addShift(int pos, int shift) { int sidx = 0; int[]
521    *          rshift=null; while (sidx<shifts.size() && (rshift=(int[])
522    *          shifts.elementAt(sidx))[0]<pos) sidx++; if (sidx==shifts.size())
523    *          shifts.insertElementAt(new int[] { pos, shift}, sidx); else
524    *          rshift[1]+=shift; }
525    */
526
527   /**
528    * shift from pos to To(pos)
529    * 
530    * @param pos
531    *          int
532    * @return int shifted position in To, frameshift in From, direction of mapped
533    *         symbol in To
534    */
535   public int[] shiftFrom(int pos)
536   {
537     return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
538   }
539
540   /**
541    * inverse of shiftFrom - maps pos in To to a position in From
542    * 
543    * @param pos
544    *          (in To)
545    * @return shifted position in From, frameshift in To, direction of mapped
546    *         symbol in From
547    */
548   public int[] shiftTo(int pos)
549   {
550     return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
551   }
552
553   /**
554    * 
555    * @param shiftTo
556    * @param fromRatio
557    * @param shiftFrom
558    * @param toRatio
559    * @return
560    */
561   protected static int[] shift(int pos, List<int[]> shiftTo, int fromRatio,
562           List<int[]> shiftFrom, int toRatio)
563   {
564     // TODO: javadoc; tests
565     int[] fromCount = countPositions(shiftTo, pos);
566     if (fromCount == null)
567     {
568       return null;
569     }
570     int fromRemainder = (fromCount[0] - 1) % fromRatio;
571     int toCount = 1 + (((fromCount[0] - 1) / fromRatio) * toRatio);
572     int[] toPos = traverseToPosition(shiftFrom, toCount);
573     if (toPos == null)
574     {
575       return null;
576     }
577     return new int[] { toPos[0], fromRemainder, toPos[1] };
578   }
579
580   /**
581    * Counts how many positions pos is along the series of intervals. Returns an
582    * array of two values:
583    * <ul>
584    * <li>the number of positions traversed (inclusive) to reach {@code pos}</li>
585    * <li>+1 if the last interval traversed is forward, -1 if in a negative
586    * direction</li>
587    * </ul>
588    * Returns null if {@code pos} does not lie in any of the given intervals.
589    * 
590    * @param intervals
591    *          a list of start-end intervals
592    * @param pos
593    *          a position that may lie in one (or more) of the intervals
594    * @return
595    */
596   protected static int[] countPositions(List<int[]> intervals, int pos)
597   {
598     int count = 0;
599     int iv = 0;
600     int ivSize = intervals.size();
601
602     while (iv < ivSize)
603     {
604       int[] intv = intervals.get(iv++);
605       if (intv[0] <= intv[1])
606       {
607         /*
608          * forwards interval
609          */
610         if (pos >= intv[0] && pos <= intv[1])
611         {
612           return new int[] { count + pos - intv[0] + 1, +1 };
613         }
614         else
615         {
616           count += intv[1] - intv[0] + 1;
617         }
618       }
619       else
620       {
621         /*
622          * reverse interval
623          */
624         if (pos >= intv[1] && pos <= intv[0])
625         {
626           return new int[] { count + intv[0] - pos + 1, -1 };
627         }
628         else
629         {
630           count += intv[0] - intv[1] + 1;
631         }
632       }
633     }
634     return null;
635   }
636
637   /**
638    * Reads through the given intervals until {@code count} positions have been
639    * traversed, and returns an array consisting of two values:
640    * <ul>
641    * <li>the value at the {@code count'th} position</li>
642    * <li>+1 if the last interval read is forwards, -1 if reverse direction</li>
643    * </ul>
644    * Returns null if the ranges include less than {@code count} positions, or if
645    * {@code count < 1}.
646    * 
647    * @param intervals
648    *          a list of [start, end] ranges
649    * @param count
650    *          the number of positions to traverse
651    * @return
652    */
653   protected static int[] traverseToPosition(List<int[]> intervals,
654           final int count)
655   {
656     int traversed = 0;
657     int ivSize = intervals.size();
658     int iv = 0;
659
660     if (count < 1)
661     {
662       return null;
663     }
664
665     while (iv < ivSize)
666     {
667       int[] intv = intervals.get(iv++);
668       int diff = intv[1] - intv[0];
669       if (diff >= 0)
670       {
671         if (count <= traversed + 1 + diff)
672         {
673           return new int[] { intv[0] + (count - traversed - 1), +1 };
674         }
675         else
676         {
677           traversed += 1 + diff;
678         }
679       }
680       else
681       {
682         if (count <= traversed + 1 - diff)
683         {
684           return new int[] { intv[0] - (count - traversed - 1), -1 };
685         }
686         else
687         {
688           traversed += 1 - diff;
689         }
690       }
691     }
692     return null;
693   }
694
695   /**
696    * find series of intervals mapping from start-end in the From map.
697    * 
698    * @param start
699    *          position mapped 'to'
700    * @param end
701    *          position mapped 'to'
702    * @return series of [start, end] ranges in sequence mapped 'from'
703    */
704   public int[] locateInFrom(int start, int end)
705   {
706     return locateInFrom2(start, end);
707     
708     // inefficient implementation
709     // int fromStart[] = shiftTo(start);
710     // needs to be inclusive of end of symbol position
711     // int fromEnd[] = shiftTo(end);
712     // return getIntervals(fromShifts, fromStart, fromEnd, fromRatio);
713   }
714
715   /**
716    * find series of intervals mapping from start-end in the to map.
717    * 
718    * @param start
719    *          position mapped 'from'
720    * @param end
721    *          position mapped 'from'
722    * @return series of [start, end] ranges in sequence mapped 'to'
723    */
724   public int[] locateInTo(int start, int end)
725   {
726     return locateInTo2(start, end);
727     
728     // int toStart[] = shiftFrom(start);
729     // int toEnd[] = shiftFrom(end);
730     // return getIntervals(toShifts, toStart, toEnd, toRatio);
731   }
732
733   /**
734    * like shift - except returns the intervals in the given vector of shifts
735    * which were spanned in traversing fromStart to fromEnd
736    * 
737    * @param shiftFrom
738    * @param fromStart
739    * @param fromEnd
740    * @param fromRatio2
741    * @return series of from,to intervals from from first position of starting
742    *         region to final position of ending region inclusive
743    */
744   protected static int[] getIntervals(List<int[]> shiftFrom,
745           int[] fromStart, int[] fromEnd, int fromRatio2)
746   {
747     if (fromStart == null || fromEnd == null)
748     {
749       return null;
750     }
751     int startpos, endpos;
752     startpos = fromStart[0]; // first position in fromStart
753     endpos = fromEnd[0]; // last position in fromEnd
754     int endindx = (fromRatio2 - 1); // additional positions to get to last
755     // position from endpos
756     int intv = 0, intvSize = shiftFrom.size();
757     int iv[], i = 0, fs = -1, fe_s = -1, fe = -1; // containing intervals
758     // search intervals to locate ones containing startpos and count endindx
759     // positions on from endpos
760     while (intv < intvSize && (fs == -1 || fe == -1))
761     {
762       iv = shiftFrom.get(intv++);
763       if (fe_s > -1)
764       {
765         endpos = iv[0]; // start counting from beginning of interval
766         endindx--; // inclusive of endpos
767       }
768       if (iv[0] <= iv[1])
769       {
770         if (fs == -1 && startpos >= iv[0] && startpos <= iv[1])
771         {
772           fs = i;
773         }
774         if (endpos >= iv[0] && endpos <= iv[1])
775         {
776           if (fe_s == -1)
777           {
778             fe_s = i;
779           }
780           if (fe_s != -1)
781           {
782             if (endpos + endindx <= iv[1])
783             {
784               fe = i;
785               endpos = endpos + endindx; // end of end token is within this
786               // interval
787             }
788             else
789             {
790               endindx -= iv[1] - endpos; // skip all this interval too
791             }
792           }
793         }
794       }
795       else
796       {
797         if (fs == -1 && startpos <= iv[0] && startpos >= iv[1])
798         {
799           fs = i;
800         }
801         if (endpos <= iv[0] && endpos >= iv[1])
802         {
803           if (fe_s == -1)
804           {
805             fe_s = i;
806           }
807           if (fe_s != -1)
808           {
809             if (endpos - endindx >= iv[1])
810             {
811               fe = i;
812               endpos = endpos - endindx; // end of end token is within this
813               // interval
814             }
815             else
816             {
817               endindx -= endpos - iv[1]; // skip all this interval too
818             }
819           }
820         }
821       }
822       i++;
823     }
824     if (fs == fe && fe == -1)
825     {
826       return null;
827     }
828     List<int[]> ranges = new ArrayList<>();
829     if (fs <= fe)
830     {
831       intv = fs;
832       i = fs;
833       // truncate initial interval
834       iv = shiftFrom.get(intv++);
835       iv = new int[] { iv[0], iv[1] };// clone
836       if (i == fs)
837       {
838         iv[0] = startpos;
839       }
840       while (i != fe)
841       {
842         ranges.add(iv); // add initial range
843         iv = shiftFrom.get(intv++); // get next interval
844         iv = new int[] { iv[0], iv[1] };// clone
845         i++;
846       }
847       if (i == fe)
848       {
849         iv[1] = endpos;
850       }
851       ranges.add(iv); // add only - or final range
852     }
853     else
854     {
855       // walk from end of interval.
856       i = shiftFrom.size() - 1;
857       while (i > fs)
858       {
859         i--;
860       }
861       iv = shiftFrom.get(i);
862       iv = new int[] { iv[1], iv[0] };// reverse and clone
863       // truncate initial interval
864       if (i == fs)
865       {
866         iv[0] = startpos;
867       }
868       while (--i != fe)
869       { // fix apparent logic bug when fe==-1
870         ranges.add(iv); // add (truncated) reversed interval
871         iv = shiftFrom.get(i);
872         iv = new int[] { iv[1], iv[0] }; // reverse and clone
873       }
874       if (i == fe)
875       {
876         // interval is already reversed
877         iv[1] = endpos;
878       }
879       ranges.add(iv); // add only - or final range
880     }
881     // create array of start end intervals.
882     int[] range = null;
883     if (ranges != null && ranges.size() > 0)
884     {
885       range = new int[ranges.size() * 2];
886       intv = 0;
887       intvSize = ranges.size();
888       i = 0;
889       while (intv < intvSize)
890       {
891         iv = ranges.get(intv);
892         range[i++] = iv[0];
893         range[i++] = iv[1];
894         ranges.set(intv++, null); // remove
895       }
896     }
897     return range;
898   }
899
900   /**
901    * get the 'initial' position of mpos in To
902    * 
903    * @param mpos
904    *          position in from
905    * @return position of first word in to reference frame
906    */
907   public int getToPosition(int mpos)
908   {
909     // TODO not used - remove??
910     int[] mp = shiftTo(mpos);
911     if (mp != null)
912     {
913       return mp[0];
914     }
915     return mpos;
916   }
917
918   /**
919    * get range of positions in To frame for the mpos word in From
920    * 
921    * @param mpos
922    *          position in From
923    * @return null or int[] first position in To for mpos, last position in to
924    *         for Mpos
925    */
926   public int[] getToWord(int mpos)
927   {
928     int[] mp = shiftTo(mpos);
929     if (mp != null)
930     {
931       return new int[] { mp[0], mp[0] + mp[2] * (getFromRatio() - 1) };
932     }
933     return null;
934   }
935
936   /**
937    * get From position in the associated reference frame for position pos in the
938    * associated sequence.
939    * 
940    * @param pos
941    * @return
942    */
943   public int getMappedPosition(int pos)
944   {
945     // TODO not used - remove??
946     int[] mp = shiftFrom(pos);
947     if (mp != null)
948     {
949       return mp[0];
950     }
951     return pos;
952   }
953
954   public int[] getMappedWord(int pos)
955   {
956     // TODO not used - remove??
957     int[] mp = shiftFrom(pos);
958     if (mp != null)
959     {
960       return new int[] { mp[0], mp[0] + mp[2] * (getToRatio() - 1) };
961     }
962     return null;
963   }
964
965   /**
966    * 
967    * @return a MapList whose From range is this maplist's To Range, and vice
968    *         versa
969    */
970   public MapList getInverse()
971   {
972     return new MapList(getToRanges(), getFromRanges(), getToRatio(),
973             getFromRatio());
974   }
975
976   /**
977    * test for containment rather than equivalence to another mapping
978    * 
979    * @param map
980    *          to be tested for containment
981    * @return true if local or mapped range map contains or is contained by this
982    *         mapping
983    */
984   public boolean containsEither(boolean local, MapList map)
985   {
986     // TODO not used - remove?
987     if (local)
988     {
989       return ((getFromLowest() >= map.getFromLowest()
990               && getFromHighest() <= map.getFromHighest())
991               || (getFromLowest() <= map.getFromLowest()
992                       && getFromHighest() >= map.getFromHighest()));
993     }
994     else
995     {
996       return ((getToLowest() >= map.getToLowest()
997               && getToHighest() <= map.getToHighest())
998               || (getToLowest() <= map.getToLowest()
999                       && getToHighest() >= map.getToHighest()));
1000     }
1001   }
1002
1003   /**
1004    * String representation - for debugging, not guaranteed not to change
1005    */
1006   @Override
1007   public String toString()
1008   {
1009     StringBuilder sb = new StringBuilder(64);
1010     sb.append("[");
1011     for (int[] shift : fromShifts)
1012     {
1013       sb.append(" ").append(Arrays.toString(shift));
1014     }
1015     sb.append(" ] ");
1016     sb.append(fromRatio).append(":").append(toRatio);
1017     sb.append(" to [");
1018     for (int[] shift : toShifts)
1019     {
1020       sb.append(" ").append(Arrays.toString(shift));
1021     }
1022     sb.append(" ]");
1023     return sb.toString();
1024   }
1025
1026   /**
1027    * Extend this map list by adding the given map's ranges. There is no
1028    * validation check that the ranges do not overlap existing ranges (or each
1029    * other), but contiguous ranges are merged.
1030    * 
1031    * @param map
1032    */
1033   public void addMapList(MapList map)
1034   {
1035     if (this.equals(map))
1036     {
1037       return;
1038     }
1039     this.fromLowest = Math.min(fromLowest, map.fromLowest);
1040     this.toLowest = Math.min(toLowest, map.toLowest);
1041     this.fromHighest = Math.max(fromHighest, map.fromHighest);
1042     this.toHighest = Math.max(toHighest, map.toHighest);
1043
1044     for (int[] range : map.getFromRanges())
1045     {
1046       addRange(range, fromShifts);
1047     }
1048     for (int[] range : map.getToRanges())
1049     {
1050       addRange(range, toShifts);
1051     }
1052   }
1053
1054   /**
1055    * Adds the given range to a list of ranges. If the new range just extends
1056    * existing ranges, the current endpoint is updated instead.
1057    * 
1058    * @param range
1059    * @param addTo
1060    */
1061   static void addRange(int[] range, List<int[]> addTo)
1062   {
1063     /*
1064      * list is empty - add to it!
1065      */
1066     if (addTo.size() == 0)
1067     {
1068       addTo.add(range);
1069       return;
1070     }
1071
1072     int[] last = addTo.get(addTo.size() - 1);
1073     boolean lastForward = last[1] >= last[0];
1074     boolean newForward = range[1] >= range[0];
1075
1076     /*
1077      * contiguous range in the same direction - just update endpoint
1078      */
1079     if (lastForward == newForward && last[1] == range[0])
1080     {
1081       last[1] = range[1];
1082       return;
1083     }
1084
1085     /*
1086      * next range starts at +1 in forward sense - update endpoint
1087      */
1088     if (lastForward && newForward && range[0] == last[1] + 1)
1089     {
1090       last[1] = range[1];
1091       return;
1092     }
1093
1094     /*
1095      * next range starts at -1 in reverse sense - update endpoint
1096      */
1097     if (!lastForward && !newForward && range[0] == last[1] - 1)
1098     {
1099       last[1] = range[1];
1100       return;
1101     }
1102
1103     /*
1104      * just add the new range
1105      */
1106     addTo.add(range);
1107   }
1108
1109   /**
1110    * Returns true if mapping is from forward strand, false if from reverse
1111    * strand. Result is just based on the first 'from' range that is not a single
1112    * position. Default is true unless proven to be false. Behaviour is not well
1113    * defined if the mapping has a mixture of forward and reverse ranges.
1114    * 
1115    * @return
1116    */
1117   public boolean isFromForwardStrand()
1118   {
1119     return isForwardStrand(getFromRanges());
1120   }
1121
1122   /**
1123    * Returns true if mapping is to forward strand, false if to reverse strand.
1124    * Result is just based on the first 'to' range that is not a single position.
1125    * Default is true unless proven to be false. Behaviour is not well defined if
1126    * the mapping has a mixture of forward and reverse ranges.
1127    * 
1128    * @return
1129    */
1130   public boolean isToForwardStrand()
1131   {
1132     return isForwardStrand(getToRanges());
1133   }
1134
1135   /**
1136    * A helper method that returns true unless at least one range has start >
1137    * end. Behaviour is undefined for a mixture of forward and reverse ranges.
1138    * 
1139    * @param ranges
1140    * @return
1141    */
1142   private boolean isForwardStrand(List<int[]> ranges)
1143   {
1144     boolean forwardStrand = true;
1145     for (int[] range : ranges)
1146     {
1147       if (range[1] > range[0])
1148       {
1149         break; // forward strand confirmed
1150       }
1151       else if (range[1] < range[0])
1152       {
1153         forwardStrand = false;
1154         break; // reverse strand confirmed
1155       }
1156     }
1157     return forwardStrand;
1158   }
1159
1160   /**
1161    * 
1162    * @return true if from, or to is a three to 1 mapping
1163    */
1164   public boolean isTripletMap()
1165   {
1166     return (toRatio == 3 && fromRatio == 1)
1167             || (fromRatio == 3 && toRatio == 1);
1168   }
1169
1170   /**
1171    * Returns a map which is the composite of this one and the input map. That
1172    * is, the output map has the fromRanges of this map, and its toRanges are the
1173    * toRanges of this map as transformed by the input map.
1174    * <p>
1175    * Returns null if the mappings cannot be traversed (not all toRanges of this
1176    * map correspond to fromRanges of the input), or if this.toRatio does not
1177    * match map.fromRatio.
1178    * 
1179    * <pre>
1180    * Example 1:
1181    *    this:   from [1-100] to [501-600]
1182    *    input:  from [10-40] to [60-90]
1183    *    output: from [10-40] to [560-590]
1184    * Example 2 ('reverse strand exons'):
1185    *    this:   from [1-100] to [2000-1951], [1000-951] // transcript to loci
1186    *    input:  from [1-50]  to [41-90] // CDS to transcript
1187    *    output: from [10-40] to [1960-1951], [1000-971] // CDS to gene loci
1188    * </pre>
1189    * 
1190    * @param map
1191    * @return
1192    */
1193   public MapList traverse(MapList map)
1194   {
1195     if (map == null)
1196     {
1197       return null;
1198     }
1199
1200     /*
1201      * compound the ratios by this rule:
1202      * A:B with M:N gives A*M:B*N
1203      * reduced by greatest common divisor
1204      * so 1:3 with 3:3 is 3:9 or 1:3
1205      * 1:3 with 3:1 is 3:3 or 1:1
1206      * 1:3 with 1:3 is 1:9
1207      * 2:5 with 3:7 is 6:35
1208      */
1209     int outFromRatio = getFromRatio() * map.getFromRatio();
1210     int outToRatio = getToRatio() * map.getToRatio();
1211     int gcd = MathUtils.gcd(outFromRatio, outToRatio);
1212     outFromRatio /= gcd;
1213     outToRatio /= gcd;
1214
1215     List<int[]> toRanges = new ArrayList<>();
1216     for (int[] range : getToRanges())
1217     {
1218       int fromLength = Math.abs(range[1] - range[0]) + 1;
1219       int[] transferred = map.locateInTo(range[0], range[1]);
1220       if (transferred == null || transferred.length % 2 != 0)
1221       {
1222         return null;
1223       }
1224
1225       /*
1226        *  convert [start1, end1, start2, end2, ...] 
1227        *  to [[start1, end1], [start2, end2], ...]
1228        */
1229       int toLength = 0;
1230       for (int i = 0; i < transferred.length;)
1231       {
1232         toRanges.add(new int[] { transferred[i], transferred[i + 1] });
1233         toLength += Math.abs(transferred[i + 1] - transferred[i]) + 1;
1234         i += 2;
1235       }
1236       
1237       /*
1238        * check we mapped the full range - if not, abort
1239        */
1240       if (fromLength * map.getToRatio() != toLength * map.getFromRatio())
1241       {
1242         return null;
1243       }
1244     }
1245
1246     return new MapList(getFromRanges(), toRanges, outFromRatio, outToRatio);
1247   }
1248
1249   /**
1250    * Answers true if the mapping is from one contiguous range to another, else
1251    * false
1252    * 
1253    * @return
1254    */
1255   public boolean isContiguous()
1256   {
1257     return fromShifts.size() == 1 && toShifts.size() == 1;
1258   }
1259
1260   /**
1261    * Returns the [start, end, start, end, ...] ranges in the 'from' range that
1262    * map to positions between {@code start} and {@code end} in the 'to' range.
1263    * Returns null if no mapped positions are found in start-end.
1264    * 
1265    * @param start
1266    * @param end
1267    * @return
1268    */
1269   public int[] locateInFrom2(int start, int end)
1270   {
1271     List<int[]> ranges = mapBetween(start, end, toShifts, fromShifts,
1272             toRatio, fromRatio);
1273
1274     // TODO: or just return the List and adjust calling code to match
1275     return ranges.isEmpty() ? null : MappingUtils.rangeListToArray(ranges);
1276   }
1277
1278   /**
1279    * Returns the [start, end, start, end, ...] ranges in the 'to' range that map
1280    * to the given start-end in the 'from' range. Returns null if either
1281    * {@code start} or {@code end} is not a mapped 'from' range position.
1282    * 
1283    * @param start
1284    * @param end
1285    * @return
1286    */
1287   public int[] locateInTo2(int start, int end)
1288   {
1289     List<int[]> ranges = mapBetween(start, end, fromShifts, toShifts,
1290             fromRatio, toRatio);
1291
1292     return ranges.isEmpty() ? null : MappingUtils.rangeListToArray(ranges);
1293   }
1294
1295   /**
1296    * A helper method for navigating the mapping. Returns a (possibly empty) list
1297    * of [start-end] positions in {@code ranges2} that map to positions in
1298    * {@code ranges1} between {@code start} and {@code end}.
1299    * 
1300    * @param start
1301    * @param end
1302    * @param ranges1
1303    * @param ranges2
1304    * @param wordLength1
1305    * @param wordLength2
1306    * @return
1307    */
1308   final static List<int[]> mapBetween(int start, int end,
1309           List<int[]> ranges1, List<int[]> ranges2, int wordLength1,
1310           int wordLength2)
1311   {
1312     if (end < start)
1313     {
1314       int tmp = end;
1315       end = start;
1316       start = tmp;
1317     }
1318
1319     /*
1320      * first traverse ranges1 and record count of mapped positions 
1321      * to any that overlap start-end
1322      */
1323     List<int[]> overlaps = findOverlapPositions(ranges1, start, end);
1324     if (overlaps.isEmpty())
1325     {
1326       return overlaps;
1327     }
1328
1329     /*
1330      * convert positions to equivalent 'word' positions in ranges2
1331      */
1332     mapWords(overlaps, wordLength1, wordLength2);
1333
1334     /*
1335      * walk ranges2 and record the values found at 
1336      * the offsets in 'overlaps'
1337      */
1338     List<int[]> mapped = new ArrayList<>();
1339     final int s1 = overlaps.size();
1340     final int s2 = ranges2.size();
1341     int ranges2Index = 0;
1342     
1343     /*
1344      * count of mapped positions preceding ranges2[ranges2Index] 
1345      */
1346     int traversed = 0;
1347
1348     /*
1349      * for each [from-to] range in overlaps:
1350      * - walk (what remains of) ranges2
1351      * - record the values at offsets [from-to]
1352      * - stop when past 'to' positions (or at end of ranges2)
1353      */
1354     for (int i = 0; i < s1; i++)
1355     {
1356       int[] overlap = overlaps.get(i);
1357       final int toAdd = overlap[1] - overlap[0] + 1;
1358       int added = 0; // how much of overlap has been 'found'
1359       for (; added < toAdd && ranges2Index < s2; ranges2Index++)
1360       {
1361         int[] range2 = ranges2.get(ranges2Index);
1362         int rangeStart = range2[0];
1363         int rangeEnd = range2[1];
1364         boolean reverseStrand = range2[1] < range2[0];
1365         int rangeLength = Math.abs(rangeEnd - rangeStart) + 1;
1366         if (traversed + rangeLength <= overlap[0])
1367         {
1368           /*
1369            * precedes overlap - keep looking
1370            */
1371           traversed += rangeLength;
1372           continue;
1373         }
1374         int overlapStart = overlap[0] - traversed;
1375         int overlapEnd = Math.min(overlapStart + toAdd - added - 1,
1376                 rangeLength - 1);
1377         int mappedFrom = range2[0] + (reverseStrand ? - overlapStart : overlapStart);
1378         int mappedTo = range2[0] + (reverseStrand ? - overlapEnd : overlapEnd);
1379         mapped.add(new int[] { mappedFrom, mappedTo });
1380         int found = overlapEnd - overlapStart + 1;
1381         added += found;
1382         overlap[0] += found;
1383         traversed += rangeLength;
1384       }
1385     }
1386
1387     return mapped;
1388   }
1389
1390   /**
1391    * Converts the start-end positions (counted from zero) in the {@code ranges}
1392    * list from one word length to another. Start-end positions are expanded if
1393    * necessary to cover a whole word of length {@code wordLength1}. Positions
1394    * are then divided by {@code wordLength1} and multiplied by
1395    * {@code wordLength2} to give equivalent mapped words.
1396    * <p>
1397    * Put simply, this converts peptide residue positions to the corresponding
1398    * codon ranges, and codons - including partial codons - to the corresponding
1399    * peptide positions; for example
1400    * 
1401    * <pre>
1402    * [1, 10] with word lengths 3:1 converts (as if bases [0-11]) to [1, 4]
1403    * </pre>
1404    * 
1405    * @param ranges
1406    * @param wordLength1
1407    * @param wordLength2
1408    * @return
1409    */
1410   final static void mapWords(List<int[]> ranges, int wordLength1,
1411           int wordLength2)
1412   {
1413     if (wordLength1 == 1 && wordLength2 == 1)
1414     {
1415       return; // nothing to do here
1416     }
1417     int s = ranges.size();
1418     for (int i = 0; i < s; i++)
1419     {
1420       int[] range = ranges.get(i);
1421
1422       /*
1423        * expand range start to the start of a word, 
1424        * and convert to wordLength2
1425        */
1426       range[0] -= range[0] % wordLength1;
1427       range[0] = range[0] / wordLength1 * wordLength2;
1428
1429       /*
1430        * similar calculation for range end, adding 
1431        * (wordLength2 - 1) for end of mapped word
1432        */
1433       range[1] -= range[1] % wordLength1;
1434       range[1] = range[1] / wordLength1 * wordLength2;
1435       range[1] += wordLength2 - 1;
1436     }
1437   }
1438
1439   /**
1440    * Helper method that returns a (possibly empty) list of offsets in
1441    * {@code ranges} to subranges that overlap {@code start-end} (where start <=
1442    * end}. The list returned holds counts of the number of positions traversed
1443    * (exclusive) to reach the overlapping positions, not the overlapping values.
1444    * Returns null if there are no overlaps.
1445    * 
1446    * @param ranges
1447    * @param start
1448    * @param end
1449    * @return
1450    */
1451   final static List<int[]> findOverlapPositions(List<int[]> ranges,
1452           int start, int end)
1453   {
1454     List<int[]> positions = new ArrayList<>();
1455     int pos = 0;
1456     int s = ranges.size();
1457     for (int i = 0; i < s; i++)
1458     {
1459       int[] range = ranges.get(i);
1460       addOverlap(positions, pos, range, start, end);
1461       pos += 1 + Math.abs(range[1] - range[0]);
1462     }
1463     return positions;
1464   }
1465
1466   /**
1467    * A helper method that checks whether {@code range} overlaps
1468    * {@code start-end}, and if so adds the offset of the overlap in
1469    * {@code range}, plus {@code pos}, to {@code positions}.
1470    * 
1471    * @param positions
1472    *          a list of map offsets to add to
1473    * @param pos
1474    *          the number of mapped positions already visited
1475    * @param range
1476    *          a from-to range (may be forward or reverse)
1477    * @param start
1478    *          position to test for overlap in range
1479    * @param end
1480    *          position to test for overlap in range
1481    * @return
1482    */
1483   final static void addOverlap(List<int[]> positions, int pos, int[] range,
1484           int start, int end)
1485   {
1486     if (range[1] >= range[0])
1487     {
1488       /*
1489        * forward direction range
1490        */
1491       if (start <= range[1] && end >= range[0])
1492       {
1493         /*
1494          * overlap
1495          */
1496         int overlapStart = Math.max(start, range[0]);
1497         int overlapStartOffset = pos + overlapStart - range[0];
1498         int overlapEnd = Math.min(end, range[1]);
1499         int overlapEndOffset = pos + overlapEnd - range[0];
1500         int[] lastOverlap = positions.isEmpty() ? null
1501                 : positions.get(positions.size() - 1);
1502         if (lastOverlap != null && overlapStartOffset == lastOverlap[1] + 1)
1503         {
1504           /*
1505            * just extending the last overlap range
1506            */
1507           lastOverlap[1] = overlapEndOffset;
1508         }
1509         else
1510         {
1511           /*
1512            * add a new (discontiguous) overlap range
1513            */
1514           positions.add(new int[] { overlapStartOffset, overlapEndOffset });
1515         }
1516       }
1517     }
1518     else
1519     {
1520       /*
1521        * reverse direction range
1522        */
1523       if (start <= range[0] && end >= range[1])
1524       {
1525         /*
1526          * overlap
1527          */
1528         int overlapStart = Math.max(start, range[1]);
1529         int overlapEnd = Math.min(end, range[0]);
1530         positions
1531                 .add(new int[]
1532                 { pos + range[0] - overlapEnd,
1533                     pos + range[0] - overlapStart });
1534       }
1535     }
1536   }
1537 }