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 = new ArrayList<>();
64 Iterator<int[]> it = copy.iterator();
67 hiddenColumns.add(it.next());
73 LOCK.writeLock().unlock();
78 * Copy constructor within bounds and with offset. Copies hidden column
79 * regions fully contained between start and end, and offsets positions by
83 * HiddenColumns instance to copy from
85 * lower bound to copy from
87 * upper bound to copy to
89 * offset to subtract from each region boundary position
92 public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
96 LOCK.writeLock().lock();
99 hiddenColumns = new ArrayList<>();
100 Iterator<int[]> it = copy.getBoundedIterator(start, end);
103 int[] region = it.next();
104 // still need to check boundaries because iterator returns
105 // all overlapping regions and we need contained regions
106 if (region[0] >= start && region[1] <= end)
110 { region[0] - offset, region[1] - offset });
116 LOCK.writeLock().unlock();
121 * Output regions data as a string. String is in the format:
122 * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
125 * string to delimit regions
126 * @param betweenstring
127 * to put between start and end region values
128 * @return regions formatted according to delimiter and between strings
130 public String regionsToString(String delimiter, String between)
134 LOCK.readLock().lock();
135 StringBuilder regionBuilder = new StringBuilder();
136 if (hiddenColumns != null)
138 Iterator<int[]> it = hiddenColumns.iterator();
141 int[] range = it.next();
142 regionBuilder.append(delimiter).append(range[0]).append(between)
146 regionBuilder.deleteCharAt(0);
150 return regionBuilder.toString();
153 LOCK.readLock().unlock();
158 * Find the number of hidden columns
160 * @return number of hidden columns
166 LOCK.readLock().lock();
168 if (hiddenColumns != null)
170 Iterator<int[]> it = hiddenColumns.iterator();
173 int[] range = it.next();
174 size += range[1] - range[0] + 1;
180 LOCK.readLock().unlock();
185 * Get the number of distinct hidden regions
187 * @return number of regions
189 public int getNumberOfRegions()
193 LOCK.readLock().lock();
195 if (hasHiddenColumns())
197 num = hiddenColumns.size();
202 LOCK.readLock().unlock();
207 public boolean equals(Object obj)
211 LOCK.readLock().lock();
213 if (!(obj instanceof HiddenColumns))
217 HiddenColumns that = (HiddenColumns) obj;
220 * check hidden columns are either both null, or match
222 if (this.hiddenColumns == null)
224 return (that.hiddenColumns == null);
226 if (that.hiddenColumns == null
227 || that.hiddenColumns.size() != this.hiddenColumns.size())
232 Iterator<int[]> it = hiddenColumns.iterator();
233 Iterator<int[]> thatit = that.iterator();
236 int[] thisRange = it.next();
237 int[] thatRange = thatit.next();
238 if (thisRange[0] != thatRange[0] || thisRange[1] != thatRange[1])
246 LOCK.readLock().unlock();
251 * Return absolute column index for a visible column index
254 * int column index in alignment view (count from zero)
255 * @return alignment column index for column
257 public int adjustForHiddenColumns(int column)
261 LOCK.readLock().lock();
264 if (hiddenColumns != null)
266 Iterator<int[]> it = hiddenColumns.iterator();
269 int[] region = it.next();
270 if (result >= region[0])
272 result += region[1] - region[0] + 1;
280 LOCK.readLock().unlock();
285 * Use this method to find out where a column will appear in the visible
286 * alignment when hidden columns exist. If the column is not visible, then the
287 * left-most visible column will always be returned.
289 * @param hiddenColumn
290 * the column index in the full alignment including hidden columns
291 * @return the position of the column in the visible alignment
293 public int findColumnPosition(int hiddenColumn)
297 LOCK.readLock().lock();
298 int result = hiddenColumn;
300 if (hiddenColumns != null)
302 Iterator<int[]> it = new RegionsIterator(0,
307 if (hiddenColumn > region[1])
309 result -= region[1] + 1 - region[0];
313 if (region != null && hiddenColumn >= region[0]
314 && hiddenColumn <= region[1])
316 // Here the hidden column is within a region, so
317 // we want to return the position of region[0]-1, adjusted for any
318 // earlier hidden columns.
319 // Calculate the difference between the actual hidden col position
320 // and region[0]-1, and then subtract from result to convert result
321 // from the adjusted hiddenColumn value to the adjusted region[0]-1
324 // However, if the region begins at 0 we cannot return region[0]-1
332 return result - (hiddenColumn - region[0] + 1);
336 return result; // return the shifted position after removing hidden
340 LOCK.readLock().unlock();
345 * Find the visible column which is a given visible number of columns to the
346 * left of another visible column. i.e. for a startColumn x, the column which
347 * is distance 1 away will be column x-1.
349 * @param visibleDistance
350 * the number of visible columns to offset by
352 * the column to start from
353 * @return the position of the column in the visible alignment
355 public int subtractVisibleColumns(int visibleDistance, int startColumn)
359 LOCK.readLock().lock();
360 int distance = visibleDistance;
362 // in case startColumn is in a hidden region, move it to the left
363 int start = adjustForHiddenColumns(findColumnPosition(startColumn));
365 Iterator<int[]> it = new ReverseRegionsIterator(0, start);
367 while (it.hasNext() && (distance > 0))
369 int[] region = it.next();
371 if (start > region[1])
373 // subtract the gap to right of region from distance
374 if (start - region[1] <= distance)
376 distance -= start - region[1];
377 start = region[0] - 1;
381 start = start - distance;
387 return start - distance;
391 LOCK.readLock().unlock();
396 * This method returns the rightmost limit of a region of an alignment with
397 * hidden columns. In otherwords, the next hidden column.
400 * the (visible) alignmentPosition to find the next hidden column for
402 public int getHiddenBoundaryRight(int alPos)
406 LOCK.readLock().lock();
407 if (hiddenColumns != null)
409 Iterator<int[]> it = hiddenColumns.iterator();
412 int[] region = it.next();
413 if (alPos < region[0])
422 LOCK.readLock().unlock();
427 * This method returns the leftmost limit of a region of an alignment with
428 * hidden columns. In otherwords, the previous hidden column.
431 * the (visible) alignmentPosition to find the previous hidden column
434 public int getHiddenBoundaryLeft(int alPos)
438 LOCK.readLock().lock();
440 Iterator<int[]> it = new ReverseRegionsIterator(0, alPos);
443 int[] region = it.next();
444 if (alPos > region[1])
453 LOCK.readLock().unlock();
458 * Adds the specified column range to the hidden columns collection
461 * start of range to add (absolute position in alignment)
463 * end of range to add (absolute position in alignment)
465 public void hideColumns(int start, int end)
467 boolean wasAlreadyLocked = false;
470 // check if the write lock was already locked by this thread,
471 // as this method can be called internally in loops within HiddenColumns
472 if (!LOCK.isWriteLockedByCurrentThread())
474 LOCK.writeLock().lock();
478 wasAlreadyLocked = true;
481 if (hiddenColumns == null)
483 hiddenColumns = new ArrayList<>();
487 * new range follows everything else; check first to avoid looping over whole hiddenColumns collection
489 if (hiddenColumns.isEmpty()
490 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
492 hiddenColumns.add(new int[] { start, end });
497 * traverse existing hidden ranges and insert / amend / append as
500 boolean added = false;
501 for (int i = 0; !added && i < hiddenColumns.size(); i++)
503 added = insertRangeAtRegion(i, start, end);
508 if (!wasAlreadyLocked)
510 LOCK.writeLock().unlock();
516 * Insert [start, range] at the region at index i in hiddenColumns, if
522 * start of range to insert
524 * end of range to insert
525 * @return true if range was successfully inserted
527 private boolean insertRangeAtRegion(int i, int start, int end)
529 boolean added = false;
531 int[] region = hiddenColumns.get(i);
532 if (end < region[0] - 1)
535 * insert discontiguous preceding range
537 hiddenColumns.add(i, new int[] { start, end });
540 else if (end <= region[1])
543 * new range overlaps existing, or is contiguous preceding it - adjust
546 region[0] = Math.min(region[0], start);
549 else if (start <= region[1] + 1)
552 * new range overlaps existing, or is contiguous following it - adjust
553 * start and end columns
555 region[0] = Math.min(region[0], start);
556 region[1] = Math.max(region[1], end);
559 * also update or remove any subsequent ranges
560 * that are overlapped
562 while (i < hiddenColumns.size() - 1)
564 int[] nextRegion = hiddenColumns.get(i + 1);
565 if (nextRegion[0] > end + 1)
568 * gap to next hidden range - no more to update
572 region[1] = Math.max(nextRegion[1], end);
573 hiddenColumns.subList(i + 1, i + 2).clear();
581 * Answers if a column in the alignment is visible
584 * absolute position of column in the alignment
585 * @return true if column is visible
587 public boolean isVisible(int column)
591 LOCK.readLock().lock();
593 Iterator<int[]> it = new RegionsIterator(column, column);
596 int[] region = it.next();
597 if (column >= region[0] && column <= region[1])
606 LOCK.readLock().unlock();
611 * Get the visible sections of a set of sequences
614 * sequence position to start from
616 * sequence position to end at
618 * an array of sequences
619 * @return an array of strings encoding the visible parts of each sequence
621 public String[] getVisibleSequenceStrings(int start, int end,
626 LOCK.readLock().lock();
627 int iSize = seqs.length;
628 String[] selections = new String[iSize];
629 if (hiddenColumns != null && hiddenColumns.size() > 0)
631 for (int i = 0; i < iSize; i++)
633 StringBuffer visibleSeq = new StringBuffer();
635 Iterator<int[]> blocks = new VisibleContigsIterator(start,
638 while (blocks.hasNext())
640 int[] block = blocks.next();
641 if (blocks.hasNext())
644 .append(seqs[i].getSequence(block[0], block[1] + 1));
649 .append(seqs[i].getSequence(block[0], block[1]));
653 selections[i] = visibleSeq.toString();
658 for (int i = 0; i < iSize; i++)
660 selections[i] = seqs[i].getSequenceAsString(start, end);
667 LOCK.readLock().unlock();
672 * Locate the first position visible for this sequence. If seq isn't visible
673 * then return the position of the left side of the hidden boundary region.
676 * sequence to find position for
677 * @return visible start position
679 public int locateVisibleStartOfSequence(SequenceI seq)
683 LOCK.readLock().lock();
686 if (hiddenColumns == null || hiddenColumns.size() == 0)
688 return seq.findIndex(seq.getStart()) - 1;
691 // Simply walk along the sequence whilst watching for hidden column
693 Iterator<int[]> regions = hiddenColumns.iterator();
694 int hideStart = seq.getLength();
698 boolean foundStart = false;
700 // step through the non-gapped positions of the sequence
701 for (int i = seq.getStart(); i <= seq.getEnd() && (!foundStart); i++)
703 // get alignment position of this residue in the sequence
704 int p = seq.findIndex(i) - 1;
706 // update hidden region start/end
707 while (hideEnd < p && regions.hasNext())
709 int[] region = regions.next();
711 visNext += region[0] - visPrev;
712 hideStart = region[0];
717 hideStart = seq.getLength();
719 // update visible boundary for sequence
729 return findColumnPosition(start);
731 // otherwise, sequence was completely hidden
735 LOCK.readLock().unlock();
740 * delete any columns in alignmentAnnotation that are hidden (including
741 * sequence associated annotation).
743 * @param alignmentAnnotation
745 public void makeVisibleAnnotation(AlignmentAnnotation alignmentAnnotation)
747 makeVisibleAnnotation(0, alignmentAnnotation.annotations.length,
748 alignmentAnnotation);
752 * delete any columns in alignmentAnnotation that are hidden (including
753 * sequence associated annotation).
756 * remove any annotation to the right of this column
758 * remove any annotation to the left of this column
759 * @param alignmentAnnotation
760 * the annotation to operate on
762 public void makeVisibleAnnotation(int start, int end,
763 AlignmentAnnotation alignmentAnnotation)
767 LOCK.readLock().lock();
769 int startFrom = start;
772 if (alignmentAnnotation.annotations != null)
774 if (hiddenColumns != null && hiddenColumns.size() > 0)
776 removeHiddenAnnotation(startFrom, endAt, alignmentAnnotation);
780 alignmentAnnotation.restrict(startFrom, endAt);
785 LOCK.readLock().unlock();
789 private void removeHiddenAnnotation(int start, int end,
790 AlignmentAnnotation alignmentAnnotation)
792 // mangle the alignmentAnnotation annotation array
793 ArrayList<Annotation[]> annels = new ArrayList<>();
794 Annotation[] els = null;
798 Iterator<int[]> blocks = new VisibleContigsIterator(start, end + 1,
802 int annotationLength;
803 while (blocks.hasNext())
805 int[] block = blocks.next();
806 annotationLength = block[1] - block[0] + 1;
808 if (blocks.hasNext())
810 // copy just the visible segment of the annotation row
811 copylength = annotationLength;
815 if (annotationLength + block[0] <= alignmentAnnotation.annotations.length)
817 // copy just the visible segment of the annotation row
818 copylength = annotationLength;
822 // copy to the end of the annotation row
823 copylength = alignmentAnnotation.annotations.length - block[0];
827 els = new Annotation[annotationLength];
829 System.arraycopy(alignmentAnnotation.annotations, block[0], els, 0,
831 w += annotationLength;
836 alignmentAnnotation.annotations = new Annotation[w];
839 for (Annotation[] chnk : annels)
841 System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
850 * @return true if there are columns hidden
852 public boolean hasHiddenColumns()
856 LOCK.readLock().lock();
857 return hiddenColumns != null && hiddenColumns.size() > 0;
860 LOCK.readLock().unlock();
866 * @return true if there are more than one set of columns hidden
868 public boolean hasManyHiddenColumns()
872 LOCK.readLock().lock();
873 return hiddenColumns != null && hiddenColumns.size() > 1;
876 LOCK.readLock().unlock();
881 * mark the columns corresponding to gap characters as hidden in the column
886 public void hideInsertionsFor(SequenceI sr)
890 LOCK.writeLock().lock();
891 List<int[]> inserts = sr.getInsertions();
892 for (int[] r : inserts)
894 hideColumns(r[0], r[1]);
898 LOCK.writeLock().unlock();
903 * Unhides, and adds to the selection list, all hidden columns
905 public void revealAllHiddenColumns(ColumnSelection sel)
909 LOCK.writeLock().lock();
910 if (hiddenColumns != null)
912 Iterator<int[]> it = hiddenColumns.iterator();
915 int[] region = it.next();
916 for (int j = region[0]; j < region[1] + 1; j++)
921 hiddenColumns = null;
925 LOCK.writeLock().unlock();
930 * Reveals, and marks as selected, the hidden column range with the given
935 public void revealHiddenColumns(int start, ColumnSelection sel)
939 LOCK.writeLock().lock();
940 Iterator<int[]> it = new RegionsIterator(start, start);
943 int[] region = it.next();
944 if (start == region[0])
946 for (int j = region[0]; j < region[1] + 1; j++)
953 else if (start < region[0])
955 break; // passed all possible matching regions
959 if (hiddenColumns.size() == 0)
961 hiddenColumns = null;
965 LOCK.writeLock().unlock();
970 * Add gaps into the sequences aligned to profileseq under the given
975 * - alignment to have gaps inserted into it
977 * - alignment view where sequence corresponding to profileseq is
979 * @return new HiddenColumns for new alignment view, with insertions into
980 * profileseq marked as hidden.
982 public static HiddenColumns propagateInsertions(SequenceI profileseq,
983 AlignmentI al, AlignmentView input)
987 char gc = al.getGapCharacter();
988 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
989 HiddenColumns nview = (HiddenColumns) alandhidden[1];
990 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
991 nview.propagateInsertions(profileseq, al, origseq);
998 * - sequence in al which corresponds to origseq
1000 * - alignment which is to have gaps inserted into it
1002 * - sequence corresponding to profileseq which defines gap map for
1005 private void propagateInsertions(SequenceI profileseq, AlignmentI al,
1010 LOCK.writeLock().lock();
1012 char gc = al.getGapCharacter();
1014 // take the set of hidden columns, and the set of gaps in origseq,
1015 // and remove all the hidden gaps from hiddenColumns
1017 // first get the gaps as a Bitset
1018 BitSet gaps = origseq.gapBitset();
1020 // now calculate hidden ^ not(gap)
1021 BitSet hidden = new BitSet();
1022 markHiddenRegions(hidden);
1023 hidden.andNot(gaps);
1024 hiddenColumns = null;
1025 this.hideMarkedBits(hidden);
1027 // for each sequence in the alignment, except the profile sequence,
1028 // insert gaps corresponding to each hidden region
1029 // but where each hidden column region is shifted backwards by the number
1031 // preceding visible gaps
1032 // update hidden columns at the same time
1033 Iterator<int[]> regions = hiddenColumns.iterator();
1034 ArrayList<int[]> newhidden = new ArrayList<>();
1036 int numGapsBefore = 0;
1037 int gapPosition = 0;
1038 while (regions.hasNext())
1040 // get region coordinates accounting for gaps
1041 // we can rely on gaps not being *in* hidden regions because we already
1043 int[] region = regions.next();
1044 while (gapPosition < region[0])
1047 if (gaps.get(gapPosition))
1053 int left = region[0] - numGapsBefore;
1054 int right = region[1] - numGapsBefore;
1055 newhidden.add(new int[] { left, right });
1057 // make a string with number of gaps = length of hidden region
1058 StringBuffer sb = new StringBuffer();
1059 for (int s = 0; s < right - left + 1; s++)
1063 padGaps(sb, left, profileseq, al);
1066 hiddenColumns = newhidden;
1069 LOCK.writeLock().unlock();
1074 * Pad gaps in all sequences in alignment except profileseq
1077 * gap string to insert
1079 * position to insert at
1081 * sequence not to pad
1083 * alignment to pad sequences in
1085 private void padGaps(StringBuffer sb, int pos, SequenceI profileseq,
1088 // loop over the sequences and pad with gaps where required
1089 for (int s = 0, ns = al.getHeight(); s < ns; s++)
1091 SequenceI sqobj = al.getSequenceAt(s);
1092 if (sqobj != profileseq)
1094 String sq = al.getSequenceAt(s).getSequenceAsString();
1095 if (sq.length() <= pos)
1098 int diff = pos - sq.length() - 1;
1103 while ((diff = pos - sq.length() - 1) > 0)
1105 if (diff >= sb.length())
1107 sq += sb.toString();
1111 char[] buf = new char[diff];
1112 sb.getChars(0, diff, buf, 0);
1113 sq += buf.toString();
1117 sq += sb.toString();
1121 al.getSequenceAt(s).setSequence(
1122 sq.substring(0, pos) + sb.toString() + sq.substring(pos));
1129 * Returns a hashCode built from hidden column ranges
1132 public int hashCode()
1136 LOCK.readLock().lock();
1138 Iterator<int[]> it = hiddenColumns.iterator();
1139 while (it.hasNext())
1141 int[] hidden = it.next();
1142 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
1143 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
1148 LOCK.readLock().unlock();
1153 * Hide columns corresponding to the marked bits
1156 * - columns map to bits starting from zero
1158 public void hideMarkedBits(BitSet inserts)
1162 LOCK.writeLock().lock();
1163 for (int firstSet = inserts
1164 .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
1165 .nextSetBit(lastSet))
1167 lastSet = inserts.nextClearBit(firstSet);
1168 hideColumns(firstSet, lastSet - 1);
1172 LOCK.writeLock().unlock();
1179 * BitSet where hidden columns will be marked
1181 public void markHiddenRegions(BitSet inserts)
1185 LOCK.readLock().lock();
1186 if (hiddenColumns == null)
1190 Iterator<int[]> it = hiddenColumns.iterator();
1191 while (it.hasNext())
1193 int[] range = it.next();
1194 inserts.set(range[0], range[1] + 1);
1198 LOCK.readLock().unlock();
1203 * Calculate the visible start and end index of an alignment.
1206 * full alignment width
1207 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
1209 public int[] getVisibleStartAndEndIndex(int width)
1213 LOCK.readLock().lock();
1214 int[] alignmentStartEnd = new int[] { 0, width - 1 };
1215 int startPos = alignmentStartEnd[0];
1216 int endPos = alignmentStartEnd[1];
1218 int[] lowestRange = new int[] { -1, -1 };
1219 int[] higestRange = new int[] { -1, -1 };
1221 if (hiddenColumns == null)
1223 return new int[] { startPos, endPos };
1226 Iterator<int[]> it = hiddenColumns.iterator();
1227 while (it.hasNext())
1229 int[] range = it.next();
1230 lowestRange = (range[0] <= startPos) ? range : lowestRange;
1231 higestRange = (range[1] >= endPos) ? range : higestRange;
1234 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1236 startPos = alignmentStartEnd[0];
1240 startPos = lowestRange[1] + 1;
1243 if (higestRange[0] == -1 && higestRange[1] == -1)
1245 endPos = alignmentStartEnd[1];
1249 endPos = higestRange[0] - 1;
1251 return new int[] { startPos, endPos };
1254 LOCK.readLock().unlock();
1260 * Finds the hidden region (if any) which starts or ends at res
1263 * visible residue position, unadjusted for hidden columns
1264 * @return region as [start,end] or null if no matching region is found
1266 public int[] getRegionWithEdgeAtRes(int res)
1270 LOCK.readLock().lock();
1271 int adjres = adjustForHiddenColumns(res);
1273 int[] reveal = null;
1274 Iterator<int[]> it = new RegionsIterator(adjres - 2,
1276 while (it.hasNext())
1278 int[] region = it.next();
1279 if (adjres + 1 == region[0] || adjres - 1 == region[1])
1288 LOCK.readLock().unlock();
1293 * Return an iterator over the hidden regions
1295 public Iterator<int[]> iterator()
1297 return new BoundedHiddenColsIterator();
1301 * Return a bounded iterator over the hidden regions
1304 * position to start from (inclusive, absolute column position)
1306 * position to end at (inclusive, absolute column position)
1309 public Iterator<int[]> getBoundedIterator(int start, int end)
1311 return new BoundedHiddenColsIterator(start, end);
1315 * Return a bounded iterator over the *visible* start positions of hidden
1319 * position to start from (inclusive, visible column position)
1321 * position to end at (inclusive, visible column position)
1323 public Iterator<Integer> getBoundedStartIterator(int start, int end)
1325 return new BoundedStartRegionIterator(start, end, true);
1329 * Return an iterator over visible *columns* (not regions) between the given
1330 * start and end boundaries
1333 * first column (inclusive)
1335 * last column (inclusive)
1337 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1339 return new VisibleColsIterator(start, end);
1343 * return an iterator over visible segments between the given start and end
1347 * (first column inclusive from 0)
1349 * (last column - not inclusive)
1351 public Iterator<int[]> getVisContigsIterator(int start, int end)
1353 // return new VisibleBlocksIterator(start, end, true)
1354 return new VisibleContigsIterator(start, end, true);
1358 * return an iterator over visible segments between the given start and end
1362 * (first column - inclusive from 0)
1364 * (last column - inclusive)
1365 * @param useVisibleCoords
1366 * if true, start and end are visible column positions, not absolute
1369 public Iterator<int[]> getVisibleBlocksIterator(int start, int end,
1370 boolean useVisibleCoords)
1372 if (useVisibleCoords)
1375 // we should really just convert start and end here with
1376 // adjustForHiddenColumns
1377 // and then create a VisibleContigsIterator
1378 // but without a cursor this will be horribly slow in some situations
1379 // ... so until then...
1380 return new VisibleBlocksVisBoundsIterator(start, end, true);
1384 return new VisibleContigsIterator(start, end + 1, true);
1389 * A local iterator which iterates over hidden column regions in a range.
1390 * Intended for use ONLY within the HiddenColumns class, because it works
1391 * directly with the hiddenColumns collection without locking (callers should
1392 * lock hiddenColumns).
1394 private class RegionsIterator implements Iterator<int[]>
1396 // start position to iterate from
1399 // end position to iterate to
1402 // current index in hiddenColumns
1403 private int currentPosition = 0;
1405 // current column in hiddenColumns
1406 private int[] nextRegion = null;
1408 private int[] currentRegion = null;
1410 private int removedIndex = -1;
1412 // Constructor with bounds
1413 RegionsIterator(int lowerBound, int upperBound)
1418 if (hiddenColumns != null)
1420 // iterate until a region overlaps with [start,end]
1421 currentPosition = 0;
1422 while ((currentPosition < hiddenColumns.size())
1423 && (hiddenColumns.get(currentPosition)[1] < start))
1427 if (currentPosition < hiddenColumns.size())
1429 nextRegion = hiddenColumns.get(currentPosition);
1435 public boolean hasNext()
1437 return (hiddenColumns != null) && (nextRegion != null)
1438 && (nextRegion[0] <= end);
1444 currentRegion = nextRegion;
1446 if (currentPosition < hiddenColumns.size())
1448 nextRegion = hiddenColumns.get(currentPosition);
1454 return currentRegion;
1458 public void remove()
1460 if ((currentRegion != null) && (removedIndex != currentPosition))
1463 hiddenColumns.subList(currentPosition, currentPosition + 1).clear();
1464 removedIndex = currentPosition;
1468 // already removed element last returned by next()
1469 // or next() has not yet been called
1470 throw new IllegalStateException();
1477 * A local iterator which reverse iterates over hidden column regions in a
1478 * range. Intended for use ONLY within the HiddenColumns class, because it
1479 * works directly with the hiddenColumns collection without locking (callers
1480 * should lock hiddenColumns).
1482 private class ReverseRegionsIterator implements Iterator<int[]>
1484 // start position to iterate to
1487 // end position to iterate from
1490 // current index in hiddenColumns
1491 private int currentPosition = 0;
1493 // current column in hiddenColumns
1494 private int[] nextRegion = null;
1496 // Constructor with bounds
1497 ReverseRegionsIterator(int lowerBound, int upperBound)
1499 init(lowerBound, upperBound);
1503 * Construct an iterator over hiddenColums bounded at
1504 * [lowerBound,upperBound]
1507 * lower bound to iterate to
1509 * upper bound to iterate from
1511 private void init(int lowerBound, int upperBound)
1516 if (hiddenColumns != null)
1518 // iterate until a region overlaps with [start,end]
1519 currentPosition = hiddenColumns.size() - 1;
1520 while (currentPosition >= 0
1521 && hiddenColumns.get(currentPosition)[1] > end)
1525 if (currentPosition >= 0)
1527 nextRegion = hiddenColumns.get(currentPosition);
1533 public boolean hasNext()
1535 return (hiddenColumns != null) && (nextRegion != null)
1536 && (nextRegion[1] >= start);
1542 int[] region = nextRegion;
1544 if (currentPosition >= 0)
1546 nextRegion = hiddenColumns.get(currentPosition);
1558 * An iterator which iterates over hidden column regions in a range. Works
1559 * with a copy of the hidden columns collection. Intended to be used by
1560 * callers OUTSIDE of HiddenColumns.
1562 private class BoundedHiddenColsIterator implements Iterator<int[]>
1564 // start position to iterate from
1567 // end position to iterate to
1570 // current index in hiddenColumns
1571 private int currentPosition = 0;
1573 // current column in hiddenColumns
1574 private int[] currentRegion;
1576 // local copy or reference to hiddenColumns
1577 private List<int[]> localHidden;
1580 * Unbounded constructor
1582 BoundedHiddenColsIterator()
1584 if (hiddenColumns != null)
1586 int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1596 * Construct an iterator over hiddenColums bounded at
1597 * [lowerBound,upperBound]
1600 * lower bound to iterate from
1602 * upper bound to iterate to
1604 BoundedHiddenColsIterator(int lowerBound, int upperBound)
1606 init(lowerBound, upperBound);
1610 * Construct an iterator over hiddenColums bounded at
1611 * [lowerBound,upperBound]
1614 * lower bound to iterate from
1616 * upper bound to iterate to
1618 private void init(int lowerBound, int upperBound)
1625 LOCK.readLock().lock();
1627 if (hiddenColumns != null)
1629 localHidden = new ArrayList<>();
1631 // iterate until a region overlaps with [start,end]
1633 while ((i < hiddenColumns.size())
1634 && (hiddenColumns.get(i)[1] < start))
1639 // iterate from start to end, adding each hidden region. Positions are
1640 // absolute, and all regions which *overlap* [start,end] are added.
1641 while (i < hiddenColumns.size()
1642 && (hiddenColumns.get(i)[0] <= end))
1644 int[] rh = hiddenColumns.get(i);
1645 int[] cp = new int[2];
1646 System.arraycopy(rh, 0, cp, 0, rh.length);
1647 localHidden.add(cp);
1654 LOCK.readLock().unlock();
1659 public boolean hasNext()
1661 return (localHidden != null)
1662 && (currentPosition < localHidden.size());
1668 currentRegion = localHidden.get(currentPosition);
1670 return currentRegion;
1675 * An iterator which iterates over visible start positions of hidden column
1676 * regions in a range.
1678 private class BoundedStartRegionIterator implements Iterator<Integer>
1680 // start position to iterate from
1683 // end position to iterate to
1686 // current index in hiddenColumns
1687 private int currentPosition = 0;
1689 // local copy or reference to hiddenColumns
1690 private List<Integer> positions = null;
1693 * Construct an iterator over hiddenColums bounded at
1694 * [lowerBound,upperBound]
1697 * lower bound to iterate from
1699 * upper bound to iterate to
1700 * @param useCopyCols
1701 * whether to make a local copy of hiddenColumns for iteration (set
1702 * to true if calling from outwith the HiddenColumns class)
1704 BoundedStartRegionIterator(int lowerBound, int upperBound,
1714 // assume that if useCopy is false the calling code has locked
1716 LOCK.readLock().lock();
1719 if (hiddenColumns != null)
1721 positions = new ArrayList<>(hiddenColumns.size());
1723 // navigate to start, keeping count of hidden columns
1725 int hiddenSoFar = 0;
1726 while ((i < hiddenColumns.size())
1727 && (hiddenColumns.get(i)[0] < start + hiddenSoFar))
1729 int[] region = hiddenColumns.get(i);
1730 hiddenSoFar += region[1] - region[0] + 1;
1734 // iterate from start to end, adding start positions of each
1735 // hidden region. Positions are visible columns count, not absolute
1736 while (i < hiddenColumns.size()
1737 && (hiddenColumns.get(i)[0] <= end + hiddenSoFar))
1739 int[] region = hiddenColumns.get(i);
1740 positions.add(region[0] - hiddenSoFar);
1741 hiddenSoFar += region[1] - region[0] + 1;
1747 positions = new ArrayList<>();
1753 LOCK.readLock().unlock();
1759 public boolean hasNext()
1761 return (currentPosition < positions.size());
1765 * Get next hidden region start position
1767 * @return the start position in *visible* coordinates
1770 public Integer next()
1772 int result = positions.get(currentPosition);
1779 * Iterator over the visible *columns* (not regions) as determined by the set
1780 * of hidden columns. Uses a local copy of hidden columns.
1785 private class VisibleColsIterator implements Iterator<Integer>
1789 private int current;
1793 private List<int[]> localHidden = new ArrayList<>();
1795 private int nexthiddenregion;
1797 VisibleColsIterator(int firstcol, int lastcol)
1802 nexthiddenregion = 0;
1804 LOCK.readLock().lock();
1806 if (hiddenColumns != null)
1809 for (i = 0; i < hiddenColumns.size()
1810 && (current <= hiddenColumns.get(i)[0]); ++i)
1812 if (current >= hiddenColumns.get(i)[0]
1813 && current <= hiddenColumns.get(i)[1])
1815 // current is hidden, move to right
1816 current = hiddenColumns.get(i)[1] + 1;
1818 nexthiddenregion = i + 1;
1822 for (i = hiddenColumns.size() - 1; i >= 0
1823 && (last >= hiddenColumns.get(i)[1]); --i)
1825 if (last >= hiddenColumns.get(i)[0]
1826 && last <= hiddenColumns.get(i)[1])
1828 // last is hidden, move to left
1829 last = hiddenColumns.get(i)[0] - 1;
1833 // make a local copy of the bit we need
1834 i = nexthiddenregion;
1835 while (i < hiddenColumns.size() && hiddenColumns.get(i)[0] <= last)
1837 int[] region = new int[] { hiddenColumns.get(i)[0],
1838 hiddenColumns.get(i)[1] };
1839 localHidden.add(region);
1844 LOCK.readLock().unlock();
1848 public boolean hasNext()
1850 return next <= last;
1854 public Integer next()
1858 throw new NoSuchElementException();
1861 if ((localHidden != null)
1862 && (nexthiddenregion < localHidden.size()))
1864 // still some more hidden regions
1865 if (next + 1 < localHidden.get(nexthiddenregion)[0])
1867 // next+1 is still before the next hidden region
1870 else if ((next + 1 >= localHidden.get(nexthiddenregion)[0])
1871 && (next + 1 <= localHidden.get(nexthiddenregion)[1]))
1873 // next + 1 is in the next hidden region
1874 next = localHidden.get(nexthiddenregion)[1] + 1;
1880 // finished with hidden regions, just increment normally
1887 public void remove()
1889 throw new UnsupportedOperationException();
1894 * An iterator which iterates over visible regions in a range.
1896 private class VisibleContigsIterator implements Iterator<int[]>
1898 private List<int[]> vcontigs = new ArrayList<>();
1900 private int currentPosition = 0;
1902 VisibleContigsIterator(int start, int end, boolean usecopy)
1908 LOCK.readLock().lock();
1911 if (hiddenColumns != null && hiddenColumns.size() > 0)
1917 for (int[] region : hiddenColumns)
1919 hideStart = region[0];
1920 hideEnd = region[1];
1922 // navigate to start
1923 if (hideEnd < vstart)
1927 if (hideStart > vstart)
1929 int[] contig = new int[] { vstart, hideStart - 1 };
1930 vcontigs.add(contig);
1932 vstart = hideEnd + 1;
1934 // exit if we're past the end
1943 int[] contig = new int[] { vstart, end - 1 };
1944 vcontigs.add(contig);
1949 int[] contig = new int[] { start, end - 1 };
1950 vcontigs.add(contig);
1956 LOCK.readLock().unlock();
1962 public boolean hasNext()
1964 return (currentPosition < vcontigs.size());
1970 int[] result = vcontigs.get(currentPosition);
1977 * An iterator which iterates over visible regions in a range. The range is
1978 * specified in terms of visible column positions. Provides a special
1979 * "endsAtHidden" indicator to allow callers to determine if the final visible
1980 * column is adjacent to a hidden region.
1982 public class VisibleBlocksVisBoundsIterator implements Iterator<int[]>
1984 private List<int[]> vcontigs = new ArrayList<>();
1986 private int currentPosition = 0;
1988 private boolean endsAtHidden = false;
1991 * Constructor for iterator over visible regions in a range.
1994 * start position in terms of visible column position
1996 * end position in terms of visible column position
1998 * whether to use a local copy of hidden columns
2000 VisibleBlocksVisBoundsIterator(int start, int end, boolean usecopy)
2002 /* actually this implementation always uses a local copy but this may change in future */
2007 LOCK.readLock().lock();
2010 if (hiddenColumns != null && hiddenColumns.size() > 0)
2012 int blockStart = start;
2014 int hiddenSoFar = 0;
2017 // iterate until a region begins within (start,end]
2019 while ((i < hiddenColumns.size())
2020 && (hiddenColumns.get(i)[0] <= blockStart + hiddenSoFar))
2022 hiddenSoFar += hiddenColumns.get(i)[1] - hiddenColumns.get(i)[0]
2027 blockStart += hiddenSoFar; // convert start to absolute position
2028 blockEnd += hiddenSoFar; // convert end to absolute position
2030 // iterate from start to end, adding each visible region. Positions
2032 // absolute, and all hidden regions which overlap [start,end] are
2034 while (i < hiddenColumns.size()
2035 && (hiddenColumns.get(i)[0] <= blockEnd))
2037 int[] region = hiddenColumns.get(i);
2039 // end position of this visible region is either just before the
2040 // start of the next hidden region, or the absolute position of
2041 // 'end', whichever is lowest
2042 blockEnd = Math.min(blockEnd, region[0] - 1);
2044 vcontigs.add(new int[] { blockStart, blockEnd });
2046 visSoFar += blockEnd - blockStart + 1;
2048 // next visible region starts after this hidden region
2049 blockStart = region[1] + 1;
2051 hiddenSoFar += region[1] - region[0] + 1;
2053 // reset blockEnd to absolute position of 'end', assuming we've now
2054 // passed all hidden regions before end
2055 blockEnd = end + hiddenSoFar;
2059 if (visSoFar < end - start)
2061 // the number of visible columns we've accounted for is less than
2062 // the number specified by end-start; work out the end position of
2063 // the last visible region
2064 blockEnd = blockStart + end - start - visSoFar;
2065 vcontigs.add(new int[] { blockStart, blockEnd });
2067 // if the last visible region ends at the next hidden region, set
2068 // endsAtHidden=true
2069 if (i < hiddenColumns.size()
2070 && hiddenColumns.get(i)[0] - 1 == blockEnd)
2072 endsAtHidden = true;
2078 // there are no hidden columns, return a single visible contig
2079 vcontigs.add(new int[] { start, end });
2080 endsAtHidden = false;
2086 LOCK.readLock().unlock();
2092 public boolean hasNext()
2094 return (currentPosition < vcontigs.size());
2100 int[] result = vcontigs.get(currentPosition);
2105 public boolean endsAtHidden()
2107 return endsAtHidden;