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<>();
92 public HiddenColumns()
100 * the HiddenColumns object to copy from
102 public HiddenColumns(HiddenColumns copy)
104 this(copy, Integer.MIN_VALUE, Integer.MAX_VALUE, 0);
108 * Copy constructor within bounds and with offset. Copies hidden column
109 * regions fully contained between start and end, and offsets positions by
110 * subtracting offset.
113 * HiddenColumns instance to copy from
115 * lower bound to copy from
117 * upper bound to copy to
119 * offset to subtract from each region boundary position
122 public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
126 LOCK.writeLock().lock();
130 Iterator<int[]> it = copy.getBoundedIterator(start, end);
133 int[] region = it.next();
134 // still need to check boundaries because iterator returns
135 // all overlapping regions and we need contained regions
136 if (region[0] >= start && region[1] <= end)
140 { region[0] - offset, region[1] - offset });
141 numColumns += region[1] - region[0] + 1;
144 cursor = new HiddenColumnsCursor(hiddenColumns);
148 LOCK.writeLock().unlock();
153 * Adds the specified column range to the hidden columns collection
156 * start of range to add (absolute position in alignment)
158 * end of range to add (absolute position in alignment)
160 public void hideColumns(int start, int end)
164 LOCK.writeLock().lock();
167 int prevHiddenCount = 0;
169 if (!hiddenColumns.isEmpty())
171 // set up cursor reset values
172 HiddenCursorPosition cursorPos = cursor.findRegionForColumn(start, false);
173 regionindex = cursorPos.getRegionIndex();
177 // get previous index and hidden count for updating the cursor later
178 previndex = regionindex - 1;
179 int[] prevRegion = hiddenColumns.get(previndex);
180 prevHiddenCount = cursorPos.getHiddenSoFar()
181 - (prevRegion[1] - prevRegion[0] + 1);
185 // new range follows everything else; check first to avoid looping over
186 // whole hiddenColumns collection
187 if (hiddenColumns.isEmpty()
188 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
190 hiddenColumns.add(new int[] { start, end });
191 numColumns += end - start + 1;
196 * traverse existing hidden ranges and insert / amend / append as
199 boolean added = false;
202 added = insertRangeAtRegion(regionindex - 1, start, end);
204 if (!added && regionindex < hiddenColumns.size())
206 insertRangeAtRegion(regionindex, start, end);
210 // reset the cursor to just before our insertion point: this saves
211 // a lot of reprocessing in large alignments
212 cursor = new HiddenColumnsCursor(hiddenColumns, previndex,
216 LOCK.writeLock().unlock();
221 * Insert [start, range] at the region at index i in hiddenColumns, if
227 * start of range to insert
229 * end of range to insert
230 * @return true if range was successfully inserted
232 private boolean insertRangeAtRegion(int i, int start, int end)
234 boolean added = false;
236 int[] region = hiddenColumns.get(i);
237 if (end < region[0] - 1)
240 * insert discontiguous preceding range
242 hiddenColumns.add(i, new int[] { start, end });
243 numColumns += end - start + 1;
246 else if (end <= region[1])
249 * new range overlaps existing, or is contiguous preceding it - adjust
252 int oldstart = region[0];
253 region[0] = Math.min(region[0], start);
254 numColumns += oldstart - region[0]; // new columns are between old and
258 else if (start <= region[1] + 1)
261 * new range overlaps existing, or is contiguous following it - adjust
262 * start and end columns
264 insertRangeAtOverlap(i, start, end, region);
271 * Insert a range whose start position overlaps an existing region and/or is
272 * contiguous to the right of the region
277 * start of range to insert
279 * end of range to insert
281 * the overlapped/continued region
283 private void insertRangeAtOverlap(int i, int start, int end, int[] region)
285 int oldstart = region[0];
286 int oldend = region[1];
287 region[0] = Math.min(region[0], start);
288 region[1] = Math.max(region[1], end);
290 numColumns += oldstart - region[0];
293 * also update or remove any subsequent ranges
294 * that are overlapped
297 while (endi < hiddenColumns.size() - 1)
299 int[] nextRegion = hiddenColumns.get(endi + 1);
300 if (nextRegion[0] > end + 1)
303 * gap to next hidden range - no more to update
307 numColumns -= nextRegion[1] - nextRegion[0] + 1;
308 region[1] = Math.max(nextRegion[1], end);
311 numColumns += region[1] - oldend;
312 hiddenColumns.subList(i + 1, endi + 1).clear();
316 * hide a list of ranges
320 public void hideList(List<int[]> ranges)
324 LOCK.writeLock().lock();
325 for (int[] r : ranges)
327 hideColumns(r[0], r[1]);
329 cursor = new HiddenColumnsCursor(hiddenColumns);
333 LOCK.writeLock().unlock();
338 * Unhides, and adds to the selection list, all hidden columns
340 public void revealAllHiddenColumns(ColumnSelection sel)
344 LOCK.writeLock().lock();
346 for (int[] region : hiddenColumns)
348 for (int j = region[0]; j < region[1] + 1; j++)
353 hiddenColumns.clear();
354 cursor = new HiddenColumnsCursor(hiddenColumns);
359 LOCK.writeLock().unlock();
364 * Reveals, and marks as selected, the hidden column range with the given
368 * the start column to look for
370 * the column selection to add the hidden column range to
372 public void revealHiddenColumns(int start, ColumnSelection sel)
376 LOCK.writeLock().lock();
378 if (!hiddenColumns.isEmpty())
380 int regionIndex = cursor.findRegionForColumn(start, false)
383 if (regionIndex != -1 && regionIndex != hiddenColumns.size())
385 // regionIndex is the region which either contains start
386 // or lies to the right of start
387 int[] region = hiddenColumns.get(regionIndex);
388 if (start == region[0])
390 for (int j = region[0]; j < region[1] + 1; j++)
394 int colsToRemove = region[1] - region[0] + 1;
395 hiddenColumns.remove(regionIndex);
396 numColumns -= colsToRemove;
402 LOCK.writeLock().unlock();
407 * Output regions data as a string. String is in the format:
408 * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
411 * string to delimit regions
412 * @param betweenstring
413 * to put between start and end region values
414 * @return regions formatted according to delimiter and between strings
416 public String regionsToString(String delimiter, String between)
420 LOCK.readLock().lock();
421 StringBuilder regionBuilder = new StringBuilder();
423 boolean first = true;
424 for (int[] range : hiddenColumns)
428 regionBuilder.append(delimiter);
434 regionBuilder.append(range[0]).append(between).append(range[1]);
438 return regionBuilder.toString();
441 LOCK.readLock().unlock();
446 * Find the number of hidden columns
448 * @return number of hidden columns
456 * Get the number of distinct hidden regions
458 * @return number of regions
460 public int getNumberOfRegions()
464 LOCK.readLock().lock();
465 return hiddenColumns.size();
468 LOCK.readLock().unlock();
473 public boolean equals(Object obj)
477 LOCK.readLock().lock();
479 if (!(obj instanceof HiddenColumns))
483 HiddenColumns that = (HiddenColumns) obj;
486 * check hidden columns are either both null, or match
489 if (that.hiddenColumns.size() != this.hiddenColumns.size())
494 Iterator<int[]> it = this.iterator();
495 Iterator<int[]> thatit = that.iterator();
498 if (!(Arrays.equals(it.next(), thatit.next())))
507 LOCK.readLock().unlock();
512 * Return absolute column index for a visible column index
515 * int column index in alignment view (count from zero)
516 * @return alignment column index for column
518 public int visibleToAbsoluteColumn(int column)
522 LOCK.readLock().lock();
525 if (!hiddenColumns.isEmpty())
527 result += cursor.findRegionForColumn(column, true)
534 LOCK.readLock().unlock();
539 * Use this method to find out where a column will appear in the visible
540 * alignment when hidden columns exist. If the column is not visible, then the
541 * index of the next visible column on the left will be returned (or 0 if
542 * there is no visible column on the left)
544 * @param hiddenColumn
545 * the column index in the full alignment including hidden columns
546 * @return the position of the column in the visible alignment
548 public int absoluteToVisibleColumn(int hiddenColumn)
552 LOCK.readLock().lock();
553 int result = hiddenColumn;
555 if (!hiddenColumns.isEmpty())
557 HiddenCursorPosition cursorPos = cursor
558 .findRegionForColumn(hiddenColumn, false);
559 int index = cursorPos.getRegionIndex();
560 int hiddenBeforeCol = cursorPos.getHiddenSoFar();
562 // just subtract hidden cols count - this works fine if column is
564 result = hiddenColumn - hiddenBeforeCol;
566 // now check in case column is hidden - it will be in the returned
568 if (index < hiddenColumns.size())
570 int[] region = hiddenColumns.get(index);
571 if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
573 // actually col is hidden, return region[0]-1
574 // unless region[0]==0 in which case return 0
581 result = region[0] - 1 - hiddenBeforeCol;
587 return result; // return the shifted position after removing hidden
591 LOCK.readLock().unlock();
596 * Find the visible column which is a given visible number of columns to the
597 * left (negative visibleDistance) or right (positive visibleDistance) of
598 * startColumn. If startColumn is not visible, we use the visible column at
599 * the left boundary of the hidden region containing startColumn.
601 * @param visibleDistance
602 * the number of visible columns to offset by (left offset = negative
603 * value; right offset = positive value)
605 * the position of the column to start from (absolute position)
606 * @return the position of the column which is <visibleDistance> away
607 * (absolute position)
609 public int offsetByVisibleColumns(int visibleDistance, int startColumn)
613 LOCK.readLock().lock();
614 int start = absoluteToVisibleColumn(startColumn);
615 return visibleToAbsoluteColumn(start + visibleDistance);
619 LOCK.readLock().unlock();
624 * This method returns the rightmost limit of a region of an alignment with
625 * hidden columns. In otherwords, the next hidden column.
628 * the absolute (visible) alignmentPosition to find the next hidden
630 * @return the index of the next hidden column, or alPos if there is no next
633 public int getNextHiddenBoundary(boolean left, int alPos)
637 LOCK.readLock().lock();
638 if (!hiddenColumns.isEmpty())
640 int index = cursor.findRegionForColumn(alPos, false)
643 if (left && index > 0)
645 int[] region = hiddenColumns.get(index - 1);
648 else if (!left && index < hiddenColumns.size())
650 int[] region = hiddenColumns.get(index);
651 if (alPos < region[0])
655 else if ((alPos <= region[1])
656 && (index + 1 < hiddenColumns.size()))
658 // alPos is within a hidden region, return the next one
660 region = hiddenColumns.get(index + 1);
668 LOCK.readLock().unlock();
673 * Answers if a column in the alignment is visible
676 * absolute position of column in the alignment
677 * @return true if column is visible
679 public boolean isVisible(int column)
683 LOCK.readLock().lock();
685 if (!hiddenColumns.isEmpty())
687 int regionindex = cursor.findRegionForColumn(column, false)
689 if (regionindex > -1 && regionindex < hiddenColumns.size())
691 int[] region = hiddenColumns.get(regionindex);
692 // already know that column <= region[1] as cursor returns containing
693 // region or region to right
694 if (column >= region[0])
704 LOCK.readLock().unlock();
710 * @return true if there are columns hidden
712 public boolean hasHiddenColumns()
716 LOCK.readLock().lock();
718 // we don't use getSize()>0 here because it has to iterate over
719 // the full hiddenColumns collection and so will be much slower
720 return (!hiddenColumns.isEmpty());
723 LOCK.readLock().unlock();
729 * @return true if there is more than one hidden column region
731 public boolean hasMultiHiddenColumnRegions()
735 LOCK.readLock().lock();
736 return !hiddenColumns.isEmpty() && hiddenColumns.size() > 1;
739 LOCK.readLock().unlock();
745 * Returns a hashCode built from hidden column ranges
748 public int hashCode()
752 LOCK.readLock().lock();
755 for (int[] hidden : hiddenColumns)
757 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
758 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
763 LOCK.readLock().unlock();
768 * Hide columns corresponding to the marked bits
771 * - columns mapped to bits starting from zero
773 public void hideColumns(BitSet inserts)
775 hideColumns(inserts, 0, inserts.length() - 1);
779 * Hide columns corresponding to the marked bits, within the range
780 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
783 * columns mapped to bits starting from zero
785 * start of range to hide columns within
787 * end of range to hide columns within
789 private void hideColumns(BitSet tohide, int start, int end)
793 LOCK.writeLock().lock();
794 for (int firstSet = tohide
795 .nextSetBit(start), lastSet = start; firstSet >= start
796 && lastSet <= end; firstSet = tohide
797 .nextSetBit(lastSet))
799 lastSet = tohide.nextClearBit(firstSet);
802 hideColumns(firstSet, lastSet - 1);
804 else if (firstSet <= end)
806 hideColumns(firstSet, end);
809 cursor = new HiddenColumnsCursor(hiddenColumns);
812 LOCK.writeLock().unlock();
817 * Hide columns corresponding to the marked bits, within the range
818 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
819 * NB Existing entries in [start,end] are cleared.
822 * columns mapped to bits starting from zero
824 * start of range to hide columns within
826 * end of range to hide columns within
828 public void clearAndHideColumns(BitSet tohide, int start, int end)
830 clearHiddenColumnsInRange(start, end);
831 hideColumns(tohide, start, end);
835 * Make all columns in the range [start,end] visible
838 * start of range to show columns
840 * end of range to show columns
842 private void clearHiddenColumnsInRange(int start, int end)
846 LOCK.writeLock().lock();
848 if (!hiddenColumns.isEmpty())
850 HiddenCursorPosition pos = cursor.findRegionForColumn(start, false);
851 int index = pos.getRegionIndex();
853 if (index != -1 && index != hiddenColumns.size())
855 // regionIndex is the region which either contains start
856 // or lies to the right of start
857 int[] region = hiddenColumns.get(index);
858 if (region[0] < start && region[1] >= start)
860 // region contains start, truncate so that it ends just before start
861 numColumns -= region[1] - start + 1;
862 region[1] = start - 1;
867 while (endi < hiddenColumns.size())
869 region = hiddenColumns.get(endi);
873 if (region[0] <= end)
875 // region contains end, truncate so it starts just after end
876 numColumns -= end - region[0] + 1;
882 numColumns -= region[1] - region[0] + 1;
885 hiddenColumns.subList(index, endi).clear();
889 cursor = new HiddenColumnsCursor(hiddenColumns);
893 LOCK.writeLock().unlock();
900 * BitSet where hidden columns will be marked
902 protected void andNot(BitSet updates)
906 LOCK.writeLock().lock();
908 BitSet hiddenBitSet = new BitSet();
909 for (int[] range : hiddenColumns)
911 hiddenBitSet.set(range[0], range[1] + 1);
913 hiddenBitSet.andNot(updates);
914 hiddenColumns.clear();
915 hideColumns(hiddenBitSet);
918 LOCK.writeLock().unlock();
923 * Calculate the visible start and end index of an alignment.
926 * full alignment width
927 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
929 public int[] getVisibleStartAndEndIndex(int width)
933 LOCK.readLock().lock();
935 int firstVisible = 0;
936 int lastVisible = width - 1;
938 if (!hiddenColumns.isEmpty())
940 // first visible col with index 0, convert to absolute index
941 firstVisible = visibleToAbsoluteColumn(0);
943 // last visible column is either immediately to left of
944 // last hidden region, or is just the last column in the alignment
945 int[] lastregion = hiddenColumns.get(hiddenColumns.size() - 1);
946 if (lastregion[1] == width - 1)
948 // last region is at very end of alignment
949 // last visible column immediately precedes it
950 lastVisible = lastregion[0] - 1;
953 return new int[] { firstVisible, lastVisible };
957 LOCK.readLock().unlock();
962 * Finds the hidden region (if any) which starts or ends at res
965 * visible residue position, unadjusted for hidden columns
966 * @return region as [start,end] or null if no matching region is found. If
967 * res is adjacent to two regions, returns the left region.
969 public int[] getRegionWithEdgeAtRes(int res)
973 LOCK.readLock().lock();
974 int adjres = visibleToAbsoluteColumn(res);
978 if (!hiddenColumns.isEmpty())
980 // look for a region ending just before adjres
981 int regionindex = cursor.findRegionForColumn(adjres - 1, false)
983 if (regionindex < hiddenColumns.size()
984 && hiddenColumns.get(regionindex)[1] == adjres - 1)
986 reveal = hiddenColumns.get(regionindex);
988 // check if the region ends just after adjres
989 else if (regionindex < hiddenColumns.size()
990 && hiddenColumns.get(regionindex)[0] == adjres + 1)
992 reveal = hiddenColumns.get(regionindex);
999 LOCK.readLock().unlock();
1004 * Return an iterator over the hidden regions
1006 public Iterator<int[]> iterator()
1010 LOCK.readLock().lock();
1011 return new RangeIterator(hiddenColumns);
1014 LOCK.readLock().unlock();
1019 * Return a bounded iterator over the hidden regions
1022 * position to start from (inclusive, absolute column position)
1024 * position to end at (inclusive, absolute column position)
1027 public Iterator<int[]> getBoundedIterator(int start, int end)
1031 LOCK.readLock().lock();
1032 return new RangeIterator(start, end, hiddenColumns);
1035 LOCK.readLock().unlock();
1040 * Return a bounded iterator over the *visible* start positions of hidden
1044 * position to start from (inclusive, visible column position)
1046 * position to end at (inclusive, visible column position)
1048 public Iterator<Integer> getStartRegionIterator(int start, int end)
1052 LOCK.readLock().lock();
1054 // get absolute position of column in alignment
1055 int absoluteStart = visibleToAbsoluteColumn(start);
1057 // Get cursor position and supply it to the iterator:
1058 // Since we want visible region start, we look for a cursor for the
1059 // (absoluteStart-1), then if absoluteStart is the start of a visible
1060 // region we'll get the cursor pointing to the region before, which is
1062 HiddenCursorPosition pos = cursor
1063 .findRegionForColumn(absoluteStart - 1, false);
1065 return new StartRegionIterator(pos, start, end,
1069 LOCK.readLock().unlock();
1074 * Return an iterator over visible *columns* (not regions) between the given
1075 * start and end boundaries
1078 * first column (inclusive)
1080 * last column (inclusive)
1082 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1086 LOCK.readLock().lock();
1087 return new RangeElementsIterator(
1088 new VisibleContigsIterator(start, end + 1, hiddenColumns));
1091 LOCK.readLock().unlock();
1096 * return an iterator over visible segments between the given start and end
1100 * first column, inclusive from 0
1102 * last column - not inclusive
1103 * @param useVisibleCoords
1104 * if true, start and end are visible column positions, not absolute
1107 public VisibleContigsIterator getVisContigsIterator(int start,
1109 boolean useVisibleCoords)
1111 int adjstart = start;
1113 if (useVisibleCoords)
1115 adjstart = visibleToAbsoluteColumn(start);
1116 adjend = visibleToAbsoluteColumn(end);
1121 LOCK.readLock().lock();
1122 return new VisibleContigsIterator(adjstart, adjend, hiddenColumns);
1125 LOCK.readLock().unlock();