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 fromRange = coalesceRanges(fromRange);
301 toRange = coalesceRanges(toRange);
302 this.fromShifts = fromRange;
303 this.toShifts = toRange;
304 this.fromRatio = fromRatio;
305 this.toRatio = toRatio;
307 fromLowest = Integer.MAX_VALUE;
308 fromHighest = Integer.MIN_VALUE;
309 for (int[] range : fromRange)
311 fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
312 fromHighest = Math.max(fromHighest, Math.max(range[0], range[1]));
315 toLowest = Integer.MAX_VALUE;
316 toHighest = Integer.MIN_VALUE;
317 for (int[] range : toRange)
319 toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
320 toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
325 * Consolidates a list of ranges so that any contiguous ranges are merged.
326 * This assumes the ranges are already in start order (does not sort them).
329 * @return the same list (if unchanged), else a new merged list, leaving the
330 * input list unchanged
332 public static List<int[]> coalesceRanges(final List<int[]> ranges)
334 if (ranges == null || ranges.size() < 2) {
338 boolean changed = false;
339 List<int[]> merged = new ArrayList<int[]>();
340 int[] lastRange = ranges.get(0);
341 int lastDirection = lastRange[1] >= lastRange[0] ? 1 : -1;
342 lastRange = new int[] { lastRange[0], lastRange[1] };
343 merged.add(lastRange);
344 boolean first = true;
346 for (final int[] range : ranges)
353 if (range[0] == lastRange[0] && range[1] == lastRange[1])
355 // drop duplicate range
361 * drop this range if it lies within the last range
363 if ((lastDirection == 1 && range[0] >= lastRange[0]
364 && range[0] <= lastRange[1] && range[1] >= lastRange[0] && range[1] <= lastRange[1])
365 || (lastDirection == -1 && range[0] <= lastRange[0]
366 && range[0] >= lastRange[1]
367 && range[1] <= lastRange[0] && range[1] >= lastRange[1]))
373 int direction = range[1] >= range[0] ? 1 : -1;
376 * if next range is in the same direction as last and contiguous,
377 * just update the end position of the last range
379 boolean sameDirection = range[1] == range[0] || direction == lastDirection;
380 boolean extending = range[0] == lastRange[1] + lastDirection;
381 boolean overlapping = (lastDirection == 1 && range[0] >= lastRange[0] && range[0] <= lastRange[1])
382 || (lastDirection == -1 && range[0] <= lastRange[0] && range[0] >= lastRange[1]);
383 if (sameDirection && (overlapping || 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<int[]>();
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() && getFromHighest() <= map
952 .getFromHighest()) || (getFromLowest() <= map.getFromLowest() && getFromHighest() >= map
957 return ((getToLowest() >= map.getToLowest() && getToHighest() <= map
958 .getToHighest()) || (getToLowest() <= map.getToLowest() && getToHighest() >= map
964 * String representation - for debugging, not guaranteed not to change
967 public String toString()
969 StringBuilder sb = new StringBuilder(64);
971 for (int[] shift : fromShifts)
973 sb.append(" ").append(Arrays.toString(shift));
975 sb.append(" ] To [");
976 for (int[] shift : toShifts)
978 sb.append(" ").append(Arrays.toString(shift));
981 return sb.toString();
985 * Extend this map list by adding the given map's ranges. There is no
986 * validation check that the ranges do not overlap existing ranges (or each
987 * other), but contiguous ranges are merged.
991 public void addMapList(MapList map)
993 this.fromLowest = Math.min(fromLowest, map.fromLowest);
994 this.toLowest = Math.min(toLowest, map.toLowest);
995 this.fromHighest = Math.max(fromHighest, map.fromHighest);
996 this.toHighest = Math.max(toHighest, map.toHighest);
998 for (int[] range : map.getFromRanges())
1000 addRange(range, fromShifts);
1002 for (int[] range : map.getToRanges())
1004 addRange(range, toShifts);
1009 * Adds the given range to a list of ranges. If the new range just extends
1010 * existing ranges, the current endpoint is updated instead.
1015 static void addRange(int[] range, List<int[]> addTo)
1018 * list is empty - add to it!
1020 if (addTo.size() == 0)
1026 int[] last = addTo.get(addTo.size() - 1);
1027 boolean lastForward = last[1] >= last[0];
1028 boolean newForward = range[1] >= range[0];
1031 * contiguous range in the same direction - just update endpoint
1033 if (lastForward == newForward && last[1] == range[0])
1040 * next range starts at +1 in forward sense - update endpoint
1042 if (lastForward && newForward && range[0] == last[1] + 1)
1049 * next range starts at -1 in reverse sense - update endpoint
1051 if (!lastForward && !newForward && range[0] == last[1] - 1)
1058 * just add the new range
1064 * Returns true if mapping is from forward strand, false if from reverse
1065 * strand. Result is just based on the first 'from' range that is not a single
1066 * position. Default is true unless proven to be false. Behaviour is not well
1067 * defined if the mapping has a mixture of forward and reverse ranges.
1071 public boolean isFromForwardStrand()
1073 boolean forwardStrand = true;
1074 for (int[] range : getFromRanges())
1076 if (range[1] > range[0])
1078 break; // forward strand confirmed
1080 else if (range[1] < range[0])
1082 forwardStrand = false;
1083 break; // reverse strand confirmed
1086 return forwardStrand;