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
330 public static List<int[]> coalesceRanges(List<int[]> ranges)
332 if (ranges == null || ranges.size() < 2) {
336 boolean changed = false;
337 List<int[]> merged = new ArrayList<int[]>();
338 int[] lastRange = ranges.get(0);
339 int lastDirection = lastRange[1] >= lastRange[0] ? 1 : -1;
340 merged.add(lastRange);
342 for (int[] range : ranges)
344 if (range == lastRange)
348 int direction = range[1] >= range[0] ? 1 : -1;
351 * if next range is in the same direction as last and contiguous,
352 * just update the end position of the last range
354 if ((range[1] == range[0] || direction == lastDirection)
355 && (range[0] == lastRange[1] || range[0] == lastRange[1]
358 lastRange[1] = range[1];
365 // careful: merging [5, 5] after [7, 6] should keep negative direction
366 lastDirection = (range[1] == range[0]) ? lastDirection : direction;
370 return changed ? merged : ranges;
374 * get all mapped positions from 'from' to 'to'
376 * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int
377 * [fromFinish-fromStart+2] { toStart..toFinish mappings}}
379 protected int[][] makeFromMap()
381 // TODO not used - remove??
382 return posMap(fromShifts, fromRatio, toShifts, toRatio);
386 * get all mapped positions from 'to' to 'from'
388 * @return int[to position]=position mapped in from
390 protected int[][] makeToMap()
392 // TODO not used - remove??
393 return posMap(toShifts, toRatio, fromShifts, fromRatio);
397 * construct an int map for intervals in intVals
400 * @return int[] { from, to pos in range }, int[range.to-range.from+1]
401 * returning mapped position
403 private int[][] posMap(List<int[]> shiftTo, int ratio,
404 List<int[]> shiftFrom, int toRatio)
406 // TODO not used - remove??
407 int iv = 0, ivSize = shiftTo.size();
412 int[] intv = shiftTo.get(iv++);
413 int from = intv[0], to = intv[1];
421 intv = shiftTo.get(iv++);
440 int mp[][] = new int[to - from + 2][];
441 for (int i = 0; i < mp.length; i++)
443 int[] m = shift(i + from, shiftTo, ratio, shiftFrom, toRatio);
464 int[][] map = new int[][] { new int[] { from, to, tF, tT },
465 new int[to - from + 2] };
470 for (int i = 0; i < mp.length; i++)
474 map[1][i] = mp[i][0] - tF;
478 map[1][i] = -1; // indicates an out of range mapping
488 * start position for shift (in original reference frame)
492 * public void addShift(int pos, int shift) { int sidx = 0; int[]
493 * rshift=null; while (sidx<shifts.size() && (rshift=(int[])
494 * shifts.elementAt(sidx))[0]<pos) sidx++; if (sidx==shifts.size())
495 * shifts.insertElementAt(new int[] { pos, shift}, sidx); else
496 * rshift[1]+=shift; }
500 * shift from pos to To(pos)
504 * @return int shifted position in To, frameshift in From, direction of mapped
507 public int[] shiftFrom(int pos)
509 return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
513 * inverse of shiftFrom - maps pos in To to a position in From
517 * @return shifted position in From, frameshift in To, direction of mapped
520 public int[] shiftTo(int pos)
522 return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
533 protected static int[] shift(int pos, List<int[]> shiftTo, int fromRatio,
534 List<int[]> shiftFrom, int toRatio)
536 // TODO: javadoc; tests
537 int[] fromCount = countPos(shiftTo, pos);
538 if (fromCount == null)
542 int fromRemainder = (fromCount[0] - 1) % fromRatio;
543 int toCount = 1 + (((fromCount[0] - 1) / fromRatio) * toRatio);
544 int[] toPos = countToPos(shiftFrom, toCount);
547 return null; // throw new Error("Bad Mapping!");
549 // System.out.println(fromCount[0]+" "+fromCount[1]+" "+toCount);
550 return new int[] { toPos[0], fromRemainder, toPos[1] };
554 * count how many positions pos is along the series of intervals.
558 * @return number of positions or null if pos is not within intervals
560 protected static int[] countPos(List<int[]> shiftTo, int pos)
562 int count = 0, intv[], iv = 0, ivSize = shiftTo.size();
565 intv = shiftTo.get(iv++);
566 if (intv[0] <= intv[1])
568 if (pos >= intv[0] && pos <= intv[1])
570 return new int[] { count + pos - intv[0] + 1, +1 };
574 count += intv[1] - intv[0] + 1;
579 if (pos >= intv[1] && pos <= intv[0])
581 return new int[] { count + intv[0] - pos + 1, -1 };
585 count += intv[0] - intv[1] + 1;
593 * count out pos positions into a series of intervals and return the position
597 * @return position pos in interval set
599 protected static int[] countToPos(List<int[]> shiftFrom, int pos)
601 int count = 0, diff = 0, iv = 0, ivSize = shiftFrom.size();
602 int[] intv = { 0, 0 };
605 intv = shiftFrom.get(iv++);
606 diff = intv[1] - intv[0];
609 if (pos <= count + 1 + diff)
611 return new int[] { pos - count - 1 + intv[0], +1 };
620 if (pos <= count + 1 - diff)
622 return new int[] { intv[0] - (pos - count - 1), -1 };
630 return null;// (diff<0) ? (intv[1]-1) : (intv[0]+1);
634 * find series of intervals mapping from start-end in the From map.
637 * position mapped 'to'
639 * position mapped 'to'
640 * @return series of [start, end] ranges in sequence mapped 'from'
642 public int[] locateInFrom(int start, int end)
644 // inefficient implementation
645 int fromStart[] = shiftTo(start);
646 // needs to be inclusive of end of symbol position
647 int fromEnd[] = shiftTo(end);
649 return getIntervals(fromShifts, fromStart, fromEnd, fromRatio);
653 * find series of intervals mapping from start-end in the to map.
656 * position mapped 'from'
658 * position mapped 'from'
659 * @return series of [start, end] ranges in sequence mapped 'to'
661 public int[] locateInTo(int start, int end)
663 int toStart[] = shiftFrom(start);
664 int toEnd[] = shiftFrom(end);
665 return getIntervals(toShifts, toStart, toEnd, toRatio);
669 * like shift - except returns the intervals in the given vector of shifts
670 * which were spanned in traversing fromStart to fromEnd
676 * @return series of from,to intervals from from first position of starting
677 * region to final position of ending region inclusive
679 protected static int[] getIntervals(List<int[]> shiftFrom,
680 int[] fromStart, int[] fromEnd, int fromRatio2)
682 if (fromStart == null || fromEnd == null)
686 int startpos, endpos;
687 startpos = fromStart[0]; // first position in fromStart
688 endpos = fromEnd[0]; // last position in fromEnd
689 int endindx = (fromRatio2 - 1); // additional positions to get to last
690 // position from endpos
691 int intv = 0, intvSize = shiftFrom.size();
692 int iv[], i = 0, fs = -1, fe_s = -1, fe = -1; // containing intervals
693 // search intervals to locate ones containing startpos and count endindx
694 // positions on from endpos
695 while (intv < intvSize && (fs == -1 || fe == -1))
697 iv = shiftFrom.get(intv++);
700 endpos = iv[0]; // start counting from beginning of interval
701 endindx--; // inclusive of endpos
705 if (fs == -1 && startpos >= iv[0] && startpos <= iv[1])
709 if (endpos >= iv[0] && endpos <= iv[1])
717 if (endpos + endindx <= iv[1])
720 endpos = endpos + endindx; // end of end token is within this
725 endindx -= iv[1] - endpos; // skip all this interval too
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 -= endpos - iv[1]; // skip all this interval too
759 if (fs == fe && fe == -1)
763 List<int[]> ranges = new ArrayList<int[]>();
768 // truncate initial interval
769 iv = shiftFrom.get(intv++);
770 iv = new int[] { iv[0], iv[1] };// clone
777 ranges.add(iv); // add initial range
778 iv = shiftFrom.get(intv++); // get next interval
779 iv = new int[] { iv[0], iv[1] };// clone
786 ranges.add(iv); // add only - or final range
790 // walk from end of interval.
791 i = shiftFrom.size() - 1;
796 iv = shiftFrom.get(i);
797 iv = new int[] { iv[1], iv[0] };// reverse and clone
798 // truncate initial interval
804 { // fix apparent logic bug when fe==-1
805 ranges.add(iv); // add (truncated) reversed interval
806 iv = shiftFrom.get(i);
807 iv = new int[] { iv[1], iv[0] }; // reverse and clone
811 // interval is already reversed
814 ranges.add(iv); // add only - or final range
816 // create array of start end intervals.
818 if (ranges != null && ranges.size() > 0)
820 range = new int[ranges.size() * 2];
822 intvSize = ranges.size();
824 while (intv < intvSize)
826 iv = ranges.get(intv);
829 ranges.set(intv++, null); // remove
836 * get the 'initial' position of mpos in To
840 * @return position of first word in to reference frame
842 public int getToPosition(int mpos)
844 // TODO not used - remove??
845 int[] mp = shiftTo(mpos);
854 * get range of positions in To frame for the mpos word in From
858 * @return null or int[] first position in To for mpos, last position in to
861 public int[] getToWord(int mpos)
863 int[] mp = shiftTo(mpos);
866 return new int[] { mp[0], mp[0] + mp[2] * (getFromRatio() - 1) };
872 * get From position in the associated reference frame for position pos in the
873 * associated sequence.
878 public int getMappedPosition(int pos)
880 // TODO not used - remove??
881 int[] mp = shiftFrom(pos);
889 public int[] getMappedWord(int pos)
891 // TODO not used - remove??
892 int[] mp = shiftFrom(pos);
895 return new int[] { mp[0], mp[0] + mp[2] * (getToRatio() - 1) };
902 * @return a MapList whose From range is this maplist's To Range, and vice
905 public MapList getInverse()
907 return new MapList(getToRanges(), getFromRanges(), getToRatio(),
912 * test for containment rather than equivalence to another mapping
915 * to be tested for containment
916 * @return true if local or mapped range map contains or is contained by this
919 public boolean containsEither(boolean local, MapList map)
921 // TODO not used - remove?
924 return ((getFromLowest() >= map.getFromLowest() && getFromHighest() <= map
925 .getFromHighest()) || (getFromLowest() <= map.getFromLowest() && getFromHighest() >= map
930 return ((getToLowest() >= map.getToLowest() && getToHighest() <= map
931 .getToHighest()) || (getToLowest() <= map.getToLowest() && getToHighest() >= map
937 * String representation - for debugging, not guaranteed not to change
940 public String toString()
942 StringBuilder sb = new StringBuilder(64);
944 for (int[] shift : fromShifts)
946 sb.append(" ").append(Arrays.toString(shift));
948 sb.append(" ] To [");
949 for (int[] shift : toShifts)
951 sb.append(" ").append(Arrays.toString(shift));
954 return sb.toString();
958 * Extend this map list by adding the given map's ranges. There is no
959 * validation check that the ranges do not overlap existing ranges (or each
960 * other), but contiguous ranges are merged.
964 public void addMapList(MapList map)
966 this.fromLowest = Math.min(fromLowest, map.fromLowest);
967 this.toLowest = Math.min(toLowest, map.toLowest);
968 this.fromHighest = Math.max(fromHighest, map.fromHighest);
969 this.toHighest = Math.max(toHighest, map.toHighest);
971 for (int[] range : map.getFromRanges())
973 addRange(range, fromShifts);
975 for (int[] range : map.getToRanges())
977 addRange(range, toShifts);
981 public static void addRange(int[] range, List<int[]> addTo)
984 * list is empty - add to it!
986 if (addTo.size() == 0)
992 int[] last = addTo.get(addTo.size() - 1);
993 boolean lastForward = last[1] >= last[0];
994 boolean newForward = range[1] >= range[0];
997 * contiguous range in the same direction - just update endpoint
999 if (lastForward == newForward && last[1] == range[0])
1006 * next range starts at +1 in forward sense - update endpoint
1008 if (lastForward && newForward && range[0] == last[1] + 1)
1015 * next range starts at -1 in reverse sense - update endpoint
1017 if (!lastForward && !newForward && range[0] == last[1] - 1)
1024 * just add the new range
1030 * Returns true if mapping is from forward strand, false if from reverse
1031 * strand. Result is just based on the first 'from' range that is not a single
1032 * position. Default is true unless proven to be false. Behaviour is not well
1033 * defined if the mapping has a mixture of forward and reverse ranges.
1037 public boolean isFromForwardStrand()
1039 boolean forwardStrand = true;
1040 for (int[] range : getFromRanges())
1042 if (range[1] > range[0])
1044 break; // forward strand confirmed
1046 else if (range[1] < range[0])
1048 forwardStrand = false;
1049 break; // reverse strand confirmed
1052 return forwardStrand;