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 Iterator<int[]> it = hiddenColumns.iterator();
913 int[] region = it.next();
914 for (int j = region[0]; j < region[1] + 1; j++)
919 hiddenColumns = null;
922 LOCK.writeLock().unlock();
927 * Reveals, and marks as selected, the hidden column range with the given
932 public void revealHiddenColumns(int start, ColumnSelection sel)
936 LOCK.writeLock().lock();
937 Iterator<int[]> it = new RegionsIterator(start, start);
940 int[] region = it.next();
941 if (start == region[0])
943 for (int j = region[0]; j < region[1] + 1; j++)
950 else if (start < region[0])
952 break; // passed all possible matching regions
956 if (hiddenColumns.size() == 0)
958 hiddenColumns = null;
962 LOCK.writeLock().unlock();
967 * Add gaps into the sequences aligned to profileseq under the given
972 * - alignment to have gaps inserted into it
974 * - alignment view where sequence corresponding to profileseq is
976 * @return new HiddenColumns for new alignment view, with insertions into
977 * profileseq marked as hidden.
979 public static HiddenColumns propagateInsertions(SequenceI profileseq,
980 AlignmentI al, AlignmentView input)
984 char gc = al.getGapCharacter();
985 Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
986 HiddenColumns nview = (HiddenColumns) alandhidden[1];
987 SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
988 nview.propagateInsertions(profileseq, al, origseq);
995 * - sequence in al which corresponds to origseq
997 * - alignment which is to have gaps inserted into it
999 * - sequence corresponding to profileseq which defines gap map for
1002 private void propagateInsertions(SequenceI profileseq, AlignmentI al,
1007 LOCK.writeLock().lock();
1009 char gc = al.getGapCharacter();
1011 // take the set of hidden columns, and the set of gaps in origseq,
1012 // and remove all the hidden gaps from hiddenColumns
1014 // first get the gaps as a Bitset
1015 BitSet gaps = origseq.gapBitset();
1017 // now calculate hidden ^ not(gap)
1018 BitSet hidden = new BitSet();
1019 markHiddenRegions(hidden);
1020 hidden.andNot(gaps);
1021 hiddenColumns = null;
1022 this.hideMarkedBits(hidden);
1024 // for each sequence in the alignment, except the profile sequence,
1025 // insert gaps corresponding to each hidden region
1026 // but where each hidden column region is shifted backwards by the number
1028 // preceding visible gaps
1029 // update hidden columns at the same time
1030 Iterator<int[]> regions = hiddenColumns.iterator();
1031 ArrayList<int[]> newhidden = new ArrayList<>();
1033 int numGapsBefore = 0;
1034 int gapPosition = 0;
1035 while (regions.hasNext())
1037 // get region coordinates accounting for gaps
1038 // we can rely on gaps not being *in* hidden regions because we already
1040 int[] region = regions.next();
1041 while (gapPosition < region[0])
1044 if (gaps.get(gapPosition))
1050 int left = region[0] - numGapsBefore;
1051 int right = region[1] - numGapsBefore;
1052 newhidden.add(new int[] { left, right });
1054 // make a string with number of gaps = length of hidden region
1055 StringBuffer sb = new StringBuffer();
1056 for (int s = 0; s < right - left + 1; s++)
1060 padGaps(sb, left, profileseq, al);
1063 hiddenColumns = newhidden;
1066 LOCK.writeLock().unlock();
1071 * Pad gaps in all sequences in alignment except profileseq
1074 * gap string to insert
1076 * position to insert at
1078 * sequence not to pad
1080 * alignment to pad sequences in
1082 private void padGaps(StringBuffer sb, int pos, SequenceI profileseq,
1085 // loop over the sequences and pad with gaps where required
1086 for (int s = 0, ns = al.getHeight(); s < ns; s++)
1088 SequenceI sqobj = al.getSequenceAt(s);
1089 if (sqobj != profileseq)
1091 String sq = al.getSequenceAt(s).getSequenceAsString();
1092 if (sq.length() <= pos)
1095 int diff = pos - sq.length() - 1;
1100 while ((diff = pos - sq.length() - 1) > 0)
1102 if (diff >= sb.length())
1104 sq += sb.toString();
1108 char[] buf = new char[diff];
1109 sb.getChars(0, diff, buf, 0);
1110 sq += buf.toString();
1114 sq += sb.toString();
1118 al.getSequenceAt(s).setSequence(
1119 sq.substring(0, pos) + sb.toString() + sq.substring(pos));
1126 * Returns a hashCode built from hidden column ranges
1129 public int hashCode()
1133 LOCK.readLock().lock();
1135 Iterator<int[]> it = hiddenColumns.iterator();
1136 while (it.hasNext())
1138 int[] hidden = it.next();
1139 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
1140 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
1145 LOCK.readLock().unlock();
1150 * Hide columns corresponding to the marked bits
1153 * - columns map to bits starting from zero
1155 public void hideMarkedBits(BitSet inserts)
1159 LOCK.writeLock().lock();
1160 for (int firstSet = inserts
1161 .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
1162 .nextSetBit(lastSet))
1164 lastSet = inserts.nextClearBit(firstSet);
1165 hideColumns(firstSet, lastSet - 1);
1169 LOCK.writeLock().unlock();
1176 * BitSet where hidden columns will be marked
1178 public void markHiddenRegions(BitSet inserts)
1182 LOCK.readLock().lock();
1183 if (hiddenColumns == null)
1187 Iterator<int[]> it = hiddenColumns.iterator();
1188 while (it.hasNext())
1190 int[] range = it.next();
1191 inserts.set(range[0], range[1] + 1);
1195 LOCK.readLock().unlock();
1200 * Calculate the visible start and end index of an alignment.
1203 * full alignment width
1204 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
1206 public int[] getVisibleStartAndEndIndex(int width)
1210 LOCK.readLock().lock();
1211 int[] alignmentStartEnd = new int[] { 0, width - 1 };
1212 int startPos = alignmentStartEnd[0];
1213 int endPos = alignmentStartEnd[1];
1215 int[] lowestRange = new int[] { -1, -1 };
1216 int[] higestRange = new int[] { -1, -1 };
1218 if (hiddenColumns == null)
1220 return new int[] { startPos, endPos };
1223 Iterator<int[]> it = hiddenColumns.iterator();
1224 while (it.hasNext())
1226 int[] range = it.next();
1227 lowestRange = (range[0] <= startPos) ? range : lowestRange;
1228 higestRange = (range[1] >= endPos) ? range : higestRange;
1231 if (lowestRange[0] == -1 && lowestRange[1] == -1)
1233 startPos = alignmentStartEnd[0];
1237 startPos = lowestRange[1] + 1;
1240 if (higestRange[0] == -1 && higestRange[1] == -1)
1242 endPos = alignmentStartEnd[1];
1246 endPos = higestRange[0] - 1;
1248 return new int[] { startPos, endPos };
1251 LOCK.readLock().unlock();
1257 * Finds the hidden region (if any) which starts or ends at res
1260 * visible residue position, unadjusted for hidden columns
1261 * @return region as [start,end] or null if no matching region is found
1263 public int[] getRegionWithEdgeAtRes(int res)
1267 LOCK.readLock().lock();
1268 int adjres = adjustForHiddenColumns(res);
1270 int[] reveal = null;
1271 Iterator<int[]> it = new RegionsIterator(adjres - 2,
1273 while (it.hasNext())
1275 int[] region = it.next();
1276 if (adjres + 1 == region[0] || adjres - 1 == region[1])
1285 LOCK.readLock().unlock();
1290 * Return an iterator over the hidden regions
1292 public Iterator<int[]> iterator()
1294 return new BoundedHiddenColsIterator();
1298 * Return a bounded iterator over the hidden regions
1301 * position to start from (inclusive, absolute column position)
1303 * position to end at (inclusive, absolute column position)
1306 public Iterator<int[]> getBoundedIterator(int start, int end)
1308 return new BoundedHiddenColsIterator(start, end);
1312 * Return a bounded iterator over the *visible* start positions of hidden
1316 * position to start from (inclusive, visible column position)
1318 * position to end at (inclusive, visible column position)
1320 public Iterator<Integer> getBoundedStartIterator(int start, int end)
1322 return new BoundedStartRegionIterator(start, end, true);
1326 * Return an iterator over visible *columns* (not regions) between the given
1327 * start and end boundaries
1330 * first column (inclusive)
1332 * last column (inclusive)
1334 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1336 return new VisibleColsIterator(start, end);
1340 * return an iterator over visible segments between the given start and end
1344 * (first column inclusive from 0)
1346 * (last column - not inclusive)
1348 public Iterator<int[]> getVisContigsIterator(int start, int end)
1350 // return new VisibleBlocksIterator(start, end, true)
1351 return new VisibleContigsIterator(start, end, true);
1355 * return an iterator over visible segments between the given start and end
1359 * (first column - inclusive from 0)
1361 * (last column - inclusive)
1362 * @param useVisibleCoords
1363 * if true, start and end are visible column positions, not absolute
1366 public Iterator<int[]> getVisibleBlocksIterator(int start, int end,
1367 boolean useVisibleCoords)
1369 if (useVisibleCoords)
1372 // we should really just convert start and end here with
1373 // adjustForHiddenColumns
1374 // and then create a VisibleContigsIterator
1375 // but without a cursor this will be horribly slow in some situations
1376 // ... so until then...
1377 return new VisibleBlocksVisBoundsIterator(start, end, true);
1381 return new VisibleContigsIterator(start, end + 1, true);
1386 * A local iterator which iterates over hidden column regions in a range.
1387 * Intended for use ONLY within the HiddenColumns class, because it works
1388 * directly with the hiddenColumns collection without locking (callers should
1389 * lock hiddenColumns).
1391 private class RegionsIterator implements Iterator<int[]>
1393 // start position to iterate from
1396 // end position to iterate to
1399 // current index in hiddenColumns
1400 private int currentPosition = 0;
1402 // current column in hiddenColumns
1403 private int[] nextRegion = null;
1405 private int[] currentRegion = null;
1407 private int removedIndex = -1;
1409 // Constructor with bounds
1410 RegionsIterator(int lowerBound, int upperBound)
1415 if (hiddenColumns != null)
1417 // iterate until a region overlaps with [start,end]
1418 currentPosition = 0;
1419 while ((currentPosition < hiddenColumns.size())
1420 && (hiddenColumns.get(currentPosition)[1] < start))
1424 if (currentPosition < hiddenColumns.size())
1426 nextRegion = hiddenColumns.get(currentPosition);
1432 public boolean hasNext()
1434 return (hiddenColumns != null) && (nextRegion != null)
1435 && (nextRegion[0] <= end);
1441 currentRegion = nextRegion;
1443 if (currentPosition < hiddenColumns.size())
1445 nextRegion = hiddenColumns.get(currentPosition);
1451 return currentRegion;
1455 public void remove()
1457 if ((currentRegion != null) && (removedIndex != currentPosition))
1460 hiddenColumns.subList(currentPosition, currentPosition + 1).clear();
1461 removedIndex = currentPosition;
1465 // already removed element last returned by next()
1466 // or next() has not yet been called
1467 throw new IllegalStateException();
1474 * A local iterator which reverse iterates over hidden column regions in a
1475 * range. Intended for use ONLY within the HiddenColumns class, because it
1476 * works directly with the hiddenColumns collection without locking (callers
1477 * should lock hiddenColumns).
1479 private class ReverseRegionsIterator implements Iterator<int[]>
1481 // start position to iterate to
1484 // end position to iterate from
1487 // current index in hiddenColumns
1488 private int currentPosition = 0;
1490 // current column in hiddenColumns
1491 private int[] nextRegion = null;
1493 // Constructor with bounds
1494 ReverseRegionsIterator(int lowerBound, int upperBound)
1496 init(lowerBound, upperBound);
1500 * Construct an iterator over hiddenColums bounded at
1501 * [lowerBound,upperBound]
1504 * lower bound to iterate to
1506 * upper bound to iterate from
1508 private void init(int lowerBound, int upperBound)
1513 if (hiddenColumns != null)
1515 // iterate until a region overlaps with [start,end]
1516 currentPosition = hiddenColumns.size() - 1;
1517 while (currentPosition >= 0
1518 && hiddenColumns.get(currentPosition)[1] > end)
1522 if (currentPosition >= 0)
1524 nextRegion = hiddenColumns.get(currentPosition);
1530 public boolean hasNext()
1532 return (hiddenColumns != null) && (nextRegion != null)
1533 && (nextRegion[1] >= start);
1539 int[] region = nextRegion;
1541 if (currentPosition >= 0)
1543 nextRegion = hiddenColumns.get(currentPosition);
1555 * An iterator which iterates over hidden column regions in a range. Works
1556 * with a copy of the hidden columns collection. Intended to be used by
1557 * callers OUTSIDE of HiddenColumns.
1559 private class BoundedHiddenColsIterator implements Iterator<int[]>
1561 // start position to iterate from
1564 // end position to iterate to
1567 // current index in hiddenColumns
1568 private int currentPosition = 0;
1570 // current column in hiddenColumns
1571 private int[] currentRegion;
1573 // local copy or reference to hiddenColumns
1574 private List<int[]> localHidden;
1577 * Unbounded constructor
1579 BoundedHiddenColsIterator()
1581 if (hiddenColumns != null)
1583 int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1593 * Construct an iterator over hiddenColums bounded at
1594 * [lowerBound,upperBound]
1597 * lower bound to iterate from
1599 * upper bound to iterate to
1601 BoundedHiddenColsIterator(int lowerBound, int upperBound)
1603 init(lowerBound, upperBound);
1607 * Construct an iterator over hiddenColums bounded at
1608 * [lowerBound,upperBound]
1611 * lower bound to iterate from
1613 * upper bound to iterate to
1615 private void init(int lowerBound, int upperBound)
1622 LOCK.readLock().lock();
1624 if (hiddenColumns != null)
1626 localHidden = new ArrayList<>();
1628 // iterate until a region overlaps with [start,end]
1630 while ((i < hiddenColumns.size())
1631 && (hiddenColumns.get(i)[1] < start))
1636 // iterate from start to end, adding each hidden region. Positions are
1637 // absolute, and all regions which *overlap* [start,end] are added.
1638 while (i < hiddenColumns.size()
1639 && (hiddenColumns.get(i)[0] <= end))
1641 int[] rh = hiddenColumns.get(i);
1642 int[] cp = new int[2];
1643 System.arraycopy(rh, 0, cp, 0, rh.length);
1644 localHidden.add(cp);
1651 LOCK.readLock().unlock();
1656 public boolean hasNext()
1658 return (localHidden != null)
1659 && (currentPosition < localHidden.size());
1665 currentRegion = localHidden.get(currentPosition);
1667 return currentRegion;
1672 * An iterator which iterates over visible start positions of hidden column
1673 * regions in a range.
1675 private class BoundedStartRegionIterator implements Iterator<Integer>
1677 // start position to iterate from
1680 // end position to iterate to
1683 // current index in hiddenColumns
1684 private int currentPosition = 0;
1686 // local copy or reference to hiddenColumns
1687 private List<Integer> positions = null;
1690 * Construct an iterator over hiddenColums bounded at
1691 * [lowerBound,upperBound]
1694 * lower bound to iterate from
1696 * upper bound to iterate to
1697 * @param useCopyCols
1698 * whether to make a local copy of hiddenColumns for iteration (set
1699 * to true if calling from outwith the HiddenColumns class)
1701 BoundedStartRegionIterator(int lowerBound, int upperBound,
1711 // assume that if useCopy is false the calling code has locked
1713 LOCK.readLock().lock();
1716 if (hiddenColumns != null)
1718 positions = new ArrayList<>(hiddenColumns.size());
1720 // navigate to start, keeping count of hidden columns
1722 int hiddenSoFar = 0;
1723 while ((i < hiddenColumns.size())
1724 && (hiddenColumns.get(i)[0] < start + hiddenSoFar))
1726 int[] region = hiddenColumns.get(i);
1727 hiddenSoFar += region[1] - region[0] + 1;
1731 // iterate from start to end, adding start positions of each
1732 // hidden region. Positions are visible columns count, not absolute
1733 while (i < hiddenColumns.size()
1734 && (hiddenColumns.get(i)[0] <= end + hiddenSoFar))
1736 int[] region = hiddenColumns.get(i);
1737 positions.add(region[0] - hiddenSoFar);
1738 hiddenSoFar += region[1] - region[0] + 1;
1744 positions = new ArrayList<>();
1750 LOCK.readLock().unlock();
1756 public boolean hasNext()
1758 return (currentPosition < positions.size());
1762 * Get next hidden region start position
1764 * @return the start position in *visible* coordinates
1767 public Integer next()
1769 int result = positions.get(currentPosition);
1776 * Iterator over the visible *columns* (not regions) as determined by the set
1777 * of hidden columns. Uses a local copy of hidden columns.
1782 private class VisibleColsIterator implements Iterator<Integer>
1786 private int current;
1790 private List<int[]> localHidden = new ArrayList<>();
1792 private int nexthiddenregion;
1794 VisibleColsIterator(int firstcol, int lastcol)
1799 nexthiddenregion = 0;
1801 LOCK.readLock().lock();
1803 if (hiddenColumns != null)
1806 for (i = 0; i < hiddenColumns.size()
1807 && (current <= hiddenColumns.get(i)[0]); ++i)
1809 if (current >= hiddenColumns.get(i)[0]
1810 && current <= hiddenColumns.get(i)[1])
1812 // current is hidden, move to right
1813 current = hiddenColumns.get(i)[1] + 1;
1815 nexthiddenregion = i + 1;
1819 for (i = hiddenColumns.size() - 1; i >= 0
1820 && (last >= hiddenColumns.get(i)[1]); --i)
1822 if (last >= hiddenColumns.get(i)[0]
1823 && last <= hiddenColumns.get(i)[1])
1825 // last is hidden, move to left
1826 last = hiddenColumns.get(i)[0] - 1;
1830 // make a local copy of the bit we need
1831 i = nexthiddenregion;
1832 while (i < hiddenColumns.size() && hiddenColumns.get(i)[0] <= last)
1834 int[] region = new int[] { hiddenColumns.get(i)[0],
1835 hiddenColumns.get(i)[1] };
1836 localHidden.add(region);
1841 LOCK.readLock().unlock();
1845 public boolean hasNext()
1847 return next <= last;
1851 public Integer next()
1855 throw new NoSuchElementException();
1858 if ((localHidden != null)
1859 && (nexthiddenregion < localHidden.size()))
1861 // still some more hidden regions
1862 if (next + 1 < localHidden.get(nexthiddenregion)[0])
1864 // next+1 is still before the next hidden region
1867 else if ((next + 1 >= localHidden.get(nexthiddenregion)[0])
1868 && (next + 1 <= localHidden.get(nexthiddenregion)[1]))
1870 // next + 1 is in the next hidden region
1871 next = localHidden.get(nexthiddenregion)[1] + 1;
1877 // finished with hidden regions, just increment normally
1884 public void remove()
1886 throw new UnsupportedOperationException();
1891 * An iterator which iterates over visible regions in a range.
1893 private class VisibleContigsIterator implements Iterator<int[]>
1895 private List<int[]> vcontigs = new ArrayList<>();
1897 private int currentPosition = 0;
1899 VisibleContigsIterator(int start, int end, boolean usecopy)
1905 LOCK.readLock().lock();
1908 if (hiddenColumns != null && hiddenColumns.size() > 0)
1914 for (int[] region : hiddenColumns)
1916 hideStart = region[0];
1917 hideEnd = region[1];
1919 // navigate to start
1920 if (hideEnd < vstart)
1924 if (hideStart > vstart)
1926 int[] contig = new int[] { vstart, hideStart - 1 };
1927 vcontigs.add(contig);
1929 vstart = hideEnd + 1;
1931 // exit if we're past the end
1940 int[] contig = new int[] { vstart, end - 1 };
1941 vcontigs.add(contig);
1946 int[] contig = new int[] { start, end - 1 };
1947 vcontigs.add(contig);
1953 LOCK.readLock().unlock();
1959 public boolean hasNext()
1961 return (currentPosition < vcontigs.size());
1967 int[] result = vcontigs.get(currentPosition);
1974 * An iterator which iterates over visible regions in a range. The range is
1975 * specified in terms of visible column positions. Provides a special
1976 * "endsAtHidden" indicator to allow callers to determine if the final visible
1977 * column is adjacent to a hidden region.
1979 public class VisibleBlocksVisBoundsIterator implements Iterator<int[]>
1981 private List<int[]> vcontigs = new ArrayList<>();
1983 private int currentPosition = 0;
1985 private boolean endsAtHidden = false;
1988 * Constructor for iterator over visible regions in a range.
1991 * start position in terms of visible column position
1993 * end position in terms of visible column position
1995 * whether to use a local copy of hidden columns
1997 VisibleBlocksVisBoundsIterator(int start, int end, boolean usecopy)
1999 /* actually this implementation always uses a local copy but this may change in future */
2004 LOCK.readLock().lock();
2007 if (hiddenColumns != null && hiddenColumns.size() > 0)
2009 int blockStart = start;
2011 int hiddenSoFar = 0;
2014 // iterate until a region begins within (start,end]
2016 while ((i < hiddenColumns.size())
2017 && (hiddenColumns.get(i)[0] <= blockStart + hiddenSoFar))
2019 hiddenSoFar += hiddenColumns.get(i)[1] - hiddenColumns.get(i)[0]
2024 blockStart += hiddenSoFar; // convert start to absolute position
2025 blockEnd += hiddenSoFar; // convert end to absolute position
2027 // iterate from start to end, adding each visible region. Positions
2029 // absolute, and all hidden regions which overlap [start,end] are
2031 while (i < hiddenColumns.size()
2032 && (hiddenColumns.get(i)[0] <= blockEnd))
2034 int[] region = hiddenColumns.get(i);
2036 // end position of this visible region is either just before the
2037 // start of the next hidden region, or the absolute position of
2038 // 'end', whichever is lowest
2039 blockEnd = Math.min(blockEnd, region[0] - 1);
2041 vcontigs.add(new int[] { blockStart, blockEnd });
2043 visSoFar += blockEnd - blockStart + 1;
2045 // next visible region starts after this hidden region
2046 blockStart = region[1] + 1;
2048 hiddenSoFar += region[1] - region[0] + 1;
2050 // reset blockEnd to absolute position of 'end', assuming we've now
2051 // passed all hidden regions before end
2052 blockEnd = end + hiddenSoFar;
2056 if (visSoFar < end - start)
2058 // the number of visible columns we've accounted for is less than
2059 // the number specified by end-start; work out the end position of
2060 // the last visible region
2061 blockEnd = blockStart + end - start - visSoFar;
2062 vcontigs.add(new int[] { blockStart, blockEnd });
2064 // if the last visible region ends at the next hidden region, set
2065 // endsAtHidden=true
2066 if (i < hiddenColumns.size()
2067 && hiddenColumns.get(i)[0] - 1 == blockEnd)
2069 endsAtHidden = true;
2075 // there are no hidden columns, return a single visible contig
2076 vcontigs.add(new int[] { start, end });
2077 endsAtHidden = false;
2083 LOCK.readLock().unlock();
2089 public boolean hasNext()
2091 return (currentPosition < vcontigs.size());
2097 int[] result = vcontigs.get(currentPosition);
2102 public boolean endsAtHidden()
2104 return endsAtHidden;