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 * There is no validation check that the ranges do not overlap each other.
215 * contiguous regions as [start1, end1, start2, end2, ...]
217 * same format as 'from'
219 * phrase length in 'from' (e.g. 3 for dna)
221 * phrase length in 'to' (e.g. 1 for protein)
223 public MapList(int from[], int to[], int fromRatio, int toRatio)
226 this.fromRatio = fromRatio;
227 this.toRatio = toRatio;
228 fromLowest = Integer.MAX_VALUE;
229 fromHighest = Integer.MIN_VALUE;
231 for (int i = 0; i < from.length; i += 2)
234 * note lowest and highest values - bearing in mind the
235 * direction may be reversed
237 fromLowest = Math.min(fromLowest, Math.min(from[i], from[i + 1]));
238 fromHighest = Math.max(fromHighest, Math.max(from[i], from[i + 1]));
239 fromShifts.add(new int[] { from[i], from[i + 1] });
242 toLowest = Integer.MAX_VALUE;
243 toHighest = Integer.MIN_VALUE;
244 for (int i = 0; i < to.length; i += 2)
246 toLowest = Math.min(toLowest, Math.min(to[i], to[i + 1]));
247 toHighest = Math.max(toHighest, Math.max(to[i], to[i + 1]));
248 toShifts.add(new int[] { to[i], to[i + 1] });
253 * Copy constructor. Creates an identical mapping.
257 public MapList(MapList map)
260 // TODO not used - remove?
261 this.fromLowest = map.fromLowest;
262 this.fromHighest = map.fromHighest;
263 this.toLowest = map.toLowest;
264 this.toHighest = map.toHighest;
266 this.fromRatio = map.fromRatio;
267 this.toRatio = map.toRatio;
268 if (map.fromShifts != null)
270 for (int[] r : map.fromShifts)
272 fromShifts.add(new int[] { r[0], r[1] });
275 if (map.toShifts != null)
277 for (int[] r : map.toShifts)
279 toShifts.add(new int[] { r[0], r[1] });
285 * Constructor given ranges as lists of [start, end] positions. There is no
286 * validation check that the ranges do not overlap each other.
293 public MapList(List<int[]> fromRange, List<int[]> toRange, int fromRatio,
297 fromRange = coalesceRanges(fromRange);
298 toRange = coalesceRanges(toRange);
299 this.fromShifts = fromRange;
300 this.toShifts = toRange;
301 this.fromRatio = fromRatio;
302 this.toRatio = toRatio;
304 fromLowest = Integer.MAX_VALUE;
305 fromHighest = Integer.MIN_VALUE;
306 for (int[] range : fromRange)
308 if (range.length != 2)
310 // throw new IllegalArgumentException(range);
311 System.err.println("Invalid format for fromRange "
312 + Arrays.toString(range) + " may cause errors");
314 fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
315 fromHighest = Math.max(fromHighest, Math.max(range[0], range[1]));
318 toLowest = Integer.MAX_VALUE;
319 toHighest = Integer.MIN_VALUE;
320 for (int[] range : toRange)
322 if (range.length != 2)
324 // throw new IllegalArgumentException(range);
325 System.err.println("Invalid format for toRange "
326 + Arrays.toString(range) + " may cause errors");
328 toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
329 toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
334 * Consolidates a list of ranges so that any contiguous ranges are merged.
335 * This assumes the ranges are already in start order (does not sort them).
337 * The main use case for this method is when mapping cDNA sequence to its
338 * protein product, based on CDS feature ranges which derive from spliced
339 * 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 not used - 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 not used - 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 ratio,
431 List<int[]> shiftFrom, int toRatio)
433 // TODO not used - 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, ratio, shiftFrom, toRatio);
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 = countPos(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 = countToPos(shiftFrom, toCount);
574 return null; // throw new Error("Bad Mapping!");
576 // System.out.println(fromCount[0]+" "+fromCount[1]+" "+toCount);
577 return new int[] { toPos[0], fromRemainder, toPos[1] };
581 * count how many positions pos is along the series of intervals.
585 * @return number of positions or null if pos is not within intervals
587 protected static int[] countPos(List<int[]> shiftTo, int pos)
589 int count = 0, intv[], iv = 0, ivSize = shiftTo.size();
592 intv = shiftTo.get(iv++);
593 if (intv[0] <= intv[1])
595 if (pos >= intv[0] && pos <= intv[1])
597 return new int[] { count + pos - intv[0] + 1, +1 };
601 count += intv[1] - intv[0] + 1;
606 if (pos >= intv[1] && pos <= intv[0])
608 return new int[] { count + intv[0] - pos + 1, -1 };
612 count += intv[0] - intv[1] + 1;
620 * count out pos positions into a series of intervals and return the position
624 * @return position pos in interval set
626 protected static int[] countToPos(List<int[]> shiftFrom, int pos)
628 int count = 0, diff = 0, iv = 0, ivSize = shiftFrom.size();
629 int[] intv = { 0, 0 };
632 intv = shiftFrom.get(iv++);
633 diff = intv[1] - intv[0];
636 if (pos <= count + 1 + diff)
638 return new int[] { pos - count - 1 + intv[0], +1 };
647 if (pos <= count + 1 - diff)
649 return new int[] { intv[0] - (pos - count - 1), -1 };
657 return null;// (diff<0) ? (intv[1]-1) : (intv[0]+1);
661 * find series of intervals mapping from start-end in the From map.
664 * position mapped 'to'
666 * position mapped 'to'
667 * @return series of [start, end] ranges in sequence mapped 'from'
669 public int[] locateInFrom(int start, int end)
671 // inefficient implementation
672 int fromStart[] = shiftTo(start);
673 // needs to be inclusive of end of symbol position
674 int fromEnd[] = shiftTo(end);
676 return getIntervals(fromShifts, fromStart, fromEnd, fromRatio);
680 * find series of intervals mapping from start-end in the to map.
683 * position mapped 'from'
685 * position mapped 'from'
686 * @return series of [start, end] ranges in sequence mapped 'to'
688 public int[] locateInTo(int start, int end)
690 int toStart[] = shiftFrom(start);
691 int toEnd[] = shiftFrom(end);
692 return getIntervals(toShifts, toStart, toEnd, toRatio);
696 * like shift - except returns the intervals in the given vector of shifts
697 * which were spanned in traversing fromStart to fromEnd
703 * @return series of from,to intervals from from first position of starting
704 * region to final position of ending region inclusive
706 protected static int[] getIntervals(List<int[]> shiftFrom,
707 int[] fromStart, int[] fromEnd, int fromRatio2)
709 if (fromStart == null || fromEnd == null)
713 int startpos, endpos;
714 startpos = fromStart[0]; // first position in fromStart
715 endpos = fromEnd[0]; // last position in fromEnd
716 int endindx = (fromRatio2 - 1); // additional positions to get to last
717 // position from endpos
718 int intv = 0, intvSize = shiftFrom.size();
719 int iv[], i = 0, fs = -1, fe_s = -1, fe = -1; // containing intervals
720 // search intervals to locate ones containing startpos and count endindx
721 // positions on from endpos
722 while (intv < intvSize && (fs == -1 || fe == -1))
724 iv = shiftFrom.get(intv++);
727 endpos = iv[0]; // start counting from beginning of interval
728 endindx--; // inclusive of endpos
732 if (fs == -1 && startpos >= iv[0] && startpos <= iv[1])
736 if (endpos >= iv[0] && endpos <= iv[1])
744 if (endpos + endindx <= iv[1])
747 endpos = endpos + endindx; // end of end token is within this
752 endindx -= iv[1] - endpos; // skip all this interval too
759 if (fs == -1 && startpos <= iv[0] && startpos >= iv[1])
763 if (endpos <= iv[0] && endpos >= iv[1])
771 if (endpos - endindx >= iv[1])
774 endpos = endpos - endindx; // end of end token is within this
779 endindx -= endpos - iv[1]; // skip all this interval too
786 if (fs == fe && fe == -1)
790 List<int[]> ranges = new ArrayList<>();
795 // truncate initial interval
796 iv = shiftFrom.get(intv++);
797 iv = new int[] { iv[0], iv[1] };// clone
804 ranges.add(iv); // add initial range
805 iv = shiftFrom.get(intv++); // get next interval
806 iv = new int[] { iv[0], iv[1] };// clone
813 ranges.add(iv); // add only - or final range
817 // walk from end of interval.
818 i = shiftFrom.size() - 1;
823 iv = shiftFrom.get(i);
824 iv = new int[] { iv[1], iv[0] };// reverse and clone
825 // truncate initial interval
831 { // fix apparent logic bug when fe==-1
832 ranges.add(iv); // add (truncated) reversed interval
833 iv = shiftFrom.get(i);
834 iv = new int[] { iv[1], iv[0] }; // reverse and clone
838 // interval is already reversed
841 ranges.add(iv); // add only - or final range
843 // create array of start end intervals.
845 if (ranges != null && ranges.size() > 0)
847 range = new int[ranges.size() * 2];
849 intvSize = ranges.size();
851 while (intv < intvSize)
853 iv = ranges.get(intv);
856 ranges.set(intv++, null); // remove
863 * get the 'initial' position of mpos in To
867 * @return position of first word in to reference frame
869 public int getToPosition(int mpos)
871 // TODO not used - remove??
872 int[] mp = shiftTo(mpos);
881 * get range of positions in To frame for the mpos word in From
885 * @return null or int[] first position in To for mpos, last position in to
888 public int[] getToWord(int mpos)
890 int[] mp = shiftTo(mpos);
893 return new int[] { mp[0], mp[0] + mp[2] * (getFromRatio() - 1) };
899 * get From position in the associated reference frame for position pos in the
900 * associated sequence.
905 public int getMappedPosition(int pos)
907 // TODO not used - remove??
908 int[] mp = shiftFrom(pos);
916 public int[] getMappedWord(int pos)
918 // TODO not used - remove??
919 int[] mp = shiftFrom(pos);
922 return new int[] { mp[0], mp[0] + mp[2] * (getToRatio() - 1) };
929 * @return a MapList whose From range is this maplist's To Range, and vice
932 public MapList getInverse()
934 return new MapList(getToRanges(), getFromRanges(), getToRatio(),
939 * test for containment rather than equivalence to another mapping
942 * to be tested for containment
943 * @return true if local or mapped range map contains or is contained by this
946 public boolean containsEither(boolean local, MapList map)
948 // TODO not used - remove?
951 return ((getFromLowest() >= map.getFromLowest()
952 && getFromHighest() <= map.getFromHighest())
953 || (getFromLowest() <= map.getFromLowest()
954 && getFromHighest() >= map.getFromHighest()));
958 return ((getToLowest() >= map.getToLowest()
959 && getToHighest() <= map.getToHighest())
960 || (getToLowest() <= map.getToLowest()
961 && getToHighest() >= map.getToHighest()));
966 * String representation - for debugging, not guaranteed not to change
969 public String toString()
971 StringBuilder sb = new StringBuilder(64);
973 for (int[] shift : fromShifts)
975 sb.append(" ").append(Arrays.toString(shift));
978 sb.append(fromRatio).append(":").append(toRatio);
980 for (int[] shift : toShifts)
982 sb.append(" ").append(Arrays.toString(shift));
985 return sb.toString();
989 * Extend this map list by adding the given map's ranges. There is no
990 * validation check that the ranges do not overlap existing ranges (or each
991 * other), but contiguous ranges are merged.
995 public void addMapList(MapList map)
997 if (this.equals(map))
1001 this.fromLowest = Math.min(fromLowest, map.fromLowest);
1002 this.toLowest = Math.min(toLowest, map.toLowest);
1003 this.fromHighest = Math.max(fromHighest, map.fromHighest);
1004 this.toHighest = Math.max(toHighest, map.toHighest);
1006 for (int[] range : map.getFromRanges())
1008 addRange(range, fromShifts);
1010 for (int[] range : map.getToRanges())
1012 addRange(range, toShifts);
1017 * Adds the given range to a list of ranges. If the new range just extends
1018 * existing ranges, the current endpoint is updated instead.
1023 static void addRange(int[] range, List<int[]> addTo)
1026 * list is empty - add to it!
1028 if (addTo.size() == 0)
1034 int[] last = addTo.get(addTo.size() - 1);
1035 boolean lastForward = last[1] >= last[0];
1036 boolean newForward = range[1] >= range[0];
1039 * contiguous range in the same direction - just update endpoint
1041 if (lastForward == newForward && last[1] == range[0])
1048 * next range starts at +1 in forward sense - update endpoint
1050 if (lastForward && newForward && range[0] == last[1] + 1)
1057 * next range starts at -1 in reverse sense - update endpoint
1059 if (!lastForward && !newForward && range[0] == last[1] - 1)
1066 * just add the new range
1072 * Returns true if mapping is from forward strand, false if from reverse
1073 * strand. Result is just based on the first 'from' range that is not a single
1074 * position. Default is true unless proven to be false. Behaviour is not well
1075 * defined if the mapping has a mixture of forward and reverse ranges.
1079 public boolean isFromForwardStrand()
1081 return isForwardStrand(getFromRanges());
1085 * Returns true if mapping is to forward strand, false if to reverse strand.
1086 * Result is just based on the first 'to' range that is not a single position.
1087 * Default is true unless proven to be false. Behaviour is not well defined if
1088 * the mapping has a mixture of forward and reverse ranges.
1092 public boolean isToForwardStrand()
1094 return isForwardStrand(getToRanges());
1098 * A helper method that returns true unless at least one range has start >
1099 * end. Behaviour is undefined for a mixture of forward and reverse ranges.
1104 private boolean isForwardStrand(List<int[]> ranges)
1106 boolean forwardStrand = true;
1107 for (int[] range : ranges)
1109 if (range[1] > range[0])
1111 break; // forward strand confirmed
1113 else if (range[1] < range[0])
1115 forwardStrand = false;
1116 break; // reverse strand confirmed
1119 return forwardStrand;
1124 * @return true if from, or to is a three to 1 mapping
1126 public boolean isTripletMap()
1128 return (toRatio == 3 && fromRatio == 1)
1129 || (fromRatio == 3 && toRatio == 1);
1133 * Returns a map which is the composite of this one and the input map. That
1134 * is, the output map has the fromRanges of this map, and its toRanges are the
1135 * toRanges of this map as transformed by the input map.
1137 * Returns null if the mappings cannot be traversed (not all toRanges of this
1138 * map correspond to fromRanges of the input), or if this.toRatio does not
1139 * match map.fromRatio.
1143 * this: from [1-100] to [501-600]
1144 * input: from [10-40] to [60-90]
1145 * output: from [10-40] to [560-590]
1146 * Example 2 ('reverse strand exons'):
1147 * this: from [1-100] to [2000-1951], [1000-951] // transcript to loci
1148 * input: from [1-50] to [41-90] // CDS to transcript
1149 * output: from [10-40] to [1960-1951], [1000-971] // CDS to gene loci
1155 public MapList traverse(MapList map)
1163 * compound the ratios by this rule:
1164 * A:B with M:N gives A*M:B*N
1165 * reduced by greatest common divisor
1166 * so 1:3 with 3:3 is 3:9 or 1:3
1167 * 1:3 with 3:1 is 3:3 or 1:1
1168 * 1:3 with 1:3 is 1:9
1169 * 2:5 with 3:7 is 6:35
1171 int outFromRatio = getFromRatio() * map.getFromRatio();
1172 int outToRatio = getToRatio() * map.getToRatio();
1173 int gcd = MathUtils.gcd(outFromRatio, outToRatio);
1174 outFromRatio /= gcd;
1177 List<int[]> toRanges = new ArrayList<>();
1178 for (int[] range : getToRanges())
1180 int[] transferred = map.locateInTo(range[0], range[1]);
1181 if (transferred == null || transferred.length % 2 != 0)
1187 * convert [start1, end1, start2, end2, ...]
1188 * to [[start1, end1], [start2, end2], ...]
1190 for (int i = 0; i < transferred.length;)
1192 toRanges.add(new int[] { transferred[i], transferred[i + 1] });
1197 return new MapList(getFromRanges(), toRanges, outFromRatio, outToRatio);
1201 * Answers true if the mapping is from one contiguous range to another, else
1206 public boolean isContiguous()
1208 return fromShifts.size() == 1 && toShifts.size() == 1;