Clover icon

Coverage Report

  1. Project Clover database Wed Dec 3 2025 15:58:31 GMT
  2. Package jalview.util

File MapList.java

 

Coverage histogram

../../img/srcFileCovDistChart7.png
30% of files have more coverage

Code metrics

194
412
44
1
1,465
836
171
0.42
9.36
44
3.89

Classes

Class Line # Actions
MapList 39 412 171
0.643076964.3%
 

Contributing tests

This file is covered by 238 tests. .

Source view

1    /*
2    * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3    * Copyright (C) $$Year-Rel$$ The Jalview Authors
4    *
5    * This file is part of Jalview.
6    *
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.
11    *
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.
16    *
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.
20    */
21    package jalview.util;
22   
23    import java.util.ArrayList;
24    import java.util.Arrays;
25    import java.util.BitSet;
26    import java.util.List;
27   
28    import jalview.bin.Console;
29   
30    /**
31    * A simple way of bijectively mapping a non-contiguous linear range to another
32    * non-contiguous linear range.
33    *
34    * Use at your own risk!
35    *
36    * TODO: test/ensure that sense of from and to ratio start position is conserved
37    * (codon start position recovery)
38    */
 
39    public class MapList
40    {
41   
42    /*
43    * Subregions (base 1) described as { [start1, end1], [start2, end2], ...}
44    */
45    private List<int[]> fromShifts;
46   
47    /*
48    * Same format as fromShifts, for the 'mapped to' sequence
49    */
50    private List<int[]> toShifts;
51   
52    /*
53    * number of steps in fromShifts to one toRatio unit
54    */
55    private int fromRatio;
56   
57    /*
58    * number of steps in toShifts to one fromRatio
59    */
60    private int toRatio;
61   
62    /*
63    * lowest and highest value in the from Map
64    */
65    private int fromLowest;
66   
67    private int fromHighest;
68   
69    /*
70    * lowest and highest value in the to Map
71    */
72    private int toLowest;
73   
74    private int toHighest;
75   
76    /**
77    * Constructor
78    */
 
79  1464 toggle public MapList()
80    {
81  1464 fromShifts = new ArrayList<>();
82  1464 toShifts = new ArrayList<>();
83    }
84   
85    /**
86    * Two MapList objects are equal if they are the same object, or they both
87    * have populated shift ranges and all values are the same.
88    */
 
89  136 toggle @Override
90    public boolean equals(Object o)
91    {
92  136 if (o == null || !(o instanceof MapList))
93    {
94  2 return false;
95    }
96   
97  134 MapList obj = (MapList) o;
98  134 if (obj == this)
99    {
100  18 return true;
101    }
102  116 if (obj.fromRatio != fromRatio || obj.toRatio != toRatio
103    || obj.fromShifts == null || obj.toShifts == null)
104    {
105  25 return false;
106    }
107  91 return Arrays.deepEquals(fromShifts.toArray(), obj.fromShifts.toArray())
108    && Arrays.deepEquals(toShifts.toArray(),
109    obj.toShifts.toArray());
110    }
111   
112    /**
113    * Returns a hashcode made from the fromRatio, toRatio, and from/to ranges
114    */
 
115  102 toggle @Override
116    public int hashCode()
117    {
118  102 int hashCode = 31 * fromRatio;
119  102 hashCode = 31 * hashCode + toRatio;
120  102 for (int[] shift : fromShifts)
121    {
122  122 hashCode = 31 * hashCode + shift[0];
123  122 hashCode = 31 * hashCode + shift[1];
124    }
125  102 for (int[] shift : toShifts)
126    {
127  102 hashCode = 31 * hashCode + shift[0];
128  102 hashCode = 31 * hashCode + shift[1];
129    }
130   
131  102 return hashCode;
132    }
133   
134    /**
135    * Returns the 'from' ranges as {[start1, end1], [start2, end2], ...}
136    *
137    * @return
138    */
 
139  652 toggle public List<int[]> getFromRanges()
140    {
141  652 return fromShifts;
142    }
143   
144    /**
145    * Returns the 'to' ranges as {[start1, end1], [start2, end2], ...}
146    *
147    * @return
148    */
 
149  621 toggle public List<int[]> getToRanges()
150    {
151  621 return toShifts;
152    }
153   
154    /**
155    * Flattens a list of [start, end] into a single [start1, end1, start2,
156    * end2,...] array.
157    *
158    * @param shifts
159    * @return
160    */
 
161  1 toggle protected static int[] getRanges(List<int[]> shifts)
162    {
163  1 int[] rnges = new int[2 * shifts.size()];
164  1 int i = 0;
165  1 for (int[] r : shifts)
166    {
167  2 rnges[i++] = r[0];
168  2 rnges[i++] = r[1];
169    }
170  1 return rnges;
171    }
172   
173    /**
174    *
175    * @return length of mapped phrase in from
176    */
 
177  22225 toggle public int getFromRatio()
178    {
179  22225 return fromRatio;
180    }
181   
182    /**
183    *
184    * @return length of mapped phrase in to
185    */
 
186  524 toggle public int getToRatio()
187    {
188  524 return toRatio;
189    }
190   
 
191  89 toggle public int getFromLowest()
192    {
193  89 return fromLowest;
194    }
195   
 
196  90 toggle public int getFromHighest()
197    {
198  90 return fromHighest;
199    }
200   
 
201  354 toggle public int getToLowest()
202    {
203  354 return toLowest;
204    }
205   
 
206  5572 toggle public int getToHighest()
207    {
208  5572 return toHighest;
209    }
210   
211    /**
212    * Constructor given from and to ranges as [start1, end1, start2, end2,...].
213    * There is no validation check that the ranges do not overlap each other.
214    *
215    * @param from
216    * contiguous regions as [start1, end1, start2, end2, ...]
217    * @param to
218    * same format as 'from'
219    * @param fromRatio
220    * phrase length in 'from' (e.g. 3 for dna)
221    * @param toRatio
222    * phrase length in 'to' (e.g. 1 for protein)
223    */
 
224  1247 toggle public MapList(int from[], int to[], int fromRatio, int toRatio)
225    {
226  1247 this();
227  1247 this.fromRatio = fromRatio;
228  1247 this.toRatio = toRatio;
229  1247 fromLowest = Integer.MAX_VALUE;
230  1247 fromHighest = Integer.MIN_VALUE;
231  1245 if ((from.length % 2==1) || (to.length % 2==1))
232    {
233  0 throw new Error(
234    "Cannot construct MapList: unterminated interval pairs in ("
235  0 + ((from.length % 2 == 1) ? "[from]" : "")
236  0 + ((to.length % 2 == 1) ? " [to] " : "")+")");
237    }
238  2752 for (int i = 0; i < from.length; i += 2)
239    {
240    /*
241    * note lowest and highest values - bearing in mind the
242    * direction may be reversed
243    */
244  1507 fromLowest = Math.min(fromLowest, Math.min(from[i], from[i + 1]));
245  1507 fromHighest = Math.max(fromHighest, Math.max(from[i], from[i + 1]));
246  1507 fromShifts.add(new int[] { from[i], from[i + 1] });
247    }
248   
249  1245 toLowest = Integer.MAX_VALUE;
250  1245 toHighest = Integer.MIN_VALUE;
251  2834 for (int i = 0; i < to.length; i += 2)
252    {
253  1589 toLowest = Math.min(toLowest, Math.min(to[i], to[i + 1]));
254  1589 toHighest = Math.max(toHighest, Math.max(to[i], to[i + 1]));
255  1589 toShifts.add(new int[] { to[i], to[i + 1] });
256    }
257    }
258   
259    /**
260    * Copy constructor. Creates an identical mapping.
261    *
262    * @param map
263    */
 
264  23 toggle public MapList(MapList map)
265    {
266  23 this();
267    // TODO not used - remove?
268  23 this.fromLowest = map.fromLowest;
269  23 this.fromHighest = map.fromHighest;
270  23 this.toLowest = map.toLowest;
271  23 this.toHighest = map.toHighest;
272   
273  23 this.fromRatio = map.fromRatio;
274  23 this.toRatio = map.toRatio;
275  23 if (map.fromShifts != null)
276    {
277  23 for (int[] r : map.fromShifts)
278    {
279  35 fromShifts.add(new int[] { r[0], r[1] });
280    }
281    }
282  23 if (map.toShifts != null)
283    {
284  23 for (int[] r : map.toShifts)
285    {
286  28 toShifts.add(new int[] { r[0], r[1] });
287    }
288    }
289    }
290   
291    /**
292    * Constructor given ranges as lists of [start, end] positions. There is no
293    * validation check that the ranges do not overlap each other.
294    *
295    * @param fromRange
296    * @param toRange
297    * @param fromRatio
298    * @param toRatio
299    */
 
300  194 toggle public MapList(List<int[]> fromRange, List<int[]> toRange, int fromRatio,
301    int toRatio)
302    {
303  194 this();
304  194 fromRange = coalesceRanges(fromRange);
305  194 toRange = coalesceRanges(toRange);
306  194 this.fromShifts = fromRange;
307  194 this.toShifts = toRange;
308  194 this.fromRatio = fromRatio;
309  194 this.toRatio = toRatio;
310   
311  194 fromLowest = Integer.MAX_VALUE;
312  194 fromHighest = Integer.MIN_VALUE;
313  194 for (int[] range : fromRange)
314    {
315  239 if (range.length != 2)
316    {
317    // throw new IllegalArgumentException(range);
318  0 Console.error("Invalid format for fromRange "
319    + Arrays.toString(range) + " may cause errors");
320    }
321  239 fromLowest = Math.min(fromLowest, Math.min(range[0], range[1]));
322  239 fromHighest = Math.max(fromHighest, Math.max(range[0], range[1]));
323    }
324   
325  194 toLowest = Integer.MAX_VALUE;
326  194 toHighest = Integer.MIN_VALUE;
327  194 for (int[] range : toRange)
328    {
329  346 if (range.length != 2)
330    {
331    // throw new IllegalArgumentException(range);
332  0 Console.error("Invalid format for toRange " + Arrays.toString(range)
333    + " may cause errors");
334    }
335  346 toLowest = Math.min(toLowest, Math.min(range[0], range[1]));
336  346 toHighest = Math.max(toHighest, Math.max(range[0], range[1]));
337    }
338    }
339   
340    /**
341    * Consolidates a list of ranges so that any contiguous ranges are merged.
342    * This assumes the ranges are already in start order (does not sort them).
343    * <p>
344    * The main use case for this method is when mapping cDNA sequence to its
345    * protein product, based on CDS feature ranges which derive from spliced
346    * exons, but are contiguous on the cDNA sequence. For example
347    *
348    * <pre>
349    * CDS 1-20 // from exon1
350    * CDS 21-35 // from exon2
351    * CDS 36-71 // from exon3
352    * 'coalesce' to range 1-71
353    * </pre>
354    *
355    * @param ranges
356    * @return the same list (if unchanged), else a new merged list, leaving the
357    * input list unchanged
358    */
 
359  397 toggle public static List<int[]> coalesceRanges(final List<int[]> ranges)
360    {
361  397 if (ranges == null || ranges.size() < 2)
362    {
363  327 return ranges;
364    }
365   
366  70 boolean changed = false;
367  70 List<int[]> merged = new ArrayList<>();
368  70 int[] lastRange = ranges.get(0);
369  70 int lastDirection = lastRange[1] >= lastRange[0] ? 1 : -1;
370  70 lastRange = new int[] { lastRange[0], lastRange[1] };
371  70 merged.add(lastRange);
372  70 boolean first = true;
373   
374  70 for (final int[] range : ranges)
375    {
376  287 if (first)
377    {
378  70 first = false;
379  70 continue;
380    }
381   
382  217 int direction = range[1] >= range[0] ? 1 : -1;
383   
384    /*
385    * if next range is in the same direction as last and contiguous,
386    * just update the end position of the last range
387    */
388  217 boolean sameDirection = range[1] == range[0]
389    || direction == lastDirection;
390  217 boolean extending = range[0] == lastRange[1] + lastDirection;
391  217 if (sameDirection && extending)
392    {
393  10 lastRange[1] = range[1];
394  10 changed = true;
395    }
396    else
397    {
398  207 lastRange = new int[] { range[0], range[1] };
399  207 merged.add(lastRange);
400    // careful: merging [5, 5] after [7, 6] should keep negative direction
401  207 lastDirection = (range[1] == range[0]) ? lastDirection : direction;
402    }
403    }
404   
405  70 return changed ? merged : ranges;
406    }
407   
408    /**
409    * get all mapped positions from 'from' to 'to'
410    *
411    * @return int[][] { int[] { fromStart, fromFinish, toStart, toFinish }, int
412    * [fromFinish-fromStart+2] { toStart..toFinish mappings}}
413    */
 
414  0 toggle protected int[][] makeFromMap()
415    {
416    // TODO only used for test - remove??
417  0 return posMap(fromShifts, fromRatio, toShifts, toRatio);
418    }
419   
420    /**
421    * get all mapped positions from 'to' to 'from'
422    *
423    * @return int[to position]=position mapped in from
424    */
 
425  0 toggle protected int[][] makeToMap()
426    {
427    // TODO only used for test - remove??
428  0 return posMap(toShifts, toRatio, fromShifts, fromRatio);
429    }
430   
431    /**
432    * construct an int map for intervals in intVals
433    *
434    * @param shiftTo
435    * @return int[] { from, to pos in range }, int[range.to-range.from+1]
436    * returning mapped position
437    */
 
438  0 toggle private int[][] posMap(List<int[]> shiftTo, int sourceRatio,
439    List<int[]> shiftFrom, int targetRatio)
440    {
441    // TODO only used for test - remove??
442  0 int iv = 0, ivSize = shiftTo.size();
443  0 if (iv >= ivSize)
444    {
445  0 return null;
446    }
447  0 int[] intv = shiftTo.get(iv++);
448  0 int from = intv[0], to = intv[1];
449  0 if (from > to)
450    {
451  0 from = intv[1];
452  0 to = intv[0];
453    }
454  0 while (iv < ivSize)
455    {
456  0 intv = shiftTo.get(iv++);
457  0 if (intv[0] < from)
458    {
459  0 from = intv[0];
460    }
461  0 if (intv[1] < from)
462    {
463  0 from = intv[1];
464    }
465  0 if (intv[0] > to)
466    {
467  0 to = intv[0];
468    }
469  0 if (intv[1] > to)
470    {
471  0 to = intv[1];
472    }
473    }
474  0 int tF = 0, tT = 0;
475  0 int mp[][] = new int[to - from + 2][];
476  0 for (int i = 0; i < mp.length; i++)
477    {
478  0 int[] m = shift(i + from, shiftTo, sourceRatio, shiftFrom,
479    targetRatio);
480  0 if (m != null)
481    {
482  0 if (i == 0)
483    {
484  0 tF = tT = m[0];
485    }
486    else
487    {
488  0 if (m[0] < tF)
489    {
490  0 tF = m[0];
491    }
492  0 if (m[0] > tT)
493    {
494  0 tT = m[0];
495    }
496    }
497    }
498  0 mp[i] = m;
499    }
500  0 int[][] map = new int[][] { new int[] { from, to, tF, tT },
501    new int[to - from + 2] };
502   
503  0 map[0][2] = tF;
504  0 map[0][3] = tT;
505   
506  0 for (int i = 0; i < mp.length; i++)
507    {
508  0 if (mp[i] != null)
509    {
510  0 map[1][i] = mp[i][0] - tF;
511    }
512    else
513    {
514  0 map[1][i] = -1; // indicates an out of range mapping
515    }
516    }
517  0 return map;
518    }
519   
520    /**
521    * addShift
522    *
523    * @param pos
524    * start position for shift (in original reference frame)
525    * @param shift
526    * length of shift
527    *
528    * public void addShift(int pos, int shift) { int sidx = 0; int[]
529    * rshift=null; while (sidx<shifts.size() && (rshift=(int[])
530    * shifts.elementAt(sidx))[0]<pos) sidx++; if (sidx==shifts.size())
531    * shifts.insertElementAt(new int[] { pos, shift}, sidx); else
532    * rshift[1]+=shift; }
533    */
534   
535    /**
536    * shift from pos to To(pos)
537    *
538    * @param pos
539    * int
540    * @return int shifted position in To, frameshift in From, direction of mapped
541    * symbol in To
542    */
 
543  11 toggle public int[] shiftFrom(int pos)
544    {
545  11 return shift(pos, fromShifts, fromRatio, toShifts, toRatio);
546    }
547   
548    /**
549    * inverse of shiftFrom - maps pos in To to a position in From
550    *
551    * @param pos
552    * (in To)
553    * @return shifted position in From, frameshift in To, direction of mapped
554    * symbol in From
555    */
 
556  21912 toggle public int[] shiftTo(int pos)
557    {
558  21912 return shift(pos, toShifts, toRatio, fromShifts, fromRatio);
559    }
560   
561    /**
562    *
563    * @param shiftTo
564    * @param fromRatio
565    * @param shiftFrom
566    * @param toRatio
567    * @return
568    */
 
569  21923 toggle protected static int[] shift(int pos, List<int[]> shiftTo, int fromRatio,
570    List<int[]> shiftFrom, int toRatio)
571    {
572    // TODO: javadoc; tests
573  21923 int[] fromCount = countPositions(shiftTo, pos);
574  21923 if (fromCount == null)
575    {
576  20 return null;
577    }
578  21903 int fromRemainder = (fromCount[0] - 1) % fromRatio;
579  21903 int toCount = 1 + (((fromCount[0] - 1) / fromRatio) * toRatio);
580  21903 int[] toPos = traverseToPosition(shiftFrom, toCount);
581  21903 if (toPos == null)
582    {
583  0 return null;
584    }
585  21903 return new int[] { toPos[0], fromRemainder, toPos[1] };
586    }
587   
588    /**
589    * Counts how many positions pos is along the series of intervals. Returns an
590    * array of two values:
591    * <ul>
592    * <li>the number of positions traversed (inclusive) to reach {@code pos}</li>
593    * <li>+1 if the last interval traversed is forward, -1 if in a negative
594    * direction</li>
595    * </ul>
596    * Returns null if {@code pos} does not lie in any of the given intervals.
597    *
598    * @param intervals
599    * a list of start-end intervals
600    * @param pos
601    * a position that may lie in one (or more) of the intervals
602    * @return
603    */
 
604  21943 toggle protected static int[] countPositions(List<int[]> intervals, int pos)
605    {
606  21943 int count = 0;
607  21943 int iv = 0;
608  21943 int ivSize = intervals.size();
609   
610  22069 while (iv < ivSize)
611    {
612  22044 int[] intv = intervals.get(iv++);
613  22044 if (intv[0] <= intv[1])
614    {
615    /*
616    * forwards interval
617    */
618  22033 if (pos >= intv[0] && pos <= intv[1])
619    {
620  21912 return new int[] { count + pos - intv[0] + 1, +1 };
621    }
622    else
623    {
624  121 count += intv[1] - intv[0] + 1;
625    }
626    }
627    else
628    {
629    /*
630    * reverse interval
631    */
632  11 if (pos >= intv[1] && pos <= intv[0])
633    {
634  5 return new int[] { count + intv[0] - pos + 1, -1 };
635    }
636    else
637    {
638  6 count += intv[0] - intv[1] + 1;
639    }
640    }
641    }
642  25 return null;
643    }
644   
645    /**
646    * Reads through the given intervals until {@code count} positions have been
647    * traversed, and returns an array consisting of two values:
648    * <ul>
649    * <li>the value at the {@code count'th} position</li>
650    * <li>+1 if the last interval read is forwards, -1 if reverse direction</li>
651    * </ul>
652    * Returns null if the ranges include less than {@code count} positions, or if
653    * {@code count < 1}.
654    *
655    * @param intervals
656    * a list of [start, end] ranges
657    * @param count
658    * the number of positions to traverse
659    * @return
660    */
 
661  21905 toggle protected static int[] traverseToPosition(List<int[]> intervals,
662    final int count)
663    {
664  21905 int traversed = 0;
665  21905 int ivSize = intervals.size();
666  21905 int iv = 0;
667   
668  21905 if (count < 1)
669    {
670  2 return null;
671    }
672   
673  21986 while (iv < ivSize)
674    {
675  21986 int[] intv = intervals.get(iv++);
676  21986 int diff = intv[1] - intv[0];
677  21986 if (diff >= 0)
678    {
679  21986 if (count <= traversed + 1 + diff)
680    {
681  21903 return new int[] { intv[0] + (count - traversed - 1), +1 };
682    }
683    else
684    {
685  83 traversed += 1 + diff;
686    }
687    }
688    else
689    {
690  0 if (count <= traversed + 1 - diff)
691    {
692  0 return new int[] { intv[0] - (count - traversed - 1), -1 };
693    }
694    else
695    {
696  0 traversed += 1 - diff;
697    }
698    }
699    }
700  0 return null;
701    }
702   
703    /**
704    * like shift - except returns the intervals in the given vector of shifts
705    * which were spanned in traversing fromStart to fromEnd
706    *
707    * @param shiftFrom
708    * @param fromStart
709    * @param fromEnd
710    * @param fromRatio2
711    * @return series of from,to intervals from from first position of starting
712    * region to final position of ending region inclusive
713    */
 
714  0 toggle protected static int[] getIntervals(List<int[]> shiftFrom,
715    int[] fromStart, int[] fromEnd, int fromRatio2)
716    {
717  0 if (fromStart == null || fromEnd == null)
718    {
719  0 return null;
720    }
721  0 int startpos, endpos;
722  0 startpos = fromStart[0]; // first position in fromStart
723  0 endpos = fromEnd[0]; // last position in fromEnd
724  0 int endindx = (fromRatio2 - 1); // additional positions to get to last
725    // position from endpos
726  0 int intv = 0, intvSize = shiftFrom.size();
727  0 int iv[], i = 0, fs = -1, fe_s = -1, fe = -1; // containing intervals
728    // search intervals to locate ones containing startpos and count endindx
729    // positions on from endpos
730  0 while (intv < intvSize && (fs == -1 || fe == -1))
731    {
732  0 iv = shiftFrom.get(intv++);
733  0 if (fe_s > -1)
734    {
735  0 endpos = iv[0]; // start counting from beginning of interval
736  0 endindx--; // inclusive of endpos
737    }
738  0 if (iv[0] <= iv[1])
739    {
740  0 if (fs == -1 && startpos >= iv[0] && startpos <= iv[1])
741    {
742  0 fs = i;
743    }
744  0 if (endpos >= iv[0] && endpos <= iv[1])
745    {
746  0 if (fe_s == -1)
747    {
748  0 fe_s = i;
749    }
750  0 if (fe_s != -1)
751    {
752  0 if (endpos + endindx <= iv[1])
753    {
754  0 fe = i;
755  0 endpos = endpos + endindx; // end of end token is within this
756    // interval
757    }
758    else
759    {
760  0 endindx -= iv[1] - endpos; // skip all this interval too
761    }
762    }
763    }
764    }
765    else
766    {
767  0 if (fs == -1 && startpos <= iv[0] && startpos >= iv[1])
768    {
769  0 fs = i;
770    }
771  0 if (endpos <= iv[0] && endpos >= iv[1])
772    {
773  0 if (fe_s == -1)
774    {
775  0 fe_s = i;
776    }
777  0 if (fe_s != -1)
778    {
779  0 if (endpos - endindx >= iv[1])
780    {
781  0 fe = i;
782  0 endpos = endpos - endindx; // end of end token is within this
783    // interval
784    }
785    else
786    {
787  0 endindx -= endpos - iv[1]; // skip all this interval too
788    }
789    }
790    }
791    }
792  0 i++;
793    }
794  0 if (fs == fe && fe == -1)
795    {
796  0 return null;
797    }
798  0 List<int[]> ranges = new ArrayList<>();
799  0 if (fs <= fe)
800    {
801  0 intv = fs;
802  0 i = fs;
803    // truncate initial interval
804  0 iv = shiftFrom.get(intv++);
805  0 iv = new int[] { iv[0], iv[1] };// clone
806  0 if (i == fs)
807    {
808  0 iv[0] = startpos;
809    }
810  0 while (i != fe)
811    {
812  0 ranges.add(iv); // add initial range
813  0 iv = shiftFrom.get(intv++); // get next interval
814  0 iv = new int[] { iv[0], iv[1] };// clone
815  0 i++;
816    }
817  0 if (i == fe)
818    {
819  0 iv[1] = endpos;
820    }
821  0 ranges.add(iv); // add only - or final range
822    }
823    else
824    {
825    // walk from end of interval.
826  0 i = shiftFrom.size() - 1;
827  0 while (i > fs)
828    {
829  0 i--;
830    }
831  0 iv = shiftFrom.get(i);
832  0 iv = new int[] { iv[1], iv[0] };// reverse and clone
833    // truncate initial interval
834  0 if (i == fs)
835    {
836  0 iv[0] = startpos;
837    }
838  0 while (--i != fe)
839    { // fix apparent logic bug when fe==-1
840  0 ranges.add(iv); // add (truncated) reversed interval
841  0 iv = shiftFrom.get(i);
842  0 iv = new int[] { iv[1], iv[0] }; // reverse and clone
843    }
844  0 if (i == fe)
845    {
846    // interval is already reversed
847  0 iv[1] = endpos;
848    }
849  0 ranges.add(iv); // add only - or final range
850    }
851    // create array of start end intervals.
852  0 int[] range = null;
853  0 if (ranges != null && ranges.size() > 0)
854    {
855  0 range = new int[ranges.size() * 2];
856  0 intv = 0;
857  0 intvSize = ranges.size();
858  0 i = 0;
859  0 while (intv < intvSize)
860    {
861  0 iv = ranges.get(intv);
862  0 range[i++] = iv[0];
863  0 range[i++] = iv[1];
864  0 ranges.set(intv++, null); // remove
865    }
866    }
867  0 return range;
868    }
869   
870    /**
871    * get the 'initial' position of mpos in To
872    *
873    * @param mpos
874    * position in from
875    * @return position of first word in to reference frame
876    */
 
877  3 toggle public int getToPosition(int mpos)
878    {
879  3 int[] mp = shiftTo(mpos);
880  3 if (mp != null)
881    {
882  3 return mp[0];
883    }
884  0 return mpos;
885    }
886   
887    /**
888    *
889    * @return a MapList whose From range is this maplist's To Range, and vice
890    * versa
891    */
 
892  68 toggle public MapList getInverse()
893    {
894  68 return new MapList(getToRanges(), getFromRanges(), getToRatio(),
895    getFromRatio());
896    }
897   
898    /**
899    * String representation - for debugging, not guaranteed not to change
900    */
 
901  14 toggle @Override
902    public String toString()
903    {
904  14 StringBuilder sb = new StringBuilder(64);
905  14 sb.append("[");
906  14 for (int[] shift : fromShifts)
907    {
908  49 sb.append(" ").append(Arrays.toString(shift));
909    }
910  14 sb.append(" ] ");
911  14 sb.append(fromRatio).append(":").append(toRatio);
912  14 sb.append(" to [");
913  14 for (int[] shift : toShifts)
914    {
915  40 sb.append(" ").append(Arrays.toString(shift));
916    }
917  14 sb.append(" ]");
918  14 return sb.toString();
919    }
920   
921    /**
922    * Extend this map list by adding the given map's ranges. There is no
923    * validation check that the ranges do not overlap existing ranges (or each
924    * other), but contiguous ranges are merged.
925    *
926    * @param map
927    */
 
928  12 toggle public void addMapList(MapList map)
929    {
930  12 if (this.equals(map))
931    {
932  3 return;
933    }
934  9 this.fromLowest = Math.min(fromLowest, map.fromLowest);
935  9 this.toLowest = Math.min(toLowest, map.toLowest);
936  9 this.fromHighest = Math.max(fromHighest, map.fromHighest);
937  9 this.toHighest = Math.max(toHighest, map.toHighest);
938   
939  9 for (int[] range : map.getFromRanges())
940    {
941  10 addRange(range, fromShifts);
942    }
943  9 for (int[] range : map.getToRanges())
944    {
945  11 addRange(range, toShifts);
946    }
947    }
948   
949    /**
950    * Adds the given range to a list of ranges. If the new range just extends
951    * existing ranges, the current endpoint is updated instead.
952    *
953    * @param range
954    * @param addTo
955    */
 
956  29 toggle static void addRange(int[] range, List<int[]> addTo)
957    {
958    /*
959    * list is empty - add to it!
960    */
961  29 if (addTo.size() == 0)
962    {
963  1 addTo.add(range);
964  1 return;
965    }
966   
967  28 int[] last = addTo.get(addTo.size() - 1);
968  28 boolean lastForward = last[1] >= last[0];
969  28 boolean newForward = range[1] >= range[0];
970   
971    /*
972    * contiguous range in the same direction - just update endpoint
973    */
974  28 if (lastForward == newForward && last[1] == range[0])
975    {
976  4 last[1] = range[1];
977  4 return;
978    }
979   
980    /*
981    * next range starts at +1 in forward sense - update endpoint
982    */
983  24 if (lastForward && newForward && range[0] == last[1] + 1)
984    {
985  3 last[1] = range[1];
986  3 return;
987    }
988   
989    /*
990    * next range starts at -1 in reverse sense - update endpoint
991    */
992  21 if (!lastForward && !newForward && range[0] == last[1] - 1)
993    {
994  4 last[1] = range[1];
995  4 return;
996    }
997   
998    /*
999    * just add the new range
1000    */
1001  17 addTo.add(range);
1002    }
1003   
1004    /**
1005    * Returns true if mapping is from forward strand, false if from reverse
1006    * strand. Result is just based on the first 'from' range that is not a single
1007    * position. Default is true unless proven to be false. Behaviour is not well
1008    * defined if the mapping has a mixture of forward and reverse ranges.
1009    *
1010    * @return
1011    */
 
1012  3 toggle public boolean isFromForwardStrand()
1013    {
1014  3 return isForwardStrand(getFromRanges());
1015    }
1016   
1017    /**
1018    * Returns true if mapping is to forward strand, false if to reverse strand.
1019    * Result is just based on the first 'to' range that is not a single position.
1020    * Default is true unless proven to be false. Behaviour is not well defined if
1021    * the mapping has a mixture of forward and reverse ranges.
1022    *
1023    * @return
1024    */
 
1025  27 toggle public boolean isToForwardStrand()
1026    {
1027  27 return isForwardStrand(getToRanges());
1028    }
1029   
1030    /**
1031    * A helper method that returns true unless at least one range has start >
1032    * end. Behaviour is undefined for a mixture of forward and reverse ranges.
1033    *
1034    * @param ranges
1035    * @return
1036    */
 
1037  30 toggle private boolean isForwardStrand(List<int[]> ranges)
1038    {
1039  30 boolean forwardStrand = true;
1040  30 for (int[] range : ranges)
1041    {
1042  38 if (range[1] > range[0])
1043    {
1044  20 break; // forward strand confirmed
1045    }
1046  18 else if (range[1] < range[0])
1047    {
1048  8 forwardStrand = false;
1049  8 break; // reverse strand confirmed
1050    }
1051    }
1052  30 return forwardStrand;
1053    }
1054   
1055    /**
1056    *
1057    * @return true if from, or to is a three to 1 mapping
1058    */
 
1059  94 toggle public boolean isTripletMap()
1060    {
1061  94 return (toRatio == 3 && fromRatio == 1)
1062    || (fromRatio == 3 && toRatio == 1);
1063    }
1064   
1065    /**
1066    * Returns a map which is the composite of this one and the input map. That
1067    * is, the output map has the fromRanges of this map, and its toRanges are the
1068    * toRanges of this map as transformed by the input map.
1069    * <p>
1070    * Returns null if the mappings cannot be traversed (not all toRanges of this
1071    * map correspond to fromRanges of the input), or if this.toRatio does not
1072    * match map.fromRatio.
1073    *
1074    * <pre>
1075    * Example 1:
1076    * this: from [1-100] to [501-600]
1077    * input: from [10-40] to [60-90]
1078    * output: from [10-40] to [560-590]
1079    * Example 2 ('reverse strand exons'):
1080    * this: from [1-100] to [2000-1951], [1000-951] // transcript to loci
1081    * input: from [1-50] to [41-90] // CDS to transcript
1082    * output: from [10-40] to [1960-1951], [1000-971] // CDS to gene loci
1083    * </pre>
1084    *
1085    * @param map
1086    * @return
1087    */
 
1088  19 toggle public MapList traverse(MapList map)
1089    {
1090  19 if (map == null)
1091    {
1092  0 return null;
1093    }
1094   
1095    /*
1096    * compound the ratios by this rule:
1097    * A:B with M:N gives A*M:B*N
1098    * reduced by greatest common divisor
1099    * so 1:3 with 3:3 is 3:9 or 1:3
1100    * 1:3 with 3:1 is 3:3 or 1:1
1101    * 1:3 with 1:3 is 1:9
1102    * 2:5 with 3:7 is 6:35
1103    */
1104  19 int outFromRatio = getFromRatio() * map.getFromRatio();
1105  19 int outToRatio = getToRatio() * map.getToRatio();
1106  19 int gcd = MathUtils.gcd(outFromRatio, outToRatio);
1107  19 outFromRatio /= gcd;
1108  19 outToRatio /= gcd;
1109   
1110  19 List<int[]> toRanges = new ArrayList<>();
1111  19 for (int[] range : getToRanges())
1112    {
1113  20 int fromLength = Math.abs(range[1] - range[0]) + 1;
1114  20 int[] transferred = map.locateInTo(range[0], range[1]);
1115  20 if (transferred == null || transferred.length % 2 != 0)
1116    {
1117  0 return null;
1118    }
1119   
1120    /*
1121    * convert [start1, end1, start2, end2, ...]
1122    * to [[start1, end1], [start2, end2], ...]
1123    */
1124  20 int toLength = 0;
1125  169 for (int i = 0; i < transferred.length;)
1126    {
1127  149 toRanges.add(new int[] { transferred[i], transferred[i + 1] });
1128  149 toLength += Math.abs(transferred[i + 1] - transferred[i]) + 1;
1129  149 i += 2;
1130    }
1131   
1132    /*
1133    * check we mapped the full range - if not, abort
1134    */
1135  20 if (fromLength * map.getToRatio() != toLength * map.getFromRatio())
1136    {
1137  1 return null;
1138    }
1139    }
1140   
1141  18 return new MapList(getFromRanges(), toRanges, outFromRatio, outToRatio);
1142    }
1143   
1144    /**
1145    * Answers true if the mapping is from one contiguous range to another, else
1146    * false
1147    *
1148    * @return
1149    */
 
1150  0 toggle public boolean isContiguous()
1151    {
1152  0 return fromShifts.size() == 1 && toShifts.size() == 1;
1153    }
1154   
1155    /**
1156    * <<<<<<< HEAD Returns the [start1, end1, start2, end2, ...] positions in the
1157    * 'from' range that map to positions between {@code start} and {@code end} in
1158    * the 'to' range. Note that for a reverse strand mapping this will return
1159    * ranges with end < start. Returns null if no mapped positions are found in
1160    * start-end.
1161    *
1162    * @param start
1163    * @param end
1164    * @return
1165    */
 
1166  229541 toggle public int[] locateInFrom(int start, int end)
1167    {
1168  229541 return mapPositions(start, end, toShifts, fromShifts, toRatio,
1169    fromRatio);
1170    }
1171   
1172    /**
1173    * Returns the [start1, end1, start2, end2, ...] positions in the 'to' range
1174    * that map to positions between {@code start} and {@code end} in the 'from'
1175    * range. Note that for a reverse strand mapping this will return ranges with
1176    * end < start. Returns null if no mapped positions are found in start-end.
1177    *
1178    * @param start
1179    * @param end
1180    * @return
1181    */
 
1182  29141 toggle public int[] locateInTo(int start, int end)
1183    {
1184  29141 return mapPositions(start, end, fromShifts, toShifts, fromRatio,
1185    toRatio);
1186    }
1187   
1188    /**
1189    * Helper method that returns the [start1, end1, start2, end2, ...] positions
1190    * in {@code targetRange} that map to positions between {@code start} and
1191    * {@code end} in {@code sourceRange}. Note that for a reverse strand mapping
1192    * this will return ranges with end < start. Returns null if no mapped
1193    * positions are found in start-end.
1194    *
1195    * @param start
1196    * @param end
1197    * @param sourceRange
1198    * @param targetRange
1199    * @param sourceWordLength
1200    * @param targetWordLength
1201    * @return
1202    */
 
1203  258676 toggle final static int[] mapPositions(int start, int end,
1204    List<int[]> sourceRange, List<int[]> targetRange,
1205    int sourceWordLength, int targetWordLength)
1206    {
1207  258676 if (end < start)
1208    {
1209  2 int tmp = end;
1210  2 end = start;
1211  2 start = tmp;
1212    }
1213   
1214    /*
1215    * traverse sourceRange and mark offsets in targetRange
1216    * of any positions that lie in [start, end]
1217    */
1218  258674 BitSet offsets = getMappedOffsetsForPositions(start, end, sourceRange,
1219    sourceWordLength, targetWordLength);
1220   
1221    /*
1222    * traverse targetRange and collect positions at the marked offsets
1223    */
1224  258683 List<int[]> mapped = getPositionsForOffsets(targetRange, offsets);
1225   
1226    // TODO: or just return the List and adjust calling code to match
1227  258672 return mapped.isEmpty() ? null : MappingUtils.rangeListToArray(mapped);
1228    }
1229   
1230    /**
1231    * Scans the list of {@code ranges} for any values (positions) that lie
1232    * between start and end (inclusive), and records the <em>offsets</em> from
1233    * the start of the list as a BitSet. The offset positions are converted to
1234    * corresponding words in blocks of {@code wordLength2}.
1235    *
1236    * <pre>
1237    * For example:
1238    * 1:1 (e.g. gene to CDS):
1239    * ranges { [10-20], [31-40] }, wordLengthFrom = wordLength 2 = 1
1240    * for start = 1, end = 9, returns a BitSet with no bits set
1241    * for start = 1, end = 11, returns a BitSet with bits 0-1 set
1242    * for start = 15, end = 35, returns a BitSet with bits 5-15 set
1243    * 1:3 (peptide to codon):
1244    * ranges { [1-200] }, wordLengthFrom = 1, wordLength 2 = 3
1245    * for start = 9, end = 9, returns a BitSet with bits 24-26 set
1246    * 3:1 (codon to peptide):
1247    * ranges { [101-150], [171-180] }, wordLengthFrom = 3, wordLength 2 = 1
1248    * for start = 101, end = 102 (partial first codon), returns a BitSet with bit 0 set
1249    * for start = 150, end = 171 (partial 17th codon), returns a BitSet with bit 16 set
1250    * 3:1 (circular DNA to peptide):
1251    * ranges { [101-150], [21-30] }, wordLengthFrom = 3, wordLength 2 = 1
1252    * for start = 24, end = 40 (spans codons 18-20), returns a BitSet with bits 17-19 set
1253    * </pre>
1254    *
1255    * @param start
1256    * @param end
1257    * @param sourceRange
1258    * @param sourceWordLength
1259    * @param targetWordLength
1260    * @return
1261    */
 
1262  258686 toggle protected final static BitSet getMappedOffsetsForPositions(int start,
1263    int end, List<int[]> sourceRange, int sourceWordLength,
1264    int targetWordLength)
1265    {
1266  258686 BitSet overlaps = new BitSet();
1267  258688 int offset = 0;
1268  258688 final int s1 = sourceRange.size();
1269  523160 for (int i = 0; i < s1; i++)
1270    {
1271  264462 int[] range = sourceRange.get(i);
1272  264462 final int offset1 = offset;
1273  264462 int overlapStartOffset = -1;
1274  264458 int overlapEndOffset = -1;
1275   
1276  264458 if (range[1] >= range[0])
1277    {
1278    /*
1279    * forward direction range
1280    */
1281  264346 if (start <= range[1] && end >= range[0])
1282    {
1283    /*
1284    * overlap
1285    */
1286  245155 int overlapStart = Math.max(start, range[0]);
1287  245156 overlapStartOffset = offset1 + overlapStart - range[0];
1288  245156 int overlapEnd = Math.min(end, range[1]);
1289  245161 overlapEndOffset = offset1 + overlapEnd - range[0];
1290    }
1291    }
1292    else
1293    {
1294    /*
1295    * reverse direction range
1296    */
1297  114 if (start <= range[0] && end >= range[1])
1298    {
1299    /*
1300    * overlap
1301    */
1302  29 int overlapStart = Math.max(start, range[1]);
1303  29 int overlapEnd = Math.min(end, range[0]);
1304  29 overlapStartOffset = offset1 + range[0] - overlapEnd;
1305  29 overlapEndOffset = offset1 + range[0] - overlapStart;
1306    }
1307    }
1308   
1309  264463 if (overlapStartOffset > -1)
1310    {
1311    /*
1312    * found an overlap
1313    */
1314  245189 if (sourceWordLength != targetWordLength)
1315    {
1316    /*
1317    * convert any overlap found to whole words in the target range
1318    * (e.g. treat any partial codon overlap as if the whole codon)
1319    */
1320  21658 overlapStartOffset -= overlapStartOffset % sourceWordLength;
1321  21658 overlapStartOffset = overlapStartOffset / sourceWordLength
1322    * targetWordLength;
1323   
1324    /*
1325    * similar calculation for range end, adding
1326    * (wordLength2 - 1) for end of mapped word
1327    */
1328  21658 overlapEndOffset -= overlapEndOffset % sourceWordLength;
1329  21658 overlapEndOffset = overlapEndOffset / sourceWordLength
1330    * targetWordLength;
1331  21658 overlapEndOffset += targetWordLength - 1;
1332    }
1333  245189 overlaps.set(overlapStartOffset, overlapEndOffset + 1);
1334    }
1335  264472 offset += 1 + Math.abs(range[1] - range[0]);
1336    }
1337  258700 return overlaps;
1338    }
1339   
1340    /**
1341    * Returns a (possibly empty) list of the [start-end] values (positions) at
1342    * offsets in the {@code targetRange} list that are marked by 'on' bits in the
1343    * {@code offsets} bitset.
1344    *
1345    * @param targetRange
1346    * @param offsets
1347    * @return
1348    */
 
1349  258687 toggle protected final static List<int[]> getPositionsForOffsets(
1350    List<int[]> targetRange, BitSet offsets)
1351    {
1352  258686 List<int[]> mapped = new ArrayList<>();
1353  258683 if (offsets.isEmpty())
1354    {
1355  13541 return mapped;
1356    }
1357   
1358    /*
1359    * count of positions preceding ranges[i]
1360    */
1361  245141 int traversed = 0;
1362   
1363    /*
1364    * for each [from-to] range in ranges:
1365    * - find subranges (if any) at marked offsets
1366    * - add the start-end values at the marked positions
1367    */
1368  245141 final int toAdd = offsets.cardinality();
1369  245138 int added = 0;
1370  245139 final int s2 = targetRange.size();
1371  492430 for (int i = 0; added < toAdd && i < s2; i++)
1372    {
1373  247288 int[] range = targetRange.get(i);
1374  247287 added += addOffsetPositions(mapped, traversed, range, offsets);
1375  247290 traversed += Math.abs(range[1] - range[0]) + 1;
1376    }
1377  245140 return mapped;
1378    }
1379   
1380    /**
1381    * Helper method that adds any start-end subranges of {@code range} that are
1382    * at offsets in {@code range} marked by set bits in overlaps.
1383    * {@code mapOffset} is added to {@code range} offset positions. Returns the
1384    * count of positions added.
1385    *
1386    * @param mapped
1387    * @param mapOffset
1388    * @param range
1389    * @param overlaps
1390    * @return
1391    */
 
1392  247291 toggle final static int addOffsetPositions(List<int[]> mapped,
1393    final int mapOffset, final int[] range, final BitSet overlaps)
1394    {
1395  247290 final int rangeLength = 1 + Math.abs(range[1] - range[0]);
1396  247287 final int step = range[1] < range[0] ? -1 : 1;
1397  247288 int offsetStart = 0; // offset into range
1398  247288 int added = 0;
1399   
1400  492633 while (offsetStart < rangeLength)
1401    {
1402    /*
1403    * find the start of the next marked overlap offset;
1404    * if there is none, or it is beyond range, then finished
1405    */
1406  481678 int overlapStart = overlaps.nextSetBit(mapOffset + offsetStart);
1407  481690 if (overlapStart == -1 || overlapStart - mapOffset >= rangeLength)
1408    {
1409    /*
1410    * no more overlaps, or no more within range[]
1411    */
1412  236351 return added;
1413    }
1414  245337 overlapStart -= mapOffset;
1415   
1416    /*
1417    * end of the overlap range is just before the next clear bit;
1418    * restrict it to end of range if necessary;
1419    * note we may add a reverse strand range here (end < start)
1420    */
1421  245336 int overlapEnd = overlaps.nextClearBit(mapOffset + overlapStart + 1);
1422  245335 overlapEnd = (overlapEnd == -1) ? rangeLength - 1
1423    : Math.min(rangeLength - 1, overlapEnd - mapOffset - 1);
1424  245336 int startPosition = range[0] + step * overlapStart;
1425  245336 int endPosition = range[0] + step * overlapEnd;
1426  245335 mapped.add(new int[] { startPosition, endPosition });
1427  245355 offsetStart = overlapEnd + 1;
1428  245354 added += Math.abs(endPosition - startPosition) + 1;
1429    }
1430   
1431  10953 return added;
1432    }
1433   
1434    /*
1435    * Returns the [start, end...] positions in the range mapped from, that are
1436    * mapped to by part or all of the given begin-end of the range mapped to.
1437    * Returns null if begin-end does not overlap any position mapped to.
1438    *
1439    * @param begin
1440    * @param end
1441    * @return
1442    */
 
1443  7 toggle public int[] getOverlapsInFrom(final int begin, final int end)
1444    {
1445  7 int[] overlaps = MappingUtils.findOverlap(toShifts, begin, end);
1446   
1447  7 return overlaps == null ? null : locateInFrom(overlaps[0], overlaps[1]);
1448    }
1449   
1450    /**
1451    * Returns the [start, end...] positions in the range mapped to, that are
1452    * mapped to by part or all of the given begin-end of the range mapped from.
1453    * Returns null if begin-end does not overlap any position mapped from.
1454    *
1455    * @param begin
1456    * @param end
1457    * @return
1458    */
 
1459  15 toggle public int[] getOverlapsInTo(final int begin, final int end)
1460    {
1461  15 int[] overlaps = MappingUtils.findOverlap(fromShifts, begin, end);
1462   
1463  15 return overlaps == null ? null : locateInTo(overlaps[0], overlaps[1]);
1464    }
1465    }