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.Arrays;
25 import java.util.BitSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.concurrent.locks.ReentrantReadWriteLock;
31 * This class manages the collection of hidden columns associated with an
32 * alignment. To iterate over the collection, or over visible columns/regions,
33 * use an iterator obtained from one of:
35 * - getBoundedIterator: iterates over the hidden regions, within some bounds,
36 * returning *absolute* positions
38 * - getBoundedStartIterator: iterates over the start positions of hidden
39 * regions, within some bounds, returning *visible* positions
41 * - getVisContigsIterator: iterates over visible regions in a range, returning
42 * *absolute* positions
44 * - getVisibleColsIterator: iterates over the visible *columns*
46 * For performance reasons, provide bounds where possible. Note that column
47 * numbering begins at 0 throughout this class.
52 /* Implementation notes:
54 * Methods which change the hiddenColumns collection should use a writeLock to
55 * prevent other threads accessing the hiddenColumns collection while changes
56 * are being made. They should also reset the hidden columns cursor, and either
57 * update the hidden columns count, or set it to 0 (so that it will later be
58 * updated when needed).
61 * Methods which only need read access to the hidden columns collection should
62 * use a readLock to prevent other threads changing the hidden columns
63 * collection while it is in use.
65 public class HiddenColumns
67 private static final int HASH_MULTIPLIER = 31;
69 private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
72 * Cursor which tracks the last used hidden columns region, and the number
73 * of hidden columns up to (but not including) that region.
75 private HiddenColumnsCursor cursor = new HiddenColumnsCursor();
78 * cache of the number of hidden columns: must be kept up to date by methods
79 * which add or remove hidden columns
81 private int numColumns = 0;
84 * list of hidden column [start, end] ranges; the list is maintained in
85 * ascending start column order
87 private List<int[]> hiddenColumns = new ArrayList<>();
89 private BitSet hiddenBitSet;
91 public BitSet getBitset()
93 if (hiddenBitSet == null)
95 hiddenBitSet = new BitSet();
96 for (int[] range : hiddenColumns)
98 hiddenBitSet.set(range[0], range[1] + 1);
106 public HiddenColumns()
114 * the HiddenColumns object to copy from
116 public HiddenColumns(HiddenColumns copy)
118 this(copy, Integer.MIN_VALUE, Integer.MAX_VALUE, 0);
122 * Copy constructor within bounds and with offset. Copies hidden column
123 * regions fully contained between start and end, and offsets positions by
124 * subtracting offset.
127 * HiddenColumns instance to copy from
129 * lower bound to copy from
131 * upper bound to copy to
133 * offset to subtract from each region boundary position
136 public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
140 LOCK.writeLock().lock();
144 Iterator<int[]> it = copy.getBoundedIterator(start, end);
147 int[] region = it.next();
148 // still need to check boundaries because iterator returns
149 // all overlapping regions and we need contained regions
150 if (region[0] >= start && region[1] <= end)
154 { region[0] - offset, region[1] - offset });
155 numColumns += region[1] - region[0] + 1;
158 cursor = new HiddenColumnsCursor(hiddenColumns);
162 LOCK.writeLock().unlock();
167 * Adds the specified column range to the hidden columns collection
170 * start of range to add (absolute position in alignment)
172 * end of range to add (absolute position in alignment)
174 public void hideColumns(int start, int end)
178 LOCK.writeLock().lock();
181 int prevHiddenCount = 0;
183 if (!hiddenColumns.isEmpty())
185 // set up cursor reset values
186 HiddenCursorPosition cursorPos = cursor.findRegionForColumn(start, false);
187 regionindex = cursorPos.getRegionIndex();
191 // get previous index and hidden count for updating the cursor later
192 previndex = regionindex - 1;
193 int[] prevRegion = hiddenColumns.get(previndex);
194 prevHiddenCount = cursorPos.getHiddenSoFar()
195 - (prevRegion[1] - prevRegion[0] + 1);
199 // new range follows everything else; check first to avoid looping over
200 // whole hiddenColumns collection
201 if (hiddenColumns.isEmpty()
202 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
204 hiddenColumns.add(new int[] { start, end });
205 numColumns += end - start + 1;
210 * traverse existing hidden ranges and insert / amend / append as
213 boolean added = false;
216 added = insertRangeAtRegion(regionindex - 1, start, end);
218 if (!added && regionindex < hiddenColumns.size())
220 insertRangeAtRegion(regionindex, start, end);
224 // reset the cursor to just before our insertion point: this saves
225 // a lot of reprocessing in large alignments
226 cursor = new HiddenColumnsCursor(hiddenColumns, previndex,
231 LOCK.writeLock().unlock();
236 * Insert [start, range] at the region at index i in hiddenColumns, if
242 * start of range to insert
244 * end of range to insert
245 * @return true if range was successfully inserted
247 private boolean insertRangeAtRegion(int i, int start, int end)
249 boolean added = false;
251 int[] region = hiddenColumns.get(i);
252 if (end < region[0] - 1)
255 * insert discontiguous preceding range
257 hiddenColumns.add(i, new int[] { start, end });
258 numColumns += end - start + 1;
261 else if (end <= region[1])
264 * new range overlaps existing, or is contiguous preceding it - adjust
267 int oldstart = region[0];
268 region[0] = Math.min(region[0], start);
269 numColumns += oldstart - region[0]; // new columns are between old and
273 else if (start <= region[1] + 1)
276 * new range overlaps existing, or is contiguous following it - adjust
277 * start and end columns
279 insertRangeAtOverlap(i, start, end, region);
287 * Insert a range whose start position overlaps an existing region and/or is
288 * contiguous to the right of the region
293 * start of range to insert
295 * end of range to insert
297 * the overlapped/continued region
299 private void insertRangeAtOverlap(int i, int start, int end, int[] region)
301 int oldstart = region[0];
302 int oldend = region[1];
303 region[0] = Math.min(region[0], start);
304 region[1] = Math.max(region[1], end);
306 numColumns += oldstart - region[0];
309 * also update or remove any subsequent ranges
310 * that are overlapped
313 while (endi < hiddenColumns.size() - 1)
315 int[] nextRegion = hiddenColumns.get(endi + 1);
316 if (nextRegion[0] > end + 1)
319 * gap to next hidden range - no more to update
323 numColumns -= nextRegion[1] - nextRegion[0] + 1;
324 region[1] = Math.max(nextRegion[1], end);
327 numColumns += region[1] - oldend;
328 hiddenColumns.subList(i + 1, endi + 1).clear();
333 * hide a list of ranges
337 public void hideList(List<int[]> ranges)
341 LOCK.writeLock().lock();
342 for (int[] r : ranges)
344 hideColumns(r[0], r[1]);
346 cursor = new HiddenColumnsCursor(hiddenColumns);
351 LOCK.writeLock().unlock();
356 * Unhides, and adds to the selection list, all hidden columns
358 public void revealAllHiddenColumns(ColumnSelection sel)
362 LOCK.writeLock().lock();
364 for (int[] region : hiddenColumns)
366 for (int j = region[0]; j < region[1] + 1; j++)
371 hiddenColumns.clear();
372 cursor = new HiddenColumnsCursor(hiddenColumns);
378 LOCK.writeLock().unlock();
383 * Reveals, and marks as selected, the hidden column range with the given
387 * the start column to look for
389 * the column selection to add the hidden column range to
391 public void revealHiddenColumns(int start, ColumnSelection sel)
395 LOCK.writeLock().lock();
397 if (!hiddenColumns.isEmpty())
399 int regionIndex = cursor.findRegionForColumn(start, false)
402 if (regionIndex != -1 && regionIndex != hiddenColumns.size())
404 // regionIndex is the region which either contains start
405 // or lies to the right of start
406 int[] region = hiddenColumns.get(regionIndex);
407 if (start == region[0])
409 for (int j = region[0]; j < region[1] + 1; j++)
413 int colsToRemove = region[1] - region[0] + 1;
414 hiddenColumns.remove(regionIndex);
415 numColumns -= colsToRemove;
422 LOCK.writeLock().unlock();
427 * Output regions data as a string. String is in the format:
428 * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
431 * string to delimit regions
432 * @param betweenstring
433 * to put between start and end region values
434 * @return regions formatted according to delimiter and between strings
436 public String regionsToString(String delimiter, String between)
440 LOCK.readLock().lock();
441 StringBuilder regionBuilder = new StringBuilder();
443 boolean first = true;
444 for (int[] range : hiddenColumns)
448 regionBuilder.append(delimiter);
454 regionBuilder.append(range[0]).append(between).append(range[1]);
458 return regionBuilder.toString();
461 LOCK.readLock().unlock();
466 * Find the number of hidden columns
468 * @return number of hidden columns
476 * Get the number of distinct hidden regions
478 * @return number of regions
480 public int getNumberOfRegions()
484 LOCK.readLock().lock();
485 return hiddenColumns.size();
488 LOCK.readLock().unlock();
493 * Answers true if obj is an instance of HiddenColumns, and holds the same
494 * array of start-end column ranges as this, else answers false
497 public boolean equals(Object obj)
501 LOCK.readLock().lock();
503 if (!(obj instanceof HiddenColumns))
507 HiddenColumns that = (HiddenColumns) obj;
510 * check hidden columns are either both null, or match
513 if (that.hiddenColumns.size() != this.hiddenColumns.size())
518 Iterator<int[]> it = this.iterator();
519 Iterator<int[]> thatit = that.iterator();
522 if (!(Arrays.equals(it.next(), thatit.next())))
531 LOCK.readLock().unlock();
536 * Return absolute column index for a visible column index
539 * int column index in alignment view (count from zero)
540 * @return alignment column index for column
542 public int visibleToAbsoluteColumn(int column)
546 LOCK.readLock().lock();
549 if (!hiddenColumns.isEmpty())
551 result += cursor.findRegionForColumn(column, true)
558 LOCK.readLock().unlock();
563 * Use this method to find out where a column will appear in the visible
564 * alignment when hidden columns exist. If the column is not visible, then the
565 * index of the next visible column on the left will be returned (or 0 if
566 * there is no visible column on the left)
568 * @param hiddenColumn
569 * the column index in the full alignment including hidden columns
570 * @return the position of the column in the visible alignment
572 public int absoluteToVisibleColumn(int hiddenColumn)
576 LOCK.readLock().lock();
577 int result = hiddenColumn;
579 if (!hiddenColumns.isEmpty())
581 HiddenCursorPosition cursorPos = cursor
582 .findRegionForColumn(hiddenColumn, false);
583 int index = cursorPos.getRegionIndex();
584 int hiddenBeforeCol = cursorPos.getHiddenSoFar();
586 // just subtract hidden cols count - this works fine if column is
588 result = hiddenColumn - hiddenBeforeCol;
590 // now check in case column is hidden - it will be in the returned
592 if (index < hiddenColumns.size())
594 int[] region = hiddenColumns.get(index);
595 if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
597 // actually col is hidden, return region[0]-1
598 // unless region[0]==0 in which case return 0
605 result = region[0] - 1 - hiddenBeforeCol;
611 return result; // return the shifted position after removing hidden
615 LOCK.readLock().unlock();
620 * Find the visible column which is a given visible number of columns to the
621 * left (negative visibleDistance) or right (positive visibleDistance) of
622 * startColumn. If startColumn is not visible, we use the visible column at
623 * the left boundary of the hidden region containing startColumn.
625 * @param visibleDistance
626 * the number of visible columns to offset by (left offset = negative
627 * value; right offset = positive value)
629 * the position of the column to start from (absolute position)
630 * @return the position of the column which is <visibleDistance> away
631 * (absolute position)
633 public int offsetByVisibleColumns(int visibleDistance, int startColumn)
637 LOCK.readLock().lock();
638 int start = absoluteToVisibleColumn(startColumn);
639 return visibleToAbsoluteColumn(start + visibleDistance);
644 LOCK.readLock().unlock();
649 * This method returns the rightmost limit of a region of an alignment with
650 * hidden columns. In otherwords, the next hidden column.
653 * the absolute (visible) alignmentPosition to find the next hidden
655 * @return the index of the next hidden column, or alPos if there is no next
658 public int getNextHiddenBoundary(boolean left, int alPos)
662 LOCK.readLock().lock();
663 if (!hiddenColumns.isEmpty())
665 int index = cursor.findRegionForColumn(alPos, false)
668 if (left && index > 0)
670 int[] region = hiddenColumns.get(index - 1);
673 else if (!left && index < hiddenColumns.size())
675 int[] region = hiddenColumns.get(index);
676 if (alPos < region[0])
680 else if ((alPos <= region[1])
681 && (index + 1 < hiddenColumns.size()))
683 // alPos is within a hidden region, return the next one
685 region = hiddenColumns.get(index + 1);
693 LOCK.readLock().unlock();
698 * Answers if a column in the alignment is visible
701 * absolute position of column in the alignment
702 * @return true if column is visible
704 public boolean isVisible(int column)
708 LOCK.readLock().lock();
710 if (!hiddenColumns.isEmpty())
712 int regionindex = cursor.findRegionForColumn(column, false)
714 if (regionindex > -1 && regionindex < hiddenColumns.size())
716 int[] region = hiddenColumns.get(regionindex);
717 // already know that column <= region[1] as cursor returns containing
718 // region or region to right
719 if (column >= region[0])
729 LOCK.readLock().unlock();
735 * @return true if there are columns hidden
737 public boolean hasHiddenColumns()
741 LOCK.readLock().lock();
743 // we don't use getSize()>0 here because it has to iterate over
744 // the full hiddenColumns collection and so will be much slower
745 return (!hiddenColumns.isEmpty());
748 LOCK.readLock().unlock();
754 * @return true if there is more than one hidden column region
756 public boolean hasMultiHiddenColumnRegions()
760 LOCK.readLock().lock();
761 return !hiddenColumns.isEmpty() && hiddenColumns.size() > 1;
764 LOCK.readLock().unlock();
770 * Returns a hashCode built from hidden column ranges
773 public int hashCode()
777 LOCK.readLock().lock();
780 for (int[] hidden : hiddenColumns)
782 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
783 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
788 LOCK.readLock().unlock();
793 * Hide columns corresponding to the marked bits
796 * - columns mapped to bits starting from zero
798 public void hideColumns(BitSet inserts)
800 hideColumns(inserts, 0, inserts.length() - 1);
804 * Hide columns corresponding to the marked bits, within the range
805 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
808 * columns mapped to bits starting from zero
810 * start of range to hide columns within
812 * end of range to hide columns within
814 private void hideColumns(BitSet tohide, int start, int end)
818 LOCK.writeLock().lock();
819 for (int firstSet = tohide
820 .nextSetBit(start), lastSet = start; firstSet >= start
821 && lastSet <= end; firstSet = tohide
822 .nextSetBit(lastSet))
824 lastSet = tohide.nextClearBit(firstSet);
827 hideColumns(firstSet, lastSet - 1);
829 else if (firstSet <= end)
831 hideColumns(firstSet, end);
834 cursor = new HiddenColumnsCursor(hiddenColumns);
838 LOCK.writeLock().unlock();
843 * Hide columns corresponding to the marked bits, within the range
844 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
845 * NB Existing entries in [start,end] are cleared.
848 * columns mapped to bits starting from zero
850 * start of range to hide columns within
852 * end of range to hide columns within
854 public void clearAndHideColumns(BitSet tohide, int start, int end)
856 clearHiddenColumnsInRange(start, end);
857 hideColumns(tohide, start, end);
861 * Make all columns in the range [start,end] visible
864 * start of range to show columns
866 * end of range to show columns
868 private void clearHiddenColumnsInRange(int start, int end)
872 LOCK.writeLock().lock();
874 if (!hiddenColumns.isEmpty())
876 HiddenCursorPosition pos = cursor.findRegionForColumn(start, false);
877 int index = pos.getRegionIndex();
879 if (index != -1 && index != hiddenColumns.size())
881 // regionIndex is the region which either contains start
882 // or lies to the right of start
883 int[] region = hiddenColumns.get(index);
884 if (region[0] < start && region[1] >= start)
886 // region contains start, truncate so that it ends just before start
887 numColumns -= region[1] - start + 1;
888 region[1] = start - 1;
893 while (endi < hiddenColumns.size())
895 region = hiddenColumns.get(endi);
899 if (region[0] <= end)
901 // region contains end, truncate so it starts just after end
902 numColumns -= end - region[0] + 1;
908 numColumns -= region[1] - region[0] + 1;
911 hiddenColumns.subList(index, endi).clear();
915 cursor = new HiddenColumnsCursor(hiddenColumns);
920 LOCK.writeLock().unlock();
927 * BitSet where hidden columns will be marked
929 protected void andNot(BitSet updates)
933 LOCK.writeLock().lock();
935 getBitset().andNot(updates);
936 hiddenColumns.clear();
937 hideColumns(hiddenBitSet);
941 LOCK.writeLock().unlock();
946 * Calculate the visible start and end index of an alignment.
949 * full alignment width
950 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
952 public int[] getVisibleStartAndEndIndex(int width)
956 LOCK.readLock().lock();
958 int firstVisible = 0;
959 int lastVisible = width - 1;
961 if (!hiddenColumns.isEmpty())
963 // first visible col with index 0, convert to absolute index
964 firstVisible = visibleToAbsoluteColumn(0);
966 // last visible column is either immediately to left of
967 // last hidden region, or is just the last column in the alignment
968 int[] lastregion = hiddenColumns.get(hiddenColumns.size() - 1);
969 if (lastregion[1] == width - 1)
971 // last region is at very end of alignment
972 // last visible column immediately precedes it
973 lastVisible = lastregion[0] - 1;
976 return new int[] { firstVisible, lastVisible };
980 LOCK.readLock().unlock();
985 * Finds the hidden region (if any) which starts or ends at res
988 * visible residue position, unadjusted for hidden columns
989 * @return region as [start,end] or null if no matching region is found. If
990 * res is adjacent to two regions, returns the left region.
992 public int[] getRegionWithEdgeAtRes(int res)
996 LOCK.readLock().lock();
997 int adjres = visibleToAbsoluteColumn(res);
1001 if (!hiddenColumns.isEmpty())
1003 // look for a region ending just before adjres
1004 int regionindex = cursor.findRegionForColumn(adjres - 1, false)
1006 if (regionindex < hiddenColumns.size()
1007 && hiddenColumns.get(regionindex)[1] == adjres - 1)
1009 reveal = hiddenColumns.get(regionindex);
1011 // check if the region ends just after adjres
1012 else if (regionindex < hiddenColumns.size()
1013 && hiddenColumns.get(regionindex)[0] == adjres + 1)
1015 reveal = hiddenColumns.get(regionindex);
1022 LOCK.readLock().unlock();
1027 * Return an iterator over the hidden regions
1029 public Iterator<int[]> iterator()
1033 LOCK.readLock().lock();
1034 return new RangeIterator(hiddenColumns);
1037 LOCK.readLock().unlock();
1042 * Return a bounded iterator over the hidden regions
1045 * position to start from (inclusive, absolute column position)
1047 * position to end at (inclusive, absolute column position)
1050 public Iterator<int[]> getBoundedIterator(int start, int end)
1054 LOCK.readLock().lock();
1055 return new RangeIterator(start, end, hiddenColumns);
1058 LOCK.readLock().unlock();
1063 * Return a bounded iterator over the *visible* start positions of hidden
1067 * position to start from (inclusive, visible column position)
1069 * position to end at (inclusive, visible column position)
1071 public Iterator<Integer> getStartRegionIterator(int start, int end)
1075 LOCK.readLock().lock();
1077 // get absolute position of column in alignment
1078 int absoluteStart = visibleToAbsoluteColumn(start);
1080 // Get cursor position and supply it to the iterator:
1081 // Since we want visible region start, we look for a cursor for the
1082 // (absoluteStart-1), then if absoluteStart is the start of a visible
1083 // region we'll get the cursor pointing to the region before, which is
1085 HiddenCursorPosition pos = cursor
1086 .findRegionForColumn(absoluteStart - 1, false);
1088 return new StartRegionIterator(pos, start, end,
1092 LOCK.readLock().unlock();
1097 * Return an iterator over visible *columns* (not regions) between the given
1098 * start and end boundaries
1101 * first column (inclusive)
1103 * last column (inclusive)
1105 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1109 LOCK.readLock().lock();
1110 return new RangeElementsIterator(
1111 new VisibleContigsIterator(start, end + 1, hiddenColumns));
1114 LOCK.readLock().unlock();
1119 * return an iterator over visible segments between the given start and end
1123 * first column, inclusive from 0
1125 * last column - not inclusive
1126 * @param useVisibleCoords
1127 * if true, start and end are visible column positions, not absolute
1130 public VisibleContigsIterator getVisContigsIterator(int start,
1132 boolean useVisibleCoords)
1134 int adjstart = start;
1136 if (useVisibleCoords)
1138 adjstart = visibleToAbsoluteColumn(start);
1139 adjend = visibleToAbsoluteColumn(end);
1144 LOCK.readLock().lock();
1145 return new VisibleContigsIterator(adjstart, adjend, hiddenColumns);
1148 LOCK.readLock().unlock();