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.Vector;
29 import java.util.concurrent.locks.ReentrantReadWriteLock;
31 public class HiddenColumns
33 private static final int HASH_MULTIPLIER = 31;
35 private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
38 * list of hidden column [start, end] ranges; the list is maintained in
39 * ascending start column order
41 private ArrayList<int[]> hiddenColumns;
46 public HiddenColumns()
55 public HiddenColumns(HiddenColumns copy)
59 LOCK.writeLock().lock();
62 if (copy.hiddenColumns != null)
64 hiddenColumns = copy.copyHiddenRegionsToArrayList(0);
69 LOCK.writeLock().unlock();
74 * Copy constructor within bounds and with offset. Copies hidden column
75 * regions fully contained between start and end, and offsets positions by
79 * HiddenColumns instance to copy from
81 * lower bound to copy from
83 * upper bound to copy to
85 * offset to subtract from each region boundary position
88 public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
92 LOCK.writeLock().lock();
95 hiddenColumns = new ArrayList<>();
96 Iterator<int[]> it = copy.getBoundedIterator(start, end);
99 int[] region = it.next();
100 // still need to check boundaries because iterator returns
101 // all overlapping regions and we need contained regions
102 if (region[0] >= start && region[1] <= end)
106 { region[0] - offset, region[1] - offset });
112 LOCK.writeLock().unlock();
117 * Output regions data as a string. String is in the format:
118 * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
121 * string to delimit regions
122 * @param betweenstring
123 * to put between start and end region values
124 * @return regions formatted according to delimiter and between strings
126 public String regionsToString(String delimiter, String between)
130 LOCK.readLock().lock();
131 StringBuilder regionBuilder = new StringBuilder();
132 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
135 int[] range = it.next();
136 regionBuilder.append(delimiter).append(range[0]).append(between)
140 regionBuilder.deleteCharAt(0);
143 return regionBuilder.toString();
146 LOCK.readLock().unlock();
151 * Find the number of hidden columns
153 * @return number of hidden columns
159 LOCK.readLock().lock();
161 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
164 int[] range = it.next();
165 size += range[1] - range[0] + 1;
171 LOCK.readLock().unlock();
176 * Get the number of distinct hidden regions
178 * @return number of regions
180 public int getNumberOfRegions()
184 LOCK.readLock().lock();
186 if (hasHiddenColumns())
188 num = hiddenColumns.size();
193 LOCK.readLock().unlock();
198 public boolean equals(Object obj)
202 LOCK.readLock().lock();
204 if (!(obj instanceof HiddenColumns))
208 HiddenColumns that = (HiddenColumns) obj;
211 * check hidden columns are either both null, or match
213 if (this.hiddenColumns == null)
215 return (that.hiddenColumns == null);
217 if (that.hiddenColumns == null
218 || that.hiddenColumns.size() != this.hiddenColumns.size())
223 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
224 Iterator<int[]> thatit = that.iterator();
227 int[] thisRange = it.next();
228 int[] thatRange = thatit.next();
229 if (thisRange[0] != thatRange[0] || thisRange[1] != thatRange[1])
237 LOCK.readLock().unlock();
242 * Return absolute column index for a visible column index
245 * int column index in alignment view (count from zero)
246 * @return alignment column index for column
248 public int adjustForHiddenColumns(int column)
252 LOCK.readLock().lock();
255 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
258 int[] region = it.next();
259 if (result >= region[0])
261 result += region[1] - region[0] + 1;
268 LOCK.readLock().unlock();
273 * Use this method to find out where a column will appear in the visible
274 * alignment when hidden columns exist. If the column is not visible, then the
275 * left-most visible column will always be returned.
277 * @param hiddenColumn
278 * the column index in the full alignment including hidden columns
279 * @return the position of the column in the visible alignment
281 public int findColumnPosition(int hiddenColumn)
285 LOCK.readLock().lock();
286 int result = hiddenColumn;
288 if (hiddenColumns != null)
290 Iterator<int[]> it = new LocalBoundedHiddenColsIterator(0,
295 if (hiddenColumn > region[1])
297 result -= region[1] + 1 - region[0];
301 if (region != null && hiddenColumn >= region[0]
302 && hiddenColumn <= region[1])
304 // Here the hidden column is within a region, so
305 // we want to return the position of region[0]-1, adjusted for any
306 // earlier hidden columns.
307 // Calculate the difference between the actual hidden col position
308 // and region[0]-1, and then subtract from result to convert result
310 // the adjusted hiddenColumn value to the adjusted region[0]-1 value
312 // However, if the region begins at 0 we cannot return region[0]-1
320 return result - (hiddenColumn - region[0] + 1);
324 return result; // return the shifted position after removing hidden
328 LOCK.readLock().unlock();
333 * Find the visible column which is a given visible number of columns to the
334 * left of another visible column. i.e. for a startColumn x, the column which
335 * is distance 1 away will be column x-1.
337 * @param visibleDistance
338 * the number of visible columns to offset by
340 * the column to start from
341 * @return the position of the column in the visible alignment
343 public int subtractVisibleColumns(int visibleDistance, int startColumn)
348 LOCK.readLock().lock();
349 int distance = visibleDistance;
351 // in case startColumn is in a hidden region, move it to the left
352 int start = adjustForHiddenColumns(findColumnPosition(startColumn));
354 // get index of hidden region to left of start
355 int index = getHiddenIndexLeft(start);
358 // no hidden regions to left of startColumn
359 return start - distance;
362 // walk backwards through the alignment subtracting the counts of visible
363 // columns from distance
366 int nextstart = start;
368 while ((index > -1) && (distance - gap > 0))
370 // subtract the gap to right of region from distance
374 // calculate the next gap
375 region = hiddenColumns.get(index);
376 gap = start - region[1];
378 // set start to just to left of current region
379 nextstart = region[0] - 1;
383 if (distance - gap > 0)
385 // fell out of loop because there are no more hidden regions
387 return nextstart - distance;
389 return start - distance;
392 LOCK.readLock().unlock();
400 * This method returns the rightmost limit of a region of an alignment with
401 * hidden columns. In otherwords, the next hidden column.
406 public int getHiddenBoundaryRight(int alPos)
410 LOCK.readLock().lock();
411 if (hiddenColumns != null)
416 int[] region = hiddenColumns.get(index);
417 if (alPos < region[0])
423 } while (index < hiddenColumns.size());
429 LOCK.readLock().unlock();
435 * This method returns the leftmost limit of a region of an alignment with
436 * hidden columns. In otherwords, the previous hidden column.
441 public int getHiddenBoundaryLeft(int alPos)
445 LOCK.readLock().lock();
447 if (hiddenColumns != null)
449 int index = hiddenColumns.size() - 1;
452 int[] region = hiddenColumns.get(index);
453 if (alPos > region[1])
459 } while (index > -1);
465 LOCK.readLock().unlock();
470 * This method returns the index of the hidden region to the left of a column
471 * position. If the column is in a hidden region it returns the index of the
472 * region to the left. If there is no hidden region to the left it returns -1.
477 private int getHiddenIndexLeft(int pos)
482 LOCK.readLock().lock();
483 if (hiddenColumns != null)
485 int index = hiddenColumns.size() - 1;
488 int[] region = hiddenColumns.get(index);
495 } while (index > -1);
501 LOCK.readLock().unlock();
507 * Adds the specified column range to the hidden columns
512 public void hideColumns(int start, int end)
514 boolean wasAlreadyLocked = false;
517 // check if the write lock was already locked by this thread,
518 // as this method can be called internally in loops within HiddenColumns
519 if (!LOCK.isWriteLockedByCurrentThread())
521 LOCK.writeLock().lock();
525 wasAlreadyLocked = true;
528 if (hiddenColumns == null)
530 hiddenColumns = new ArrayList<>();
534 * new range follows everything else; check first to avoid looping over whole hiddenColumns collection
536 if (hiddenColumns.isEmpty()
537 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
539 hiddenColumns.add(new int[] { start, end });
544 * traverse existing hidden ranges and insert / amend / append as
547 boolean added = false;
548 for (int i = 0; !added && i < hiddenColumns.size(); i++)
550 int[] region = hiddenColumns.get(i);
552 if (end < region[0] - 1)
555 * insert discontiguous preceding range
557 hiddenColumns.add(i, new int[] { start, end });
560 else if (end <= region[1])
563 * new range overlaps existing, or is contiguous preceding it - adjust
566 region[0] = Math.min(region[0], start);
569 else if (start <= region[1] + 1)
572 * new range overlaps existing, or is contiguous following it - adjust
573 * start and end columns
575 region[0] = Math.min(region[0], start);
576 region[1] = Math.max(region[1], end);
579 * also update or remove any subsequent ranges
580 * that are overlapped
582 while (i < hiddenColumns.size() - 1)
584 int[] nextRegion = hiddenColumns.get(i + 1);
585 if (nextRegion[0] > end + 1)
588 * gap to next hidden range - no more to update
592 region[1] = Math.max(nextRegion[1], end);
593 hiddenColumns.remove(i + 1);
601 if (!wasAlreadyLocked)
603 LOCK.writeLock().unlock();
608 public boolean isVisible(int column)
612 LOCK.readLock().lock();
614 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
617 int[] region = it.next();
618 if (column >= region[0] && column <= region[1])
627 LOCK.readLock().unlock();
631 private ArrayList<int[]> copyHiddenRegionsToArrayList(int startIndex)
634 if (hiddenColumns != null)
636 size = hiddenColumns.size();
638 ArrayList<int[]> copy = new ArrayList<>(size);
640 for (int i = startIndex, j = size; i < j; i++)
644 rh = hiddenColumns.get(i);
647 cp = new int[rh.length];
648 System.arraycopy(rh, 0, cp, 0, rh.length);
656 public String[] getVisibleSequenceStrings(int start, int end,
661 LOCK.readLock().lock();
662 int iSize = seqs.length;
663 String[] selections = new String[iSize];
664 if (hiddenColumns != null && hiddenColumns.size() > 0)
666 for (int i = 0; i < iSize; i++)
668 StringBuffer visibleSeq = new StringBuffer();
670 Iterator<int[]> blocks = new VisibleContigsIterator(start,
673 while (blocks.hasNext())
675 int[] block = blocks.next();
676 if (blocks.hasNext())
679 .append(seqs[i].getSequence(block[0], block[1] + 1));
684 .append(seqs[i].getSequence(block[0], block[1]));
688 selections[i] = visibleSeq.toString();
693 for (int i = 0; i < iSize; i++)
695 selections[i] = seqs[i].getSequenceAsString(start, end);
702 LOCK.readLock().unlock();
707 * Locate the first position visible for this sequence. If seq isn't visible
708 * then return the position of the left side of the hidden boundary region.
711 * sequence to find position for
712 * @return visible start position
714 public int locateVisibleStartOfSequence(SequenceI seq)
718 LOCK.readLock().lock();
721 if (hiddenColumns == null || hiddenColumns.size() == 0)
723 return seq.findIndex(seq.getStart()) - 1;
726 // Simply walk along the sequence whilst watching for hidden column
728 Iterator<int[]> regions = new LocalBoundedHiddenColsIterator();
729 int hideStart = seq.getLength();
733 boolean foundStart = false;
735 // step through the non-gapped positions of the sequence
736 for (int i = seq.getStart(); i <= seq.getEnd() && (!foundStart); i++)
738 // get alignment position of this residue in the sequence
739 int p = seq.findIndex(i) - 1;
741 // update hidden region start/end
742 while (hideEnd < p && regions.hasNext())
744 int[] region = regions.next();
746 visNext += region[0] - visPrev;
747 hideStart = region[0];
752 hideStart = seq.getLength();
754 // update visible boundary for sequence
764 return findColumnPosition(start);
766 // otherwise, sequence was completely hidden
770 LOCK.readLock().unlock();
775 * delete any columns in alignmentAnnotation that are hidden (including
776 * sequence associated annotation).
778 * @param alignmentAnnotation
780 public void makeVisibleAnnotation(AlignmentAnnotation alignmentAnnotation)
782 makeVisibleAnnotation(0, alignmentAnnotation.annotations.length,
783 alignmentAnnotation);
787 * delete any columns in alignmentAnnotation that are hidden (including
788 * sequence associated annotation).
791 * remove any annotation to the right of this column
793 * remove any annotation to the left of this column
794 * @param alignmentAnnotation
795 * the annotation to operate on
797 public void makeVisibleAnnotation(int start, int end,
798 AlignmentAnnotation alignmentAnnotation)
802 LOCK.readLock().lock();
804 int startFrom = start;
807 if (alignmentAnnotation.annotations != null)
809 if (hiddenColumns != null && hiddenColumns.size() > 0)
811 removeHiddenAnnotation(startFrom, endAt, alignmentAnnotation);
815 alignmentAnnotation.restrict(startFrom, endAt);
820 LOCK.readLock().unlock();
824 private void removeHiddenAnnotation(int start, int end,
825 AlignmentAnnotation alignmentAnnotation)
827 // mangle the alignmentAnnotation annotation array
828 Vector<Annotation[]> annels = new Vector<>();
829 Annotation[] els = null;
833 Iterator<int[]> blocks = new VisibleContigsIterator(start, end + 1,
837 int annotationLength;
838 while (blocks.hasNext())
840 int[] block = blocks.next();
841 annotationLength = block[1] - block[0] + 1;
843 if (blocks.hasNext())
845 // copy just the visible segment of the annotation row
846 copylength = annotationLength;
850 if (annotationLength + block[0] <= alignmentAnnotation.annotations.length)
852 // copy just the visible segment of the annotation row
853 copylength = annotationLength;
857 // copy to the end of the annotation row
858 copylength = alignmentAnnotation.annotations.length - block[0];
862 els = new Annotation[annotationLength];
863 annels.addElement(els);
864 System.arraycopy(alignmentAnnotation.annotations, block[0], els, 0,
866 w += annotationLength;
871 alignmentAnnotation.annotations = new Annotation[w];
874 for (Annotation[] chnk : annels)
876 System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
885 * @return true if there are columns hidden
887 public boolean hasHiddenColumns()
891 LOCK.readLock().lock();
892 return hiddenColumns != null && hiddenColumns.size() > 0;
895 LOCK.readLock().unlock();
901 * @return true if there are more than one set of columns hidden
903 public boolean hasManyHiddenColumns()
907 LOCK.readLock().lock();
908 return hiddenColumns != null && hiddenColumns.size() > 1;
911 LOCK.readLock().unlock();
916 * mark the columns corresponding to gap characters as hidden in the column
921 public void hideInsertionsFor(SequenceI sr)
925 LOCK.writeLock().lock();
926 List<int[]> inserts = sr.getInsertions();
927 for (int[] r : inserts)
929 hideColumns(r[0], r[1]);
933 LOCK.writeLock().unlock();
938 * Unhides, and adds to the selection list, all hidden columns
940 public void revealAllHiddenColumns(ColumnSelection sel)
944 LOCK.writeLock().lock();
945 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
948 int[] region = it.next();
949 for (int j = region[0]; j < region[1] + 1; j++)
955 hiddenColumns = null;
958 LOCK.writeLock().unlock();
963 * Reveals, and marks as selected, the hidden column range with the given
968 public void revealHiddenColumns(int start, ColumnSelection sel)
972 LOCK.writeLock().lock();
973 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
976 int[] region = it.next();
977 if (start == region[0])
979 for (int j = region[0]; j < region[1] + 1; j++)
984 hiddenColumns.remove(region);
987 else if (start < region[0])
989 break; // passed all possible matching regions
993 if (hiddenColumns.size() == 0)
995 hiddenColumns = null;
999 LOCK.writeLock().unlock();
1004 * Add gaps into the sequences aligned to profileseq under the given
1009 * - alignment to have gaps inserted into it
1011 * - alignment view where sequence corresponding to profileseq is
1013 * @return new HiddenColumns for new alignment view, with insertions into
1014 * profileseq marked as hidden.
1016 public static HiddenColumns propagateInsertions(SequenceI profileseq,
1017 AlignmentI al, AlignmentView input)
1021 char gc = al.getGapCharacter();
1022 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1023 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1024 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1025 nview.propagateInsertions(profileseq, al, origseq);
1032 * - sequence in al which corresponds to origseq
1034 * - alignment which is to have gaps inserted into it
1036 * - sequence corresponding to profileseq which defines gap map for
1039 private void propagateInsertions(SequenceI profileseq, AlignmentI al,
1044 LOCK.writeLock().lock();
1046 char gc = al.getGapCharacter();
1048 // take the set of hidden columns, and the set of gaps in origseq,
1049 // and remove all the hidden gaps from hiddenColumns
1051 // first get the gaps as a Bitset
1052 BitSet gaps = origseq.gapBitset();
1054 // now calculate hidden ^ not(gap)
1055 BitSet hidden = new BitSet();
1056 markHiddenRegions(hidden);
1057 hidden.andNot(gaps);
1058 hiddenColumns = null;
1059 this.hideMarkedBits(hidden);
1061 // for each sequence in the alignment, except the profile sequence,
1062 // insert gaps corresponding to each hidden region
1063 // but where each hidden column region is shifted backwards by the number
1065 // preceding visible gaps
1066 // update hidden columns at the same time
1067 Iterator<int[]> regions = new LocalBoundedHiddenColsIterator();
1068 ArrayList<int[]> newhidden = new ArrayList<>();
1070 int numGapsBefore = 0;
1071 int gapPosition = 0;
1072 while (regions.hasNext())
1074 // get region coordinates accounting for gaps
1075 // we can rely on gaps not being *in* hidden regions because we already
1077 int[] region = regions.next();
1078 while (gapPosition < region[0])
1081 if (gaps.get(gapPosition))
1087 int left = region[0] - numGapsBefore;
1088 int right = region[1] - numGapsBefore;
1089 newhidden.add(new int[] { left, right });
1091 // make a string with number of gaps = length of hidden region
1092 StringBuffer sb = new StringBuffer();
1093 for (int s = 0; s < right - left + 1; s++)
1097 padGaps(sb, left, profileseq, al);
1100 hiddenColumns = newhidden;
1103 LOCK.writeLock().unlock();
1108 * Pad gaps in all sequences in alignment except profileseq
1111 * gap string to insert
1113 * position to insert at
1115 * sequence not to pad
1117 * alignment to pad sequences in
1119 private void padGaps(StringBuffer sb, int pos, SequenceI profileseq,
1122 // loop over the sequences and pad with gaps where required
1123 for (int s = 0, ns = al.getHeight(); s < ns; s++)
1125 SequenceI sqobj = al.getSequenceAt(s);
1126 if (sqobj != profileseq)
1128 String sq = al.getSequenceAt(s).getSequenceAsString();
1129 if (sq.length() <= pos)
1132 int diff = pos - sq.length() - 1;
1137 while ((diff = pos - sq.length() - 1) > 0)
1139 if (diff >= sb.length())
1141 sq += sb.toString();
1145 char[] buf = new char[diff];
1146 sb.getChars(0, diff, buf, 0);
1147 sq += buf.toString();
1151 sq += sb.toString();
1155 al.getSequenceAt(s).setSequence(
1156 sq.substring(0, pos) + sb.toString() + sq.substring(pos));
1163 * Returns a hashCode built from hidden column ranges
1166 public int hashCode()
1170 LOCK.readLock().lock();
1172 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
1173 while (it.hasNext())
1175 int[] hidden = it.next();
1176 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
1177 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
1182 LOCK.readLock().unlock();
1187 * Hide columns corresponding to the marked bits
1190 * - columns map to bits starting from zero
1192 public void hideMarkedBits(BitSet inserts)
1196 LOCK.writeLock().lock();
1197 for (int firstSet = inserts
1198 .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
1199 .nextSetBit(lastSet))
1201 lastSet = inserts.nextClearBit(firstSet);
1202 hideColumns(firstSet, lastSet - 1);
1206 LOCK.writeLock().unlock();
1213 * BitSet where hidden columns will be marked
1215 public void markHiddenRegions(BitSet inserts)
1219 LOCK.readLock().lock();
1220 if (hiddenColumns == null)
1224 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
1225 while (it.hasNext())
1227 int[] range = it.next();
1228 inserts.set(range[0], range[1] + 1);
1232 LOCK.readLock().unlock();
1237 * Calculate the visible start and end index of an alignment.
1240 * full alignment width
1241 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
1243 public int[] getVisibleStartAndEndIndex(int width)
1247 LOCK.readLock().lock();
1248 int[] alignmentStartEnd = new int[] { 0, width - 1 };
1249 int startPos = alignmentStartEnd[0];
1250 int endPos = alignmentStartEnd[1];
1252 int[] lowestRange = new int[] { -1, -1 };
1253 int[] higestRange = new int[] { -1, -1 };
1255 if (hiddenColumns == null)
1257 return new int[] { startPos, endPos };
1260 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
1261 while (it.hasNext())
1263 int[] range = it.next();
1264 lowestRange = (range[0] <= startPos) ? range : lowestRange;
1265 higestRange = (range[1] >= endPos) ? range : higestRange;
1268 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1270 startPos = alignmentStartEnd[0];
1274 startPos = lowestRange[1] + 1;
1277 if (higestRange[0] == -1 && higestRange[1] == -1)
1279 endPos = alignmentStartEnd[1];
1283 endPos = higestRange[0] - 1;
1285 return new int[] { startPos, endPos };
1288 LOCK.readLock().unlock();
1294 * Finds the hidden region (if any) which starts or ends at res
1297 * visible residue position, unadjusted for hidden columns
1298 * @return region as [start,end] or null if no matching region is found
1300 public int[] getRegionWithEdgeAtRes(int res)
1304 LOCK.readLock().lock();
1305 int adjres = adjustForHiddenColumns(res);
1307 int[] reveal = null;
1308 Iterator<int[]> it = new LocalBoundedHiddenColsIterator(adjres - 2,
1310 while (it.hasNext())
1312 int[] region = it.next();
1313 if (adjres + 1 == region[0] || adjres - 1 == region[1])
1322 LOCK.readLock().unlock();
1327 * Return an iterator over the hidden regions
1329 public Iterator<int[]> iterator()
1331 return new BoundedHiddenColsIterator();
1335 * Return a bounded iterator over the hidden regions
1338 * position to start from (inclusive, absolute column position)
1340 * position to end at (inclusive, absolute column position)
1343 public Iterator<int[]> getBoundedIterator(int start, int end)
1345 return new BoundedHiddenColsIterator(start, end);
1349 * Return a bounded iterator over the *visible* start positions of hidden
1353 * position to start from (inclusive, visible column position)
1355 * position to end at (inclusive, visible column position)
1357 public Iterator<Integer> getBoundedStartIterator(int start, int end)
1359 return new BoundedStartRegionIterator(start, end, true);
1363 * Return an iterator over visible *columns* (not regions) between the given
1364 * start and end boundaries
1367 * first column (inclusive)
1369 * last column (inclusive)
1371 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1373 return new VisibleColsIterator(start, end);
1377 * return an iterator over visible segments between the given start and end
1381 * (first column inclusive from 0)
1383 * (last column - not inclusive)
1385 public Iterator<int[]> getVisContigsIterator(int start, int end)
1387 // return new VisibleBlocksIterator(start, end, true)
1388 return new VisibleContigsIterator(start, end, true);
1392 * return an iterator over visible segments between the given start and end
1396 * (first column - inclusive from 0)
1398 * (last column - inclusive)
1399 * @param useVisibleCoords
1400 * if true, start and end are visible column positions, not absolute
1403 public Iterator<int[]> getVisibleBlocksIterator(int start, int end,
1404 boolean useVisibleCoords)
1406 if (useVisibleCoords)
1409 // we should really just convert start and end here with
1410 // adjustForHiddenColumns
1411 // and then create a VisibleContigsIterator
1412 // but without a cursor this will be horribly slow in some situations
1413 // ... so until then...
1414 return new VisibleBlocksVisBoundsIterator(start, end, true);
1418 return new VisibleContigsIterator(start, end - 1, true);
1423 * A local iterator which iterates over hidden column regions in a range.
1424 * Works with the actual hidden columns collection (so locking before use may
1427 private class LocalBoundedHiddenColsIterator implements Iterator<int[]>
1429 private int start; // start position to iterate from
1431 private int end; // end position to iterate to
1433 // current index in hiddenColumns
1434 private int currentPosition = 0;
1436 // current column in hiddenColumns
1437 private int[] nextRegion = null;
1439 LocalBoundedHiddenColsIterator(int lowerBound, int upperBound)
1441 init(lowerBound, upperBound);
1444 LocalBoundedHiddenColsIterator()
1446 if (hiddenColumns != null)
1448 int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1458 * Construct an iterator over hiddenColums bounded at
1459 * [lowerBound,upperBound]
1462 * lower bound to iterate from
1464 * upper bound to iterate to
1465 * @param useCopyCols
1466 * whether to make a local copy of hiddenColumns for iteration (set
1467 * to true if calling from outwith the HiddenColumns class)
1469 private void init(int lowerBound, int upperBound)
1474 if (hiddenColumns != null)
1476 // iterate until a region overlaps with [start,end]
1477 currentPosition = 0;
1478 while ((currentPosition < hiddenColumns.size())
1479 && (hiddenColumns.get(currentPosition)[1] < start))
1483 if (currentPosition < hiddenColumns.size())
1485 nextRegion = hiddenColumns.get(currentPosition);
1491 public boolean hasNext()
1493 return (hiddenColumns != null) && (nextRegion != null)
1494 && (nextRegion[0] <= end);
1500 int[] region = nextRegion;
1502 if (currentPosition < hiddenColumns.size())
1504 nextRegion = hiddenColumns.get(currentPosition);
1516 * An iterator which iterates over hidden column regions in a range. Works
1517 * with a copy of the hidden columns collection.
1519 private class BoundedHiddenColsIterator implements Iterator<int[]>
1521 private int start; // start position to iterate from
1523 private int end; // end position to iterate to
1525 // current index in hiddenColumns
1526 private int currentPosition = 0;
1528 // current column in hiddenColumns
1529 private int[] currentRegion;
1531 // local copy or reference to hiddenColumns
1532 private List<int[]> localHidden;
1534 BoundedHiddenColsIterator()
1536 if (hiddenColumns != null)
1538 int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1548 * Construct an iterator over hiddenColums bounded at
1549 * [lowerBound,upperBound]
1552 * lower bound to iterate from
1554 * upper bound to iterate to
1556 BoundedHiddenColsIterator(int lowerBound, int upperBound)
1558 init(lowerBound, upperBound);
1562 * Construct an iterator over hiddenColums bounded at
1563 * [lowerBound,upperBound]
1566 * lower bound to iterate from
1568 * upper bound to iterate to
1570 private void init(int lowerBound, int upperBound)
1577 LOCK.readLock().lock();
1579 if (hiddenColumns != null)
1581 localHidden = new ArrayList<>();
1583 // iterate until a region overlaps with [start,end]
1585 while ((i < hiddenColumns.size())
1586 && (hiddenColumns.get(i)[1] < start))
1591 // iterate from start to end, adding each hidden region. Positions are
1592 // absolute, and all regions which *overlap* [start,end] are added.
1593 while (i < hiddenColumns.size()
1594 && (hiddenColumns.get(i)[0] <= end))
1596 int[] rh = hiddenColumns.get(i);
1597 int[] cp = new int[2];
1598 System.arraycopy(rh, 0, cp, 0, rh.length);
1599 localHidden.add(cp);
1606 LOCK.readLock().unlock();
1611 public boolean hasNext()
1613 return (localHidden != null)
1614 && (currentPosition < localHidden.size());
1620 currentRegion = localHidden.get(currentPosition);
1622 return currentRegion;
1627 * An iterator which iterates over visible start positions of hidden column
1628 * regions in a range.
1630 private class BoundedStartRegionIterator implements Iterator<Integer>
1632 // start position to iterate from
1635 // end position to iterate to
1638 // current index in hiddenColumns
1639 private int currentPosition = 0;
1641 // local copy or reference to hiddenColumns
1642 private List<Integer> positions = null;
1645 * Construct an iterator over hiddenColums bounded at
1646 * [lowerBound,upperBound]
1649 * lower bound to iterate from
1651 * upper bound to iterate to
1652 * @param useCopyCols
1653 * whether to make a local copy of hiddenColumns for iteration (set
1654 * to true if calling from outwith the HiddenColumns class)
1656 BoundedStartRegionIterator(int lowerBound, int upperBound,
1666 // assume that if useCopy is false the calling code has locked
1668 LOCK.readLock().lock();
1671 if (hiddenColumns != null)
1673 positions = new ArrayList<>(hiddenColumns.size());
1675 // navigate to start, keeping count of hidden columns
1677 int hiddenSoFar = 0;
1678 while ((i < hiddenColumns.size())
1679 && (hiddenColumns.get(i)[0] < start + hiddenSoFar))
1681 int[] region = hiddenColumns.get(i);
1682 hiddenSoFar += region[1] - region[0] + 1;
1686 // iterate from start to end, adding start positions of each
1687 // hidden region. Positions are visible columns count, not absolute
1688 while (i < hiddenColumns.size()
1689 && (hiddenColumns.get(i)[0] <= end + hiddenSoFar))
1691 int[] region = hiddenColumns.get(i);
1692 positions.add(region[0] - hiddenSoFar);
1693 hiddenSoFar += region[1] - region[0] + 1;
1699 positions = new ArrayList<>();
1705 LOCK.readLock().unlock();
1711 public boolean hasNext()
1713 return (currentPosition < positions.size());
1717 * Get next hidden region start position
1719 * @return the start position in *visible* coordinates
1722 public Integer next()
1724 int result = positions.get(currentPosition);
1731 * Iterator over the visible *columns* (not regions) as determined by the set
1732 * of hidden columns. Uses a local copy of hidden columns.
1737 private class VisibleColsIterator implements Iterator<Integer>
1741 private int current;
1745 private List<int[]> localHidden = new ArrayList<>();
1747 private int nexthiddenregion;
1749 VisibleColsIterator(int firstcol, int lastcol)
1754 nexthiddenregion = 0;
1756 LOCK.readLock().lock();
1758 if (hiddenColumns != null)
1761 for (i = 0; i < hiddenColumns.size()
1762 && (current <= hiddenColumns.get(i)[0]); ++i)
1764 if (current >= hiddenColumns.get(i)[0]
1765 && current <= hiddenColumns.get(i)[1])
1767 // current is hidden, move to right
1768 current = hiddenColumns.get(i)[1] + 1;
1770 nexthiddenregion = i + 1;
1774 for (i = hiddenColumns.size() - 1; i >= 0
1775 && (last >= hiddenColumns.get(i)[1]); --i)
1777 if (last >= hiddenColumns.get(i)[0]
1778 && last <= hiddenColumns.get(i)[1])
1780 // last is hidden, move to left
1781 last = hiddenColumns.get(i)[0] - 1;
1785 // make a local copy of the bit we need
1786 i = nexthiddenregion;
1787 while (i < hiddenColumns.size() && hiddenColumns.get(i)[0] <= last)
1789 int[] region = new int[] { hiddenColumns.get(i)[0],
1790 hiddenColumns.get(i)[1] };
1791 localHidden.add(region);
1796 LOCK.readLock().unlock();
1800 public boolean hasNext()
1802 return next <= last;
1806 public Integer next()
1810 throw new NoSuchElementException();
1813 if ((localHidden != null)
1814 && (nexthiddenregion < localHidden.size()))
1816 // still some more hidden regions
1817 if (next + 1 < localHidden.get(nexthiddenregion)[0])
1819 // next+1 is still before the next hidden region
1822 else if ((next + 1 >= localHidden.get(nexthiddenregion)[0])
1823 && (next + 1 <= localHidden.get(nexthiddenregion)[1]))
1825 // next + 1 is in the next hidden region
1826 next = localHidden.get(nexthiddenregion)[1] + 1;
1832 // finished with hidden regions, just increment normally
1839 public void remove()
1841 throw new UnsupportedOperationException();
1846 * An iterator which iterates over visible regions in a range.
1848 private class VisibleContigsIterator implements Iterator<int[]>
1850 private List<int[]> vcontigs = new ArrayList<>();
1852 private int currentPosition = 0;
1854 VisibleContigsIterator(int start, int end, boolean usecopy)
1860 LOCK.readLock().lock();
1863 if (hiddenColumns != null && hiddenColumns.size() > 0)
1869 for (int[] region : hiddenColumns)
1871 hideStart = region[0];
1872 hideEnd = region[1];
1874 // navigate to start
1875 if (hideEnd < vstart)
1879 if (hideStart > vstart)
1881 int[] contig = new int[] { vstart, hideStart - 1 };
1882 vcontigs.add(contig);
1884 vstart = hideEnd + 1;
1886 // exit if we're past the end
1895 int[] contig = new int[] { vstart, end - 1 };
1896 vcontigs.add(contig);
1901 int[] contig = new int[] { start, end - 1 };
1902 vcontigs.add(contig);
1908 LOCK.readLock().unlock();
1914 public boolean hasNext()
1916 return (currentPosition < vcontigs.size());
1922 int[] result = vcontigs.get(currentPosition);
1929 * An iterator which iterates over visible regions in a range. The range is
1930 * specified in terms of visible column positions. Provides a special
1931 * "endsAtHidden" indicator to allow callers to determine if the final visible
1932 * column is adjacent to a hidden region.
1934 public class VisibleBlocksVisBoundsIterator implements Iterator<int[]>
1936 private List<int[]> vcontigs = new ArrayList<>();
1938 private int currentPosition = 0;
1940 private boolean endsAtHidden = false;
1943 * Constructor for iterator over visible regions in a range.
1946 * start position in terms of visible column position
1948 * end position in terms of visible column position
1950 * whether to use a local copy of hidden columns
1952 VisibleBlocksVisBoundsIterator(int start, int end, boolean usecopy)
1954 /* actually this implementation always uses a local copy but this may change in future */
1959 LOCK.readLock().lock();
1962 if (hiddenColumns != null && hiddenColumns.size() > 0)
1964 int blockStart = start;
1966 int hiddenSoFar = 0;
1969 // iterate until a region begins within (start,end]
1971 while ((i < hiddenColumns.size())
1972 && (hiddenColumns.get(i)[0] <= blockStart + hiddenSoFar))
1974 hiddenSoFar += hiddenColumns.get(i)[1] - hiddenColumns.get(i)[0]
1979 blockStart += hiddenSoFar; // convert start to absolute position
1980 blockEnd += hiddenSoFar; // convert end to absolute position
1982 // iterate from start to end, adding each visible region. Positions
1984 // absolute, and all hidden regions which overlap [start,end] are
1986 while (i < hiddenColumns.size()
1987 && (hiddenColumns.get(i)[0] <= blockEnd))
1989 int[] region = hiddenColumns.get(i);
1991 // end position of this visible region is either just before the
1992 // start of the next hidden region, or the absolute position of
1993 // 'end', whichever is lowest
1994 blockEnd = Math.min(blockEnd, region[0] - 1);
1996 vcontigs.add(new int[] { blockStart, blockEnd });
1998 visSoFar += blockEnd - blockStart + 1;
2000 // next visible region starts after this hidden region
2001 blockStart = region[1] + 1;
2003 hiddenSoFar += region[1] - region[0] + 1;
2005 // reset blockEnd to absolute position of 'end', assuming we've now
2006 // passed all hidden regions before end
2007 blockEnd = end + hiddenSoFar;
2011 if (visSoFar < end - start)
2013 // the number of visible columns we've accounted for is less than
2014 // the number specified by end-start; work out the end position of
2015 // the last visible region
2016 blockEnd = blockStart + end - start - visSoFar;
2017 vcontigs.add(new int[] { blockStart, blockEnd });
2019 // if the last visible region ends at the next hidden region, set
2020 // endsAtHidden=true
2021 if (i < hiddenColumns.size()
2022 && hiddenColumns.get(i)[0] - 1 == blockEnd)
2024 endsAtHidden = true;
2030 // there are no hidden columns, return a single visible contig
2031 vcontigs.add(new int[] { start, end });
2032 endsAtHidden = false;
2038 LOCK.readLock().unlock();
2044 public boolean hasNext()
2046 return (currentPosition < vcontigs.size());
2052 int[] result = vcontigs.get(currentPosition);
2057 public boolean endsAtHidden()
2059 return endsAtHidden;