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.
21 package jalview.datamodel;
23 import java.util.ArrayList;
24 import java.util.BitSet;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.NoSuchElementException;
28 import java.util.concurrent.locks.ReentrantReadWriteLock;
30 public class HiddenColumns
32 private static final int HASH_MULTIPLIER = 31;
34 private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
37 * list of hidden column [start, end] ranges; the list is maintained in
38 * ascending start column order
40 private ArrayList<int[]> hiddenColumns;
45 public HiddenColumns()
54 public HiddenColumns(HiddenColumns copy)
58 LOCK.writeLock().lock();
61 if (copy.hiddenColumns != null)
63 hiddenColumns = copy.copyHiddenRegionsToArrayList(0);
68 LOCK.writeLock().unlock();
73 * Copy constructor within bounds and with offset. Copies hidden column
74 * regions fully contained between start and end, and offsets positions by
78 * HiddenColumns instance to copy from
80 * lower bound to copy from
82 * upper bound to copy to
84 * offset to subtract from each region boundary position
87 public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
91 LOCK.writeLock().lock();
94 hiddenColumns = new ArrayList<>();
95 Iterator<int[]> it = copy.getBoundedIterator(start, end);
98 int[] region = it.next();
99 // still need to check boundaries because iterator returns
100 // all overlapping regions and we need contained regions
101 if (region[0] >= start && region[1] <= end)
105 { region[0] - offset, region[1] - offset });
111 LOCK.writeLock().unlock();
116 * Output regions data as a string. String is in the format:
117 * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
120 * string to delimit regions
121 * @param betweenstring
122 * to put between start and end region values
123 * @return regions formatted according to delimiter and between strings
125 public String regionsToString(String delimiter, String between)
129 LOCK.readLock().lock();
130 StringBuilder regionBuilder = new StringBuilder();
131 Iterator<int[]> it = new RegionsIterator();
134 int[] range = it.next();
135 regionBuilder.append(delimiter).append(range[0]).append(between)
139 regionBuilder.deleteCharAt(0);
142 return regionBuilder.toString();
145 LOCK.readLock().unlock();
150 * Find the number of hidden columns
152 * @return number of hidden columns
158 LOCK.readLock().lock();
160 Iterator<int[]> it = new RegionsIterator();
163 int[] range = it.next();
164 size += range[1] - range[0] + 1;
170 LOCK.readLock().unlock();
175 * Get the number of distinct hidden regions
177 * @return number of regions
179 public int getNumberOfRegions()
183 LOCK.readLock().lock();
185 if (hasHiddenColumns())
187 num = hiddenColumns.size();
192 LOCK.readLock().unlock();
197 public boolean equals(Object obj)
201 LOCK.readLock().lock();
203 if (!(obj instanceof HiddenColumns))
207 HiddenColumns that = (HiddenColumns) obj;
210 * check hidden columns are either both null, or match
212 if (this.hiddenColumns == null)
214 return (that.hiddenColumns == null);
216 if (that.hiddenColumns == null
217 || that.hiddenColumns.size() != this.hiddenColumns.size())
222 Iterator<int[]> it = new RegionsIterator();
223 Iterator<int[]> thatit = that.iterator();
226 int[] thisRange = it.next();
227 int[] thatRange = thatit.next();
228 if (thisRange[0] != thatRange[0] || thisRange[1] != thatRange[1])
236 LOCK.readLock().unlock();
241 * Return absolute column index for a visible column index
244 * int column index in alignment view (count from zero)
245 * @return alignment column index for column
247 public int adjustForHiddenColumns(int column)
251 LOCK.readLock().lock();
254 Iterator<int[]> it = new RegionsIterator();
257 int[] region = it.next();
258 if (result >= region[0])
260 result += region[1] - region[0] + 1;
267 LOCK.readLock().unlock();
272 * Use this method to find out where a column will appear in the visible
273 * alignment when hidden columns exist. If the column is not visible, then the
274 * left-most visible column will always be returned.
276 * @param hiddenColumn
277 * the column index in the full alignment including hidden columns
278 * @return the position of the column in the visible alignment
280 public int findColumnPosition(int hiddenColumn)
284 LOCK.readLock().lock();
285 int result = hiddenColumn;
287 if (hiddenColumns != null)
289 Iterator<int[]> it = new RegionsIterator(0,
294 if (hiddenColumn > region[1])
296 result -= region[1] + 1 - region[0];
300 if (region != null && hiddenColumn >= region[0]
301 && hiddenColumn <= region[1])
303 // Here the hidden column is within a region, so
304 // we want to return the position of region[0]-1, adjusted for any
305 // earlier hidden columns.
306 // Calculate the difference between the actual hidden col position
307 // and region[0]-1, and then subtract from result to convert result
309 // the adjusted hiddenColumn value to the adjusted region[0]-1 value
311 // However, if the region begins at 0 we cannot return region[0]-1
319 return result - (hiddenColumn - region[0] + 1);
323 return result; // return the shifted position after removing hidden
327 LOCK.readLock().unlock();
332 * Find the visible column which is a given visible number of columns to the
333 * left of another visible column. i.e. for a startColumn x, the column which
334 * is distance 1 away will be column x-1.
336 * @param visibleDistance
337 * the number of visible columns to offset by
339 * the column to start from
340 * @return the position of the column in the visible alignment
342 public int subtractVisibleColumns(int visibleDistance, int startColumn)
347 LOCK.readLock().lock();
348 int distance = visibleDistance;
350 // in case startColumn is in a hidden region, move it to the left
351 int start = adjustForHiddenColumns(findColumnPosition(startColumn));
353 Iterator<int[]> it = new ReverseRegionsIterator(0, start);
357 int nextstart = start;
359 while (it.hasNext() && (distance - gap > 0))
363 if (start > region[1])
367 // subtract the gap to right of region from distance
368 distance -= start - region[1]; // gap;
371 nextstart = region[0] - 1;// nextstart;
374 // calculate the next gap
376 // gap = start - region[1];
378 // set start to just to left of current region
379 // nextstart = region[0] - 1;
385 // no hidden regions to left of startColumn
386 return start - distance;
391 /* // walk backwards through the alignment subtracting the counts of
393 // columns from distance
396 int nextstart = start;
398 while (it.hasNext() && (distance - gap > 0))
402 // subtract the gap to right of region from distance
406 // calculate the next gap
408 gap = start - region[1];
410 // set start to just to left of current region
411 nextstart = region[0] - 1;
414 if (distance - gap > 0)
416 // fell out of loop because there are no more hidden regions
418 return nextstart - distance;
420 return start - distance;
424 LOCK.readLock().unlock();
429 * This method returns the rightmost limit of a region of an alignment with
430 * hidden columns. In otherwords, the next hidden column.
433 * the (visible) alignmentPosition to find the next hidden column for
435 public int getHiddenBoundaryRight(int alPos)
439 LOCK.readLock().lock();
440 if (hiddenColumns != null)
442 Iterator<int[]> it = new RegionsIterator();
445 int[] region = it.next();
446 if (alPos < region[0])
455 LOCK.readLock().unlock();
460 * This method returns the leftmost limit of a region of an alignment with
461 * hidden columns. In otherwords, the previous hidden column.
464 * the (visible) alignmentPosition to find the previous hidden column
467 public int getHiddenBoundaryLeft(int alPos)
471 LOCK.readLock().lock();
473 Iterator<int[]> it = new ReverseRegionsIterator(0, alPos);
476 int[] region = it.next();
477 if (alPos > region[1])
486 LOCK.readLock().unlock();
491 * This method returns the index of the hidden region to the left of a column
492 * position. If the column is in a hidden region it returns the index of the
493 * region to the left. If there is no hidden region to the left it returns -1.
496 * position to find index relative to
498 private int getHiddenIndexLeft(int pos)
502 LOCK.readLock().lock();
505 Iterator<int[]> it = new ReverseRegionsIterator(0, pos);
508 int index = hiddenColumns.size() - 1; // need index of region not last
512 int[] region = it.next();
523 LOCK.readLock().unlock();
529 * Adds the specified column range to the hidden columns
534 public void hideColumns(int start, int end)
536 boolean wasAlreadyLocked = false;
539 // check if the write lock was already locked by this thread,
540 // as this method can be called internally in loops within HiddenColumns
541 if (!LOCK.isWriteLockedByCurrentThread())
543 LOCK.writeLock().lock();
547 wasAlreadyLocked = true;
550 if (hiddenColumns == null)
552 hiddenColumns = new ArrayList<>();
556 * new range follows everything else; check first to avoid looping over whole hiddenColumns collection
558 if (hiddenColumns.isEmpty()
559 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
561 hiddenColumns.add(new int[] { start, end });
566 * traverse existing hidden ranges and insert / amend / append as
569 boolean added = false;
570 for (int i = 0; !added && i < hiddenColumns.size(); i++)
572 int[] region = hiddenColumns.get(i);
574 if (end < region[0] - 1)
577 * insert discontiguous preceding range
579 hiddenColumns.add(i, new int[] { start, end });
582 else if (end <= region[1])
585 * new range overlaps existing, or is contiguous preceding it - adjust
588 region[0] = Math.min(region[0], start);
591 else if (start <= region[1] + 1)
594 * new range overlaps existing, or is contiguous following it - adjust
595 * start and end columns
597 region[0] = Math.min(region[0], start);
598 region[1] = Math.max(region[1], end);
601 * also update or remove any subsequent ranges
602 * that are overlapped
604 while (i < hiddenColumns.size() - 1)
606 int[] nextRegion = hiddenColumns.get(i + 1);
607 if (nextRegion[0] > end + 1)
610 * gap to next hidden range - no more to update
614 region[1] = Math.max(nextRegion[1], end);
615 hiddenColumns.remove(i + 1);
623 if (!wasAlreadyLocked)
625 LOCK.writeLock().unlock();
630 public boolean isVisible(int column)
634 LOCK.readLock().lock();
636 Iterator<int[]> it = new RegionsIterator();
639 int[] region = it.next();
640 if (column >= region[0] && column <= region[1])
649 LOCK.readLock().unlock();
653 private ArrayList<int[]> copyHiddenRegionsToArrayList(int startIndex)
656 if (hiddenColumns != null)
658 size = hiddenColumns.size();
660 ArrayList<int[]> copy = new ArrayList<>(size);
662 for (int i = startIndex, j = size; i < j; i++)
666 rh = hiddenColumns.get(i);
669 cp = new int[rh.length];
670 System.arraycopy(rh, 0, cp, 0, rh.length);
678 public String[] getVisibleSequenceStrings(int start, int end,
683 LOCK.readLock().lock();
684 int iSize = seqs.length;
685 String[] selections = new String[iSize];
686 if (hiddenColumns != null && hiddenColumns.size() > 0)
688 for (int i = 0; i < iSize; i++)
690 StringBuffer visibleSeq = new StringBuffer();
692 Iterator<int[]> blocks = new VisibleContigsIterator(start,
695 while (blocks.hasNext())
697 int[] block = blocks.next();
698 if (blocks.hasNext())
701 .append(seqs[i].getSequence(block[0], block[1] + 1));
706 .append(seqs[i].getSequence(block[0], block[1]));
710 selections[i] = visibleSeq.toString();
715 for (int i = 0; i < iSize; i++)
717 selections[i] = seqs[i].getSequenceAsString(start, end);
724 LOCK.readLock().unlock();
729 * Locate the first position visible for this sequence. If seq isn't visible
730 * then return the position of the left side of the hidden boundary region.
733 * sequence to find position for
734 * @return visible start position
736 public int locateVisibleStartOfSequence(SequenceI seq)
740 LOCK.readLock().lock();
743 if (hiddenColumns == null || hiddenColumns.size() == 0)
745 return seq.findIndex(seq.getStart()) - 1;
748 // Simply walk along the sequence whilst watching for hidden column
750 Iterator<int[]> regions = new RegionsIterator();
751 int hideStart = seq.getLength();
755 boolean foundStart = false;
757 // step through the non-gapped positions of the sequence
758 for (int i = seq.getStart(); i <= seq.getEnd() && (!foundStart); i++)
760 // get alignment position of this residue in the sequence
761 int p = seq.findIndex(i) - 1;
763 // update hidden region start/end
764 while (hideEnd < p && regions.hasNext())
766 int[] region = regions.next();
768 visNext += region[0] - visPrev;
769 hideStart = region[0];
774 hideStart = seq.getLength();
776 // update visible boundary for sequence
786 return findColumnPosition(start);
788 // otherwise, sequence was completely hidden
792 LOCK.readLock().unlock();
797 * delete any columns in alignmentAnnotation that are hidden (including
798 * sequence associated annotation).
800 * @param alignmentAnnotation
802 public void makeVisibleAnnotation(AlignmentAnnotation alignmentAnnotation)
804 makeVisibleAnnotation(0, alignmentAnnotation.annotations.length,
805 alignmentAnnotation);
809 * delete any columns in alignmentAnnotation that are hidden (including
810 * sequence associated annotation).
813 * remove any annotation to the right of this column
815 * remove any annotation to the left of this column
816 * @param alignmentAnnotation
817 * the annotation to operate on
819 public void makeVisibleAnnotation(int start, int end,
820 AlignmentAnnotation alignmentAnnotation)
824 LOCK.readLock().lock();
826 int startFrom = start;
829 if (alignmentAnnotation.annotations != null)
831 if (hiddenColumns != null && hiddenColumns.size() > 0)
833 removeHiddenAnnotation(startFrom, endAt, alignmentAnnotation);
837 alignmentAnnotation.restrict(startFrom, endAt);
842 LOCK.readLock().unlock();
846 private void removeHiddenAnnotation(int start, int end,
847 AlignmentAnnotation alignmentAnnotation)
849 // mangle the alignmentAnnotation annotation array
850 ArrayList<Annotation[]> annels = new ArrayList<>();
851 Annotation[] els = null;
855 Iterator<int[]> blocks = new VisibleContigsIterator(start, end + 1,
859 int annotationLength;
860 while (blocks.hasNext())
862 int[] block = blocks.next();
863 annotationLength = block[1] - block[0] + 1;
865 if (blocks.hasNext())
867 // copy just the visible segment of the annotation row
868 copylength = annotationLength;
872 if (annotationLength + block[0] <= alignmentAnnotation.annotations.length)
874 // copy just the visible segment of the annotation row
875 copylength = annotationLength;
879 // copy to the end of the annotation row
880 copylength = alignmentAnnotation.annotations.length - block[0];
884 els = new Annotation[annotationLength];
886 System.arraycopy(alignmentAnnotation.annotations, block[0], els, 0,
888 w += annotationLength;
893 alignmentAnnotation.annotations = new Annotation[w];
896 for (Annotation[] chnk : annels)
898 System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
907 * @return true if there are columns hidden
909 public boolean hasHiddenColumns()
913 LOCK.readLock().lock();
914 return hiddenColumns != null && hiddenColumns.size() > 0;
917 LOCK.readLock().unlock();
923 * @return true if there are more than one set of columns hidden
925 public boolean hasManyHiddenColumns()
929 LOCK.readLock().lock();
930 return hiddenColumns != null && hiddenColumns.size() > 1;
933 LOCK.readLock().unlock();
938 * mark the columns corresponding to gap characters as hidden in the column
943 public void hideInsertionsFor(SequenceI sr)
947 LOCK.writeLock().lock();
948 List<int[]> inserts = sr.getInsertions();
949 for (int[] r : inserts)
951 hideColumns(r[0], r[1]);
955 LOCK.writeLock().unlock();
960 * Unhides, and adds to the selection list, all hidden columns
962 public void revealAllHiddenColumns(ColumnSelection sel)
966 LOCK.writeLock().lock();
967 Iterator<int[]> it = new RegionsIterator();
970 int[] region = it.next();
971 for (int j = region[0]; j < region[1] + 1; j++)
977 hiddenColumns = null;
980 LOCK.writeLock().unlock();
985 * Reveals, and marks as selected, the hidden column range with the given
990 public void revealHiddenColumns(int start, ColumnSelection sel)
994 LOCK.writeLock().lock();
995 Iterator<int[]> it = new RegionsIterator();
998 int[] region = it.next();
999 if (start == region[0])
1001 for (int j = region[0]; j < region[1] + 1; j++)
1006 hiddenColumns.remove(region);
1009 else if (start < region[0])
1011 break; // passed all possible matching regions
1015 if (hiddenColumns.size() == 0)
1017 hiddenColumns = null;
1021 LOCK.writeLock().unlock();
1026 * Add gaps into the sequences aligned to profileseq under the given
1031 * - alignment to have gaps inserted into it
1033 * - alignment view where sequence corresponding to profileseq is
1035 * @return new HiddenColumns for new alignment view, with insertions into
1036 * profileseq marked as hidden.
1038 public static HiddenColumns propagateInsertions(SequenceI profileseq,
1039 AlignmentI al, AlignmentView input)
1043 char gc = al.getGapCharacter();
1044 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1045 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1046 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1047 nview.propagateInsertions(profileseq, al, origseq);
1054 * - sequence in al which corresponds to origseq
1056 * - alignment which is to have gaps inserted into it
1058 * - sequence corresponding to profileseq which defines gap map for
1061 private void propagateInsertions(SequenceI profileseq, AlignmentI al,
1066 LOCK.writeLock().lock();
1068 char gc = al.getGapCharacter();
1070 // take the set of hidden columns, and the set of gaps in origseq,
1071 // and remove all the hidden gaps from hiddenColumns
1073 // first get the gaps as a Bitset
1074 BitSet gaps = origseq.gapBitset();
1076 // now calculate hidden ^ not(gap)
1077 BitSet hidden = new BitSet();
1078 markHiddenRegions(hidden);
1079 hidden.andNot(gaps);
1080 hiddenColumns = null;
1081 this.hideMarkedBits(hidden);
1083 // for each sequence in the alignment, except the profile sequence,
1084 // insert gaps corresponding to each hidden region
1085 // but where each hidden column region is shifted backwards by the number
1087 // preceding visible gaps
1088 // update hidden columns at the same time
1089 Iterator<int[]> regions = new RegionsIterator();
1090 ArrayList<int[]> newhidden = new ArrayList<>();
1092 int numGapsBefore = 0;
1093 int gapPosition = 0;
1094 while (regions.hasNext())
1096 // get region coordinates accounting for gaps
1097 // we can rely on gaps not being *in* hidden regions because we already
1099 int[] region = regions.next();
1100 while (gapPosition < region[0])
1103 if (gaps.get(gapPosition))
1109 int left = region[0] - numGapsBefore;
1110 int right = region[1] - numGapsBefore;
1111 newhidden.add(new int[] { left, right });
1113 // make a string with number of gaps = length of hidden region
1114 StringBuffer sb = new StringBuffer();
1115 for (int s = 0; s < right - left + 1; s++)
1119 padGaps(sb, left, profileseq, al);
1122 hiddenColumns = newhidden;
1125 LOCK.writeLock().unlock();
1130 * Pad gaps in all sequences in alignment except profileseq
1133 * gap string to insert
1135 * position to insert at
1137 * sequence not to pad
1139 * alignment to pad sequences in
1141 private void padGaps(StringBuffer sb, int pos, SequenceI profileseq,
1144 // loop over the sequences and pad with gaps where required
1145 for (int s = 0, ns = al.getHeight(); s < ns; s++)
1147 SequenceI sqobj = al.getSequenceAt(s);
1148 if (sqobj != profileseq)
1150 String sq = al.getSequenceAt(s).getSequenceAsString();
1151 if (sq.length() <= pos)
1154 int diff = pos - sq.length() - 1;
1159 while ((diff = pos - sq.length() - 1) > 0)
1161 if (diff >= sb.length())
1163 sq += sb.toString();
1167 char[] buf = new char[diff];
1168 sb.getChars(0, diff, buf, 0);
1169 sq += buf.toString();
1173 sq += sb.toString();
1177 al.getSequenceAt(s).setSequence(
1178 sq.substring(0, pos) + sb.toString() + sq.substring(pos));
1185 * Returns a hashCode built from hidden column ranges
1188 public int hashCode()
1192 LOCK.readLock().lock();
1194 Iterator<int[]> it = new RegionsIterator();
1195 while (it.hasNext())
1197 int[] hidden = it.next();
1198 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
1199 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
1204 LOCK.readLock().unlock();
1209 * Hide columns corresponding to the marked bits
1212 * - columns map to bits starting from zero
1214 public void hideMarkedBits(BitSet inserts)
1218 LOCK.writeLock().lock();
1219 for (int firstSet = inserts
1220 .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
1221 .nextSetBit(lastSet))
1223 lastSet = inserts.nextClearBit(firstSet);
1224 hideColumns(firstSet, lastSet - 1);
1228 LOCK.writeLock().unlock();
1235 * BitSet where hidden columns will be marked
1237 public void markHiddenRegions(BitSet inserts)
1241 LOCK.readLock().lock();
1242 if (hiddenColumns == null)
1246 Iterator<int[]> it = new RegionsIterator();
1247 while (it.hasNext())
1249 int[] range = it.next();
1250 inserts.set(range[0], range[1] + 1);
1254 LOCK.readLock().unlock();
1259 * Calculate the visible start and end index of an alignment.
1262 * full alignment width
1263 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
1265 public int[] getVisibleStartAndEndIndex(int width)
1269 LOCK.readLock().lock();
1270 int[] alignmentStartEnd = new int[] { 0, width - 1 };
1271 int startPos = alignmentStartEnd[0];
1272 int endPos = alignmentStartEnd[1];
1274 int[] lowestRange = new int[] { -1, -1 };
1275 int[] higestRange = new int[] { -1, -1 };
1277 if (hiddenColumns == null)
1279 return new int[] { startPos, endPos };
1282 Iterator<int[]> it = new RegionsIterator();
1283 while (it.hasNext())
1285 int[] range = it.next();
1286 lowestRange = (range[0] <= startPos) ? range : lowestRange;
1287 higestRange = (range[1] >= endPos) ? range : higestRange;
1290 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1292 startPos = alignmentStartEnd[0];
1296 startPos = lowestRange[1] + 1;
1299 if (higestRange[0] == -1 && higestRange[1] == -1)
1301 endPos = alignmentStartEnd[1];
1305 endPos = higestRange[0] - 1;
1307 return new int[] { startPos, endPos };
1310 LOCK.readLock().unlock();
1316 * Finds the hidden region (if any) which starts or ends at res
1319 * visible residue position, unadjusted for hidden columns
1320 * @return region as [start,end] or null if no matching region is found
1322 public int[] getRegionWithEdgeAtRes(int res)
1326 LOCK.readLock().lock();
1327 int adjres = adjustForHiddenColumns(res);
1329 int[] reveal = null;
1330 Iterator<int[]> it = new RegionsIterator(adjres - 2,
1332 while (it.hasNext())
1334 int[] region = it.next();
1335 if (adjres + 1 == region[0] || adjres - 1 == region[1])
1344 LOCK.readLock().unlock();
1349 * Return an iterator over the hidden regions
1351 public Iterator<int[]> iterator()
1353 return new BoundedHiddenColsIterator();
1357 * Return a bounded iterator over the hidden regions
1360 * position to start from (inclusive, absolute column position)
1362 * position to end at (inclusive, absolute column position)
1365 public Iterator<int[]> getBoundedIterator(int start, int end)
1367 return new BoundedHiddenColsIterator(start, end);
1371 * Return a bounded iterator over the *visible* start positions of hidden
1375 * position to start from (inclusive, visible column position)
1377 * position to end at (inclusive, visible column position)
1379 public Iterator<Integer> getBoundedStartIterator(int start, int end)
1381 return new BoundedStartRegionIterator(start, end, true);
1385 * Return an iterator over visible *columns* (not regions) between the given
1386 * start and end boundaries
1389 * first column (inclusive)
1391 * last column (inclusive)
1393 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1395 return new VisibleColsIterator(start, end);
1399 * return an iterator over visible segments between the given start and end
1403 * (first column inclusive from 0)
1405 * (last column - not inclusive)
1407 public Iterator<int[]> getVisContigsIterator(int start, int end)
1409 // return new VisibleBlocksIterator(start, end, true)
1410 return new VisibleContigsIterator(start, end, true);
1414 * return an iterator over visible segments between the given start and end
1418 * (first column - inclusive from 0)
1420 * (last column - inclusive)
1421 * @param useVisibleCoords
1422 * if true, start and end are visible column positions, not absolute
1425 public Iterator<int[]> getVisibleBlocksIterator(int start, int end,
1426 boolean useVisibleCoords)
1428 if (useVisibleCoords)
1431 // we should really just convert start and end here with
1432 // adjustForHiddenColumns
1433 // and then create a VisibleContigsIterator
1434 // but without a cursor this will be horribly slow in some situations
1435 // ... so until then...
1436 return new VisibleBlocksVisBoundsIterator(start, end, true);
1440 return new VisibleContigsIterator(start, end - 1, true);
1445 * A local iterator which iterates over hidden column regions in a range.
1446 * Intended for use ONLY within the HiddenColumns class, because it works
1447 * directly with the hiddenColumns collection without locking (callers should
1448 * lock hiddenColumns).
1450 private class RegionsIterator implements Iterator<int[]>
1452 // start position to iterate from
1455 // end position to iterate to
1458 // current index in hiddenColumns
1459 private int currentPosition = 0;
1461 // current column in hiddenColumns
1462 private int[] nextRegion = null;
1464 // Constructor with bounds
1465 RegionsIterator(int lowerBound, int upperBound)
1467 init(lowerBound, upperBound);
1470 // Unbounded constructor
1473 if (hiddenColumns != null)
1475 // iterator over full hiddenColumns collection
1476 int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1487 * Construct an iterator over hiddenColums bounded at
1488 * [lowerBound,upperBound]
1491 * lower bound to iterate from
1493 * upper bound to iterate to
1495 private void init(int lowerBound, int upperBound)
1500 if (hiddenColumns != null)
1502 // iterate until a region overlaps with [start,end]
1503 currentPosition = 0;
1504 while ((currentPosition < hiddenColumns.size())
1505 && (hiddenColumns.get(currentPosition)[1] < start))
1509 if (currentPosition < hiddenColumns.size())
1511 nextRegion = hiddenColumns.get(currentPosition);
1517 public boolean hasNext()
1519 return (hiddenColumns != null) && (nextRegion != null)
1520 && (nextRegion[0] <= end);
1526 int[] region = nextRegion;
1528 if (currentPosition < hiddenColumns.size())
1530 nextRegion = hiddenColumns.get(currentPosition);
1542 * A local iterator which reverse iterates over hidden column regions in a
1543 * range. Intended for use ONLY within the HiddenColumns class, because it
1544 * works directly with the hiddenColumns collection without locking (callers
1545 * should lock hiddenColumns).
1547 private class ReverseRegionsIterator implements Iterator<int[]>
1549 // start position to iterate to
1552 // end position to iterate from
1555 // current index in hiddenColumns
1556 private int currentPosition = 0;
1558 // current column in hiddenColumns
1559 private int[] nextRegion = null;
1561 // Constructor with bounds
1562 ReverseRegionsIterator(int lowerBound, int upperBound)
1564 init(lowerBound, upperBound);
1567 // Unbounded constructor
1568 ReverseRegionsIterator()
1570 if (hiddenColumns != null)
1572 // iterator over full hiddenColumns collection
1573 int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1584 * Construct an iterator over hiddenColums bounded at
1585 * [lowerBound,upperBound]
1588 * lower bound to iterate to
1590 * upper bound to iterate from
1592 private void init(int lowerBound, int upperBound)
1597 if (hiddenColumns != null)
1599 // iterate until a region overlaps with [start,end]
1600 currentPosition = hiddenColumns.size() - 1;
1601 while (currentPosition >= 0
1602 && hiddenColumns.get(currentPosition)[1] > end)
1606 if (currentPosition >= 0)
1608 nextRegion = hiddenColumns.get(currentPosition);
1614 public boolean hasNext()
1616 return (hiddenColumns != null) && (nextRegion != null)
1617 && (nextRegion[1] >= start);
1623 int[] region = nextRegion;
1625 if (currentPosition >= 0)
1627 nextRegion = hiddenColumns.get(currentPosition);
1639 * An iterator which iterates over hidden column regions in a range. Works
1640 * with a copy of the hidden columns collection. Intended to be used by
1641 * callers OUTSIDE of HiddenColumns.
1643 private class BoundedHiddenColsIterator implements Iterator<int[]>
1645 // start position to iterate from
1648 // end position to iterate to
1651 // current index in hiddenColumns
1652 private int currentPosition = 0;
1654 // current column in hiddenColumns
1655 private int[] currentRegion;
1657 // local copy or reference to hiddenColumns
1658 private List<int[]> localHidden;
1661 * Unbounded constructor
1663 BoundedHiddenColsIterator()
1665 if (hiddenColumns != null)
1667 int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1677 * Construct an iterator over hiddenColums bounded at
1678 * [lowerBound,upperBound]
1681 * lower bound to iterate from
1683 * upper bound to iterate to
1685 BoundedHiddenColsIterator(int lowerBound, int upperBound)
1687 init(lowerBound, upperBound);
1691 * Construct an iterator over hiddenColums bounded at
1692 * [lowerBound,upperBound]
1695 * lower bound to iterate from
1697 * upper bound to iterate to
1699 private void init(int lowerBound, int upperBound)
1706 LOCK.readLock().lock();
1708 if (hiddenColumns != null)
1710 localHidden = new ArrayList<>();
1712 // iterate until a region overlaps with [start,end]
1714 while ((i < hiddenColumns.size())
1715 && (hiddenColumns.get(i)[1] < start))
1720 // iterate from start to end, adding each hidden region. Positions are
1721 // absolute, and all regions which *overlap* [start,end] are added.
1722 while (i < hiddenColumns.size()
1723 && (hiddenColumns.get(i)[0] <= end))
1725 int[] rh = hiddenColumns.get(i);
1726 int[] cp = new int[2];
1727 System.arraycopy(rh, 0, cp, 0, rh.length);
1728 localHidden.add(cp);
1735 LOCK.readLock().unlock();
1740 public boolean hasNext()
1742 return (localHidden != null)
1743 && (currentPosition < localHidden.size());
1749 currentRegion = localHidden.get(currentPosition);
1751 return currentRegion;
1756 * An iterator which iterates over visible start positions of hidden column
1757 * regions in a range.
1759 private class BoundedStartRegionIterator implements Iterator<Integer>
1761 // start position to iterate from
1764 // end position to iterate to
1767 // current index in hiddenColumns
1768 private int currentPosition = 0;
1770 // local copy or reference to hiddenColumns
1771 private List<Integer> positions = null;
1774 * Construct an iterator over hiddenColums bounded at
1775 * [lowerBound,upperBound]
1778 * lower bound to iterate from
1780 * upper bound to iterate to
1781 * @param useCopyCols
1782 * whether to make a local copy of hiddenColumns for iteration (set
1783 * to true if calling from outwith the HiddenColumns class)
1785 BoundedStartRegionIterator(int lowerBound, int upperBound,
1795 // assume that if useCopy is false the calling code has locked
1797 LOCK.readLock().lock();
1800 if (hiddenColumns != null)
1802 positions = new ArrayList<>(hiddenColumns.size());
1804 // navigate to start, keeping count of hidden columns
1806 int hiddenSoFar = 0;
1807 while ((i < hiddenColumns.size())
1808 && (hiddenColumns.get(i)[0] < start + hiddenSoFar))
1810 int[] region = hiddenColumns.get(i);
1811 hiddenSoFar += region[1] - region[0] + 1;
1815 // iterate from start to end, adding start positions of each
1816 // hidden region. Positions are visible columns count, not absolute
1817 while (i < hiddenColumns.size()
1818 && (hiddenColumns.get(i)[0] <= end + hiddenSoFar))
1820 int[] region = hiddenColumns.get(i);
1821 positions.add(region[0] - hiddenSoFar);
1822 hiddenSoFar += region[1] - region[0] + 1;
1828 positions = new ArrayList<>();
1834 LOCK.readLock().unlock();
1840 public boolean hasNext()
1842 return (currentPosition < positions.size());
1846 * Get next hidden region start position
1848 * @return the start position in *visible* coordinates
1851 public Integer next()
1853 int result = positions.get(currentPosition);
1860 * Iterator over the visible *columns* (not regions) as determined by the set
1861 * of hidden columns. Uses a local copy of hidden columns.
1866 private class VisibleColsIterator implements Iterator<Integer>
1870 private int current;
1874 private List<int[]> localHidden = new ArrayList<>();
1876 private int nexthiddenregion;
1878 VisibleColsIterator(int firstcol, int lastcol)
1883 nexthiddenregion = 0;
1885 LOCK.readLock().lock();
1887 if (hiddenColumns != null)
1890 for (i = 0; i < hiddenColumns.size()
1891 && (current <= hiddenColumns.get(i)[0]); ++i)
1893 if (current >= hiddenColumns.get(i)[0]
1894 && current <= hiddenColumns.get(i)[1])
1896 // current is hidden, move to right
1897 current = hiddenColumns.get(i)[1] + 1;
1899 nexthiddenregion = i + 1;
1903 for (i = hiddenColumns.size() - 1; i >= 0
1904 && (last >= hiddenColumns.get(i)[1]); --i)
1906 if (last >= hiddenColumns.get(i)[0]
1907 && last <= hiddenColumns.get(i)[1])
1909 // last is hidden, move to left
1910 last = hiddenColumns.get(i)[0] - 1;
1914 // make a local copy of the bit we need
1915 i = nexthiddenregion;
1916 while (i < hiddenColumns.size() && hiddenColumns.get(i)[0] <= last)
1918 int[] region = new int[] { hiddenColumns.get(i)[0],
1919 hiddenColumns.get(i)[1] };
1920 localHidden.add(region);
1925 LOCK.readLock().unlock();
1929 public boolean hasNext()
1931 return next <= last;
1935 public Integer next()
1939 throw new NoSuchElementException();
1942 if ((localHidden != null)
1943 && (nexthiddenregion < localHidden.size()))
1945 // still some more hidden regions
1946 if (next + 1 < localHidden.get(nexthiddenregion)[0])
1948 // next+1 is still before the next hidden region
1951 else if ((next + 1 >= localHidden.get(nexthiddenregion)[0])
1952 && (next + 1 <= localHidden.get(nexthiddenregion)[1]))
1954 // next + 1 is in the next hidden region
1955 next = localHidden.get(nexthiddenregion)[1] + 1;
1961 // finished with hidden regions, just increment normally
1968 public void remove()
1970 throw new UnsupportedOperationException();
1975 * An iterator which iterates over visible regions in a range.
1977 private class VisibleContigsIterator implements Iterator<int[]>
1979 private List<int[]> vcontigs = new ArrayList<>();
1981 private int currentPosition = 0;
1983 VisibleContigsIterator(int start, int end, boolean usecopy)
1989 LOCK.readLock().lock();
1992 if (hiddenColumns != null && hiddenColumns.size() > 0)
1998 for (int[] region : hiddenColumns)
2000 hideStart = region[0];
2001 hideEnd = region[1];
2003 // navigate to start
2004 if (hideEnd < vstart)
2008 if (hideStart > vstart)
2010 int[] contig = new int[] { vstart, hideStart - 1 };
2011 vcontigs.add(contig);
2013 vstart = hideEnd + 1;
2015 // exit if we're past the end
2024 int[] contig = new int[] { vstart, end - 1 };
2025 vcontigs.add(contig);
2030 int[] contig = new int[] { start, end - 1 };
2031 vcontigs.add(contig);
2037 LOCK.readLock().unlock();
2043 public boolean hasNext()
2045 return (currentPosition < vcontigs.size());
2051 int[] result = vcontigs.get(currentPosition);
2058 * An iterator which iterates over visible regions in a range. The range is
2059 * specified in terms of visible column positions. Provides a special
2060 * "endsAtHidden" indicator to allow callers to determine if the final visible
2061 * column is adjacent to a hidden region.
2063 public class VisibleBlocksVisBoundsIterator implements Iterator<int[]>
2065 private List<int[]> vcontigs = new ArrayList<>();
2067 private int currentPosition = 0;
2069 private boolean endsAtHidden = false;
2072 * Constructor for iterator over visible regions in a range.
2075 * start position in terms of visible column position
2077 * end position in terms of visible column position
2079 * whether to use a local copy of hidden columns
2081 VisibleBlocksVisBoundsIterator(int start, int end, boolean usecopy)
2083 /* actually this implementation always uses a local copy but this may change in future */
2088 LOCK.readLock().lock();
2091 if (hiddenColumns != null && hiddenColumns.size() > 0)
2093 int blockStart = start;
2095 int hiddenSoFar = 0;
2098 // iterate until a region begins within (start,end]
2100 while ((i < hiddenColumns.size())
2101 && (hiddenColumns.get(i)[0] <= blockStart + hiddenSoFar))
2103 hiddenSoFar += hiddenColumns.get(i)[1] - hiddenColumns.get(i)[0]
2108 blockStart += hiddenSoFar; // convert start to absolute position
2109 blockEnd += hiddenSoFar; // convert end to absolute position
2111 // iterate from start to end, adding each visible region. Positions
2113 // absolute, and all hidden regions which overlap [start,end] are
2115 while (i < hiddenColumns.size()
2116 && (hiddenColumns.get(i)[0] <= blockEnd))
2118 int[] region = hiddenColumns.get(i);
2120 // end position of this visible region is either just before the
2121 // start of the next hidden region, or the absolute position of
2122 // 'end', whichever is lowest
2123 blockEnd = Math.min(blockEnd, region[0] - 1);
2125 vcontigs.add(new int[] { blockStart, blockEnd });
2127 visSoFar += blockEnd - blockStart + 1;
2129 // next visible region starts after this hidden region
2130 blockStart = region[1] + 1;
2132 hiddenSoFar += region[1] - region[0] + 1;
2134 // reset blockEnd to absolute position of 'end', assuming we've now
2135 // passed all hidden regions before end
2136 blockEnd = end + hiddenSoFar;
2140 if (visSoFar < end - start)
2142 // the number of visible columns we've accounted for is less than
2143 // the number specified by end-start; work out the end position of
2144 // the last visible region
2145 blockEnd = blockStart + end - start - visSoFar;
2146 vcontigs.add(new int[] { blockStart, blockEnd });
2148 // if the last visible region ends at the next hidden region, set
2149 // endsAtHidden=true
2150 if (i < hiddenColumns.size()
2151 && hiddenColumns.get(i)[0] - 1 == blockEnd)
2153 endsAtHidden = true;
2159 // there are no hidden columns, return a single visible contig
2160 vcontigs.add(new int[] { start, end });
2161 endsAtHidden = false;
2167 LOCK.readLock().unlock();
2173 public boolean hasNext()
2175 return (currentPosition < vcontigs.size());
2181 int[] result = vcontigs.get(currentPosition);
2186 public boolean endsAtHidden()
2188 return endsAtHidden;