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;
92 * Returns a BitSet with a set bit for each hidden column (0, 1, ...). This is
93 * valid at the time of calling, but will not reflect any changes made
98 public BitSet getBitset()
100 if (hiddenBitSet == null)
102 hiddenBitSet = new BitSet();
103 for (int[] range : hiddenColumns)
105 hiddenBitSet.set(range[0], range[1] + 1);
113 public HiddenColumns()
121 * the HiddenColumns object to copy from
123 public HiddenColumns(HiddenColumns copy)
125 this(copy, Integer.MIN_VALUE, Integer.MAX_VALUE, 0);
129 * Copy constructor within bounds and with offset. Copies hidden column
130 * regions fully contained between start and end, and offsets positions by
131 * subtracting offset.
134 * HiddenColumns instance to copy from
136 * lower bound to copy from
138 * upper bound to copy to
140 * offset to subtract from each region boundary position
143 public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
147 LOCK.writeLock().lock();
151 Iterator<int[]> it = copy.getBoundedIterator(start, end);
154 int[] region = it.next();
155 // still need to check boundaries because iterator returns
156 // all overlapping regions and we need contained regions
157 if (region[0] >= start && region[1] <= end)
161 { region[0] - offset, region[1] - offset });
162 numColumns += region[1] - region[0] + 1;
165 cursor = new HiddenColumnsCursor(hiddenColumns);
169 LOCK.writeLock().unlock();
174 * Adds the specified column range to the hidden columns collection
177 * start of range to add (absolute position in alignment)
179 * end of range to add (absolute position in alignment)
181 public void hideColumns(int start, int end)
185 LOCK.writeLock().lock();
188 int prevHiddenCount = 0;
190 if (!hiddenColumns.isEmpty())
192 // set up cursor reset values
193 HiddenCursorPosition cursorPos = cursor.findRegionForColumn(start, false);
194 regionindex = cursorPos.getRegionIndex();
198 // get previous index and hidden count for updating the cursor later
199 previndex = regionindex - 1;
200 int[] prevRegion = hiddenColumns.get(previndex);
201 prevHiddenCount = cursorPos.getHiddenSoFar()
202 - (prevRegion[1] - prevRegion[0] + 1);
206 // new range follows everything else; check first to avoid looping over
207 // whole hiddenColumns collection
208 if (hiddenColumns.isEmpty()
209 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
211 hiddenColumns.add(new int[] { start, end });
212 numColumns += end - start + 1;
217 * traverse existing hidden ranges and insert / amend / append as
220 boolean added = false;
223 added = insertRangeAtRegion(regionindex - 1, start, end);
225 if (!added && regionindex < hiddenColumns.size())
227 insertRangeAtRegion(regionindex, start, end);
231 // reset the cursor to just before our insertion point: this saves
232 // a lot of reprocessing in large alignments
233 cursor = new HiddenColumnsCursor(hiddenColumns, previndex,
238 LOCK.writeLock().unlock();
243 * Insert [start, range] at the region at index i in hiddenColumns, if
249 * start of range to insert
251 * end of range to insert
252 * @return true if range was successfully inserted
254 private boolean insertRangeAtRegion(int i, int start, int end)
256 boolean added = false;
258 int[] region = hiddenColumns.get(i);
259 if (end < region[0] - 1)
262 * insert discontiguous preceding range
264 hiddenColumns.add(i, new int[] { start, end });
265 numColumns += end - start + 1;
268 else if (end <= region[1])
271 * new range overlaps existing, or is contiguous preceding it - adjust
274 int oldstart = region[0];
275 region[0] = Math.min(region[0], start);
276 numColumns += oldstart - region[0]; // new columns are between old and
280 else if (start <= region[1] + 1)
283 * new range overlaps existing, or is contiguous following it - adjust
284 * start and end columns
286 insertRangeAtOverlap(i, start, end, region);
294 * Insert a range whose start position overlaps an existing region and/or is
295 * contiguous to the right of the region
300 * start of range to insert
302 * end of range to insert
304 * the overlapped/continued region
306 private void insertRangeAtOverlap(int i, int start, int end, int[] region)
308 int oldstart = region[0];
309 int oldend = region[1];
310 region[0] = Math.min(region[0], start);
311 region[1] = Math.max(region[1], end);
313 numColumns += oldstart - region[0];
316 * also update or remove any subsequent ranges
317 * that are overlapped
320 while (endi < hiddenColumns.size() - 1)
322 int[] nextRegion = hiddenColumns.get(endi + 1);
323 if (nextRegion[0] > end + 1)
326 * gap to next hidden range - no more to update
330 numColumns -= nextRegion[1] - nextRegion[0] + 1;
331 region[1] = Math.max(nextRegion[1], end);
334 numColumns += region[1] - oldend;
335 hiddenColumns.subList(i + 1, endi + 1).clear();
340 * hide a list of ranges
344 public void hideList(List<int[]> ranges)
348 LOCK.writeLock().lock();
349 for (int[] r : ranges)
351 hideColumns(r[0], r[1]);
353 cursor = new HiddenColumnsCursor(hiddenColumns);
358 LOCK.writeLock().unlock();
363 * Unhides, and adds to the selection list, all hidden columns
365 public void revealAllHiddenColumns(ColumnSelection sel)
369 LOCK.writeLock().lock();
371 for (int[] region : hiddenColumns)
373 for (int j = region[0]; j < region[1] + 1; j++)
378 hiddenColumns.clear();
379 cursor = new HiddenColumnsCursor(hiddenColumns);
385 LOCK.writeLock().unlock();
390 * Reveals, and marks as selected, the hidden column range with the given
394 * the start column to look for
396 * the column selection to add the hidden column range to
398 public void revealHiddenColumns(int start, ColumnSelection sel)
402 LOCK.writeLock().lock();
404 if (!hiddenColumns.isEmpty())
406 int regionIndex = cursor.findRegionForColumn(start, false)
409 if (regionIndex != -1 && regionIndex != hiddenColumns.size())
411 // regionIndex is the region which either contains start
412 // or lies to the right of start
413 int[] region = hiddenColumns.get(regionIndex);
414 if (start == region[0])
416 for (int j = region[0]; j < region[1] + 1; j++)
420 int colsToRemove = region[1] - region[0] + 1;
421 hiddenColumns.remove(regionIndex);
422 numColumns -= colsToRemove;
429 LOCK.writeLock().unlock();
434 * Output regions data as a string. String is in the format:
435 * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
438 * string to delimit regions
439 * @param betweenstring
440 * to put between start and end region values
441 * @return regions formatted according to delimiter and between strings
443 public String regionsToString(String delimiter, String between)
447 LOCK.readLock().lock();
448 StringBuilder regionBuilder = new StringBuilder();
450 boolean first = true;
451 for (int[] range : hiddenColumns)
455 regionBuilder.append(delimiter);
461 regionBuilder.append(range[0]).append(between).append(range[1]);
465 return regionBuilder.toString();
468 LOCK.readLock().unlock();
473 * Find the number of hidden columns
475 * @return number of hidden columns
483 * Get the number of distinct hidden regions
485 * @return number of regions
487 public int getNumberOfRegions()
491 LOCK.readLock().lock();
492 return hiddenColumns.size();
495 LOCK.readLock().unlock();
500 * Answers true if obj is an instance of HiddenColumns, and holds the same
501 * array of start-end column ranges as this, else answers false
504 public boolean equals(Object obj)
508 LOCK.readLock().lock();
510 if (!(obj instanceof HiddenColumns))
514 HiddenColumns that = (HiddenColumns) obj;
517 * check hidden columns are either both null, or match
520 if (that.hiddenColumns.size() != this.hiddenColumns.size())
525 Iterator<int[]> it = this.iterator();
526 Iterator<int[]> thatit = that.iterator();
529 if (!(Arrays.equals(it.next(), thatit.next())))
538 LOCK.readLock().unlock();
543 * Return absolute column index for a visible column index
546 * int column index in alignment view (count from zero)
547 * @return alignment column index for column
549 public int visibleToAbsoluteColumn(int column)
553 LOCK.readLock().lock();
556 if (!hiddenColumns.isEmpty())
558 result += cursor.findRegionForColumn(column, true)
565 LOCK.readLock().unlock();
570 * Use this method to find out where a column will appear in the visible
571 * alignment when hidden columns exist. If the column is not visible, then the
572 * index of the next visible column on the left will be returned (or 0 if
573 * there is no visible column on the left)
575 * @param hiddenColumn
576 * the column index in the full alignment including hidden columns
577 * @return the position of the column in the visible alignment
579 public int absoluteToVisibleColumn(int hiddenColumn)
583 LOCK.readLock().lock();
584 int result = hiddenColumn;
586 if (!hiddenColumns.isEmpty())
588 HiddenCursorPosition cursorPos = cursor
589 .findRegionForColumn(hiddenColumn, false);
590 int index = cursorPos.getRegionIndex();
591 int hiddenBeforeCol = cursorPos.getHiddenSoFar();
593 // just subtract hidden cols count - this works fine if column is
595 result = hiddenColumn - hiddenBeforeCol;
597 // now check in case column is hidden - it will be in the returned
599 if (index < hiddenColumns.size())
601 int[] region = hiddenColumns.get(index);
602 if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
604 // actually col is hidden, return region[0]-1
605 // unless region[0]==0 in which case return 0
612 result = region[0] - 1 - hiddenBeforeCol;
618 return result; // return the shifted position after removing hidden
622 LOCK.readLock().unlock();
627 * Find the visible column which is a given visible number of columns to the
628 * left (negative visibleDistance) or right (positive visibleDistance) of
629 * startColumn. If startColumn is not visible, we use the visible column at
630 * the left boundary of the hidden region containing startColumn.
632 * @param visibleDistance
633 * the number of visible columns to offset by (left offset = negative
634 * value; right offset = positive value)
636 * the position of the column to start from (absolute position)
637 * @return the position of the column which is <visibleDistance> away
638 * (absolute position)
640 public int offsetByVisibleColumns(int visibleDistance, int startColumn)
644 LOCK.readLock().lock();
645 int start = absoluteToVisibleColumn(startColumn);
646 return visibleToAbsoluteColumn(start + visibleDistance);
651 LOCK.readLock().unlock();
656 * This method returns the rightmost limit of a region of an alignment with
657 * hidden columns. In otherwords, the next hidden column.
660 * the absolute (visible) alignmentPosition to find the next hidden
662 * @return the index of the next hidden column, or alPos if there is no next
665 public int getNextHiddenBoundary(boolean left, int alPos)
669 LOCK.readLock().lock();
670 if (!hiddenColumns.isEmpty())
672 int index = cursor.findRegionForColumn(alPos, false)
675 if (left && index > 0)
677 int[] region = hiddenColumns.get(index - 1);
680 else if (!left && index < hiddenColumns.size())
682 int[] region = hiddenColumns.get(index);
683 if (alPos < region[0])
687 else if ((alPos <= region[1])
688 && (index + 1 < hiddenColumns.size()))
690 // alPos is within a hidden region, return the next one
692 region = hiddenColumns.get(index + 1);
700 LOCK.readLock().unlock();
705 * Answers if a column in the alignment is visible
708 * absolute position of column in the alignment
709 * @return true if column is visible
711 public boolean isVisible(int column)
715 LOCK.readLock().lock();
717 if (!hiddenColumns.isEmpty())
719 int regionindex = cursor.findRegionForColumn(column, false)
721 if (regionindex > -1 && regionindex < hiddenColumns.size())
723 int[] region = hiddenColumns.get(regionindex);
724 // already know that column <= region[1] as cursor returns containing
725 // region or region to right
726 if (column >= region[0])
736 LOCK.readLock().unlock();
742 * @return true if there are columns hidden
744 public boolean hasHiddenColumns()
748 LOCK.readLock().lock();
750 // we don't use getSize()>0 here because it has to iterate over
751 // the full hiddenColumns collection and so will be much slower
752 return (!hiddenColumns.isEmpty());
755 LOCK.readLock().unlock();
761 * @return true if there is more than one hidden column region
763 public boolean hasMultiHiddenColumnRegions()
767 LOCK.readLock().lock();
768 return !hiddenColumns.isEmpty() && hiddenColumns.size() > 1;
771 LOCK.readLock().unlock();
777 * Returns a hashCode built from hidden column ranges
780 public int hashCode()
784 LOCK.readLock().lock();
787 for (int[] hidden : hiddenColumns)
789 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
790 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
795 LOCK.readLock().unlock();
800 * Hide columns corresponding to the marked bits
803 * - columns mapped to bits starting from zero
805 public void hideColumns(BitSet inserts)
807 hideColumns(inserts, 0, inserts.length() - 1);
811 * Hide columns corresponding to the marked bits, within the range
812 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
815 * columns mapped to bits starting from zero
817 * start of range to hide columns within
819 * end of range to hide columns within
821 private void hideColumns(BitSet tohide, int start, int end)
825 LOCK.writeLock().lock();
826 for (int firstSet = tohide
827 .nextSetBit(start), lastSet = start; firstSet >= start
828 && lastSet <= end; firstSet = tohide
829 .nextSetBit(lastSet))
831 lastSet = tohide.nextClearBit(firstSet);
834 hideColumns(firstSet, lastSet - 1);
836 else if (firstSet <= end)
838 hideColumns(firstSet, end);
841 cursor = new HiddenColumnsCursor(hiddenColumns);
845 LOCK.writeLock().unlock();
850 * Hide columns corresponding to the marked bits, within the range
851 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
852 * NB Existing entries in [start,end] are cleared.
855 * columns mapped to bits starting from zero
857 * start of range to hide columns within
859 * end of range to hide columns within
861 public void clearAndHideColumns(BitSet tohide, int start, int end)
863 clearHiddenColumnsInRange(start, end);
864 hideColumns(tohide, start, end);
868 * Make all columns in the range [start,end] visible
871 * start of range to show columns
873 * end of range to show columns
875 private void clearHiddenColumnsInRange(int start, int end)
879 LOCK.writeLock().lock();
881 if (!hiddenColumns.isEmpty())
883 HiddenCursorPosition pos = cursor.findRegionForColumn(start, false);
884 int index = pos.getRegionIndex();
886 if (index != -1 && index != hiddenColumns.size())
888 // regionIndex is the region which either contains start
889 // or lies to the right of start
890 int[] region = hiddenColumns.get(index);
891 if (region[0] < start && region[1] >= start)
893 // region contains start, truncate so that it ends just before start
894 numColumns -= region[1] - start + 1;
895 region[1] = start - 1;
900 while (endi < hiddenColumns.size())
902 region = hiddenColumns.get(endi);
906 if (region[0] <= end)
908 // region contains end, truncate so it starts just after end
909 numColumns -= end - region[0] + 1;
915 numColumns -= region[1] - region[0] + 1;
918 hiddenColumns.subList(index, endi).clear();
922 cursor = new HiddenColumnsCursor(hiddenColumns);
927 LOCK.writeLock().unlock();
934 * BitSet where hidden columns will be marked
936 protected void andNot(BitSet updates)
940 LOCK.writeLock().lock();
942 getBitset().andNot(updates);
943 hiddenColumns.clear();
944 hideColumns(hiddenBitSet);
948 LOCK.writeLock().unlock();
953 * Calculate the visible start and end index of an alignment.
956 * full alignment width
957 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
959 public int[] getVisibleStartAndEndIndex(int width)
963 LOCK.readLock().lock();
965 int firstVisible = 0;
966 int lastVisible = width - 1;
968 if (!hiddenColumns.isEmpty())
970 // first visible col with index 0, convert to absolute index
971 firstVisible = visibleToAbsoluteColumn(0);
973 // last visible column is either immediately to left of
974 // last hidden region, or is just the last column in the alignment
975 int[] lastregion = hiddenColumns.get(hiddenColumns.size() - 1);
976 if (lastregion[1] == width - 1)
978 // last region is at very end of alignment
979 // last visible column immediately precedes it
980 lastVisible = lastregion[0] - 1;
983 return new int[] { firstVisible, lastVisible };
987 LOCK.readLock().unlock();
992 * Finds the hidden region (if any) which starts or ends at res
995 * visible residue position, unadjusted for hidden columns
996 * @return region as [start,end] or null if no matching region is found. If
997 * res is adjacent to two regions, returns the left region.
999 public int[] getRegionWithEdgeAtRes(int res)
1003 LOCK.readLock().lock();
1004 int adjres = visibleToAbsoluteColumn(res);
1006 int[] reveal = null;
1008 if (!hiddenColumns.isEmpty())
1010 // look for a region ending just before adjres
1011 int regionindex = cursor.findRegionForColumn(adjres - 1, false)
1013 if (regionindex < hiddenColumns.size()
1014 && hiddenColumns.get(regionindex)[1] == adjres - 1)
1016 reveal = hiddenColumns.get(regionindex);
1018 // check if the region ends just after adjres
1019 else if (regionindex < hiddenColumns.size()
1020 && hiddenColumns.get(regionindex)[0] == adjres + 1)
1022 reveal = hiddenColumns.get(regionindex);
1029 LOCK.readLock().unlock();
1034 * Return an iterator over the hidden regions
1036 public Iterator<int[]> iterator()
1040 LOCK.readLock().lock();
1041 return new RangeIterator(hiddenColumns);
1044 LOCK.readLock().unlock();
1049 * Return a bounded iterator over the hidden regions
1052 * position to start from (inclusive, absolute column position)
1054 * position to end at (inclusive, absolute column position)
1057 public Iterator<int[]> getBoundedIterator(int start, int end)
1061 LOCK.readLock().lock();
1062 return new RangeIterator(start, end, hiddenColumns);
1065 LOCK.readLock().unlock();
1070 * Return a bounded iterator over the *visible* start positions of hidden
1074 * position to start from (inclusive, visible column position)
1076 * position to end at (inclusive, visible column position)
1078 public Iterator<Integer> getStartRegionIterator(int start, int end)
1082 LOCK.readLock().lock();
1084 // get absolute position of column in alignment
1085 int absoluteStart = visibleToAbsoluteColumn(start);
1087 // Get cursor position and supply it to the iterator:
1088 // Since we want visible region start, we look for a cursor for the
1089 // (absoluteStart-1), then if absoluteStart is the start of a visible
1090 // region we'll get the cursor pointing to the region before, which is
1092 HiddenCursorPosition pos = cursor
1093 .findRegionForColumn(absoluteStart - 1, false);
1095 return new StartRegionIterator(pos, start, end,
1099 LOCK.readLock().unlock();
1104 * Return an iterator over visible *columns* (not regions) between the given
1105 * start and end boundaries
1108 * first column (inclusive)
1110 * last column (inclusive)
1112 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1116 LOCK.readLock().lock();
1117 return new RangeElementsIterator(
1118 new VisibleContigsIterator(start, end + 1, hiddenColumns));
1121 LOCK.readLock().unlock();
1126 * return an iterator over visible segments between the given start and end
1130 * first column, inclusive from 0
1132 * last column - not inclusive
1133 * @param useVisibleCoords
1134 * if true, start and end are visible column positions, not absolute
1137 public VisibleContigsIterator getVisContigsIterator(int start,
1139 boolean useVisibleCoords)
1141 int adjstart = start;
1143 if (useVisibleCoords)
1145 adjstart = visibleToAbsoluteColumn(start);
1146 adjend = visibleToAbsoluteColumn(end);
1151 LOCK.readLock().lock();
1152 return new VisibleContigsIterator(adjstart, adjend, hiddenColumns);
1155 LOCK.readLock().unlock();