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 MappingUtils.addRange(range, fromShifts);
937 for (int[] range : map.getToRanges())
939 MappingUtils.addRange(range, toShifts);
944 * Returns true if mapping is from forward strand, false if from reverse
945 * strand. Result is just based on the first 'from' range that is not a single
946 * position. Default is true unless proven to be false. Behaviour is not well
947 * defined if the mapping has a mixture of forward and reverse ranges.
951 public boolean isFromForwardStrand()
953 return isForwardStrand(getFromRanges());
957 * Returns true if mapping is to forward strand, false if to reverse strand.
958 * Result is just based on the first 'to' range that is not a single position.
959 * Default is true unless proven to be false. Behaviour is not well defined if
960 * the mapping has a mixture of forward and reverse ranges.
964 public boolean isToForwardStrand()
966 return isForwardStrand(getToRanges());
970 * A helper method that returns true unless at least one range has start >
971 * end. Behaviour is undefined for a mixture of forward and reverse ranges.
976 private boolean isForwardStrand(List<int[]> ranges)
978 boolean forwardStrand = true;
979 for (int[] range : ranges)
981 if (range[1] > range[0])
983 break; // forward strand confirmed
985 else if (range[1] < range[0])
987 forwardStrand = false;
988 break; // reverse strand confirmed
991 return forwardStrand;
996 * @return true if from, or to is a three to 1 mapping
998 public boolean isTripletMap()
1000 return (toRatio == 3 && fromRatio == 1)
1001 || (fromRatio == 3 && toRatio == 1);
1005 * Returns a map which is the composite of this one and the input map. That
1006 * is, the output map has the fromRanges of this map, and its toRanges are the
1007 * toRanges of this map as transformed by the input map.
1009 * Returns null if the mappings cannot be traversed (not all toRanges of this
1010 * map correspond to fromRanges of the input), or if this.toRatio does not
1011 * match map.fromRatio.
1015 * this: from [1-100] to [501-600]
1016 * input: from [10-40] to [60-90]
1017 * output: from [10-40] to [560-590]
1018 * Example 2 ('reverse strand exons'):
1019 * this: from [1-100] to [2000-1951], [1000-951] // transcript to loci
1020 * input: from [1-50] to [41-90] // CDS to transcript
1021 * output: from [10-40] to [1960-1951], [1000-971] // CDS to gene loci
1027 public MapList traverse(MapList map)
1035 * compound the ratios by this rule:
1036 * A:B with M:N gives A*M:B*N
1037 * reduced by greatest common divisor
1038 * so 1:3 with 3:3 is 3:9 or 1:3
1039 * 1:3 with 3:1 is 3:3 or 1:1
1040 * 1:3 with 1:3 is 1:9
1041 * 2:5 with 3:7 is 6:35
1043 int outFromRatio = getFromRatio() * map.getFromRatio();
1044 int outToRatio = getToRatio() * map.getToRatio();
1045 int gcd = MathUtils.gcd(outFromRatio, outToRatio);
1046 outFromRatio /= gcd;
1049 List<int[]> toRanges = new ArrayList<>();
1050 for (int[] range : getToRanges())
1052 int fromLength = Math.abs(range[1] - range[0]) + 1;
1053 int[] transferred = map.locateInTo(range[0], range[1]);
1054 if (transferred == null || transferred.length % 2 != 0)
1060 * convert [start1, end1, start2, end2, ...]
1061 * to [[start1, end1], [start2, end2], ...]
1064 for (int i = 0; i < transferred.length;)
1066 toRanges.add(new int[] { transferred[i], transferred[i + 1] });
1067 toLength += Math.abs(transferred[i + 1] - transferred[i]) + 1;
1072 * check we mapped the full range - if not, abort
1074 if (fromLength * map.getToRatio() != toLength * map.getFromRatio())
1080 return new MapList(getFromRanges(), toRanges, outFromRatio, outToRatio);
1084 * Answers true if the mapping is from one contiguous range to another, else
1089 public boolean isContiguous()
1091 return fromShifts.size() == 1 && toShifts.size() == 1;
1095 * <<<<<<< HEAD Returns the [start1, end1, start2, end2, ...] positions in the
1096 * 'from' range that map to positions between {@code start} and {@code end} in
1097 * the 'to' range. Note that for a reverse strand mapping this will return
1098 * ranges with end < start. Returns null if no mapped positions are found in
1105 public int[] locateInFrom(int start, int end)
1107 return mapPositions(start, end, toShifts, fromShifts, toRatio,
1112 * Returns the [start1, end1, start2, end2, ...] positions in the 'to' range
1113 * that map to positions between {@code start} and {@code end} in the 'from'
1114 * range. Note that for a reverse strand mapping this will return ranges with
1115 * end < start. Returns null if no mapped positions are found in start-end.
1121 public int[] locateInTo(int start, int end)
1123 return mapPositions(start, end, fromShifts, toShifts, fromRatio,
1128 * Helper method that returns the [start1, end1, start2, end2, ...] positions
1129 * in {@code targetRange} that map to positions between {@code start} and
1130 * {@code end} in {@code sourceRange}. Note that for a reverse strand mapping
1131 * this will return ranges with end < start. Returns null if no mapped
1132 * positions are found in start-end.
1136 * @param sourceRange
1137 * @param targetRange
1138 * @param sourceWordLength
1139 * @param targetWordLength
1142 final static int[] mapPositions(int start, int end,
1143 List<int[]> sourceRange, List<int[]> targetRange,
1144 int sourceWordLength, int targetWordLength)
1154 * traverse sourceRange and mark offsets in targetRange
1155 * of any positions that lie in [start, end]
1157 BitSet offsets = getMappedOffsetsForPositions(start, end, sourceRange,
1158 sourceWordLength, targetWordLength);
1161 * traverse targetRange and collect positions at the marked offsets
1163 List<int[]> mapped = getPositionsForOffsets(targetRange, offsets);
1165 // TODO: or just return the List and adjust calling code to match
1166 return mapped.isEmpty() ? null : MappingUtils.rangeListToArray(mapped);
1170 * Scans the list of {@code ranges} for any values (positions) that lie
1171 * between start and end (inclusive), and records the <em>offsets</em> from
1172 * the start of the list as a BitSet. The offset positions are converted to
1173 * corresponding words in blocks of {@code wordLength2}.
1177 * 1:1 (e.g. gene to CDS):
1178 * ranges { [10-20], [31-40] }, wordLengthFrom = wordLength 2 = 1
1179 * for start = 1, end = 9, returns a BitSet with no bits set
1180 * for start = 1, end = 11, returns a BitSet with bits 0-1 set
1181 * for start = 15, end = 35, returns a BitSet with bits 5-15 set
1182 * 1:3 (peptide to codon):
1183 * ranges { [1-200] }, wordLengthFrom = 1, wordLength 2 = 3
1184 * for start = 9, end = 9, returns a BitSet with bits 24-26 set
1185 * 3:1 (codon to peptide):
1186 * ranges { [101-150], [171-180] }, wordLengthFrom = 3, wordLength 2 = 1
1187 * for start = 101, end = 102 (partial first codon), returns a BitSet with bit 0 set
1188 * for start = 150, end = 171 (partial 17th codon), returns a BitSet with bit 16 set
1189 * 3:1 (circular DNA to peptide):
1190 * ranges { [101-150], [21-30] }, wordLengthFrom = 3, wordLength 2 = 1
1191 * for start = 24, end = 40 (spans codons 18-20), returns a BitSet with bits 17-19 set
1196 * @param sourceRange
1197 * @param sourceWordLength
1198 * @param targetWordLength
1201 protected final static BitSet getMappedOffsetsForPositions(int start,
1202 int end, List<int[]> sourceRange, int sourceWordLength,
1203 int targetWordLength)
1205 BitSet overlaps = new BitSet();
1207 final int s1 = sourceRange.size();
1208 for (int i = 0; i < s1; i++)
1210 int[] range = sourceRange.get(i);
1211 final int offset1 = offset;
1212 int overlapStartOffset = -1;
1213 int overlapEndOffset = -1;
1215 if (range[1] >= range[0])
1218 * forward direction range
1220 if (start <= range[1] && end >= range[0])
1225 int overlapStart = Math.max(start, range[0]);
1226 overlapStartOffset = offset1 + overlapStart - range[0];
1227 int overlapEnd = Math.min(end, range[1]);
1228 overlapEndOffset = offset1 + overlapEnd - range[0];
1234 * reverse direction range
1236 if (start <= range[0] && end >= range[1])
1241 int overlapStart = Math.max(start, range[1]);
1242 int overlapEnd = Math.min(end, range[0]);
1243 overlapStartOffset = offset1 + range[0] - overlapEnd;
1244 overlapEndOffset = offset1 + range[0] - overlapStart;
1248 if (overlapStartOffset > -1)
1253 if (sourceWordLength != targetWordLength)
1256 * convert any overlap found to whole words in the target range
1257 * (e.g. treat any partial codon overlap as if the whole codon)
1259 overlapStartOffset -= overlapStartOffset % sourceWordLength;
1260 overlapStartOffset = overlapStartOffset / sourceWordLength
1264 * similar calculation for range end, adding
1265 * (wordLength2 - 1) for end of mapped word
1267 overlapEndOffset -= overlapEndOffset % sourceWordLength;
1268 overlapEndOffset = overlapEndOffset / sourceWordLength
1270 overlapEndOffset += targetWordLength - 1;
1272 overlaps.set(overlapStartOffset, overlapEndOffset + 1);
1274 offset += 1 + Math.abs(range[1] - range[0]);
1280 * Returns a (possibly empty) list of the [start-end] values (positions) at
1281 * offsets in the {@code targetRange} list that are marked by 'on' bits in the
1282 * {@code offsets} bitset.
1284 * @param targetRange
1288 protected final static List<int[]> getPositionsForOffsets(
1289 List<int[]> targetRange, BitSet offsets)
1291 List<int[]> mapped = new ArrayList<>();
1292 if (offsets.isEmpty())
1298 * count of positions preceding ranges[i]
1303 * for each [from-to] range in ranges:
1304 * - find subranges (if any) at marked offsets
1305 * - add the start-end values at the marked positions
1307 final int toAdd = offsets.cardinality();
1309 final int s2 = targetRange.size();
1310 for (int i = 0; added < toAdd && i < s2; i++)
1312 int[] range = targetRange.get(i);
1313 added += addOffsetPositions(mapped, traversed, range, offsets);
1314 traversed += Math.abs(range[1] - range[0]) + 1;
1320 * Helper method that adds any start-end subranges of {@code range} that are
1321 * at offsets in {@code range} marked by set bits in overlaps.
1322 * {@code mapOffset} is added to {@code range} offset positions. Returns the
1323 * count of positions added.
1331 final static int addOffsetPositions(List<int[]> mapped,
1332 final int mapOffset, final int[] range, final BitSet overlaps)
1334 final int rangeLength = 1 + Math.abs(range[1] - range[0]);
1335 final int step = range[1] < range[0] ? -1 : 1;
1336 int offsetStart = 0; // offset into range
1339 while (offsetStart < rangeLength)
1342 * find the start of the next marked overlap offset;
1343 * if there is none, or it is beyond range, then finished
1345 int overlapStart = overlaps.nextSetBit(mapOffset + offsetStart);
1346 if (overlapStart == -1 || overlapStart - mapOffset >= rangeLength)
1349 * no more overlaps, or no more within range[]
1353 overlapStart -= mapOffset;
1356 * end of the overlap range is just before the next clear bit;
1357 * restrict it to end of range if necessary;
1358 * note we may add a reverse strand range here (end < start)
1360 int overlapEnd = overlaps.nextClearBit(mapOffset + overlapStart + 1);
1361 overlapEnd = (overlapEnd == -1) ? rangeLength - 1
1362 : Math.min(rangeLength - 1, overlapEnd - mapOffset - 1);
1363 int startPosition = range[0] + step * overlapStart;
1364 int endPosition = range[0] + step * overlapEnd;
1365 mapped.add(new int[] { startPosition, endPosition });
1366 offsetStart = overlapEnd + 1;
1367 added += Math.abs(endPosition - startPosition) + 1;
1374 * Returns the [start, end...] positions in the range mapped from, that are
1375 * mapped to by part or all of the given begin-end of the range mapped to.
1376 * Returns null if begin-end does not overlap any position mapped to.
1382 public int[] getOverlapsInFrom(final int begin, final int end)
1384 int[] overlaps = MappingUtils.findOverlap(toShifts, begin, end);
1386 return overlaps == null ? null : locateInFrom(overlaps[0], overlaps[1]);
1390 * Returns the [start, end...] positions in the range mapped to, that are
1391 * mapped to by part or all of the given begin-end of the range mapped from.
1392 * Returns null if begin-end does not overlap any position mapped from.
1398 public int[] getOverlapsInTo(final int begin, final int end)
1400 int[] overlaps = MappingUtils.findOverlap(fromShifts, begin, end);
1402 return overlaps == null ? null : locateInTo(overlaps[0], overlaps[1]);