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<int[]>();
81 toShifts = new ArrayList<int[]>();
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 // TODO should also override hashCode to ensure equal objects have equal
93 if (o == null || !(o instanceof MapList))
98 MapList obj = (MapList) o;
103 if (obj.fromRatio != fromRatio || obj.toRatio != toRatio
104 || obj.fromShifts == null || obj.toShifts == null)
109 .deepEquals(fromShifts.toArray(), obj.fromShifts.toArray())
111 .deepEquals(toShifts.toArray(), obj.toShifts.toArray());
115 * Returns the 'from' ranges as {[start1, end1], [start2, end2], ...}
119 public List<int[]> getFromRanges()
125 * Returns the 'to' ranges as {[start1, end1], [start2, end2], ...}
129 public List<int[]> getToRanges()
135 * Flattens a list of [start, end] into a single [start1, end1, start2,
141 protected static int[] getRanges(List<int[]> shifts)
143 int[] rnges = new int[2 * shifts.size()];
145 for (int[] r : shifts)
155 * @return length of mapped phrase in from
157 public int getFromRatio()
164 * @return length of mapped phrase in to
166 public int getToRatio()
171 public int getFromLowest()
176 public int getFromHighest()
181 public int getToLowest()
186 public int getToHighest()
192 * Constructor given from and to ranges as [start1, end1, start2, end2,...].
193 * If any end is equal to the next start, the ranges will be merged. There is
194 * no validation check that the ranges do not overlap each other.
197 * contiguous regions as [start1, end1, start2, end2, ...]
199 * same format as 'from'
201 * phrase length in 'from' (e.g. 3 for dna)
203 * phrase length in 'to' (e.g. 1 for protein)
205 public MapList(int from[], int to[], int fromRatio, int toRatio)
208 this.fromRatio = fromRatio;
209 this.toRatio = toRatio;
210 fromLowest = Integer.MAX_VALUE;
211 fromHighest = Integer.MIN_VALUE;
214 for (int i = 0; i < from.length; i += 2)
217 * note lowest and highest values - bearing in mind the
218 * direction may be revesed
220 fromLowest = Math.min(fromLowest, Math.min(from[i], from[i + 1]));
221 fromHighest = Math.max(fromHighest, Math.max(from[i], from[i + 1]));
222 if (added > 0 && from[i] == fromShifts.get(added - 1)[1])
225 * this range starts where the last ended - just extend it
227 fromShifts.get(added - 1)[1] = from[i + 1];
231 fromShifts.add(new int[] { from[i], from[i + 1] });
236 toLowest = Integer.MAX_VALUE;
237 toHighest = Integer.MIN_VALUE;
239 for (int i = 0; i < to.length; i += 2)
241 toLowest = Math.min(toLowest, Math.min(to[i], to[i + 1]));
242 toHighest = Math.max(toHighest, Math.max(to[i], to[i + 1]));
243 if (added > 0 && to[i] == toShifts.get(added - 1)[1])
245 toShifts.get(added - 1)[1] = to[i + 1];
249 toShifts.add(new int[] { to[i], to[i + 1] });
256 * Copy constructor. Creates an identical mapping.
260 public MapList(MapList map)
263 // TODO not used - remove?
264 this.fromLowest = map.fromLowest;
265 this.fromHighest = map.fromHighest;
266 this.toLowest = map.toLowest;
267 this.toHighest = map.toHighest;
269 this.fromRatio = map.fromRatio;
270 this.toRatio = map.toRatio;
271 if (map.fromShifts != null)
273 for (int[] r : map.fromShifts)
275 fromShifts.add(new int[] { r[0], r[1] });
278 if (map.toShifts != null)
280 for (int[] r : map.toShifts)
282 toShifts.add(new int[] { r[0], r[1] });
288 * Constructor given ranges as lists of [start, end] positions. There is no
289 * validation check that the ranges do not overlap each other.
296 public MapList(List<int[]> fromRange, List<int[]> toRange, int fromRatio,
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 fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
310 fromHighest = Math.max(fromHighest, Math.max(range[0], range[1]));
313 toLowest = Integer.MAX_VALUE;
314 toHighest = Integer.MIN_VALUE;
315 for (int[] range : toRange)
317 toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
318 toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
323 * get all mapped positions from 'from' to 'to'
325 * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int
326 * [fromFinish-fromStart+2] { toStart..toFinish mappings}}
328 protected int[][] makeFromMap()
330 // TODO not used - remove??
331 return posMap(fromShifts, fromRatio, toShifts, toRatio);
335 * get all mapped positions from 'to' to 'from'
337 * @return int[to position]=position mapped in from
339 protected int[][] makeToMap()
341 // TODO not used - remove??
342 return posMap(toShifts, toRatio, fromShifts, fromRatio);
346 * construct an int map for intervals in intVals
349 * @return int[] { from, to pos in range }, int[range.to-range.from+1]
350 * returning mapped position
352 private int[][] posMap(List<int[]> shiftTo, int ratio,
353 List<int[]> shiftFrom, int toRatio)
355 // TODO not used - remove??
356 int iv = 0, ivSize = shiftTo.size();
361 int[] intv = shiftTo.get(iv++);
362 int from = intv[0], to = intv[1];
370 intv = shiftTo.get(iv++);
389 int mp[][] = new int[to - from + 2][];
390 for (int i = 0; i < mp.length; i++)
392 int[] m = shift(i + from, shiftTo, ratio, shiftFrom, toRatio);
413 int[][] map = new int[][] { new int[] { from, to, tF, tT },
414 new int[to - from + 2] };
419 for (int i = 0; i < mp.length; i++)
423 map[1][i] = mp[i][0] - tF;
427 map[1][i] = -1; // indicates an out of range mapping
437 * start position for shift (in original reference frame)
441 * public void addShift(int pos, int shift) { int sidx = 0; int[]
442 * rshift=null; while (sidx<shifts.size() && (rshift=(int[])
443 * shifts.elementAt(sidx))[0]<pos) sidx++; if (sidx==shifts.size())
444 * shifts.insertElementAt(new int[] { pos, shift}, sidx); else
445 * rshift[1]+=shift; }
449 * shift from pos to To(pos)
453 * @return int shifted position in To, frameshift in From, direction of mapped
456 public int[] shiftFrom(int pos)
458 return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
462 * inverse of shiftFrom - maps pos in To to a position in From
466 * @return shifted position in From, frameshift in To, direction of mapped
469 public int[] shiftTo(int pos)
471 return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
482 protected static int[] shift(int pos, List<int[]> shiftTo, int fromRatio,
483 List<int[]> shiftFrom, int toRatio)
485 // TODO: javadoc; tests
486 int[] fromCount = countPos(shiftTo, pos);
487 if (fromCount == null)
491 int fromRemainder = (fromCount[0] - 1) % fromRatio;
492 int toCount = 1 + (((fromCount[0] - 1) / fromRatio) * toRatio);
493 int[] toPos = countToPos(shiftFrom, toCount);
496 return null; // throw new Error("Bad Mapping!");
498 // System.out.println(fromCount[0]+" "+fromCount[1]+" "+toCount);
499 return new int[] { toPos[0], fromRemainder, toPos[1] };
503 * count how many positions pos is along the series of intervals.
507 * @return number of positions or null if pos is not within intervals
509 protected static int[] countPos(List<int[]> shiftTo, int pos)
511 int count = 0, intv[], iv = 0, ivSize = shiftTo.size();
514 intv = shiftTo.get(iv++);
515 if (intv[0] <= intv[1])
517 if (pos >= intv[0] && pos <= intv[1])
519 return new int[] { count + pos - intv[0] + 1, +1 };
523 count += intv[1] - intv[0] + 1;
528 if (pos >= intv[1] && pos <= intv[0])
530 return new int[] { count + intv[0] - pos + 1, -1 };
534 count += intv[0] - intv[1] + 1;
542 * count out pos positions into a series of intervals and return the position
546 * @return position pos in interval set
548 protected static int[] countToPos(List<int[]> shiftFrom, int pos)
550 int count = 0, diff = 0, iv = 0, ivSize = shiftFrom.size();
551 int[] intv = { 0, 0 };
554 intv = shiftFrom.get(iv++);
555 diff = intv[1] - intv[0];
558 if (pos <= count + 1 + diff)
560 return new int[] { pos - count - 1 + intv[0], +1 };
569 if (pos <= count + 1 - diff)
571 return new int[] { intv[0] - (pos - count - 1), -1 };
579 return null;// (diff<0) ? (intv[1]-1) : (intv[0]+1);
583 * find series of intervals mapping from start-end in the From map.
586 * position mapped 'to'
588 * position mapped 'to'
589 * @return series of [start, end] ranges in sequence mapped 'from'
591 public int[] locateInFrom(int start, int end)
593 // inefficient implementation
594 int fromStart[] = shiftTo(start);
595 // needs to be inclusive of end of symbol position
596 int fromEnd[] = shiftTo(end);
598 return getIntervals(fromShifts, fromStart, fromEnd, fromRatio);
602 * find series of intervals mapping from start-end in the to map.
605 * position mapped 'from'
607 * position mapped 'from'
608 * @return series of [start, end] ranges in sequence mapped 'to'
610 public int[] locateInTo(int start, int end)
612 int toStart[] = shiftFrom(start);
613 int toEnd[] = shiftFrom(end);
614 return getIntervals(toShifts, toStart, toEnd, toRatio);
618 * like shift - except returns the intervals in the given vector of shifts
619 * which were spanned in traversing fromStart to fromEnd
625 * @return series of from,to intervals from from first position of starting
626 * region to final position of ending region inclusive
628 protected static int[] getIntervals(List<int[]> shiftFrom,
629 int[] fromStart, int[] fromEnd, int fromRatio2)
631 if (fromStart == null || fromEnd == null)
635 int startpos, endpos;
636 startpos = fromStart[0]; // first position in fromStart
637 endpos = fromEnd[0]; // last position in fromEnd
638 int endindx = (fromRatio2 - 1); // additional positions to get to last
639 // position from endpos
640 int intv = 0, intvSize = shiftFrom.size();
641 int iv[], i = 0, fs = -1, fe_s = -1, fe = -1; // containing intervals
642 // search intervals to locate ones containing startpos and count endindx
643 // positions on from endpos
644 while (intv < intvSize && (fs == -1 || fe == -1))
646 iv = shiftFrom.get(intv++);
649 endpos = iv[0]; // start counting from beginning of interval
650 endindx--; // inclusive of endpos
654 if (fs == -1 && startpos >= iv[0] && startpos <= iv[1])
658 if (endpos >= iv[0] && endpos <= iv[1])
666 if (endpos + endindx <= iv[1])
669 endpos = endpos + endindx; // end of end token is within this
674 endindx -= iv[1] - endpos; // skip all this interval too
681 if (fs == -1 && startpos <= iv[0] && startpos >= iv[1])
685 if (endpos <= iv[0] && endpos >= iv[1])
693 if (endpos - endindx >= iv[1])
696 endpos = endpos - endindx; // end of end token is within this
701 endindx -= endpos - iv[1]; // skip all this interval too
708 if (fs == fe && fe == -1)
712 List<int[]> ranges = new ArrayList<int[]>();
717 // truncate initial interval
718 iv = shiftFrom.get(intv++);
719 iv = new int[] { iv[0], iv[1] };// clone
726 ranges.add(iv); // add initial range
727 iv = shiftFrom.get(intv++); // get next interval
728 iv = new int[] { iv[0], iv[1] };// clone
735 ranges.add(iv); // add only - or final range
739 // walk from end of interval.
740 i = shiftFrom.size() - 1;
745 iv = shiftFrom.get(i);
746 iv = new int[] { iv[1], iv[0] };// reverse and clone
747 // truncate initial interval
753 { // fix apparent logic bug when fe==-1
754 ranges.add(iv); // add (truncated) reversed interval
755 iv = shiftFrom.get(i);
756 iv = new int[] { iv[1], iv[0] }; // reverse and clone
760 // interval is already reversed
763 ranges.add(iv); // add only - or final range
765 // create array of start end intervals.
767 if (ranges != null && ranges.size() > 0)
769 range = new int[ranges.size() * 2];
771 intvSize = ranges.size();
773 while (intv < intvSize)
775 iv = ranges.get(intv);
778 ranges.set(intv++, null); // remove
785 * get the 'initial' position of mpos in To
789 * @return position of first word in to reference frame
791 public int getToPosition(int mpos)
793 // TODO not used - remove??
794 int[] mp = shiftTo(mpos);
803 * get range of positions in To frame for the mpos word in From
807 * @return null or int[] first position in To for mpos, last position in to
810 public int[] getToWord(int mpos)
812 int[] mp = shiftTo(mpos);
815 return new int[] { mp[0], mp[0] + mp[2] * (getFromRatio() - 1) };
821 * get From position in the associated reference frame for position pos in the
822 * associated sequence.
827 public int getMappedPosition(int pos)
829 // TODO not used - remove??
830 int[] mp = shiftFrom(pos);
838 public int[] getMappedWord(int pos)
840 // TODO not used - remove??
841 int[] mp = shiftFrom(pos);
844 return new int[] { mp[0], mp[0] + mp[2] * (getToRatio() - 1) };
851 * @return a MapList whose From range is this maplist's To Range, and vice
854 public MapList getInverse()
856 return new MapList(getToRanges(), getFromRanges(), getToRatio(),
861 * test for containment rather than equivalence to another mapping
864 * to be tested for containment
865 * @return true if local or mapped range map contains or is contained by this
868 public boolean containsEither(boolean local, MapList map)
870 // TODO not used - remove?
873 return ((getFromLowest() >= map.getFromLowest() && getFromHighest() <= map
874 .getFromHighest()) || (getFromLowest() <= map.getFromLowest() && getFromHighest() >= map
879 return ((getToLowest() >= map.getToLowest() && getToHighest() <= map
880 .getToHighest()) || (getToLowest() <= map.getToLowest() && getToHighest() >= map
886 * String representation - for debugging, not guaranteed not to change
889 public String toString()
891 StringBuilder sb = new StringBuilder(64);
893 for (int[] shift : fromShifts)
895 sb.append(" ").append(Arrays.toString(shift));
897 sb.append(" ] To [");
898 for (int[] shift : toShifts)
900 sb.append(" ").append(Arrays.toString(shift));
903 return sb.toString();
907 * Extend this map list by adding the given map's ranges. There is no
908 * validation check that the ranges do not overlap existing ranges (or each
909 * other), but contiguous ranges are merged.
913 public void addMapList(MapList map)
915 this.fromLowest = Math.min(fromLowest, map.fromLowest);
916 this.toLowest = Math.min(toLowest, map.toLowest);
917 this.fromHighest = Math.max(fromHighest, map.fromHighest);
918 this.toHighest = Math.max(toHighest, map.toHighest);
920 for (int[] range : map.getFromRanges())
922 addRange(range, fromShifts);
924 for (int[] range : map.getToRanges())
926 addRange(range, toShifts);
930 public static void addRange(int[] range, List<int[]> addTo)
933 * list is empty - add to it!
935 if (addTo.size() == 0)
941 int[] last = addTo.get(addTo.size() - 1);
942 boolean lastForward = last[1] >= last[0];
943 boolean newForward = range[1] >= range[0];
946 * contiguous range in the same direction - just update endpoint
948 if (lastForward == newForward && last[1] == range[0])
955 * next range starts at +1 in forward sense - update endpoint
957 if (lastForward && newForward && range[0] == last[1] + 1)
964 * next range starts at -1 in reverse sense - update endpoint
966 if (!lastForward && !newForward && range[0] == last[1] - 1)
973 * just add the new range
979 * Returns true if mapping is from forward strand, false if from reverse
980 * strand. Result is just based on the first 'from' range that is not a single
981 * position. Default is true unless proven to be false. Behaviour is not well
982 * defined if the mapping has a mixture of forward and reverse ranges.
986 public boolean isFromForwardStrand()
988 boolean forwardStrand = true;
989 for (int[] range : getFromRanges())
991 if (range[1] > range[0])
993 break; // forward strand confirmed
995 else if (range[1] < range[0])
997 forwardStrand = false;
998 break; // reverse strand confirmed
1001 return forwardStrand;