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 LocalBoundedHiddenColsIterator();
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 LocalBoundedHiddenColsIterator();
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 LocalBoundedHiddenColsIterator();
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 LocalBoundedHiddenColsIterator();
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 LocalBoundedHiddenColsIterator(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 // get index of hidden region to left of start
354 int index = getHiddenIndexLeft(start);
357 // no hidden regions to left of startColumn
358 return start - distance;
361 // walk backwards through the alignment subtracting the counts of visible
362 // columns from distance
365 int nextstart = start;
367 while ((index > -1) && (distance - gap > 0))
369 // subtract the gap to right of region from distance
373 // calculate the next gap
374 region = hiddenColumns.get(index);
375 gap = start - region[1];
377 // set start to just to left of current region
378 nextstart = region[0] - 1;
382 if (distance - gap > 0)
384 // fell out of loop because there are no more hidden regions
386 return nextstart - distance;
388 return start - distance;
391 LOCK.readLock().unlock();
399 * This method returns the rightmost limit of a region of an alignment with
400 * hidden columns. In otherwords, the next hidden column.
405 public int getHiddenBoundaryRight(int alPos)
409 LOCK.readLock().lock();
410 if (hiddenColumns != null)
415 int[] region = hiddenColumns.get(index);
416 if (alPos < region[0])
422 } while (index < hiddenColumns.size());
428 LOCK.readLock().unlock();
434 * This method returns the leftmost limit of a region of an alignment with
435 * hidden columns. In otherwords, the previous hidden column.
440 public int getHiddenBoundaryLeft(int alPos)
444 LOCK.readLock().lock();
446 if (hiddenColumns != null)
448 int index = hiddenColumns.size() - 1;
451 int[] region = hiddenColumns.get(index);
452 if (alPos > region[1])
458 } while (index > -1);
464 LOCK.readLock().unlock();
469 * This method returns the index of the hidden region to the left of a column
470 * position. If the column is in a hidden region it returns the index of the
471 * region to the left. If there is no hidden region to the left it returns -1.
476 private int getHiddenIndexLeft(int pos)
481 LOCK.readLock().lock();
482 if (hiddenColumns != null)
484 int index = hiddenColumns.size() - 1;
487 int[] region = hiddenColumns.get(index);
494 } while (index > -1);
500 LOCK.readLock().unlock();
506 * Adds the specified column range to the hidden columns
511 public void hideColumns(int start, int end)
513 boolean wasAlreadyLocked = false;
516 // check if the write lock was already locked by this thread,
517 // as this method can be called internally in loops within HiddenColumns
518 if (!LOCK.isWriteLockedByCurrentThread())
520 LOCK.writeLock().lock();
524 wasAlreadyLocked = true;
527 if (hiddenColumns == null)
529 hiddenColumns = new ArrayList<>();
533 * new range follows everything else; check first to avoid looping over whole hiddenColumns collection
535 if (hiddenColumns.isEmpty()
536 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
538 hiddenColumns.add(new int[] { start, end });
543 * traverse existing hidden ranges and insert / amend / append as
546 boolean added = false;
547 for (int i = 0; !added && i < hiddenColumns.size(); i++)
549 int[] region = hiddenColumns.get(i);
551 if (end < region[0] - 1)
554 * insert discontiguous preceding range
556 hiddenColumns.add(i, new int[] { start, end });
559 else if (end <= region[1])
562 * new range overlaps existing, or is contiguous preceding it - adjust
565 region[0] = Math.min(region[0], start);
568 else if (start <= region[1] + 1)
571 * new range overlaps existing, or is contiguous following it - adjust
572 * start and end columns
574 region[0] = Math.min(region[0], start);
575 region[1] = Math.max(region[1], end);
578 * also update or remove any subsequent ranges
579 * that are overlapped
581 while (i < hiddenColumns.size() - 1)
583 int[] nextRegion = hiddenColumns.get(i + 1);
584 if (nextRegion[0] > end + 1)
587 * gap to next hidden range - no more to update
591 region[1] = Math.max(nextRegion[1], end);
592 hiddenColumns.remove(i + 1);
600 if (!wasAlreadyLocked)
602 LOCK.writeLock().unlock();
607 public boolean isVisible(int column)
611 LOCK.readLock().lock();
613 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
616 int[] region = it.next();
617 if (column >= region[0] && column <= region[1])
626 LOCK.readLock().unlock();
630 private ArrayList<int[]> copyHiddenRegionsToArrayList(int startIndex)
633 if (hiddenColumns != null)
635 size = hiddenColumns.size();
637 ArrayList<int[]> copy = new ArrayList<>(size);
639 for (int i = startIndex, j = size; i < j; i++)
643 rh = hiddenColumns.get(i);
646 cp = new int[rh.length];
647 System.arraycopy(rh, 0, cp, 0, rh.length);
655 public String[] getVisibleSequenceStrings(int start, int end,
660 LOCK.readLock().lock();
661 int iSize = seqs.length;
662 String[] selections = new String[iSize];
663 if (hiddenColumns != null && hiddenColumns.size() > 0)
665 for (int i = 0; i < iSize; i++)
667 StringBuffer visibleSeq = new StringBuffer();
669 Iterator<int[]> blocks = new VisibleContigsIterator(start,
672 while (blocks.hasNext())
674 int[] block = blocks.next();
675 if (blocks.hasNext())
678 .append(seqs[i].getSequence(block[0], block[1] + 1));
683 .append(seqs[i].getSequence(block[0], block[1]));
687 selections[i] = visibleSeq.toString();
692 for (int i = 0; i < iSize; i++)
694 selections[i] = seqs[i].getSequenceAsString(start, end);
701 LOCK.readLock().unlock();
706 * Locate the first position visible for this sequence. If seq isn't visible
707 * then return the position of the left side of the hidden boundary region.
710 * sequence to find position for
711 * @return visible start position
713 public int locateVisibleStartOfSequence(SequenceI seq)
717 LOCK.readLock().lock();
720 if (hiddenColumns == null || hiddenColumns.size() == 0)
722 return seq.findIndex(seq.getStart()) - 1;
725 // Simply walk along the sequence whilst watching for hidden column
727 Iterator<int[]> regions = new LocalBoundedHiddenColsIterator();
728 int hideStart = seq.getLength();
732 boolean foundStart = false;
734 // step through the non-gapped positions of the sequence
735 for (int i = seq.getStart(); i <= seq.getEnd() && (!foundStart); i++)
737 // get alignment position of this residue in the sequence
738 int p = seq.findIndex(i) - 1;
740 // update hidden region start/end
741 while (hideEnd < p && regions.hasNext())
743 int[] region = regions.next();
745 visNext += region[0] - visPrev;
746 hideStart = region[0];
751 hideStart = seq.getLength();
753 // update visible boundary for sequence
763 return findColumnPosition(start);
765 // otherwise, sequence was completely hidden
769 LOCK.readLock().unlock();
774 * delete any columns in alignmentAnnotation that are hidden (including
775 * sequence associated annotation).
777 * @param alignmentAnnotation
779 public void makeVisibleAnnotation(AlignmentAnnotation alignmentAnnotation)
781 makeVisibleAnnotation(0, alignmentAnnotation.annotations.length,
782 alignmentAnnotation);
786 * delete any columns in alignmentAnnotation that are hidden (including
787 * sequence associated annotation).
790 * remove any annotation to the right of this column
792 * remove any annotation to the left of this column
793 * @param alignmentAnnotation
794 * the annotation to operate on
796 public void makeVisibleAnnotation(int start, int end,
797 AlignmentAnnotation alignmentAnnotation)
801 LOCK.readLock().lock();
803 int startFrom = start;
806 if (alignmentAnnotation.annotations != null)
808 if (hiddenColumns != null && hiddenColumns.size() > 0)
810 removeHiddenAnnotation(startFrom, endAt, alignmentAnnotation);
814 alignmentAnnotation.restrict(startFrom, endAt);
819 LOCK.readLock().unlock();
823 private void removeHiddenAnnotation(int start, int end,
824 AlignmentAnnotation alignmentAnnotation)
826 // mangle the alignmentAnnotation annotation array
827 ArrayList<Annotation[]> annels = new ArrayList<>();
828 Annotation[] els = null;
832 Iterator<int[]> blocks = new VisibleContigsIterator(start, end + 1,
836 int annotationLength;
837 while (blocks.hasNext())
839 int[] block = blocks.next();
840 annotationLength = block[1] - block[0] + 1;
842 if (blocks.hasNext())
844 // copy just the visible segment of the annotation row
845 copylength = annotationLength;
849 if (annotationLength + block[0] <= alignmentAnnotation.annotations.length)
851 // copy just the visible segment of the annotation row
852 copylength = annotationLength;
856 // copy to the end of the annotation row
857 copylength = alignmentAnnotation.annotations.length - block[0];
861 els = new Annotation[annotationLength];
863 System.arraycopy(alignmentAnnotation.annotations, block[0], els, 0,
865 w += annotationLength;
870 alignmentAnnotation.annotations = new Annotation[w];
873 for (Annotation[] chnk : annels)
875 System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
884 * @return true if there are columns hidden
886 public boolean hasHiddenColumns()
890 LOCK.readLock().lock();
891 return hiddenColumns != null && hiddenColumns.size() > 0;
894 LOCK.readLock().unlock();
900 * @return true if there are more than one set of columns hidden
902 public boolean hasManyHiddenColumns()
906 LOCK.readLock().lock();
907 return hiddenColumns != null && hiddenColumns.size() > 1;
910 LOCK.readLock().unlock();
915 * mark the columns corresponding to gap characters as hidden in the column
920 public void hideInsertionsFor(SequenceI sr)
924 LOCK.writeLock().lock();
925 List<int[]> inserts = sr.getInsertions();
926 for (int[] r : inserts)
928 hideColumns(r[0], r[1]);
932 LOCK.writeLock().unlock();
937 * Unhides, and adds to the selection list, all hidden columns
939 public void revealAllHiddenColumns(ColumnSelection sel)
943 LOCK.writeLock().lock();
944 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
947 int[] region = it.next();
948 for (int j = region[0]; j < region[1] + 1; j++)
954 hiddenColumns = null;
957 LOCK.writeLock().unlock();
962 * Reveals, and marks as selected, the hidden column range with the given
967 public void revealHiddenColumns(int start, ColumnSelection sel)
971 LOCK.writeLock().lock();
972 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
975 int[] region = it.next();
976 if (start == region[0])
978 for (int j = region[0]; j < region[1] + 1; j++)
983 hiddenColumns.remove(region);
986 else if (start < region[0])
988 break; // passed all possible matching regions
992 if (hiddenColumns.size() == 0)
994 hiddenColumns = null;
998 LOCK.writeLock().unlock();
1003 * Add gaps into the sequences aligned to profileseq under the given
1008 * - alignment to have gaps inserted into it
1010 * - alignment view where sequence corresponding to profileseq is
1012 * @return new HiddenColumns for new alignment view, with insertions into
1013 * profileseq marked as hidden.
1015 public static HiddenColumns propagateInsertions(SequenceI profileseq,
1016 AlignmentI al, AlignmentView input)
1020 char gc = al.getGapCharacter();
1021 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1022 HiddenColumns nview = (HiddenColumns) alandhidden[1];
1023 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1024 nview.propagateInsertions(profileseq, al, origseq);
1031 * - sequence in al which corresponds to origseq
1033 * - alignment which is to have gaps inserted into it
1035 * - sequence corresponding to profileseq which defines gap map for
1038 private void propagateInsertions(SequenceI profileseq, AlignmentI al,
1043 LOCK.writeLock().lock();
1045 char gc = al.getGapCharacter();
1047 // take the set of hidden columns, and the set of gaps in origseq,
1048 // and remove all the hidden gaps from hiddenColumns
1050 // first get the gaps as a Bitset
1051 BitSet gaps = origseq.gapBitset();
1053 // now calculate hidden ^ not(gap)
1054 BitSet hidden = new BitSet();
1055 markHiddenRegions(hidden);
1056 hidden.andNot(gaps);
1057 hiddenColumns = null;
1058 this.hideMarkedBits(hidden);
1060 // for each sequence in the alignment, except the profile sequence,
1061 // insert gaps corresponding to each hidden region
1062 // but where each hidden column region is shifted backwards by the number
1064 // preceding visible gaps
1065 // update hidden columns at the same time
1066 Iterator<int[]> regions = new LocalBoundedHiddenColsIterator();
1067 ArrayList<int[]> newhidden = new ArrayList<>();
1069 int numGapsBefore = 0;
1070 int gapPosition = 0;
1071 while (regions.hasNext())
1073 // get region coordinates accounting for gaps
1074 // we can rely on gaps not being *in* hidden regions because we already
1076 int[] region = regions.next();
1077 while (gapPosition < region[0])
1080 if (gaps.get(gapPosition))
1086 int left = region[0] - numGapsBefore;
1087 int right = region[1] - numGapsBefore;
1088 newhidden.add(new int[] { left, right });
1090 // make a string with number of gaps = length of hidden region
1091 StringBuffer sb = new StringBuffer();
1092 for (int s = 0; s < right - left + 1; s++)
1096 padGaps(sb, left, profileseq, al);
1099 hiddenColumns = newhidden;
1102 LOCK.writeLock().unlock();
1107 * Pad gaps in all sequences in alignment except profileseq
1110 * gap string to insert
1112 * position to insert at
1114 * sequence not to pad
1116 * alignment to pad sequences in
1118 private void padGaps(StringBuffer sb, int pos, SequenceI profileseq,
1121 // loop over the sequences and pad with gaps where required
1122 for (int s = 0, ns = al.getHeight(); s < ns; s++)
1124 SequenceI sqobj = al.getSequenceAt(s);
1125 if (sqobj != profileseq)
1127 String sq = al.getSequenceAt(s).getSequenceAsString();
1128 if (sq.length() <= pos)
1131 int diff = pos - sq.length() - 1;
1136 while ((diff = pos - sq.length() - 1) > 0)
1138 if (diff >= sb.length())
1140 sq += sb.toString();
1144 char[] buf = new char[diff];
1145 sb.getChars(0, diff, buf, 0);
1146 sq += buf.toString();
1150 sq += sb.toString();
1154 al.getSequenceAt(s).setSequence(
1155 sq.substring(0, pos) + sb.toString() + sq.substring(pos));
1162 * Returns a hashCode built from hidden column ranges
1165 public int hashCode()
1169 LOCK.readLock().lock();
1171 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
1172 while (it.hasNext())
1174 int[] hidden = it.next();
1175 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
1176 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
1181 LOCK.readLock().unlock();
1186 * Hide columns corresponding to the marked bits
1189 * - columns map to bits starting from zero
1191 public void hideMarkedBits(BitSet inserts)
1195 LOCK.writeLock().lock();
1196 for (int firstSet = inserts
1197 .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
1198 .nextSetBit(lastSet))
1200 lastSet = inserts.nextClearBit(firstSet);
1201 hideColumns(firstSet, lastSet - 1);
1205 LOCK.writeLock().unlock();
1212 * BitSet where hidden columns will be marked
1214 public void markHiddenRegions(BitSet inserts)
1218 LOCK.readLock().lock();
1219 if (hiddenColumns == null)
1223 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
1224 while (it.hasNext())
1226 int[] range = it.next();
1227 inserts.set(range[0], range[1] + 1);
1231 LOCK.readLock().unlock();
1236 * Calculate the visible start and end index of an alignment.
1239 * full alignment width
1240 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
1242 public int[] getVisibleStartAndEndIndex(int width)
1246 LOCK.readLock().lock();
1247 int[] alignmentStartEnd = new int[] { 0, width - 1 };
1248 int startPos = alignmentStartEnd[0];
1249 int endPos = alignmentStartEnd[1];
1251 int[] lowestRange = new int[] { -1, -1 };
1252 int[] higestRange = new int[] { -1, -1 };
1254 if (hiddenColumns == null)
1256 return new int[] { startPos, endPos };
1259 Iterator<int[]> it = new LocalBoundedHiddenColsIterator();
1260 while (it.hasNext())
1262 int[] range = it.next();
1263 lowestRange = (range[0] <= startPos) ? range : lowestRange;
1264 higestRange = (range[1] >= endPos) ? range : higestRange;
1267 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1269 startPos = alignmentStartEnd[0];
1273 startPos = lowestRange[1] + 1;
1276 if (higestRange[0] == -1 && higestRange[1] == -1)
1278 endPos = alignmentStartEnd[1];
1282 endPos = higestRange[0] - 1;
1284 return new int[] { startPos, endPos };
1287 LOCK.readLock().unlock();
1293 * Finds the hidden region (if any) which starts or ends at res
1296 * visible residue position, unadjusted for hidden columns
1297 * @return region as [start,end] or null if no matching region is found
1299 public int[] getRegionWithEdgeAtRes(int res)
1303 LOCK.readLock().lock();
1304 int adjres = adjustForHiddenColumns(res);
1306 int[] reveal = null;
1307 Iterator<int[]> it = new LocalBoundedHiddenColsIterator(adjres - 2,
1309 while (it.hasNext())
1311 int[] region = it.next();
1312 if (adjres + 1 == region[0] || adjres - 1 == region[1])
1321 LOCK.readLock().unlock();
1326 * Return an iterator over the hidden regions
1328 public Iterator<int[]> iterator()
1330 return new BoundedHiddenColsIterator();
1334 * Return a bounded iterator over the hidden regions
1337 * position to start from (inclusive, absolute column position)
1339 * position to end at (inclusive, absolute column position)
1342 public Iterator<int[]> getBoundedIterator(int start, int end)
1344 return new BoundedHiddenColsIterator(start, end);
1348 * Return a bounded iterator over the *visible* start positions of hidden
1352 * position to start from (inclusive, visible column position)
1354 * position to end at (inclusive, visible column position)
1356 public Iterator<Integer> getBoundedStartIterator(int start, int end)
1358 return new BoundedStartRegionIterator(start, end, true);
1362 * Return an iterator over visible *columns* (not regions) between the given
1363 * start and end boundaries
1366 * first column (inclusive)
1368 * last column (inclusive)
1370 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1372 return new VisibleColsIterator(start, end);
1376 * return an iterator over visible segments between the given start and end
1380 * (first column inclusive from 0)
1382 * (last column - not inclusive)
1384 public Iterator<int[]> getVisContigsIterator(int start, int end)
1386 // return new VisibleBlocksIterator(start, end, true)
1387 return new VisibleContigsIterator(start, end, true);
1391 * return an iterator over visible segments between the given start and end
1395 * (first column - inclusive from 0)
1397 * (last column - inclusive)
1398 * @param useVisibleCoords
1399 * if true, start and end are visible column positions, not absolute
1402 public Iterator<int[]> getVisibleBlocksIterator(int start, int end,
1403 boolean useVisibleCoords)
1405 if (useVisibleCoords)
1408 // we should really just convert start and end here with
1409 // adjustForHiddenColumns
1410 // and then create a VisibleContigsIterator
1411 // but without a cursor this will be horribly slow in some situations
1412 // ... so until then...
1413 return new VisibleBlocksVisBoundsIterator(start, end, true);
1417 return new VisibleContigsIterator(start, end - 1, true);
1422 * A local iterator which iterates over hidden column regions in a range.
1423 * Works with the actual hidden columns collection (so locking before use may
1426 private class LocalBoundedHiddenColsIterator implements Iterator<int[]>
1428 private int start; // start position to iterate from
1430 private int end; // end position to iterate to
1432 // current index in hiddenColumns
1433 private int currentPosition = 0;
1435 // current column in hiddenColumns
1436 private int[] nextRegion = null;
1438 LocalBoundedHiddenColsIterator(int lowerBound, int upperBound)
1440 init(lowerBound, upperBound);
1443 LocalBoundedHiddenColsIterator()
1445 if (hiddenColumns != null)
1447 int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1457 * Construct an iterator over hiddenColums bounded at
1458 * [lowerBound,upperBound]
1461 * lower bound to iterate from
1463 * upper bound to iterate to
1464 * @param useCopyCols
1465 * whether to make a local copy of hiddenColumns for iteration (set
1466 * to true if calling from outwith the HiddenColumns class)
1468 private void init(int lowerBound, int upperBound)
1473 if (hiddenColumns != null)
1475 // iterate until a region overlaps with [start,end]
1476 currentPosition = 0;
1477 while ((currentPosition < hiddenColumns.size())
1478 && (hiddenColumns.get(currentPosition)[1] < start))
1482 if (currentPosition < hiddenColumns.size())
1484 nextRegion = hiddenColumns.get(currentPosition);
1490 public boolean hasNext()
1492 return (hiddenColumns != null) && (nextRegion != null)
1493 && (nextRegion[0] <= end);
1499 int[] region = nextRegion;
1501 if (currentPosition < hiddenColumns.size())
1503 nextRegion = hiddenColumns.get(currentPosition);
1515 * An iterator which iterates over hidden column regions in a range. Works
1516 * with a copy of the hidden columns collection.
1518 private class BoundedHiddenColsIterator implements Iterator<int[]>
1520 private int start; // start position to iterate from
1522 private int end; // end position to iterate to
1524 // current index in hiddenColumns
1525 private int currentPosition = 0;
1527 // current column in hiddenColumns
1528 private int[] currentRegion;
1530 // local copy or reference to hiddenColumns
1531 private List<int[]> localHidden;
1533 BoundedHiddenColsIterator()
1535 if (hiddenColumns != null)
1537 int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1547 * Construct an iterator over hiddenColums bounded at
1548 * [lowerBound,upperBound]
1551 * lower bound to iterate from
1553 * upper bound to iterate to
1555 BoundedHiddenColsIterator(int lowerBound, int upperBound)
1557 init(lowerBound, upperBound);
1561 * Construct an iterator over hiddenColums bounded at
1562 * [lowerBound,upperBound]
1565 * lower bound to iterate from
1567 * upper bound to iterate to
1569 private void init(int lowerBound, int upperBound)
1576 LOCK.readLock().lock();
1578 if (hiddenColumns != null)
1580 localHidden = new ArrayList<>();
1582 // iterate until a region overlaps with [start,end]
1584 while ((i < hiddenColumns.size())
1585 && (hiddenColumns.get(i)[1] < start))
1590 // iterate from start to end, adding each hidden region. Positions are
1591 // absolute, and all regions which *overlap* [start,end] are added.
1592 while (i < hiddenColumns.size()
1593 && (hiddenColumns.get(i)[0] <= end))
1595 int[] rh = hiddenColumns.get(i);
1596 int[] cp = new int[2];
1597 System.arraycopy(rh, 0, cp, 0, rh.length);
1598 localHidden.add(cp);
1605 LOCK.readLock().unlock();
1610 public boolean hasNext()
1612 return (localHidden != null)
1613 && (currentPosition < localHidden.size());
1619 currentRegion = localHidden.get(currentPosition);
1621 return currentRegion;
1626 * An iterator which iterates over visible start positions of hidden column
1627 * regions in a range.
1629 private class BoundedStartRegionIterator implements Iterator<Integer>
1631 // start position to iterate from
1634 // end position to iterate to
1637 // current index in hiddenColumns
1638 private int currentPosition = 0;
1640 // local copy or reference to hiddenColumns
1641 private List<Integer> positions = null;
1644 * Construct an iterator over hiddenColums bounded at
1645 * [lowerBound,upperBound]
1648 * lower bound to iterate from
1650 * upper bound to iterate to
1651 * @param useCopyCols
1652 * whether to make a local copy of hiddenColumns for iteration (set
1653 * to true if calling from outwith the HiddenColumns class)
1655 BoundedStartRegionIterator(int lowerBound, int upperBound,
1665 // assume that if useCopy is false the calling code has locked
1667 LOCK.readLock().lock();
1670 if (hiddenColumns != null)
1672 positions = new ArrayList<>(hiddenColumns.size());
1674 // navigate to start, keeping count of hidden columns
1676 int hiddenSoFar = 0;
1677 while ((i < hiddenColumns.size())
1678 && (hiddenColumns.get(i)[0] < start + hiddenSoFar))
1680 int[] region = hiddenColumns.get(i);
1681 hiddenSoFar += region[1] - region[0] + 1;
1685 // iterate from start to end, adding start positions of each
1686 // hidden region. Positions are visible columns count, not absolute
1687 while (i < hiddenColumns.size()
1688 && (hiddenColumns.get(i)[0] <= end + hiddenSoFar))
1690 int[] region = hiddenColumns.get(i);
1691 positions.add(region[0] - hiddenSoFar);
1692 hiddenSoFar += region[1] - region[0] + 1;
1698 positions = new ArrayList<>();
1704 LOCK.readLock().unlock();
1710 public boolean hasNext()
1712 return (currentPosition < positions.size());
1716 * Get next hidden region start position
1718 * @return the start position in *visible* coordinates
1721 public Integer next()
1723 int result = positions.get(currentPosition);
1730 * Iterator over the visible *columns* (not regions) as determined by the set
1731 * of hidden columns. Uses a local copy of hidden columns.
1736 private class VisibleColsIterator implements Iterator<Integer>
1740 private int current;
1744 private List<int[]> localHidden = new ArrayList<>();
1746 private int nexthiddenregion;
1748 VisibleColsIterator(int firstcol, int lastcol)
1753 nexthiddenregion = 0;
1755 LOCK.readLock().lock();
1757 if (hiddenColumns != null)
1760 for (i = 0; i < hiddenColumns.size()
1761 && (current <= hiddenColumns.get(i)[0]); ++i)
1763 if (current >= hiddenColumns.get(i)[0]
1764 && current <= hiddenColumns.get(i)[1])
1766 // current is hidden, move to right
1767 current = hiddenColumns.get(i)[1] + 1;
1769 nexthiddenregion = i + 1;
1773 for (i = hiddenColumns.size() - 1; i >= 0
1774 && (last >= hiddenColumns.get(i)[1]); --i)
1776 if (last >= hiddenColumns.get(i)[0]
1777 && last <= hiddenColumns.get(i)[1])
1779 // last is hidden, move to left
1780 last = hiddenColumns.get(i)[0] - 1;
1784 // make a local copy of the bit we need
1785 i = nexthiddenregion;
1786 while (i < hiddenColumns.size() && hiddenColumns.get(i)[0] <= last)
1788 int[] region = new int[] { hiddenColumns.get(i)[0],
1789 hiddenColumns.get(i)[1] };
1790 localHidden.add(region);
1795 LOCK.readLock().unlock();
1799 public boolean hasNext()
1801 return next <= last;
1805 public Integer next()
1809 throw new NoSuchElementException();
1812 if ((localHidden != null)
1813 && (nexthiddenregion < localHidden.size()))
1815 // still some more hidden regions
1816 if (next + 1 < localHidden.get(nexthiddenregion)[0])
1818 // next+1 is still before the next hidden region
1821 else if ((next + 1 >= localHidden.get(nexthiddenregion)[0])
1822 && (next + 1 <= localHidden.get(nexthiddenregion)[1]))
1824 // next + 1 is in the next hidden region
1825 next = localHidden.get(nexthiddenregion)[1] + 1;
1831 // finished with hidden regions, just increment normally
1838 public void remove()
1840 throw new UnsupportedOperationException();
1845 * An iterator which iterates over visible regions in a range.
1847 private class VisibleContigsIterator implements Iterator<int[]>
1849 private List<int[]> vcontigs = new ArrayList<>();
1851 private int currentPosition = 0;
1853 VisibleContigsIterator(int start, int end, boolean usecopy)
1859 LOCK.readLock().lock();
1862 if (hiddenColumns != null && hiddenColumns.size() > 0)
1868 for (int[] region : hiddenColumns)
1870 hideStart = region[0];
1871 hideEnd = region[1];
1873 // navigate to start
1874 if (hideEnd < vstart)
1878 if (hideStart > vstart)
1880 int[] contig = new int[] { vstart, hideStart - 1 };
1881 vcontigs.add(contig);
1883 vstart = hideEnd + 1;
1885 // exit if we're past the end
1894 int[] contig = new int[] { vstart, end - 1 };
1895 vcontigs.add(contig);
1900 int[] contig = new int[] { start, end - 1 };
1901 vcontigs.add(contig);
1907 LOCK.readLock().unlock();
1913 public boolean hasNext()
1915 return (currentPosition < vcontigs.size());
1921 int[] result = vcontigs.get(currentPosition);
1928 * An iterator which iterates over visible regions in a range. The range is
1929 * specified in terms of visible column positions. Provides a special
1930 * "endsAtHidden" indicator to allow callers to determine if the final visible
1931 * column is adjacent to a hidden region.
1933 public class VisibleBlocksVisBoundsIterator implements Iterator<int[]>
1935 private List<int[]> vcontigs = new ArrayList<>();
1937 private int currentPosition = 0;
1939 private boolean endsAtHidden = false;
1942 * Constructor for iterator over visible regions in a range.
1945 * start position in terms of visible column position
1947 * end position in terms of visible column position
1949 * whether to use a local copy of hidden columns
1951 VisibleBlocksVisBoundsIterator(int start, int end, boolean usecopy)
1953 /* actually this implementation always uses a local copy but this may change in future */
1958 LOCK.readLock().lock();
1961 if (hiddenColumns != null && hiddenColumns.size() > 0)
1963 int blockStart = start;
1965 int hiddenSoFar = 0;
1968 // iterate until a region begins within (start,end]
1970 while ((i < hiddenColumns.size())
1971 && (hiddenColumns.get(i)[0] <= blockStart + hiddenSoFar))
1973 hiddenSoFar += hiddenColumns.get(i)[1] - hiddenColumns.get(i)[0]
1978 blockStart += hiddenSoFar; // convert start to absolute position
1979 blockEnd += hiddenSoFar; // convert end to absolute position
1981 // iterate from start to end, adding each visible region. Positions
1983 // absolute, and all hidden regions which overlap [start,end] are
1985 while (i < hiddenColumns.size()
1986 && (hiddenColumns.get(i)[0] <= blockEnd))
1988 int[] region = hiddenColumns.get(i);
1990 // end position of this visible region is either just before the
1991 // start of the next hidden region, or the absolute position of
1992 // 'end', whichever is lowest
1993 blockEnd = Math.min(blockEnd, region[0] - 1);
1995 vcontigs.add(new int[] { blockStart, blockEnd });
1997 visSoFar += blockEnd - blockStart + 1;
1999 // next visible region starts after this hidden region
2000 blockStart = region[1] + 1;
2002 hiddenSoFar += region[1] - region[0] + 1;
2004 // reset blockEnd to absolute position of 'end', assuming we've now
2005 // passed all hidden regions before end
2006 blockEnd = end + hiddenSoFar;
2010 if (visSoFar < end - start)
2012 // the number of visible columns we've accounted for is less than
2013 // the number specified by end-start; work out the end position of
2014 // the last visible region
2015 blockEnd = blockStart + end - start - visSoFar;
2016 vcontigs.add(new int[] { blockStart, blockEnd });
2018 // if the last visible region ends at the next hidden region, set
2019 // endsAtHidden=true
2020 if (i < hiddenColumns.size()
2021 && hiddenColumns.get(i)[0] - 1 == blockEnd)
2023 endsAtHidden = true;
2029 // there are no hidden columns, return a single visible contig
2030 vcontigs.add(new int[] { start, end });
2031 endsAtHidden = false;
2037 LOCK.readLock().unlock();
2043 public boolean hasNext()
2045 return (currentPosition < vcontigs.size());
2051 int[] result = vcontigs.get(currentPosition);
2056 public boolean endsAtHidden()
2058 return endsAtHidden;