2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
28 * A simple way of bijectively mapping a non-contiguous linear range to another
29 * non-contiguous linear range.
31 * Use at your own risk!
33 * TODO: efficient implementation of private posMap method
35 * TODO: test/ensure that sense of from and to ratio start position is conserved
36 * (codon start position recovery)
42 * Subregions (base 1) described as { [start1, end1], [start2, end2], ...}
44 private List<int[]> fromShifts;
47 * Same format as fromShifts, for the 'mapped to' sequence
49 private List<int[]> toShifts;
52 * number of steps in fromShifts to one toRatio unit
54 private int fromRatio;
57 * number of steps in toShifts to one fromRatio
62 * lowest and highest value in the from Map
64 private int fromLowest;
66 private int fromHighest;
69 * lowest and highest value in the to Map
73 private int toHighest;
80 fromShifts = new ArrayList<int[]>();
81 toShifts = new ArrayList<int[]>();
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.
89 public boolean equals(Object o)
91 if (o == null || !(o instanceof MapList))
96 MapList obj = (MapList) o;
101 if (obj.fromRatio != fromRatio || obj.toRatio != toRatio
102 || obj.fromShifts == null || obj.toShifts == null)
107 .deepEquals(fromShifts.toArray(), obj.fromShifts.toArray())
109 .deepEquals(toShifts.toArray(), obj.toShifts.toArray());
113 * Returns a hashcode made from the fromRatio, toRatio, and from/to ranges
116 public int hashCode()
118 int hashCode = 31 * fromRatio;
119 hashCode = 31 * hashCode + toRatio;
120 hashCode = 31 * hashCode + fromShifts.toArray().hashCode();
121 hashCode = 31 * hashCode + toShifts.toArray().hashCode();
126 * Returns the 'from' ranges as {[start1, end1], [start2, end2], ...}
130 public List<int[]> getFromRanges()
136 * Returns the 'to' ranges as {[start1, end1], [start2, end2], ...}
140 public List<int[]> getToRanges()
146 * Flattens a list of [start, end] into a single [start1, end1, start2,
152 protected static int[] getRanges(List<int[]> shifts)
154 int[] rnges = new int[2 * shifts.size()];
156 for (int[] r : shifts)
166 * @return length of mapped phrase in from
168 public int getFromRatio()
175 * @return length of mapped phrase in to
177 public int getToRatio()
182 public int getFromLowest()
187 public int getFromHighest()
192 public int getToLowest()
197 public int getToHighest()
203 * Constructor given from and to ranges as [start1, end1, start2, end2,...].
204 * If any end is equal to the next start, the ranges will be merged. There is
205 * no validation check that the ranges do not overlap each other.
208 * contiguous regions as [start1, end1, start2, end2, ...]
210 * same format as 'from'
212 * phrase length in 'from' (e.g. 3 for dna)
214 * phrase length in 'to' (e.g. 1 for protein)
216 public MapList(int from[], int to[], int fromRatio, int toRatio)
219 this.fromRatio = fromRatio;
220 this.toRatio = toRatio;
221 fromLowest = Integer.MAX_VALUE;
222 fromHighest = Integer.MIN_VALUE;
225 for (int i = 0; i < from.length; i += 2)
228 * note lowest and highest values - bearing in mind the
229 * direction may be reversed
231 fromLowest = Math.min(fromLowest, Math.min(from[i], from[i + 1]));
232 fromHighest = Math.max(fromHighest, Math.max(from[i], from[i + 1]));
233 if (added > 0 && from[i] == fromShifts.get(added - 1)[1])
236 * this range starts where the last ended - just extend it
238 fromShifts.get(added - 1)[1] = from[i + 1];
242 fromShifts.add(new int[] { from[i], from[i + 1] });
247 toLowest = Integer.MAX_VALUE;
248 toHighest = Integer.MIN_VALUE;
250 for (int i = 0; i < to.length; i += 2)
252 toLowest = Math.min(toLowest, Math.min(to[i], to[i + 1]));
253 toHighest = Math.max(toHighest, Math.max(to[i], to[i + 1]));
254 if (added > 0 && to[i] == toShifts.get(added - 1)[1])
256 toShifts.get(added - 1)[1] = to[i + 1];
260 toShifts.add(new int[] { to[i], to[i + 1] });
267 * Copy constructor. Creates an identical mapping.
271 public MapList(MapList map)
274 // TODO not used - remove?
275 this.fromLowest = map.fromLowest;
276 this.fromHighest = map.fromHighest;
277 this.toLowest = map.toLowest;
278 this.toHighest = map.toHighest;
280 this.fromRatio = map.fromRatio;
281 this.toRatio = map.toRatio;
282 if (map.fromShifts != null)
284 for (int[] r : map.fromShifts)
286 fromShifts.add(new int[] { r[0], r[1] });
289 if (map.toShifts != null)
291 for (int[] r : map.toShifts)
293 toShifts.add(new int[] { r[0], r[1] });
299 * Constructor given ranges as lists of [start, end] positions. There is no
300 * validation check that the ranges do not overlap each other.
307 public MapList(List<int[]> fromRange, List<int[]> toRange, int fromRatio,
311 fromRange = coalesceRanges(fromRange);
312 toRange = coalesceRanges(toRange);
313 this.fromShifts = fromRange;
314 this.toShifts = toRange;
315 this.fromRatio = fromRatio;
316 this.toRatio = toRatio;
318 fromLowest = Integer.MAX_VALUE;
319 fromHighest = Integer.MIN_VALUE;
320 for (int[] range : fromRange)
322 fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
323 fromHighest = Math.max(fromHighest, Math.max(range[0], range[1]));
326 toLowest = Integer.MAX_VALUE;
327 toHighest = Integer.MIN_VALUE;
328 for (int[] range : toRange)
330 toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
331 toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
336 * Consolidates a list of ranges so that any contiguous ranges are merged.
337 * This assumes the ranges are already in start order (does not sort them).
340 * @return the same list (if unchanged), else a new merged list, leaving the
341 * input list unchanged
343 public static List<int[]> coalesceRanges(final List<int[]> ranges)
345 if (ranges == null || ranges.size() < 2) {
349 boolean changed = false;
350 List<int[]> merged = new ArrayList<int[]>();
351 int[] lastRange = ranges.get(0);
352 int lastDirection = lastRange[1] >= lastRange[0] ? 1 : -1;
353 lastRange = new int[] { lastRange[0], lastRange[1] };
354 merged.add(lastRange);
355 boolean first = true;
357 for (final int[] range : ranges)
364 if (range[0] == lastRange[0] && range[1] == lastRange[1])
366 // drop duplicate range
372 * drop this range if it lies within the last range
374 if ((lastDirection == 1 && range[0] >= lastRange[0]
375 && range[0] <= lastRange[1] && range[1] >= lastRange[0] && range[1] <= lastRange[1])
376 || (lastDirection == -1 && range[0] <= lastRange[0]
377 && range[0] >= lastRange[1]
378 && range[1] <= lastRange[0] && range[1] >= lastRange[1]))
384 int direction = range[1] >= range[0] ? 1 : -1;
387 * if next range is in the same direction as last and contiguous,
388 * just update the end position of the last range
390 boolean sameDirection = range[1] == range[0] || direction == lastDirection;
391 boolean extending = range[0] == lastRange[1] + lastDirection;
392 boolean overlapping = (lastDirection == 1 && range[0] >= lastRange[0] && range[0] <= lastRange[1])
393 || (lastDirection == -1 && range[0] <= lastRange[0] && range[0] >= lastRange[1]);
394 if (sameDirection && (overlapping || extending))
396 lastRange[1] = range[1];
401 lastRange = new int[] { range[0], range[1] };
402 merged.add(lastRange);
403 // careful: merging [5, 5] after [7, 6] should keep negative direction
404 lastDirection = (range[1] == range[0]) ? lastDirection : direction;
408 return changed ? merged : ranges;
412 * get all mapped positions from 'from' to 'to'
414 * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int
415 * [fromFinish-fromStart+2] { toStart..toFinish mappings}}
417 protected int[][] makeFromMap()
419 // TODO not used - remove??
420 return posMap(fromShifts, fromRatio, toShifts, toRatio);
424 * get all mapped positions from 'to' to 'from'
426 * @return int[to position]=position mapped in from
428 protected int[][] makeToMap()
430 // TODO not used - remove??
431 return posMap(toShifts, toRatio, fromShifts, fromRatio);
435 * construct an int map for intervals in intVals
438 * @return int[] { from, to pos in range }, int[range.to-range.from+1]
439 * returning mapped position
441 private int[][] posMap(List<int[]> shiftTo, int ratio,
442 List<int[]> shiftFrom, int toRatio)
444 // TODO not used - remove??
445 int iv = 0, ivSize = shiftTo.size();
450 int[] intv = shiftTo.get(iv++);
451 int from = intv[0], to = intv[1];
459 intv = shiftTo.get(iv++);
478 int mp[][] = new int[to - from + 2][];
479 for (int i = 0; i < mp.length; i++)
481 int[] m = shift(i + from, shiftTo, ratio, shiftFrom, toRatio);
502 int[][] map = new int[][] { new int[] { from, to, tF, tT },
503 new int[to - from + 2] };
508 for (int i = 0; i < mp.length; i++)
512 map[1][i] = mp[i][0] - tF;
516 map[1][i] = -1; // indicates an out of range mapping
526 * start position for shift (in original reference frame)
530 * public void addShift(int pos, int shift) { int sidx = 0; int[]
531 * rshift=null; while (sidx<shifts.size() && (rshift=(int[])
532 * shifts.elementAt(sidx))[0]<pos) sidx++; if (sidx==shifts.size())
533 * shifts.insertElementAt(new int[] { pos, shift}, sidx); else
534 * rshift[1]+=shift; }
538 * shift from pos to To(pos)
542 * @return int shifted position in To, frameshift in From, direction of mapped
545 public int[] shiftFrom(int pos)
547 return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
551 * inverse of shiftFrom - maps pos in To to a position in From
555 * @return shifted position in From, frameshift in To, direction of mapped
558 public int[] shiftTo(int pos)
560 return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
571 protected static int[] shift(int pos, List<int[]> shiftTo, int fromRatio,
572 List<int[]> shiftFrom, int toRatio)
574 // TODO: javadoc; tests
575 int[] fromCount = countPos(shiftTo, pos);
576 if (fromCount == null)
580 int fromRemainder = (fromCount[0] - 1) % fromRatio;
581 int toCount = 1 + (((fromCount[0] - 1) / fromRatio) * toRatio);
582 int[] toPos = countToPos(shiftFrom, toCount);
585 return null; // throw new Error("Bad Mapping!");
587 // System.out.println(fromCount[0]+" "+fromCount[1]+" "+toCount);
588 return new int[] { toPos[0], fromRemainder, toPos[1] };
592 * count how many positions pos is along the series of intervals.
596 * @return number of positions or null if pos is not within intervals
598 protected static int[] countPos(List<int[]> shiftTo, int pos)
600 int count = 0, intv[], iv = 0, ivSize = shiftTo.size();
603 intv = shiftTo.get(iv++);
604 if (intv[0] <= intv[1])
606 if (pos >= intv[0] && pos <= intv[1])
608 return new int[] { count + pos - intv[0] + 1, +1 };
612 count += intv[1] - intv[0] + 1;
617 if (pos >= intv[1] && pos <= intv[0])
619 return new int[] { count + intv[0] - pos + 1, -1 };
623 count += intv[0] - intv[1] + 1;
631 * count out pos positions into a series of intervals and return the position
635 * @return position pos in interval set
637 protected static int[] countToPos(List<int[]> shiftFrom, int pos)
639 int count = 0, diff = 0, iv = 0, ivSize = shiftFrom.size();
640 int[] intv = { 0, 0 };
643 intv = shiftFrom.get(iv++);
644 diff = intv[1] - intv[0];
647 if (pos <= count + 1 + diff)
649 return new int[] { pos - count - 1 + intv[0], +1 };
658 if (pos <= count + 1 - diff)
660 return new int[] { intv[0] - (pos - count - 1), -1 };
668 return null;// (diff<0) ? (intv[1]-1) : (intv[0]+1);
672 * find series of intervals mapping from start-end in the From map.
675 * position mapped 'to'
677 * position mapped 'to'
678 * @return series of [start, end] ranges in sequence mapped 'from'
680 public int[] locateInFrom(int start, int end)
682 // inefficient implementation
683 int fromStart[] = shiftTo(start);
684 // needs to be inclusive of end of symbol position
685 int fromEnd[] = shiftTo(end);
687 return getIntervals(fromShifts, fromStart, fromEnd, fromRatio);
691 * find series of intervals mapping from start-end in the to map.
694 * position mapped 'from'
696 * position mapped 'from'
697 * @return series of [start, end] ranges in sequence mapped 'to'
699 public int[] locateInTo(int start, int end)
701 int toStart[] = shiftFrom(start);
702 int toEnd[] = shiftFrom(end);
703 return getIntervals(toShifts, toStart, toEnd, toRatio);
707 * like shift - except returns the intervals in the given vector of shifts
708 * which were spanned in traversing fromStart to fromEnd
714 * @return series of from,to intervals from from first position of starting
715 * region to final position of ending region inclusive
717 protected static int[] getIntervals(List<int[]> shiftFrom,
718 int[] fromStart, int[] fromEnd, int fromRatio2)
720 if (fromStart == null || fromEnd == null)
724 int startpos, endpos;
725 startpos = fromStart[0]; // first position in fromStart
726 endpos = fromEnd[0]; // last position in fromEnd
727 int endindx = (fromRatio2 - 1); // additional positions to get to last
728 // position from endpos
729 int intv = 0, intvSize = shiftFrom.size();
730 int iv[], i = 0, fs = -1, fe_s = -1, fe = -1; // containing intervals
731 // search intervals to locate ones containing startpos and count endindx
732 // positions on from endpos
733 while (intv < intvSize && (fs == -1 || fe == -1))
735 iv = shiftFrom.get(intv++);
738 endpos = iv[0]; // start counting from beginning of interval
739 endindx--; // inclusive of endpos
743 if (fs == -1 && startpos >= iv[0] && startpos <= iv[1])
747 if (endpos >= iv[0] && endpos <= iv[1])
755 if (endpos + endindx <= iv[1])
758 endpos = endpos + endindx; // end of end token is within this
763 endindx -= iv[1] - endpos; // skip all this interval too
770 if (fs == -1 && startpos <= iv[0] && startpos >= iv[1])
774 if (endpos <= iv[0] && endpos >= iv[1])
782 if (endpos - endindx >= iv[1])
785 endpos = endpos - endindx; // end of end token is within this
790 endindx -= endpos - iv[1]; // skip all this interval too
797 if (fs == fe && fe == -1)
801 List<int[]> ranges = new ArrayList<int[]>();
806 // truncate initial interval
807 iv = shiftFrom.get(intv++);
808 iv = new int[] { iv[0], iv[1] };// clone
815 ranges.add(iv); // add initial range
816 iv = shiftFrom.get(intv++); // get next interval
817 iv = new int[] { iv[0], iv[1] };// clone
824 ranges.add(iv); // add only - or final range
828 // walk from end of interval.
829 i = shiftFrom.size() - 1;
834 iv = shiftFrom.get(i);
835 iv = new int[] { iv[1], iv[0] };// reverse and clone
836 // truncate initial interval
842 { // fix apparent logic bug when fe==-1
843 ranges.add(iv); // add (truncated) reversed interval
844 iv = shiftFrom.get(i);
845 iv = new int[] { iv[1], iv[0] }; // reverse and clone
849 // interval is already reversed
852 ranges.add(iv); // add only - or final range
854 // create array of start end intervals.
856 if (ranges != null && ranges.size() > 0)
858 range = new int[ranges.size() * 2];
860 intvSize = ranges.size();
862 while (intv < intvSize)
864 iv = ranges.get(intv);
867 ranges.set(intv++, null); // remove
874 * get the 'initial' position of mpos in To
878 * @return position of first word in to reference frame
880 public int getToPosition(int mpos)
882 // TODO not used - remove??
883 int[] mp = shiftTo(mpos);
892 * get range of positions in To frame for the mpos word in From
896 * @return null or int[] first position in To for mpos, last position in to
899 public int[] getToWord(int mpos)
901 int[] mp = shiftTo(mpos);
904 return new int[] { mp[0], mp[0] + mp[2] * (getFromRatio() - 1) };
910 * get From position in the associated reference frame for position pos in the
911 * associated sequence.
916 public int getMappedPosition(int pos)
918 // TODO not used - remove??
919 int[] mp = shiftFrom(pos);
927 public int[] getMappedWord(int pos)
929 // TODO not used - remove??
930 int[] mp = shiftFrom(pos);
933 return new int[] { mp[0], mp[0] + mp[2] * (getToRatio() - 1) };
940 * @return a MapList whose From range is this maplist's To Range, and vice
943 public MapList getInverse()
945 return new MapList(getToRanges(), getFromRanges(), getToRatio(),
950 * test for containment rather than equivalence to another mapping
953 * to be tested for containment
954 * @return true if local or mapped range map contains or is contained by this
957 public boolean containsEither(boolean local, MapList map)
959 // TODO not used - remove?
962 return ((getFromLowest() >= map.getFromLowest() && getFromHighest() <= map
963 .getFromHighest()) || (getFromLowest() <= map.getFromLowest() && getFromHighest() >= map
968 return ((getToLowest() >= map.getToLowest() && getToHighest() <= map
969 .getToHighest()) || (getToLowest() <= map.getToLowest() && getToHighest() >= map
975 * String representation - for debugging, not guaranteed not to change
978 public String toString()
980 StringBuilder sb = new StringBuilder(64);
982 for (int[] shift : fromShifts)
984 sb.append(" ").append(Arrays.toString(shift));
987 sb.append(fromRatio).append(":").append(toRatio);
989 for (int[] shift : toShifts)
991 sb.append(" ").append(Arrays.toString(shift));
994 return sb.toString();
998 * Extend this map list by adding the given map's ranges. There is no
999 * validation check that the ranges do not overlap existing ranges (or each
1000 * other), but contiguous ranges are merged.
1004 public void addMapList(MapList map)
1006 if (this.equals(map))
1010 this.fromLowest = Math.min(fromLowest, map.fromLowest);
1011 this.toLowest = Math.min(toLowest, map.toLowest);
1012 this.fromHighest = Math.max(fromHighest, map.fromHighest);
1013 this.toHighest = Math.max(toHighest, map.toHighest);
1015 for (int[] range : map.getFromRanges())
1017 addRange(range, fromShifts);
1019 for (int[] range : map.getToRanges())
1021 addRange(range, toShifts);
1026 * Adds the given range to a list of ranges. If the new range just extends
1027 * existing ranges, the current endpoint is updated instead.
1032 static void addRange(int[] range, List<int[]> addTo)
1035 * list is empty - add to it!
1037 if (addTo.size() == 0)
1043 int[] last = addTo.get(addTo.size() - 1);
1044 boolean lastForward = last[1] >= last[0];
1045 boolean newForward = range[1] >= range[0];
1048 * contiguous range in the same direction - just update endpoint
1050 if (lastForward == newForward && last[1] == range[0])
1057 * next range starts at +1 in forward sense - update endpoint
1059 if (lastForward && newForward && range[0] == last[1] + 1)
1066 * next range starts at -1 in reverse sense - update endpoint
1068 if (!lastForward && !newForward && range[0] == last[1] - 1)
1075 * just add the new range
1081 * Returns true if mapping is from forward strand, false if from reverse
1082 * strand. Result is just based on the first 'from' range that is not a single
1083 * position. Default is true unless proven to be false. Behaviour is not well
1084 * defined if the mapping has a mixture of forward and reverse ranges.
1088 public boolean isFromForwardStrand()
1090 boolean forwardStrand = true;
1091 for (int[] range : getFromRanges())
1093 if (range[1] > range[0])
1095 break; // forward strand confirmed
1097 else if (range[1] < range[0])
1099 forwardStrand = false;
1100 break; // reverse strand confirmed
1103 return forwardStrand;
1108 * @return true if from, or to is a three to 1 mapping
1110 public boolean isTripletMap()
1112 return (toRatio == 3 && fromRatio == 1)
1113 || (fromRatio == 3 && toRatio == 1);