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<>();
81 toShifts = new ArrayList<>();
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)
106 return Arrays.deepEquals(fromShifts.toArray(), obj.fromShifts.toArray())
107 && Arrays.deepEquals(toShifts.toArray(),
108 obj.toShifts.toArray());
112 * Returns a hashcode made from the fromRatio, toRatio, and from/to ranges
115 public int hashCode()
117 int hashCode = 31 * fromRatio;
118 hashCode = 31 * hashCode + toRatio;
119 for (int[] shift : fromShifts)
121 hashCode = 31 * hashCode + shift[0];
122 hashCode = 31 * hashCode + shift[1];
124 for (int[] shift : toShifts)
126 hashCode = 31 * hashCode + shift[0];
127 hashCode = 31 * hashCode + shift[1];
134 * Returns the 'from' ranges as {[start1, end1], [start2, end2], ...}
138 public List<int[]> getFromRanges()
144 * Returns the 'to' ranges as {[start1, end1], [start2, end2], ...}
148 public List<int[]> getToRanges()
154 * Flattens a list of [start, end] into a single [start1, end1, start2,
160 protected static int[] getRanges(List<int[]> shifts)
162 int[] rnges = new int[2 * shifts.size()];
164 for (int[] r : shifts)
174 * @return length of mapped phrase in from
176 public int getFromRatio()
183 * @return length of mapped phrase in to
185 public int getToRatio()
190 public int getFromLowest()
195 public int getFromHighest()
200 public int getToLowest()
205 public int getToHighest()
211 * Constructor given from and to ranges as [start1, end1, start2, end2,...].
212 * If any end is equal to the next start, the ranges will be merged. There is
213 * no validation check that the ranges do not overlap each other.
216 * contiguous regions as [start1, end1, start2, end2, ...]
218 * same format as 'from'
220 * phrase length in 'from' (e.g. 3 for dna)
222 * phrase length in 'to' (e.g. 1 for protein)
224 public MapList(int from[], int to[], int fromRatio, int toRatio)
227 this.fromRatio = fromRatio;
228 this.toRatio = toRatio;
229 fromLowest = Integer.MAX_VALUE;
230 fromHighest = Integer.MIN_VALUE;
233 for (int i = 0; i < from.length; i += 2)
236 * note lowest and highest values - bearing in mind the
237 * direction may be reversed
239 fromLowest = Math.min(fromLowest, Math.min(from[i], from[i + 1]));
240 fromHighest = Math.max(fromHighest, Math.max(from[i], from[i + 1]));
241 if (added > 0 && from[i] == fromShifts.get(added - 1)[1])
244 * this range starts where the last ended - just extend it
246 fromShifts.get(added - 1)[1] = from[i + 1];
250 fromShifts.add(new int[] { from[i], from[i + 1] });
255 toLowest = Integer.MAX_VALUE;
256 toHighest = Integer.MIN_VALUE;
258 for (int i = 0; i < to.length; i += 2)
260 toLowest = Math.min(toLowest, Math.min(to[i], to[i + 1]));
261 toHighest = Math.max(toHighest, Math.max(to[i], to[i + 1]));
262 if (added > 0 && to[i] == toShifts.get(added - 1)[1])
264 toShifts.get(added - 1)[1] = to[i + 1];
268 toShifts.add(new int[] { to[i], to[i + 1] });
275 * Copy constructor. Creates an identical mapping.
279 public MapList(MapList map)
282 // TODO not used - remove?
283 this.fromLowest = map.fromLowest;
284 this.fromHighest = map.fromHighest;
285 this.toLowest = map.toLowest;
286 this.toHighest = map.toHighest;
288 this.fromRatio = map.fromRatio;
289 this.toRatio = map.toRatio;
290 if (map.fromShifts != null)
292 for (int[] r : map.fromShifts)
294 fromShifts.add(new int[] { r[0], r[1] });
297 if (map.toShifts != null)
299 for (int[] r : map.toShifts)
301 toShifts.add(new int[] { r[0], r[1] });
307 * Constructor given ranges as lists of [start, end] positions. There is no
308 * validation check that the ranges do not overlap each other.
315 public MapList(List<int[]> fromRange, List<int[]> toRange, int fromRatio,
319 fromRange = coalesceRanges(fromRange);
320 toRange = coalesceRanges(toRange);
321 this.fromShifts = fromRange;
322 this.toShifts = toRange;
323 this.fromRatio = fromRatio;
324 this.toRatio = toRatio;
326 fromLowest = Integer.MAX_VALUE;
327 fromHighest = Integer.MIN_VALUE;
328 for (int[] range : fromRange)
330 if (range.length != 2)
332 // throw new IllegalArgumentException(range);
334 "Invalid format for fromRange " + Arrays.toString(range)
335 + " may cause errors");
337 fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
338 fromHighest = Math.max(fromHighest, Math.max(range[0], range[1]));
341 toLowest = Integer.MAX_VALUE;
342 toHighest = Integer.MIN_VALUE;
343 for (int[] range : toRange)
345 if (range.length != 2)
347 // throw new IllegalArgumentException(range);
348 System.err.println("Invalid format for toRange "
349 + Arrays.toString(range)
350 + " may cause errors");
352 toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
353 toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
358 * Consolidates a list of ranges so that any contiguous ranges are merged.
359 * This assumes the ranges are already in start order (does not sort them).
362 * @return the same list (if unchanged), else a new merged list, leaving the
363 * input list unchanged
365 public static List<int[]> coalesceRanges(final List<int[]> ranges)
367 if (ranges == null || ranges.size() < 2)
372 boolean changed = false;
373 List<int[]> merged = new ArrayList<>();
374 int[] lastRange = ranges.get(0);
375 int lastDirection = lastRange[1] >= lastRange[0] ? 1 : -1;
376 lastRange = new int[] { lastRange[0], lastRange[1] };
377 merged.add(lastRange);
378 boolean first = true;
380 for (final int[] range : ranges)
387 if (range[0] == lastRange[0] && range[1] == lastRange[1])
389 // drop duplicate range
395 * drop this range if it lies within the last range
397 if ((lastDirection == 1 && range[0] >= lastRange[0]
398 && range[0] <= lastRange[1] && range[1] >= lastRange[0]
399 && range[1] <= lastRange[1])
400 || (lastDirection == -1 && range[0] <= lastRange[0]
401 && range[0] >= lastRange[1]
402 && range[1] <= lastRange[0]
403 && range[1] >= lastRange[1]))
409 int direction = range[1] >= range[0] ? 1 : -1;
412 * if next range is in the same direction as last and contiguous,
413 * just update the end position of the last range
415 boolean sameDirection = range[1] == range[0]
416 || direction == lastDirection;
417 boolean extending = range[0] == lastRange[1] + lastDirection;
418 boolean overlapping = (lastDirection == 1 && range[0] >= lastRange[0]
419 && range[0] <= lastRange[1])
420 || (lastDirection == -1 && range[0] <= lastRange[0]
421 && range[0] >= lastRange[1]);
422 if (sameDirection && (overlapping || extending))
424 lastRange[1] = range[1];
429 lastRange = new int[] { range[0], range[1] };
430 merged.add(lastRange);
431 // careful: merging [5, 5] after [7, 6] should keep negative direction
432 lastDirection = (range[1] == range[0]) ? lastDirection : direction;
436 return changed ? merged : ranges;
440 * get all mapped positions from 'from' to 'to'
442 * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int
443 * [fromFinish-fromStart+2] { toStart..toFinish mappings}}
445 protected int[][] makeFromMap()
447 // TODO not used - remove??
448 return posMap(fromShifts, fromRatio, toShifts, toRatio);
452 * get all mapped positions from 'to' to 'from'
454 * @return int[to position]=position mapped in from
456 protected int[][] makeToMap()
458 // TODO not used - remove??
459 return posMap(toShifts, toRatio, fromShifts, fromRatio);
463 * construct an int map for intervals in intVals
466 * @return int[] { from, to pos in range }, int[range.to-range.from+1]
467 * returning mapped position
469 private int[][] posMap(List<int[]> shiftTo, int ratio,
470 List<int[]> shiftFrom, int toRatio)
472 // TODO not used - remove??
473 int iv = 0, ivSize = shiftTo.size();
478 int[] intv = shiftTo.get(iv++);
479 int from = intv[0], to = intv[1];
487 intv = shiftTo.get(iv++);
506 int mp[][] = new int[to - from + 2][];
507 for (int i = 0; i < mp.length; i++)
509 int[] m = shift(i + from, shiftTo, ratio, shiftFrom, toRatio);
530 int[][] map = new int[][] { new int[] { from, to, tF, tT },
531 new int[to - from + 2] };
536 for (int i = 0; i < mp.length; i++)
540 map[1][i] = mp[i][0] - tF;
544 map[1][i] = -1; // indicates an out of range mapping
554 * start position for shift (in original reference frame)
558 * public void addShift(int pos, int shift) { int sidx = 0; int[]
559 * rshift=null; while (sidx<shifts.size() && (rshift=(int[])
560 * shifts.elementAt(sidx))[0]<pos) sidx++; if (sidx==shifts.size())
561 * shifts.insertElementAt(new int[] { pos, shift}, sidx); else
562 * rshift[1]+=shift; }
566 * shift from pos to To(pos)
570 * @return int shifted position in To, frameshift in From, direction of mapped
573 public int[] shiftFrom(int pos)
575 return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
579 * inverse of shiftFrom - maps pos in To to a position in From
583 * @return shifted position in From, frameshift in To, direction of mapped
586 public int[] shiftTo(int pos)
588 return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
599 protected static int[] shift(int pos, List<int[]> shiftTo, int fromRatio,
600 List<int[]> shiftFrom, int toRatio)
602 // TODO: javadoc; tests
603 int[] fromCount = countPos(shiftTo, pos);
604 if (fromCount == null)
608 int fromRemainder = (fromCount[0] - 1) % fromRatio;
609 int toCount = 1 + (((fromCount[0] - 1) / fromRatio) * toRatio);
610 int[] toPos = countToPos(shiftFrom, toCount);
613 return null; // throw new Error("Bad Mapping!");
615 // System.out.println(fromCount[0]+" "+fromCount[1]+" "+toCount);
616 return new int[] { toPos[0], fromRemainder, toPos[1] };
620 * count how many positions pos is along the series of intervals.
624 * @return number of positions or null if pos is not within intervals
626 protected static int[] countPos(List<int[]> shiftTo, int pos)
628 int count = 0, intv[], iv = 0, ivSize = shiftTo.size();
631 intv = shiftTo.get(iv++);
632 if (intv[0] <= intv[1])
634 if (pos >= intv[0] && pos <= intv[1])
636 return new int[] { count + pos - intv[0] + 1, +1 };
640 count += intv[1] - intv[0] + 1;
645 if (pos >= intv[1] && pos <= intv[0])
647 return new int[] { count + intv[0] - pos + 1, -1 };
651 count += intv[0] - intv[1] + 1;
659 * count out pos positions into a series of intervals and return the position
663 * @return position pos in interval set
665 protected static int[] countToPos(List<int[]> shiftFrom, int pos)
667 int count = 0, diff = 0, iv = 0, ivSize = shiftFrom.size();
668 int[] intv = { 0, 0 };
671 intv = shiftFrom.get(iv++);
672 diff = intv[1] - intv[0];
675 if (pos <= count + 1 + diff)
677 return new int[] { pos - count - 1 + intv[0], +1 };
686 if (pos <= count + 1 - diff)
688 return new int[] { intv[0] - (pos - count - 1), -1 };
696 return null;// (diff<0) ? (intv[1]-1) : (intv[0]+1);
700 * find series of intervals mapping from start-end in the From map.
703 * position mapped 'to'
705 * position mapped 'to'
706 * @return series of [start, end] ranges in sequence mapped 'from'
708 public int[] locateInFrom(int start, int end)
710 // inefficient implementation
711 int fromStart[] = shiftTo(start);
712 // needs to be inclusive of end of symbol position
713 int fromEnd[] = shiftTo(end);
715 return getIntervals(fromShifts, fromStart, fromEnd, fromRatio);
719 * find series of intervals mapping from start-end in the to map.
722 * position mapped 'from'
724 * position mapped 'from'
725 * @return series of [start, end] ranges in sequence mapped 'to'
727 public int[] locateInTo(int start, int end)
729 int toStart[] = shiftFrom(start);
730 int toEnd[] = shiftFrom(end);
731 return getIntervals(toShifts, toStart, toEnd, toRatio);
735 * like shift - except returns the intervals in the given vector of shifts
736 * which were spanned in traversing fromStart to fromEnd
742 * @return series of from,to intervals from from first position of starting
743 * region to final position of ending region inclusive
745 protected static int[] getIntervals(List<int[]> shiftFrom,
746 int[] fromStart, int[] fromEnd, int fromRatio2)
748 if (fromStart == null || fromEnd == null)
752 int startpos, endpos;
753 startpos = fromStart[0]; // first position in fromStart
754 endpos = fromEnd[0]; // last position in fromEnd
755 int endindx = (fromRatio2 - 1); // additional positions to get to last
756 // position from endpos
757 int intv = 0, intvSize = shiftFrom.size();
758 int iv[], i = 0, fs = -1, fe_s = -1, fe = -1; // containing intervals
759 // search intervals to locate ones containing startpos and count endindx
760 // positions on from endpos
761 while (intv < intvSize && (fs == -1 || fe == -1))
763 iv = shiftFrom.get(intv++);
766 endpos = iv[0]; // start counting from beginning of interval
767 endindx--; // inclusive of endpos
771 if (fs == -1 && startpos >= iv[0] && startpos <= iv[1])
775 if (endpos >= iv[0] && endpos <= iv[1])
783 if (endpos + endindx <= iv[1])
786 endpos = endpos + endindx; // end of end token is within this
791 endindx -= iv[1] - endpos; // skip all this interval too
798 if (fs == -1 && startpos <= iv[0] && startpos >= iv[1])
802 if (endpos <= iv[0] && endpos >= iv[1])
810 if (endpos - endindx >= iv[1])
813 endpos = endpos - endindx; // end of end token is within this
818 endindx -= endpos - iv[1]; // skip all this interval too
825 if (fs == fe && fe == -1)
829 List<int[]> ranges = new ArrayList<>();
834 // truncate initial interval
835 iv = shiftFrom.get(intv++);
836 iv = new int[] { iv[0], iv[1] };// clone
843 ranges.add(iv); // add initial range
844 iv = shiftFrom.get(intv++); // get next interval
845 iv = new int[] { iv[0], iv[1] };// clone
852 ranges.add(iv); // add only - or final range
856 // walk from end of interval.
857 i = shiftFrom.size() - 1;
862 iv = shiftFrom.get(i);
863 iv = new int[] { iv[1], iv[0] };// reverse and clone
864 // truncate initial interval
870 { // fix apparent logic bug when fe==-1
871 ranges.add(iv); // add (truncated) reversed interval
872 iv = shiftFrom.get(i);
873 iv = new int[] { iv[1], iv[0] }; // reverse and clone
877 // interval is already reversed
880 ranges.add(iv); // add only - or final range
882 // create array of start end intervals.
884 if (ranges != null && ranges.size() > 0)
886 range = new int[ranges.size() * 2];
888 intvSize = ranges.size();
890 while (intv < intvSize)
892 iv = ranges.get(intv);
895 ranges.set(intv++, null); // remove
902 * get the 'initial' position of mpos in To
906 * @return position of first word in to reference frame
908 public int getToPosition(int mpos)
910 // TODO not used - remove??
911 int[] mp = shiftTo(mpos);
920 * get range of positions in To frame for the mpos word in From
924 * @return null or int[] first position in To for mpos, last position in to
927 public int[] getToWord(int mpos)
929 int[] mp = shiftTo(mpos);
932 return new int[] { mp[0], mp[0] + mp[2] * (getFromRatio() - 1) };
938 * get From position in the associated reference frame for position pos in the
939 * associated sequence.
944 public int getMappedPosition(int pos)
946 // TODO not used - remove??
947 int[] mp = shiftFrom(pos);
955 public int[] getMappedWord(int pos)
957 // TODO not used - remove??
958 int[] mp = shiftFrom(pos);
961 return new int[] { mp[0], mp[0] + mp[2] * (getToRatio() - 1) };
968 * @return a MapList whose From range is this maplist's To Range, and vice
971 public MapList getInverse()
973 return new MapList(getToRanges(), getFromRanges(), getToRatio(),
978 * test for containment rather than equivalence to another mapping
981 * to be tested for containment
982 * @return true if local or mapped range map contains or is contained by this
985 public boolean containsEither(boolean local, MapList map)
987 // TODO not used - remove?
990 return ((getFromLowest() >= map.getFromLowest()
991 && getFromHighest() <= map.getFromHighest())
992 || (getFromLowest() <= map.getFromLowest()
993 && getFromHighest() >= map.getFromHighest()));
997 return ((getToLowest() >= map.getToLowest()
998 && getToHighest() <= map.getToHighest())
999 || (getToLowest() <= map.getToLowest()
1000 && getToHighest() >= map.getToHighest()));
1005 * String representation - for debugging, not guaranteed not to change
1008 public String toString()
1010 StringBuilder sb = new StringBuilder(64);
1012 for (int[] shift : fromShifts)
1014 sb.append(" ").append(Arrays.toString(shift));
1017 sb.append(fromRatio).append(":").append(toRatio);
1019 for (int[] shift : toShifts)
1021 sb.append(" ").append(Arrays.toString(shift));
1024 return sb.toString();
1028 * Extend this map list by adding the given map's ranges. There is no
1029 * validation check that the ranges do not overlap existing ranges (or each
1030 * other), but contiguous ranges are merged.
1034 public void addMapList(MapList map)
1036 if (this.equals(map))
1040 this.fromLowest = Math.min(fromLowest, map.fromLowest);
1041 this.toLowest = Math.min(toLowest, map.toLowest);
1042 this.fromHighest = Math.max(fromHighest, map.fromHighest);
1043 this.toHighest = Math.max(toHighest, map.toHighest);
1045 for (int[] range : map.getFromRanges())
1047 MappingUtils.addRange(range, fromShifts);
1049 for (int[] range : map.getToRanges())
1051 MappingUtils.addRange(range, toShifts);
1056 * Returns true if mapping is from forward strand, false if from reverse
1057 * strand. Result is just based on the first 'from' range that is not a single
1058 * position. Default is true unless proven to be false. Behaviour is not well
1059 * defined if the mapping has a mixture of forward and reverse ranges.
1063 public boolean isFromForwardStrand()
1065 return isForwardStrand(getFromRanges());
1069 * Returns true if mapping is to forward strand, false if to reverse strand.
1070 * Result is just based on the first 'to' range that is not a single position.
1071 * Default is true unless proven to be false. Behaviour is not well defined if
1072 * the mapping has a mixture of forward and reverse ranges.
1076 public boolean isToForwardStrand()
1078 return isForwardStrand(getToRanges());
1082 * A helper method that returns true unless at least one range has start > end.
1083 * Behaviour is undefined for a mixture of forward and reverse ranges.
1088 private boolean isForwardStrand(List<int[]> ranges)
1090 boolean forwardStrand = true;
1091 for (int[] range : ranges)
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);
1117 * Returns a map which is the composite of this one and the input map. That
1118 * is, the output map has the fromRanges of this map, and its toRanges are the
1119 * toRanges of this map as transformed by the input map.
1121 * Returns null if the mappings cannot be traversed (not all toRanges of this
1122 * map correspond to fromRanges of the input), or if this.toRatio does not
1123 * match map.fromRatio.
1127 * this: from [1-100] to [501-600]
1128 * input: from [10-40] to [60-90]
1129 * output: from [10-40] to [560-590]
1130 * Example 2 ('reverse strand exons'):
1131 * this: from [1-100] to [2000-1951], [1000-951] // transcript to loci
1132 * input: from [1-50] to [41-90] // CDS to transcript
1133 * output: from [10-40] to [1960-1951], [1000-971] // CDS to gene loci
1139 public MapList traverse(MapList map)
1147 * compound the ratios by this rule:
1148 * A:B with M:N gives A*M:B*N
1149 * reduced by greatest common divisor
1150 * so 1:3 with 3:3 is 3:9 or 1:3
1151 * 1:3 with 3:1 is 3:3 or 1:1
1152 * 1:3 with 1:3 is 1:9
1153 * 2:5 with 3:7 is 6:35
1155 int outFromRatio = getFromRatio() * map.getFromRatio();
1156 int outToRatio = getToRatio() * map.getToRatio();
1157 int gcd = MathUtils.gcd(outFromRatio, outToRatio);
1158 outFromRatio /= gcd;
1161 List<int[]> toRanges = new ArrayList<>();
1162 for (int[] range : getToRanges())
1164 int[] transferred = map.locateInTo(range[0], range[1]);
1165 if (transferred == null || transferred.length % 2 != 0)
1171 * convert [start1, end1, start2, end2, ...]
1172 * to [[start1, end1], [start2, end2], ...]
1174 for (int i = 0; i < transferred.length;)
1176 toRanges.add(new int[] { transferred[i], transferred[i + 1] });
1181 return new MapList(getFromRanges(), toRanges, outFromRatio, outToRatio);
1185 * Answers true if the mapping is from one contiguous range to another, else
1190 public boolean isContiguous()
1192 return fromShifts.size() == 1 && toShifts.size() == 1;