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;
29 * A simple way of bijectively mapping a non-contiguous linear range to another
30 * non-contiguous linear range.
32 * Use at your own risk!
34 * TODO: test/ensure that sense of from and to ratio start position is conserved
35 * (codon start position recovery)
41 * Subregions (base 1) described as { [start1, end1], [start2, end2], ...}
43 private List<int[]> fromShifts;
46 * Same format as fromShifts, for the 'mapped to' sequence
48 private List<int[]> toShifts;
51 * number of steps in fromShifts to one toRatio unit
53 private int fromRatio;
56 * number of steps in toShifts to one fromRatio
61 * lowest and highest value in the from Map
63 private int fromLowest;
65 private int fromHighest;
68 * lowest and highest value in the to Map
72 private int toHighest;
79 fromShifts = new ArrayList<>();
80 toShifts = new ArrayList<>();
84 * Two MapList objects are equal if they are the same object, or they both
85 * have populated shift ranges and all values are the same.
88 public boolean equals(Object o)
90 if (o == null || !(o instanceof MapList))
95 MapList obj = (MapList) o;
100 if (obj.fromRatio != fromRatio || obj.toRatio != toRatio
101 || obj.fromShifts == null || obj.toShifts == null)
105 return Arrays.deepEquals(fromShifts.toArray(), obj.fromShifts.toArray())
106 && Arrays.deepEquals(toShifts.toArray(),
107 obj.toShifts.toArray());
111 * Returns a hashcode made from the fromRatio, toRatio, and from/to ranges
114 public int hashCode()
116 int hashCode = 31 * fromRatio;
117 hashCode = 31 * hashCode + toRatio;
118 for (int[] shift : fromShifts)
120 hashCode = 31 * hashCode + shift[0];
121 hashCode = 31 * hashCode + shift[1];
123 for (int[] shift : toShifts)
125 hashCode = 31 * hashCode + shift[0];
126 hashCode = 31 * hashCode + shift[1];
133 * Returns the 'from' ranges as {[start1, end1], [start2, end2], ...}
137 public List<int[]> getFromRanges()
143 * Returns the 'to' ranges as {[start1, end1], [start2, end2], ...}
147 public List<int[]> getToRanges()
153 * Flattens a list of [start, end] into a single [start1, end1, start2,
159 protected static int[] getRanges(List<int[]> shifts)
161 int[] rnges = new int[2 * shifts.size()];
163 for (int[] r : shifts)
173 * @return length of mapped phrase in from
175 public int getFromRatio()
182 * @return length of mapped phrase in to
184 public int getToRatio()
189 public int getFromLowest()
194 public int getFromHighest()
199 public int getToLowest()
204 public int getToHighest()
210 * Constructor given from and to ranges as [start1, end1, start2, end2,...].
211 * There is no validation check that the ranges do not overlap each other.
214 * contiguous regions as [start1, end1, start2, end2, ...]
216 * same format as 'from'
218 * phrase length in 'from' (e.g. 3 for dna)
220 * phrase length in 'to' (e.g. 1 for protein)
222 public MapList(int from[], int to[], int fromRatio, int toRatio)
225 this.fromRatio = fromRatio;
226 this.toRatio = toRatio;
227 fromLowest = Integer.MAX_VALUE;
228 fromHighest = Integer.MIN_VALUE;
230 for (int i = 0; i < from.length; i += 2)
233 * note lowest and highest values - bearing in mind the
234 * direction may be reversed
236 fromLowest = Math.min(fromLowest, Math.min(from[i], from[i + 1]));
237 fromHighest = Math.max(fromHighest, Math.max(from[i], from[i + 1]));
238 fromShifts.add(new int[] { from[i], from[i + 1] });
241 toLowest = Integer.MAX_VALUE;
242 toHighest = Integer.MIN_VALUE;
243 for (int i = 0; i < to.length; i += 2)
245 toLowest = Math.min(toLowest, Math.min(to[i], to[i + 1]));
246 toHighest = Math.max(toHighest, Math.max(to[i], to[i + 1]));
247 toShifts.add(new int[] { to[i], to[i + 1] });
252 * Copy constructor. Creates an identical mapping.
256 public MapList(MapList map)
259 // TODO not used - remove?
260 this.fromLowest = map.fromLowest;
261 this.fromHighest = map.fromHighest;
262 this.toLowest = map.toLowest;
263 this.toHighest = map.toHighest;
265 this.fromRatio = map.fromRatio;
266 this.toRatio = map.toRatio;
267 if (map.fromShifts != null)
269 for (int[] r : map.fromShifts)
271 fromShifts.add(new int[] { r[0], r[1] });
274 if (map.toShifts != null)
276 for (int[] r : map.toShifts)
278 toShifts.add(new int[] { r[0], r[1] });
284 * Constructor given ranges as lists of [start, end] positions. There is no
285 * validation check that the ranges do not overlap each other.
292 public MapList(List<int[]> fromRange, List<int[]> toRange, int fromRatio,
296 fromRange = coalesceRanges(fromRange);
297 toRange = coalesceRanges(toRange);
298 this.fromShifts = fromRange;
299 this.toShifts = toRange;
300 this.fromRatio = fromRatio;
301 this.toRatio = toRatio;
303 fromLowest = Integer.MAX_VALUE;
304 fromHighest = Integer.MIN_VALUE;
305 for (int[] range : fromRange)
307 if (range.length != 2)
309 // throw new IllegalArgumentException(range);
310 System.err.println("Invalid format for fromRange "
311 + Arrays.toString(range) + " may cause errors");
313 fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
314 fromHighest = Math.max(fromHighest, Math.max(range[0], range[1]));
317 toLowest = Integer.MAX_VALUE;
318 toHighest = Integer.MIN_VALUE;
319 for (int[] range : toRange)
321 if (range.length != 2)
323 // throw new IllegalArgumentException(range);
324 System.err.println("Invalid format for toRange "
325 + Arrays.toString(range) + " may cause errors");
327 toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
328 toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
333 * Consolidates a list of ranges so that any contiguous ranges are merged.
334 * This assumes the ranges are already in start order (does not sort them).
336 * The main use case for this method is when mapping cDNA sequence to its
337 * protein product, based on CDS feature ranges which derive from spliced
338 * exons, but are contiguous on the cDNA sequence. For example
341 * CDS 1-20 // from exon1
342 * CDS 21-35 // from exon2
343 * CDS 36-71 // from exon3
344 * 'coalesce' to range 1-71
348 * @return the same list (if unchanged), else a new merged list, leaving the
349 * input list unchanged
351 public static List<int[]> coalesceRanges(final List<int[]> ranges)
353 if (ranges == null || ranges.size() < 2)
358 boolean changed = false;
359 List<int[]> merged = new ArrayList<>();
360 int[] lastRange = ranges.get(0);
361 int lastDirection = lastRange[1] >= lastRange[0] ? 1 : -1;
362 lastRange = new int[] { lastRange[0], lastRange[1] };
363 merged.add(lastRange);
364 boolean first = true;
366 for (final int[] range : ranges)
374 int direction = range[1] >= range[0] ? 1 : -1;
377 * if next range is in the same direction as last and contiguous,
378 * just update the end position of the last range
380 boolean sameDirection = range[1] == range[0]
381 || direction == lastDirection;
382 boolean extending = range[0] == lastRange[1] + lastDirection;
383 if (sameDirection && extending)
385 lastRange[1] = range[1];
390 lastRange = new int[] { range[0], range[1] };
391 merged.add(lastRange);
392 // careful: merging [5, 5] after [7, 6] should keep negative direction
393 lastDirection = (range[1] == range[0]) ? lastDirection : direction;
397 return changed ? merged : ranges;
401 * get all mapped positions from 'from' to 'to'
403 * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int
404 * [fromFinish-fromStart+2] { toStart..toFinish mappings}}
406 protected int[][] makeFromMap()
408 // TODO only used for test - remove??
409 return posMap(fromShifts, fromRatio, toShifts, toRatio);
413 * get all mapped positions from 'to' to 'from'
415 * @return int[to position]=position mapped in from
417 protected int[][] makeToMap()
419 // TODO only used for test - remove??
420 return posMap(toShifts, toRatio, fromShifts, fromRatio);
424 * construct an int map for intervals in intVals
427 * @return int[] { from, to pos in range }, int[range.to-range.from+1]
428 * returning mapped position
430 private int[][] posMap(List<int[]> shiftTo, int sourceRatio,
431 List<int[]> shiftFrom, int targetRatio)
433 // TODO only used for test - remove??
434 int iv = 0, ivSize = shiftTo.size();
439 int[] intv = shiftTo.get(iv++);
440 int from = intv[0], to = intv[1];
448 intv = shiftTo.get(iv++);
467 int mp[][] = new int[to - from + 2][];
468 for (int i = 0; i < mp.length; i++)
470 int[] m = shift(i + from, shiftTo, sourceRatio, shiftFrom, targetRatio);
491 int[][] map = new int[][] { new int[] { from, to, tF, tT },
492 new int[to - from + 2] };
497 for (int i = 0; i < mp.length; i++)
501 map[1][i] = mp[i][0] - tF;
505 map[1][i] = -1; // indicates an out of range mapping
515 * start position for shift (in original reference frame)
519 * public void addShift(int pos, int shift) { int sidx = 0; int[]
520 * rshift=null; while (sidx<shifts.size() && (rshift=(int[])
521 * shifts.elementAt(sidx))[0]<pos) sidx++; if (sidx==shifts.size())
522 * shifts.insertElementAt(new int[] { pos, shift}, sidx); else
523 * rshift[1]+=shift; }
527 * shift from pos to To(pos)
531 * @return int shifted position in To, frameshift in From, direction of mapped
534 public int[] shiftFrom(int pos)
536 return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
540 * inverse of shiftFrom - maps pos in To to a position in From
544 * @return shifted position in From, frameshift in To, direction of mapped
547 public int[] shiftTo(int pos)
549 return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
560 protected static int[] shift(int pos, List<int[]> shiftTo, int fromRatio,
561 List<int[]> shiftFrom, int toRatio)
563 // TODO: javadoc; tests
564 int[] fromCount = countPositions(shiftTo, pos);
565 if (fromCount == null)
569 int fromRemainder = (fromCount[0] - 1) % fromRatio;
570 int toCount = 1 + (((fromCount[0] - 1) / fromRatio) * toRatio);
571 int[] toPos = traverseToPosition(shiftFrom, toCount);
576 return new int[] { toPos[0], fromRemainder, toPos[1] };
580 * Counts how many positions pos is along the series of intervals. Returns an
581 * array of two values:
583 * <li>the number of positions traversed (inclusive) to reach {@code pos}</li>
584 * <li>+1 if the last interval traversed is forward, -1 if in a negative
587 * Returns null if {@code pos} does not lie in any of the given intervals.
590 * a list of start-end intervals
592 * a position that may lie in one (or more) of the intervals
595 protected static int[] countPositions(List<int[]> intervals, int pos)
599 int ivSize = intervals.size();
603 int[] intv = intervals.get(iv++);
604 if (intv[0] <= intv[1])
609 if (pos >= intv[0] && pos <= intv[1])
611 return new int[] { count + pos - intv[0] + 1, +1 };
615 count += intv[1] - intv[0] + 1;
623 if (pos >= intv[1] && pos <= intv[0])
625 return new int[] { count + intv[0] - pos + 1, -1 };
629 count += intv[0] - intv[1] + 1;
637 * Reads through the given intervals until {@code count} positions have been
638 * traversed, and returns an array consisting of two values:
640 * <li>the value at the {@code count'th} position</li>
641 * <li>+1 if the last interval read is forwards, -1 if reverse direction</li>
643 * Returns null if the ranges include less than {@code count} positions, or if
647 * a list of [start, end] ranges
649 * the number of positions to traverse
652 protected static int[] traverseToPosition(List<int[]> intervals,
656 int ivSize = intervals.size();
666 int[] intv = intervals.get(iv++);
667 int diff = intv[1] - intv[0];
670 if (count <= traversed + 1 + diff)
672 return new int[] { intv[0] + (count - traversed - 1), +1 };
676 traversed += 1 + diff;
681 if (count <= traversed + 1 - diff)
683 return new int[] { intv[0] - (count - traversed - 1), -1 };
687 traversed += 1 - diff;
695 * like shift - except returns the intervals in the given vector of shifts
696 * which were spanned in traversing fromStart to fromEnd
702 * @return series of from,to intervals from from first position of starting
703 * region to final position of ending region inclusive
705 protected static int[] getIntervals(List<int[]> shiftFrom,
706 int[] fromStart, int[] fromEnd, int fromRatio2)
708 if (fromStart == null || fromEnd == null)
712 int startpos, endpos;
713 startpos = fromStart[0]; // first position in fromStart
714 endpos = fromEnd[0]; // last position in fromEnd
715 int endindx = (fromRatio2 - 1); // additional positions to get to last
716 // position from endpos
717 int intv = 0, intvSize = shiftFrom.size();
718 int iv[], i = 0, fs = -1, fe_s = -1, fe = -1; // containing intervals
719 // search intervals to locate ones containing startpos and count endindx
720 // positions on from endpos
721 while (intv < intvSize && (fs == -1 || fe == -1))
723 iv = shiftFrom.get(intv++);
726 endpos = iv[0]; // start counting from beginning of interval
727 endindx--; // inclusive of endpos
731 if (fs == -1 && startpos >= iv[0] && startpos <= iv[1])
735 if (endpos >= iv[0] && endpos <= iv[1])
743 if (endpos + endindx <= iv[1])
746 endpos = endpos + endindx; // end of end token is within this
751 endindx -= iv[1] - endpos; // skip all this interval too
758 if (fs == -1 && startpos <= iv[0] && startpos >= iv[1])
762 if (endpos <= iv[0] && endpos >= iv[1])
770 if (endpos - endindx >= iv[1])
773 endpos = endpos - endindx; // end of end token is within this
778 endindx -= endpos - iv[1]; // skip all this interval too
785 if (fs == fe && fe == -1)
789 List<int[]> ranges = new ArrayList<>();
794 // truncate initial interval
795 iv = shiftFrom.get(intv++);
796 iv = new int[] { iv[0], iv[1] };// clone
803 ranges.add(iv); // add initial range
804 iv = shiftFrom.get(intv++); // get next interval
805 iv = new int[] { iv[0], iv[1] };// clone
812 ranges.add(iv); // add only - or final range
816 // walk from end of interval.
817 i = shiftFrom.size() - 1;
822 iv = shiftFrom.get(i);
823 iv = new int[] { iv[1], iv[0] };// reverse and clone
824 // truncate initial interval
830 { // fix apparent logic bug when fe==-1
831 ranges.add(iv); // add (truncated) reversed interval
832 iv = shiftFrom.get(i);
833 iv = new int[] { iv[1], iv[0] }; // reverse and clone
837 // interval is already reversed
840 ranges.add(iv); // add only - or final range
842 // create array of start end intervals.
844 if (ranges != null && ranges.size() > 0)
846 range = new int[ranges.size() * 2];
848 intvSize = ranges.size();
850 while (intv < intvSize)
852 iv = ranges.get(intv);
855 ranges.set(intv++, null); // remove
862 * get the 'initial' position of mpos in To
866 * @return position of first word in to reference frame
868 public int getToPosition(int mpos)
870 int[] mp = shiftTo(mpos);
880 * @return a MapList whose From range is this maplist's To Range, and vice
883 public MapList getInverse()
885 return new MapList(getToRanges(), getFromRanges(), getToRatio(),
890 * String representation - for debugging, not guaranteed not to change
893 public String toString()
895 StringBuilder sb = new StringBuilder(64);
897 for (int[] shift : fromShifts)
899 sb.append(" ").append(Arrays.toString(shift));
902 sb.append(fromRatio).append(":").append(toRatio);
904 for (int[] shift : toShifts)
906 sb.append(" ").append(Arrays.toString(shift));
909 return sb.toString();
913 * Extend this map list by adding the given map's ranges. There is no
914 * validation check that the ranges do not overlap existing ranges (or each
915 * other), but contiguous ranges are merged.
919 public void addMapList(MapList map)
921 if (this.equals(map))
925 this.fromLowest = Math.min(fromLowest, map.fromLowest);
926 this.toLowest = Math.min(toLowest, map.toLowest);
927 this.fromHighest = Math.max(fromHighest, map.fromHighest);
928 this.toHighest = Math.max(toHighest, map.toHighest);
930 for (int[] range : map.getFromRanges())
932 addRange(range, fromShifts);
934 for (int[] range : map.getToRanges())
936 addRange(range, toShifts);
941 * Adds the given range to a list of ranges. If the new range just extends
942 * existing ranges, the current endpoint is updated instead.
947 static void addRange(int[] range, List<int[]> addTo)
950 * list is empty - add to it!
952 if (addTo.size() == 0)
958 int[] last = addTo.get(addTo.size() - 1);
959 boolean lastForward = last[1] >= last[0];
960 boolean newForward = range[1] >= range[0];
963 * contiguous range in the same direction - just update endpoint
965 if (lastForward == newForward && last[1] == range[0])
972 * next range starts at +1 in forward sense - update endpoint
974 if (lastForward && newForward && range[0] == last[1] + 1)
981 * next range starts at -1 in reverse sense - update endpoint
983 if (!lastForward && !newForward && range[0] == last[1] - 1)
990 * just add the new range
996 * Returns true if mapping is from forward strand, false if from reverse
997 * strand. Result is just based on the first 'from' range that is not a single
998 * position. Default is true unless proven to be false. Behaviour is not well
999 * defined if the mapping has a mixture of forward and reverse ranges.
1003 public boolean isFromForwardStrand()
1005 return isForwardStrand(getFromRanges());
1009 * Returns true if mapping is to forward strand, false if to reverse strand.
1010 * Result is just based on the first 'to' range that is not a single position.
1011 * Default is true unless proven to be false. Behaviour is not well defined if
1012 * the mapping has a mixture of forward and reverse ranges.
1016 public boolean isToForwardStrand()
1018 return isForwardStrand(getToRanges());
1022 * A helper method that returns true unless at least one range has start >
1023 * end. Behaviour is undefined for a mixture of forward and reverse ranges.
1028 private boolean isForwardStrand(List<int[]> ranges)
1030 boolean forwardStrand = true;
1031 for (int[] range : ranges)
1033 if (range[1] > range[0])
1035 break; // forward strand confirmed
1037 else if (range[1] < range[0])
1039 forwardStrand = false;
1040 break; // reverse strand confirmed
1043 return forwardStrand;
1048 * @return true if from, or to is a three to 1 mapping
1050 public boolean isTripletMap()
1052 return (toRatio == 3 && fromRatio == 1)
1053 || (fromRatio == 3 && toRatio == 1);
1057 * Returns a map which is the composite of this one and the input map. That
1058 * is, the output map has the fromRanges of this map, and its toRanges are the
1059 * toRanges of this map as transformed by the input map.
1061 * Returns null if the mappings cannot be traversed (not all toRanges of this
1062 * map correspond to fromRanges of the input), or if this.toRatio does not
1063 * match map.fromRatio.
1067 * this: from [1-100] to [501-600]
1068 * input: from [10-40] to [60-90]
1069 * output: from [10-40] to [560-590]
1070 * Example 2 ('reverse strand exons'):
1071 * this: from [1-100] to [2000-1951], [1000-951] // transcript to loci
1072 * input: from [1-50] to [41-90] // CDS to transcript
1073 * output: from [10-40] to [1960-1951], [1000-971] // CDS to gene loci
1079 public MapList traverse(MapList map)
1087 * compound the ratios by this rule:
1088 * A:B with M:N gives A*M:B*N
1089 * reduced by greatest common divisor
1090 * so 1:3 with 3:3 is 3:9 or 1:3
1091 * 1:3 with 3:1 is 3:3 or 1:1
1092 * 1:3 with 1:3 is 1:9
1093 * 2:5 with 3:7 is 6:35
1095 int outFromRatio = getFromRatio() * map.getFromRatio();
1096 int outToRatio = getToRatio() * map.getToRatio();
1097 int gcd = MathUtils.gcd(outFromRatio, outToRatio);
1098 outFromRatio /= gcd;
1101 List<int[]> toRanges = new ArrayList<>();
1102 for (int[] range : getToRanges())
1104 int fromLength = Math.abs(range[1] - range[0]) + 1;
1105 int[] transferred = map.locateInTo(range[0], range[1]);
1106 if (transferred == null || transferred.length % 2 != 0)
1112 * convert [start1, end1, start2, end2, ...]
1113 * to [[start1, end1], [start2, end2], ...]
1116 for (int i = 0; i < transferred.length;)
1118 toRanges.add(new int[] { transferred[i], transferred[i + 1] });
1119 toLength += Math.abs(transferred[i + 1] - transferred[i]) + 1;
1124 * check we mapped the full range - if not, abort
1126 if (fromLength * map.getToRatio() != toLength * map.getFromRatio())
1132 return new MapList(getFromRanges(), toRanges, outFromRatio, outToRatio);
1136 * Answers true if the mapping is from one contiguous range to another, else
1141 public boolean isContiguous()
1143 return fromShifts.size() == 1 && toShifts.size() == 1;
1147 * Returns the [start1, end1, start2, end2, ...] positions in the 'from' range
1148 * that map to positions between {@code start} and {@code end} in the 'to'
1149 * range. Note that for a reverse strand mapping this will return ranges with
1150 * end < start. Returns null if no mapped positions are found in start-end.
1156 public int[] locateInFrom(int start, int end)
1158 return mapPositions(start, end, toShifts, fromShifts,
1159 toRatio, fromRatio);
1163 * Returns the [start1, end1, start2, end2, ...] positions in the 'to' range
1164 * that map to positions between {@code start} and {@code end} in the 'from'
1165 * range. Note that for a reverse strand mapping this will return ranges with
1166 * end < start. Returns null if no mapped positions are found in start-end.
1172 public int[] locateInTo(int start, int end)
1174 return mapPositions(start, end, fromShifts, toShifts,
1175 fromRatio, toRatio);
1179 * Helper method that returns the [start1, end1, start2, end2, ...] positions
1180 * in {@code targetRange} that map to positions between {@code start} and
1181 * {@code end} in {@code sourceRange}. Note that for a reverse strand mapping
1182 * this will return ranges with end < start. Returns null if no mapped
1183 * positions are found in start-end.
1187 * @param sourceRange
1188 * @param targetRange
1189 * @param sourceWordLength
1190 * @param targetWordLength
1193 final static int[] mapPositions(int start, int end,
1194 List<int[]> sourceRange, List<int[]> targetRange,
1195 int sourceWordLength, int targetWordLength)
1205 * traverse sourceRange and mark offsets in targetRange
1206 * of any positions that lie in [start, end]
1208 BitSet offsets = getMappedOffsetsForPositions(start, end, sourceRange,
1209 sourceWordLength, targetWordLength);
1212 * traverse targetRange and collect positions at the marked offsets
1214 List<int[]> mapped = getPositionsForOffsets(targetRange, offsets);
1216 // TODO: or just return the List and adjust calling code to match
1217 return mapped.isEmpty() ? null : MappingUtils.rangeListToArray(mapped);
1221 * Scans the list of {@code ranges} for any values (positions) that lie
1222 * between start and end (inclusive), and records the <em>offsets</em> from
1223 * the start of the list as a BitSet. The offset positions are converted to
1224 * corresponding words in blocks of {@code wordLength2}.
1228 * 1:1 (e.g. gene to CDS):
1229 * ranges { [10-20], [31-40] }, wordLengthFrom = wordLength 2 = 1
1230 * for start = 1, end = 9, returns a BitSet with no bits set
1231 * for start = 1, end = 11, returns a BitSet with bits 0-1 set
1232 * for start = 15, end = 35, returns a BitSet with bits 5-15 set
1233 * 1:3 (peptide to codon):
1234 * ranges { [1-200] }, wordLengthFrom = 1, wordLength 2 = 3
1235 * for start = 9, end = 9, returns a BitSet with bits 24-26 set
1236 * 3:1 (codon to peptide):
1237 * ranges { [101-150], [171-180] }, wordLengthFrom = 3, wordLength 2 = 1
1238 * for start = 101, end = 102 (partial first codon), returns a BitSet with bit 0 set
1239 * for start = 150, end = 171 (partial 17th codon), returns a BitSet with bit 16 set
1240 * 3:1 (circular DNA to peptide):
1241 * ranges { [101-150], [21-30] }, wordLengthFrom = 3, wordLength 2 = 1
1242 * for start = 24, end = 40 (spans codons 18-20), returns a BitSet with bits 17-19 set
1247 * @param sourceRange
1248 * @param sourceWordLength
1249 * @param targetWordLength
1252 protected final static BitSet getMappedOffsetsForPositions(int start,
1253 int end, List<int[]> sourceRange, int sourceWordLength, int targetWordLength)
1255 BitSet overlaps = new BitSet();
1257 final int s1 = sourceRange.size();
1258 for (int i = 0; i < s1; i++)
1260 int[] range = sourceRange.get(i);
1261 final int offset1 = offset;
1262 int overlapStartOffset = -1;
1263 int overlapEndOffset = -1;
1265 if (range[1] >= range[0])
1268 * forward direction range
1270 if (start <= range[1] && end >= range[0])
1275 int overlapStart = Math.max(start, range[0]);
1276 overlapStartOffset = offset1 + overlapStart - range[0];
1277 int overlapEnd = Math.min(end, range[1]);
1278 overlapEndOffset = offset1 + overlapEnd - range[0];
1284 * reverse direction range
1286 if (start <= range[0] && end >= range[1])
1291 int overlapStart = Math.max(start, range[1]);
1292 int overlapEnd = Math.min(end, range[0]);
1293 overlapStartOffset = offset1 + range[0] - overlapEnd;
1294 overlapEndOffset = offset1 + range[0] - overlapStart;
1298 if (overlapStartOffset > -1)
1303 if (sourceWordLength != targetWordLength)
1306 * convert any overlap found to whole words in the target range
1307 * (e.g. treat any partial codon overlap as if the whole codon)
1309 overlapStartOffset -= overlapStartOffset % sourceWordLength;
1310 overlapStartOffset = overlapStartOffset / sourceWordLength
1314 * similar calculation for range end, adding
1315 * (wordLength2 - 1) for end of mapped word
1317 overlapEndOffset -= overlapEndOffset % sourceWordLength;
1318 overlapEndOffset = overlapEndOffset / sourceWordLength
1320 overlapEndOffset += targetWordLength - 1;
1322 overlaps.set(overlapStartOffset, overlapEndOffset + 1);
1324 offset += 1 + Math.abs(range[1] - range[0]);
1330 * Returns a (possibly empty) list of the [start-end] values (positions) at
1331 * offsets in the {@code targetRange} list that are marked by 'on' bits in the
1332 * {@code offsets} bitset.
1334 * @param targetRange
1338 protected final static List<int[]> getPositionsForOffsets(
1339 List<int[]> targetRange, BitSet offsets)
1341 List<int[]> mapped = new ArrayList<>();
1342 if (offsets.isEmpty())
1348 * count of positions preceding ranges[i]
1353 * for each [from-to] range in ranges:
1354 * - find subranges (if any) at marked offsets
1355 * - add the start-end values at the marked positions
1357 final int toAdd = offsets.cardinality();
1359 final int s2 = targetRange.size();
1360 for (int i = 0; added < toAdd && i < s2; i++)
1362 int[] range = targetRange.get(i);
1363 added += addOffsetPositions(mapped, traversed, range, offsets);
1364 traversed += Math.abs(range[1] - range[0]) + 1;
1370 * Helper method that adds any start-end subranges of {@code range} that are
1371 * at offsets in {@code range} marked by set bits in overlaps.
1372 * {@code mapOffset} is added to {@code range} offset positions. Returns the
1373 * count of positions added.
1381 final static int addOffsetPositions(List<int[]> mapped,
1382 final int mapOffset, final int[] range, final BitSet overlaps)
1384 final int rangeLength = 1 + Math.abs(range[1] - range[0]);
1385 final int step = range[1] < range[0] ? -1 : 1;
1386 int offsetStart = 0; // offset into range
1389 while (offsetStart < rangeLength)
1392 * find the start of the next marked overlap offset;
1393 * if there is none, or it is beyond range, then finished
1395 int overlapStart = overlaps.nextSetBit(mapOffset + offsetStart);
1396 if (overlapStart == -1 || overlapStart - mapOffset >= rangeLength)
1399 * no more overlaps, or no more within range[]
1403 overlapStart -= mapOffset;
1406 * end of the overlap range is just before the next clear bit;
1407 * restrict it to end of range if necessary;
1408 * note we may add a reverse strand range here (end < start)
1410 int overlapEnd = overlaps.nextClearBit(mapOffset + overlapStart + 1);
1411 overlapEnd = (overlapEnd == -1) ? rangeLength - 1
1412 : Math.min(rangeLength - 1, overlapEnd - mapOffset - 1);
1413 int startPosition = range[0] + step * overlapStart;
1414 int endPosition = range[0] + step * overlapEnd;
1415 mapped.add(new int[] { startPosition, endPosition });
1416 offsetStart = overlapEnd + 1;
1417 added += Math.abs(endPosition - startPosition) + 1;