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.BitSet;
26 import java.util.List;
28 import jalview.bin.Console;
31 * A simple way of bijectively mapping a non-contiguous linear range to another
32 * non-contiguous linear range.
34 * Use at your own risk!
36 * TODO: test/ensure that sense of from and to ratio start position is conserved
37 * (codon start position recovery)
43 * Subregions (base 1) described as { [start1, end1], [start2, end2], ...}
45 private List<int[]> fromShifts;
48 * Same format as fromShifts, for the 'mapped to' sequence
50 private List<int[]> toShifts;
53 * number of steps in fromShifts to one toRatio unit
55 private int fromRatio;
58 * number of steps in toShifts to one fromRatio
63 * lowest and highest value in the from Map
65 private int fromLowest;
67 private int fromHighest;
70 * lowest and highest value in the to Map
74 private int toHighest;
81 fromShifts = new ArrayList<>();
82 toShifts = new ArrayList<>();
86 * Two MapList objects are equal if they are the same object, or they both
87 * have populated shift ranges and all values are the same.
90 public boolean equals(Object o)
92 if (o == null || !(o instanceof MapList))
97 MapList obj = (MapList) o;
102 if (obj.fromRatio != fromRatio || obj.toRatio != toRatio
103 || obj.fromShifts == null || obj.toShifts == null)
107 return Arrays.deepEquals(fromShifts.toArray(), obj.fromShifts.toArray())
108 && Arrays.deepEquals(toShifts.toArray(),
109 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 for (int[] shift : fromShifts)
122 hashCode = 31 * hashCode + shift[0];
123 hashCode = 31 * hashCode + shift[1];
125 for (int[] shift : toShifts)
127 hashCode = 31 * hashCode + shift[0];
128 hashCode = 31 * hashCode + shift[1];
135 * Returns the 'from' ranges as {[start1, end1], [start2, end2], ...}
139 public List<int[]> getFromRanges()
145 * Returns the 'to' ranges as {[start1, end1], [start2, end2], ...}
149 public List<int[]> getToRanges()
155 * Flattens a list of [start, end] into a single [start1, end1, start2,
161 protected static int[] getRanges(List<int[]> shifts)
163 int[] rnges = new int[2 * shifts.size()];
165 for (int[] r : shifts)
175 * @return length of mapped phrase in from
177 public int getFromRatio()
184 * @return length of mapped phrase in to
186 public int getToRatio()
191 public int getFromLowest()
196 public int getFromHighest()
201 public int getToLowest()
206 public int getToHighest()
212 * Constructor given from and to ranges as [start1, end1, start2, end2,...].
213 * There is 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;
232 for (int i = 0; i < from.length; i += 2)
235 * note lowest and highest values - bearing in mind the
236 * direction may be reversed
238 fromLowest = Math.min(fromLowest, Math.min(from[i], from[i + 1]));
239 fromHighest = Math.max(fromHighest, Math.max(from[i], from[i + 1]));
240 fromShifts.add(new int[] { from[i], from[i + 1] });
243 toLowest = Integer.MAX_VALUE;
244 toHighest = Integer.MIN_VALUE;
245 for (int i = 0; i < to.length; i += 2)
247 toLowest = Math.min(toLowest, Math.min(to[i], to[i + 1]));
248 toHighest = Math.max(toHighest, Math.max(to[i], to[i + 1]));
249 toShifts.add(new int[] { to[i], to[i + 1] });
254 * Copy constructor. Creates an identical mapping.
258 public MapList(MapList map)
261 // TODO not used - remove?
262 this.fromLowest = map.fromLowest;
263 this.fromHighest = map.fromHighest;
264 this.toLowest = map.toLowest;
265 this.toHighest = map.toHighest;
267 this.fromRatio = map.fromRatio;
268 this.toRatio = map.toRatio;
269 if (map.fromShifts != null)
271 for (int[] r : map.fromShifts)
273 fromShifts.add(new int[] { r[0], r[1] });
276 if (map.toShifts != null)
278 for (int[] r : map.toShifts)
280 toShifts.add(new int[] { r[0], r[1] });
286 * Constructor given ranges as lists of [start, end] positions. There is no
287 * validation check that the ranges do not overlap each other.
294 public MapList(List<int[]> fromRange, List<int[]> toRange, int fromRatio,
298 fromRange = coalesceRanges(fromRange);
299 toRange = coalesceRanges(toRange);
300 this.fromShifts = fromRange;
301 this.toShifts = toRange;
302 this.fromRatio = fromRatio;
303 this.toRatio = toRatio;
305 fromLowest = Integer.MAX_VALUE;
306 fromHighest = Integer.MIN_VALUE;
307 for (int[] range : fromRange)
309 if (range.length != 2)
311 // throw new IllegalArgumentException(range);
312 Console.error("Invalid format for fromRange "
313 + Arrays.toString(range) + " may cause errors");
315 fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
316 fromHighest = Math.max(fromHighest, Math.max(range[0], range[1]));
319 toLowest = Integer.MAX_VALUE;
320 toHighest = Integer.MIN_VALUE;
321 for (int[] range : toRange)
323 if (range.length != 2)
325 // throw new IllegalArgumentException(range);
326 Console.error("Invalid format for toRange " + Arrays.toString(range)
327 + " may cause errors");
329 toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
330 toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
335 * Consolidates a list of ranges so that any contiguous ranges are merged.
336 * This assumes the ranges are already in start order (does not sort them).
338 * The main use case for this method is when mapping cDNA sequence to its
339 * protein product, based on CDS feature ranges which derive from spliced
340 * exons, but are contiguous on the cDNA sequence. For example
343 * CDS 1-20 // from exon1
344 * CDS 21-35 // from exon2
345 * CDS 36-71 // from exon3
346 * 'coalesce' to range 1-71
350 * @return the same list (if unchanged), else a new merged list, leaving the
351 * input list unchanged
353 public static List<int[]> coalesceRanges(final List<int[]> ranges)
355 if (ranges == null || ranges.size() < 2)
360 boolean changed = false;
361 List<int[]> merged = new ArrayList<>();
362 int[] lastRange = ranges.get(0);
363 int lastDirection = lastRange[1] >= lastRange[0] ? 1 : -1;
364 lastRange = new int[] { lastRange[0], lastRange[1] };
365 merged.add(lastRange);
366 boolean first = true;
368 for (final int[] range : ranges)
376 int direction = range[1] >= range[0] ? 1 : -1;
379 * if next range is in the same direction as last and contiguous,
380 * just update the end position of the last range
382 boolean sameDirection = range[1] == range[0]
383 || direction == lastDirection;
384 boolean extending = range[0] == lastRange[1] + lastDirection;
385 if (sameDirection && extending)
387 lastRange[1] = range[1];
392 lastRange = new int[] { range[0], range[1] };
393 merged.add(lastRange);
394 // careful: merging [5, 5] after [7, 6] should keep negative direction
395 lastDirection = (range[1] == range[0]) ? lastDirection : direction;
399 return changed ? merged : ranges;
403 * get all mapped positions from 'from' to 'to'
405 * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int
406 * [fromFinish-fromStart+2] { toStart..toFinish mappings}}
408 protected int[][] makeFromMap()
410 // TODO only used for test - remove??
411 return posMap(fromShifts, fromRatio, toShifts, toRatio);
415 * get all mapped positions from 'to' to 'from'
417 * @return int[to position]=position mapped in from
419 protected int[][] makeToMap()
421 // TODO only used for test - remove??
422 return posMap(toShifts, toRatio, fromShifts, fromRatio);
426 * construct an int map for intervals in intVals
429 * @return int[] { from, to pos in range }, int[range.to-range.from+1]
430 * returning mapped position
432 private int[][] posMap(List<int[]> shiftTo, int sourceRatio,
433 List<int[]> shiftFrom, int targetRatio)
435 // TODO only used for test - remove??
436 int iv = 0, ivSize = shiftTo.size();
441 int[] intv = shiftTo.get(iv++);
442 int from = intv[0], to = intv[1];
450 intv = shiftTo.get(iv++);
469 int mp[][] = new int[to - from + 2][];
470 for (int i = 0; i < mp.length; i++)
472 int[] m = shift(i + from, shiftTo, sourceRatio, shiftFrom,
494 int[][] map = new int[][] { new int[] { from, to, tF, tT },
495 new int[to - from + 2] };
500 for (int i = 0; i < mp.length; i++)
504 map[1][i] = mp[i][0] - tF;
508 map[1][i] = -1; // indicates an out of range mapping
518 * start position for shift (in original reference frame)
522 * public void addShift(int pos, int shift) { int sidx = 0; int[]
523 * rshift=null; while (sidx<shifts.size() && (rshift=(int[])
524 * shifts.elementAt(sidx))[0]<pos) sidx++; if (sidx==shifts.size())
525 * shifts.insertElementAt(new int[] { pos, shift}, sidx); else
526 * rshift[1]+=shift; }
530 * shift from pos to To(pos)
534 * @return int shifted position in To, frameshift in From, direction of mapped
537 public int[] shiftFrom(int pos)
539 return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
543 * inverse of shiftFrom - maps pos in To to a position in From
547 * @return shifted position in From, frameshift in To, direction of mapped
550 public int[] shiftTo(int pos)
552 return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
563 protected static int[] shift(int pos, List<int[]> shiftTo, int fromRatio,
564 List<int[]> shiftFrom, int toRatio)
566 // TODO: javadoc; tests
567 int[] fromCount = countPositions(shiftTo, pos);
568 if (fromCount == null)
572 int fromRemainder = (fromCount[0] - 1) % fromRatio;
573 int toCount = 1 + (((fromCount[0] - 1) / fromRatio) * toRatio);
574 int[] toPos = traverseToPosition(shiftFrom, toCount);
579 return new int[] { toPos[0], fromRemainder, toPos[1] };
583 * Counts how many positions pos is along the series of intervals. Returns an
584 * array of two values:
586 * <li>the number of positions traversed (inclusive) to reach {@code pos}</li>
587 * <li>+1 if the last interval traversed is forward, -1 if in a negative
590 * Returns null if {@code pos} does not lie in any of the given intervals.
593 * a list of start-end intervals
595 * a position that may lie in one (or more) of the intervals
598 protected static int[] countPositions(List<int[]> intervals, int pos)
602 int ivSize = intervals.size();
606 int[] intv = intervals.get(iv++);
607 if (intv[0] <= intv[1])
612 if (pos >= intv[0] && pos <= intv[1])
614 return new int[] { count + pos - intv[0] + 1, +1 };
618 count += intv[1] - intv[0] + 1;
626 if (pos >= intv[1] && pos <= intv[0])
628 return new int[] { count + intv[0] - pos + 1, -1 };
632 count += intv[0] - intv[1] + 1;
640 * Reads through the given intervals until {@code count} positions have been
641 * traversed, and returns an array consisting of two values:
643 * <li>the value at the {@code count'th} position</li>
644 * <li>+1 if the last interval read is forwards, -1 if reverse direction</li>
646 * Returns null if the ranges include less than {@code count} positions, or if
650 * a list of [start, end] ranges
652 * the number of positions to traverse
655 protected static int[] traverseToPosition(List<int[]> intervals,
659 int ivSize = intervals.size();
669 int[] intv = intervals.get(iv++);
670 int diff = intv[1] - intv[0];
673 if (count <= traversed + 1 + diff)
675 return new int[] { intv[0] + (count - traversed - 1), +1 };
679 traversed += 1 + diff;
684 if (count <= traversed + 1 - diff)
686 return new int[] { intv[0] - (count - traversed - 1), -1 };
690 traversed += 1 - diff;
698 * like shift - except returns the intervals in the given vector of shifts
699 * which were spanned in traversing fromStart to fromEnd
705 * @return series of from,to intervals from from first position of starting
706 * region to final position of ending region inclusive
708 protected static int[] getIntervals(List<int[]> shiftFrom,
709 int[] fromStart, int[] fromEnd, int fromRatio2)
711 if (fromStart == null || fromEnd == null)
715 int startpos, endpos;
716 startpos = fromStart[0]; // first position in fromStart
717 endpos = fromEnd[0]; // last position in fromEnd
718 int endindx = (fromRatio2 - 1); // additional positions to get to last
719 // position from endpos
720 int intv = 0, intvSize = shiftFrom.size();
721 int iv[], i = 0, fs = -1, fe_s = -1, fe = -1; // containing intervals
722 // search intervals to locate ones containing startpos and count endindx
723 // positions on from endpos
724 while (intv < intvSize && (fs == -1 || fe == -1))
726 iv = shiftFrom.get(intv++);
729 endpos = iv[0]; // start counting from beginning of interval
730 endindx--; // inclusive of endpos
734 if (fs == -1 && startpos >= iv[0] && startpos <= iv[1])
738 if (endpos >= iv[0] && endpos <= iv[1])
746 if (endpos + endindx <= iv[1])
749 endpos = endpos + endindx; // end of end token is within this
754 endindx -= iv[1] - endpos; // skip all this interval too
761 if (fs == -1 && startpos <= iv[0] && startpos >= iv[1])
765 if (endpos <= iv[0] && endpos >= iv[1])
773 if (endpos - endindx >= iv[1])
776 endpos = endpos - endindx; // end of end token is within this
781 endindx -= endpos - iv[1]; // skip all this interval too
788 if (fs == fe && fe == -1)
792 List<int[]> ranges = new ArrayList<>();
797 // truncate initial interval
798 iv = shiftFrom.get(intv++);
799 iv = new int[] { iv[0], iv[1] };// clone
806 ranges.add(iv); // add initial range
807 iv = shiftFrom.get(intv++); // get next interval
808 iv = new int[] { iv[0], iv[1] };// clone
815 ranges.add(iv); // add only - or final range
819 // walk from end of interval.
820 i = shiftFrom.size() - 1;
825 iv = shiftFrom.get(i);
826 iv = new int[] { iv[1], iv[0] };// reverse and clone
827 // truncate initial interval
833 { // fix apparent logic bug when fe==-1
834 ranges.add(iv); // add (truncated) reversed interval
835 iv = shiftFrom.get(i);
836 iv = new int[] { iv[1], iv[0] }; // reverse and clone
840 // interval is already reversed
843 ranges.add(iv); // add only - or final range
845 // create array of start end intervals.
847 if (ranges != null && ranges.size() > 0)
849 range = new int[ranges.size() * 2];
851 intvSize = ranges.size();
853 while (intv < intvSize)
855 iv = ranges.get(intv);
858 ranges.set(intv++, null); // remove
865 * get the 'initial' position of mpos in To
869 * @return position of first word in to reference frame
871 public int getToPosition(int mpos)
873 int[] mp = shiftTo(mpos);
883 * @return a MapList whose From range is this maplist's To Range, and vice
886 public MapList getInverse()
888 return new MapList(getToRanges(), getFromRanges(), getToRatio(),
893 * String representation - for debugging, not guaranteed not to change
896 public String toString()
898 StringBuilder sb = new StringBuilder(64);
900 for (int[] shift : fromShifts)
902 sb.append(" ").append(Arrays.toString(shift));
905 sb.append(fromRatio).append(":").append(toRatio);
907 for (int[] shift : toShifts)
909 sb.append(" ").append(Arrays.toString(shift));
912 return sb.toString();
916 * Extend this map list by adding the given map's ranges. There is no
917 * validation check that the ranges do not overlap existing ranges (or each
918 * other), but contiguous ranges are merged.
922 public void addMapList(MapList map)
924 if (this.equals(map))
928 this.fromLowest = Math.min(fromLowest, map.fromLowest);
929 this.toLowest = Math.min(toLowest, map.toLowest);
930 this.fromHighest = Math.max(fromHighest, map.fromHighest);
931 this.toHighest = Math.max(toHighest, map.toHighest);
933 for (int[] range : map.getFromRanges())
935 addRange(range, fromShifts);
937 for (int[] range : map.getToRanges())
939 addRange(range, toShifts);
944 * Adds the given range to a list of ranges. If the new range just extends
945 * existing ranges, the current endpoint is updated instead.
950 static void addRange(int[] range, List<int[]> addTo)
953 * list is empty - add to it!
955 if (addTo.size() == 0)
961 int[] last = addTo.get(addTo.size() - 1);
962 boolean lastForward = last[1] >= last[0];
963 boolean newForward = range[1] >= range[0];
966 * contiguous range in the same direction - just update endpoint
968 if (lastForward == newForward && last[1] == range[0])
975 * next range starts at +1 in forward sense - update endpoint
977 if (lastForward && newForward && range[0] == last[1] + 1)
984 * next range starts at -1 in reverse sense - update endpoint
986 if (!lastForward && !newForward && range[0] == last[1] - 1)
993 * just add the new range
999 * Returns true if mapping is from forward strand, false if from reverse
1000 * strand. Result is just based on the first 'from' range that is not a single
1001 * position. Default is true unless proven to be false. Behaviour is not well
1002 * defined if the mapping has a mixture of forward and reverse ranges.
1006 public boolean isFromForwardStrand()
1008 return isForwardStrand(getFromRanges());
1012 * Returns true if mapping is to forward strand, false if to reverse strand.
1013 * Result is just based on the first 'to' range that is not a single position.
1014 * Default is true unless proven to be false. Behaviour is not well defined if
1015 * the mapping has a mixture of forward and reverse ranges.
1019 public boolean isToForwardStrand()
1021 return isForwardStrand(getToRanges());
1025 * A helper method that returns true unless at least one range has start >
1026 * end. Behaviour is undefined for a mixture of forward and reverse ranges.
1031 private boolean isForwardStrand(List<int[]> ranges)
1033 boolean forwardStrand = true;
1034 for (int[] range : ranges)
1036 if (range[1] > range[0])
1038 break; // forward strand confirmed
1040 else if (range[1] < range[0])
1042 forwardStrand = false;
1043 break; // reverse strand confirmed
1046 return forwardStrand;
1051 * @return true if from, or to is a three to 1 mapping
1053 public boolean isTripletMap()
1055 return (toRatio == 3 && fromRatio == 1)
1056 || (fromRatio == 3 && toRatio == 1);
1060 * Returns a map which is the composite of this one and the input map. That
1061 * is, the output map has the fromRanges of this map, and its toRanges are the
1062 * toRanges of this map as transformed by the input map.
1064 * Returns null if the mappings cannot be traversed (not all toRanges of this
1065 * map correspond to fromRanges of the input), or if this.toRatio does not
1066 * match map.fromRatio.
1070 * this: from [1-100] to [501-600]
1071 * input: from [10-40] to [60-90]
1072 * output: from [10-40] to [560-590]
1073 * Example 2 ('reverse strand exons'):
1074 * this: from [1-100] to [2000-1951], [1000-951] // transcript to loci
1075 * input: from [1-50] to [41-90] // CDS to transcript
1076 * output: from [10-40] to [1960-1951], [1000-971] // CDS to gene loci
1082 public MapList traverse(MapList map)
1090 * compound the ratios by this rule:
1091 * A:B with M:N gives A*M:B*N
1092 * reduced by greatest common divisor
1093 * so 1:3 with 3:3 is 3:9 or 1:3
1094 * 1:3 with 3:1 is 3:3 or 1:1
1095 * 1:3 with 1:3 is 1:9
1096 * 2:5 with 3:7 is 6:35
1098 int outFromRatio = getFromRatio() * map.getFromRatio();
1099 int outToRatio = getToRatio() * map.getToRatio();
1100 int gcd = MathUtils.gcd(outFromRatio, outToRatio);
1101 outFromRatio /= gcd;
1104 List<int[]> toRanges = new ArrayList<>();
1105 for (int[] range : getToRanges())
1107 int fromLength = Math.abs(range[1] - range[0]) + 1;
1108 int[] transferred = map.locateInTo(range[0], range[1]);
1109 if (transferred == null || transferred.length % 2 != 0)
1115 * convert [start1, end1, start2, end2, ...]
1116 * to [[start1, end1], [start2, end2], ...]
1119 for (int i = 0; i < transferred.length;)
1121 toRanges.add(new int[] { transferred[i], transferred[i + 1] });
1122 toLength += Math.abs(transferred[i + 1] - transferred[i]) + 1;
1127 * check we mapped the full range - if not, abort
1129 if (fromLength * map.getToRatio() != toLength * map.getFromRatio())
1135 return new MapList(getFromRanges(), toRanges, outFromRatio, outToRatio);
1139 * Answers true if the mapping is from one contiguous range to another, else
1144 public boolean isContiguous()
1146 return fromShifts.size() == 1 && toShifts.size() == 1;
1150 * <<<<<<< HEAD Returns the [start1, end1, start2, end2, ...] positions in the
1151 * 'from' range that map to positions between {@code start} and {@code end} in
1152 * the 'to' range. Note that for a reverse strand mapping this will return
1153 * ranges with end < start. Returns null if no mapped positions are found in
1160 public int[] locateInFrom(int start, int end)
1162 return mapPositions(start, end, toShifts, fromShifts, toRatio,
1167 * Returns the [start1, end1, start2, end2, ...] positions in the 'to' range
1168 * that map to positions between {@code start} and {@code end} in the 'from'
1169 * range. Note that for a reverse strand mapping this will return ranges with
1170 * end < start. Returns null if no mapped positions are found in start-end.
1176 public int[] locateInTo(int start, int end)
1178 return mapPositions(start, end, fromShifts, toShifts, fromRatio,
1183 * Helper method that returns the [start1, end1, start2, end2, ...] positions
1184 * in {@code targetRange} that map to positions between {@code start} and
1185 * {@code end} in {@code sourceRange}. Note that for a reverse strand mapping
1186 * this will return ranges with end < start. Returns null if no mapped
1187 * positions are found in start-end.
1191 * @param sourceRange
1192 * @param targetRange
1193 * @param sourceWordLength
1194 * @param targetWordLength
1197 final static int[] mapPositions(int start, int end,
1198 List<int[]> sourceRange, List<int[]> targetRange,
1199 int sourceWordLength, int targetWordLength)
1209 * traverse sourceRange and mark offsets in targetRange
1210 * of any positions that lie in [start, end]
1212 BitSet offsets = getMappedOffsetsForPositions(start, end, sourceRange,
1213 sourceWordLength, targetWordLength);
1216 * traverse targetRange and collect positions at the marked offsets
1218 List<int[]> mapped = getPositionsForOffsets(targetRange, offsets);
1220 // TODO: or just return the List and adjust calling code to match
1221 return mapped.isEmpty() ? null : MappingUtils.rangeListToArray(mapped);
1225 * Scans the list of {@code ranges} for any values (positions) that lie
1226 * between start and end (inclusive), and records the <em>offsets</em> from
1227 * the start of the list as a BitSet. The offset positions are converted to
1228 * corresponding words in blocks of {@code wordLength2}.
1232 * 1:1 (e.g. gene to CDS):
1233 * ranges { [10-20], [31-40] }, wordLengthFrom = wordLength 2 = 1
1234 * for start = 1, end = 9, returns a BitSet with no bits set
1235 * for start = 1, end = 11, returns a BitSet with bits 0-1 set
1236 * for start = 15, end = 35, returns a BitSet with bits 5-15 set
1237 * 1:3 (peptide to codon):
1238 * ranges { [1-200] }, wordLengthFrom = 1, wordLength 2 = 3
1239 * for start = 9, end = 9, returns a BitSet with bits 24-26 set
1240 * 3:1 (codon to peptide):
1241 * ranges { [101-150], [171-180] }, wordLengthFrom = 3, wordLength 2 = 1
1242 * for start = 101, end = 102 (partial first codon), returns a BitSet with bit 0 set
1243 * for start = 150, end = 171 (partial 17th codon), returns a BitSet with bit 16 set
1244 * 3:1 (circular DNA to peptide):
1245 * ranges { [101-150], [21-30] }, wordLengthFrom = 3, wordLength 2 = 1
1246 * for start = 24, end = 40 (spans codons 18-20), returns a BitSet with bits 17-19 set
1251 * @param sourceRange
1252 * @param sourceWordLength
1253 * @param targetWordLength
1256 protected final static BitSet getMappedOffsetsForPositions(int start,
1257 int end, List<int[]> sourceRange, int sourceWordLength,
1258 int targetWordLength)
1260 BitSet overlaps = new BitSet();
1262 final int s1 = sourceRange.size();
1263 for (int i = 0; i < s1; i++)
1265 int[] range = sourceRange.get(i);
1266 final int offset1 = offset;
1267 int overlapStartOffset = -1;
1268 int overlapEndOffset = -1;
1270 if (range[1] >= range[0])
1273 * forward direction range
1275 if (start <= range[1] && end >= range[0])
1280 int overlapStart = Math.max(start, range[0]);
1281 overlapStartOffset = offset1 + overlapStart - range[0];
1282 int overlapEnd = Math.min(end, range[1]);
1283 overlapEndOffset = offset1 + overlapEnd - range[0];
1289 * reverse direction range
1291 if (start <= range[0] && end >= range[1])
1296 int overlapStart = Math.max(start, range[1]);
1297 int overlapEnd = Math.min(end, range[0]);
1298 overlapStartOffset = offset1 + range[0] - overlapEnd;
1299 overlapEndOffset = offset1 + range[0] - overlapStart;
1303 if (overlapStartOffset > -1)
1308 if (sourceWordLength != targetWordLength)
1311 * convert any overlap found to whole words in the target range
1312 * (e.g. treat any partial codon overlap as if the whole codon)
1314 overlapStartOffset -= overlapStartOffset % sourceWordLength;
1315 overlapStartOffset = overlapStartOffset / sourceWordLength
1319 * similar calculation for range end, adding
1320 * (wordLength2 - 1) for end of mapped word
1322 overlapEndOffset -= overlapEndOffset % sourceWordLength;
1323 overlapEndOffset = overlapEndOffset / sourceWordLength
1325 overlapEndOffset += targetWordLength - 1;
1327 overlaps.set(overlapStartOffset, overlapEndOffset + 1);
1329 offset += 1 + Math.abs(range[1] - range[0]);
1335 * Returns a (possibly empty) list of the [start-end] values (positions) at
1336 * offsets in the {@code targetRange} list that are marked by 'on' bits in the
1337 * {@code offsets} bitset.
1339 * @param targetRange
1343 protected final static List<int[]> getPositionsForOffsets(
1344 List<int[]> targetRange, BitSet offsets)
1346 List<int[]> mapped = new ArrayList<>();
1347 if (offsets.isEmpty())
1353 * count of positions preceding ranges[i]
1358 * for each [from-to] range in ranges:
1359 * - find subranges (if any) at marked offsets
1360 * - add the start-end values at the marked positions
1362 final int toAdd = offsets.cardinality();
1364 final int s2 = targetRange.size();
1365 for (int i = 0; added < toAdd && i < s2; i++)
1367 int[] range = targetRange.get(i);
1368 added += addOffsetPositions(mapped, traversed, range, offsets);
1369 traversed += Math.abs(range[1] - range[0]) + 1;
1375 * Helper method that adds any start-end subranges of {@code range} that are
1376 * at offsets in {@code range} marked by set bits in overlaps.
1377 * {@code mapOffset} is added to {@code range} offset positions. Returns the
1378 * count of positions added.
1386 final static int addOffsetPositions(List<int[]> mapped,
1387 final int mapOffset, final int[] range, final BitSet overlaps)
1389 final int rangeLength = 1 + Math.abs(range[1] - range[0]);
1390 final int step = range[1] < range[0] ? -1 : 1;
1391 int offsetStart = 0; // offset into range
1394 while (offsetStart < rangeLength)
1397 * find the start of the next marked overlap offset;
1398 * if there is none, or it is beyond range, then finished
1400 int overlapStart = overlaps.nextSetBit(mapOffset + offsetStart);
1401 if (overlapStart == -1 || overlapStart - mapOffset >= rangeLength)
1404 * no more overlaps, or no more within range[]
1408 overlapStart -= mapOffset;
1411 * end of the overlap range is just before the next clear bit;
1412 * restrict it to end of range if necessary;
1413 * note we may add a reverse strand range here (end < start)
1415 int overlapEnd = overlaps.nextClearBit(mapOffset + overlapStart + 1);
1416 overlapEnd = (overlapEnd == -1) ? rangeLength - 1
1417 : Math.min(rangeLength - 1, overlapEnd - mapOffset - 1);
1418 int startPosition = range[0] + step * overlapStart;
1419 int endPosition = range[0] + step * overlapEnd;
1420 mapped.add(new int[] { startPosition, endPosition });
1421 offsetStart = overlapEnd + 1;
1422 added += Math.abs(endPosition - startPosition) + 1;
1429 * Returns the [start, end...] positions in the range mapped from, that are
1430 * mapped to by part or all of the given begin-end of the range mapped to.
1431 * Returns null if begin-end does not overlap any position mapped to.
1437 public int[] getOverlapsInFrom(final int begin, final int end)
1439 int[] overlaps = MappingUtils.findOverlap(toShifts, begin, end);
1441 return overlaps == null ? null : locateInFrom(overlaps[0], overlaps[1]);
1445 * Returns the [start, end...] positions in the range mapped to, that are
1446 * mapped to by part or all of the given begin-end of the range mapped from.
1447 * Returns null if begin-end does not overlap any position mapped from.
1453 public int[] getOverlapsInTo(final int begin, final int end)
1455 int[] overlaps = MappingUtils.findOverlap(fromShifts, begin, end);
1457 return overlaps == null ? null : locateInTo(overlaps[0], overlaps[1]);