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 int NUMCOLUMNS_RESET = -1; // value of numColumns if it
70 // needs to be recalculated
72 private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
75 * Cursor which tracks the last used hidden columns region, and the number
76 * of hidden columns up to (but not including) that region.
78 private HiddenColumnsCursor cursor = new HiddenColumnsCursor();
81 * cache of the number of hidden columns
83 private int numColumns = 0;
86 * list of hidden column [start, end] ranges; the list is maintained in
87 * ascending start column order
89 private List<int[]> hiddenColumns = new ArrayList<>();
94 public HiddenColumns()
102 * the HiddenColumns object to copy from
104 public HiddenColumns(HiddenColumns copy)
106 this(copy, Integer.MIN_VALUE, Integer.MAX_VALUE, 0);
110 * Copy constructor within bounds and with offset. Copies hidden column
111 * regions fully contained between start and end, and offsets positions by
112 * subtracting offset.
115 * HiddenColumns instance to copy from
117 * lower bound to copy from
119 * upper bound to copy to
121 * offset to subtract from each region boundary position
124 public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
128 LOCK.writeLock().lock();
132 Iterator<int[]> it = copy.getBoundedIterator(start, end);
135 int[] region = it.next();
136 // still need to check boundaries because iterator returns
137 // all overlapping regions and we need contained regions
138 if (region[0] >= start && region[1] <= end)
142 { region[0] - offset, region[1] - offset });
143 numColumns += region[1] - region[0] + 1;
146 cursor = new HiddenColumnsCursor(hiddenColumns);
150 LOCK.writeLock().unlock();
155 * Adds the specified column range to the hidden columns collection
158 * start of range to add (absolute position in alignment)
160 * end of range to add (absolute position in alignment)
162 public void hideColumns(int start, int end)
166 LOCK.writeLock().lock();
169 int prevHiddenCount = 0;
171 if (!hiddenColumns.isEmpty())
173 // set up cursor reset values
174 HiddenCursorPosition cursorPos = cursor.findRegionForColumn(start,
176 regionindex = cursorPos.getRegionIndex();
180 // get previous index and hidden count for updating the cursor later
181 previndex = regionindex - 1;
182 int[] prevRegion = hiddenColumns.get(previndex);
183 prevHiddenCount = cursorPos.getHiddenSoFar()
184 - (prevRegion[1] - prevRegion[0] + 1);
189 * new range follows everything else; check first to avoid looping over whole hiddenColumns collection
191 if (hiddenColumns.isEmpty()
192 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
194 hiddenColumns.add(new int[] { start, end });
199 * traverse existing hidden ranges and insert / amend / append as
202 boolean added = false;
205 added = insertRangeAtRegion(regionindex - 1, start, end);
207 if (!added && regionindex < hiddenColumns.size())
209 insertRangeAtRegion(regionindex, start, end);
213 // reset the cursor to just before our insertion point: this saves
214 // a lot of reprocessing in large alignments
215 cursor = new HiddenColumnsCursor(hiddenColumns, previndex,
218 // reset the number of columns so they will be recounted
223 LOCK.writeLock().unlock();
228 * Insert [start, range] at the region at index i in hiddenColumns, if
234 * start of range to insert
236 * end of range to insert
237 * @return true if range was successfully inserted
239 private boolean insertRangeAtRegion(int i, int start, int end)
241 boolean added = false;
243 int[] region = hiddenColumns.get(i);
244 if (end < region[0] - 1)
247 * insert discontiguous preceding range
249 hiddenColumns.add(i, new int[] { start, end });
252 else if (end <= region[1])
255 * new range overlaps existing, or is contiguous preceding it - adjust
258 region[0] = Math.min(region[0], start);
261 else if (start <= region[1] + 1)
264 * new range overlaps existing, or is contiguous following it - adjust
265 * start and end columns
267 region[0] = Math.min(region[0], start);
268 region[1] = Math.max(region[1], end);
271 * also update or remove any subsequent ranges
272 * that are overlapped
274 while (i < hiddenColumns.size() - 1)
276 int[] nextRegion = hiddenColumns.get(i + 1);
277 if (nextRegion[0] > end + 1)
280 * gap to next hidden range - no more to update
284 region[1] = Math.max(nextRegion[1], end);
286 // in theory hiddenColumns.subList(i + 1, i + 2).clear() is faster than
287 // hiddenColumns.remove(i+1) but benchmarking results a bit ambivalent
288 hiddenColumns.remove(i + 1);
296 * hide a list of ranges
300 public void hideList(List<int[]> ranges)
304 LOCK.writeLock().lock();
305 for (int[] r : ranges)
307 hideColumns(r[0], r[1]);
309 cursor = new HiddenColumnsCursor(hiddenColumns);
313 LOCK.writeLock().unlock();
318 * Unhides, and adds to the selection list, all hidden columns
320 public void revealAllHiddenColumns(ColumnSelection sel)
324 LOCK.writeLock().lock();
326 for (int[] region : hiddenColumns)
328 for (int j = region[0]; j < region[1] + 1; j++)
333 hiddenColumns.clear();
334 cursor = new HiddenColumnsCursor(hiddenColumns);
339 LOCK.writeLock().unlock();
344 * Reveals, and marks as selected, the hidden column range with the given
348 * the start column to look for
350 * the column selection to add the hidden column range to
352 public void revealHiddenColumns(int start, ColumnSelection sel)
356 LOCK.writeLock().lock();
358 if (!hiddenColumns.isEmpty())
360 int regionIndex = cursor.findRegionForColumn(start, false)
363 if (regionIndex != -1 && regionIndex != hiddenColumns.size())
365 // regionIndex is the region which either contains start
366 // or lies to the right of start
367 int[] region = hiddenColumns.get(regionIndex);
368 if (start == region[0])
370 for (int j = region[0]; j < region[1] + 1; j++)
374 int colsToRemove = region[1] - region[0] + 1;
375 hiddenColumns.remove(regionIndex);
377 if (hiddenColumns.isEmpty())
383 numColumns -= colsToRemove;
385 cursor.updateForDeletedRegion(hiddenColumns);
391 LOCK.writeLock().unlock();
396 * Output regions data as a string. String is in the format:
397 * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
400 * string to delimit regions
401 * @param betweenstring
402 * to put between start and end region values
403 * @return regions formatted according to delimiter and between strings
405 public String regionsToString(String delimiter, String between)
409 LOCK.readLock().lock();
410 StringBuilder regionBuilder = new StringBuilder();
412 boolean first = true;
413 for (int[] range : hiddenColumns)
417 regionBuilder.append(delimiter);
423 regionBuilder.append(range[0]).append(between).append(range[1]);
427 return regionBuilder.toString();
430 LOCK.readLock().unlock();
435 * Find the number of hidden columns
437 * @return number of hidden columns
443 LOCK.readLock().lock();
445 if (numColumns == NUMCOLUMNS_RESET)
447 // numColumns is out of date, so recalculate
450 for (int[] range : hiddenColumns)
452 size += range[1] - range[0] + 1;
461 LOCK.readLock().unlock();
466 * Reset numColumns so that it gets recalculated. Currently the code does not
467 * recalculate numColumns on hide/reveal as it requires a full sweep of the
468 * hidden columns collection / smarter updating. Placeholder here if later on
469 * a recalculation is added.
471 private void resetNumColumns()
473 numColumns = NUMCOLUMNS_RESET;
477 * Get the number of distinct hidden regions
479 * @return number of regions
481 public int getNumberOfRegions()
485 LOCK.readLock().lock();
486 return hiddenColumns.size();
489 LOCK.readLock().unlock();
494 public boolean equals(Object obj)
498 LOCK.readLock().lock();
500 if (!(obj instanceof HiddenColumns))
504 HiddenColumns that = (HiddenColumns) obj;
507 * check hidden columns are either both null, or match
510 if (that.hiddenColumns.size() != this.hiddenColumns.size())
515 Iterator<int[]> it = this.iterator();
516 Iterator<int[]> thatit = that.iterator();
519 if (!(Arrays.equals(it.next(), thatit.next())))
528 LOCK.readLock().unlock();
533 * Return absolute column index for a visible column index
536 * int column index in alignment view (count from zero)
537 * @return alignment column index for column
539 public int visibleToAbsoluteColumn(int column)
543 LOCK.readLock().lock();
546 if (!hiddenColumns.isEmpty())
548 result += cursor.findRegionForColumn(column, true)
555 LOCK.readLock().unlock();
560 * Use this method to find out where a column will appear in the visible
561 * alignment when hidden columns exist. If the column is not visible, then the
562 * index of the next visible column on the left will be returned (or 0 if
563 * there is no visible column on the left)
565 * @param hiddenColumn
566 * the column index in the full alignment including hidden columns
567 * @return the position of the column in the visible alignment
569 public int absoluteToVisibleColumn(int hiddenColumn)
573 LOCK.readLock().lock();
574 int result = hiddenColumn;
576 if (!hiddenColumns.isEmpty())
578 HiddenCursorPosition cursorPos = cursor
579 .findRegionForColumn(hiddenColumn, false);
580 int index = cursorPos.getRegionIndex();
581 int hiddenBeforeCol = cursorPos.getHiddenSoFar();
583 // just subtract hidden cols count - this works fine if column is
585 result = hiddenColumn - hiddenBeforeCol;
587 // now check in case column is hidden - it will be in the returned
589 if (index < hiddenColumns.size())
591 int[] region = hiddenColumns.get(index);
592 if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
594 // actually col is hidden, return region[0]-1
595 // unless region[0]==0 in which case return 0
602 result = region[0] - 1 - hiddenBeforeCol;
608 return result; // return the shifted position after removing hidden
612 LOCK.readLock().unlock();
617 * Find the visible column which is a given visible number of columns to the
618 * left (negative visibleDistance) or right (positive visibleDistance) of
619 * startColumn. If startColumn is not visible, we use the visible column at
620 * the left boundary of the hidden region containing startColumn.
622 * @param visibleDistance
623 * the number of visible columns to offset by (left offset = negative
624 * value; right offset = positive value)
626 * the position of the column to start from (absolute position)
627 * @return the position of the column which is <visibleDistance> away
628 * (absolute position)
630 public int offsetByVisibleColumns(int visibleDistance, int startColumn)
634 LOCK.readLock().lock();
635 int start = absoluteToVisibleColumn(startColumn);
636 return visibleToAbsoluteColumn(start + visibleDistance);
640 LOCK.readLock().unlock();
645 * This method returns the rightmost limit of a region of an alignment with
646 * hidden columns. In otherwords, the next hidden column.
649 * the absolute (visible) alignmentPosition to find the next hidden
651 * @return the index of the next hidden column, or alPos if there is no next
654 public int getNextHiddenBoundary(boolean left, int alPos)
658 LOCK.readLock().lock();
659 if (!hiddenColumns.isEmpty())
661 int index = cursor.findRegionForColumn(alPos, false)
664 if (left && index > 0)
666 int[] region = hiddenColumns.get(index - 1);
669 else if (!left && index < hiddenColumns.size())
671 int[] region = hiddenColumns.get(index);
672 if (alPos < region[0])
676 else if ((alPos <= region[1])
677 && (index + 1 < hiddenColumns.size()))
679 // alPos is within a hidden region, return the next one
681 region = hiddenColumns.get(index + 1);
689 LOCK.readLock().unlock();
694 * Answers if a column in the alignment is visible
697 * absolute position of column in the alignment
698 * @return true if column is visible
700 public boolean isVisible(int column)
704 LOCK.readLock().lock();
706 int regionindex = cursor.findRegionForColumn(column, false)
708 if (regionindex > -1 && regionindex < hiddenColumns.size())
710 int[] region = hiddenColumns.get(regionindex);
711 // already know that column <= region[1] as cursor returns containing
712 // region or region to right
713 if (column >= region[0])
722 LOCK.readLock().unlock();
728 * @return true if there are columns hidden
730 public boolean hasHiddenColumns()
734 LOCK.readLock().lock();
736 // we don't use getSize()>0 here because it has to iterate over
737 // the full hiddenColumns collection and so will be much slower
738 return (!hiddenColumns.isEmpty());
741 LOCK.readLock().unlock();
747 * @return true if there is more than one hidden column region
749 public boolean hasMultiHiddenColumnRegions()
753 LOCK.readLock().lock();
754 return !hiddenColumns.isEmpty() && hiddenColumns.size() > 1;
757 LOCK.readLock().unlock();
763 * Returns a hashCode built from hidden column ranges
766 public int hashCode()
770 LOCK.readLock().lock();
773 for (int[] hidden : hiddenColumns)
775 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
776 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
781 LOCK.readLock().unlock();
786 * Hide columns corresponding to the marked bits
789 * - columns mapped to bits starting from zero
791 public void hideColumns(BitSet inserts)
795 LOCK.writeLock().lock();
796 for (int firstSet = inserts
797 .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
798 .nextSetBit(lastSet))
800 lastSet = inserts.nextClearBit(firstSet);
801 hideColumns(firstSet, lastSet - 1);
803 cursor = new HiddenColumnsCursor(hiddenColumns);
807 LOCK.writeLock().unlock();
812 * Hide columns corresponding to the marked bits, within the range
813 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
816 * columns mapped to bits starting from zero
818 * start of range to hide columns within
820 * end of range to hide columns within
822 public void hideColumns(BitSet tohide, int start, int end)
824 clearHiddenColumnsInRange(start, end);
826 // make sure only bits between start and end are set
827 if (!tohide.isEmpty())
829 tohide.clear(0, start);
830 tohide.clear(Math.min(end + 1, tohide.length() + 1),
831 tohide.length() + 1);
838 * Make all columns in the range [start,end] visible
841 * start of range to show columns
843 * end of range to show columns
845 private void clearHiddenColumnsInRange(int start, int end)
849 LOCK.writeLock().lock();
851 if (!hiddenColumns.isEmpty())
853 HiddenCursorPosition pos = cursor.findRegionForColumn(start, false);
854 int index = pos.getRegionIndex();
855 int startindex = index; // first index in hiddenColumns to remove
857 if (index != -1 && index != hiddenColumns.size())
859 // regionIndex is the region which either contains start
860 // or lies to the right of start
861 int[] region = hiddenColumns.get(index);
862 if (region[0] < start && region[1] >= start)
864 // region contains start, truncate so that it ends just before start
865 region[1] = start - 1;
870 pos = cursor.findRegionForColumn(end, false);
871 index = pos.getRegionIndex();
872 int endindex = index - 1; // last index in hiddenColumns to remove
874 if (index != -1 && index != hiddenColumns.size())
876 // regionIndex is the region which either contains end
877 // or lies to the right of end
878 int[] region = hiddenColumns.get(index);
879 if (region[0] <= end && region[1] > end)
881 // region contains end, truncate so that it starts just after end
886 hiddenColumns.subList(startindex, endindex + 1).clear();
887 cursor = new HiddenColumnsCursor(hiddenColumns);
892 LOCK.writeLock().unlock();
899 * BitSet where hidden columns will be marked
901 protected void andNot(BitSet updates)
905 LOCK.writeLock().lock();
907 BitSet hiddenBitSet = new BitSet();
908 for (int[] range : hiddenColumns)
910 hiddenBitSet.set(range[0], range[1] + 1);
912 hiddenBitSet.andNot(updates);
913 hiddenColumns.clear();
914 hideColumns(hiddenBitSet);
917 LOCK.writeLock().unlock();
922 * Calculate the visible start and end index of an alignment.
925 * full alignment width
926 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
928 public int[] getVisibleStartAndEndIndex(int width)
932 LOCK.readLock().lock();
934 int firstVisible = 0;
935 int lastVisible = width - 1;
937 if (!hiddenColumns.isEmpty())
939 // first visible col with index 0, convert to absolute index
940 firstVisible = visibleToAbsoluteColumn(0);
942 // last visible column is either immediately to left of
943 // last hidden region, or is just the last column in the alignment
944 int[] lastregion = hiddenColumns.get(hiddenColumns.size() - 1);
945 if (lastregion[1] == width - 1)
947 // last region is at very end of alignment
948 // last visible column immediately precedes it
949 lastVisible = lastregion[0] - 1;
952 return new int[] { firstVisible, lastVisible };
956 LOCK.readLock().unlock();
961 * Finds the hidden region (if any) which starts or ends at res
964 * visible residue position, unadjusted for hidden columns
965 * @return region as [start,end] or null if no matching region is found. If
966 * res is adjacent to two regions, returns the left region.
968 public int[] getRegionWithEdgeAtRes(int res)
972 LOCK.readLock().lock();
973 int adjres = visibleToAbsoluteColumn(res);
977 if (!hiddenColumns.isEmpty())
979 // look for a region ending just before adjres
980 int regionindex = cursor.findRegionForColumn(adjres - 1, false)
982 if (regionindex < hiddenColumns.size()
983 && hiddenColumns.get(regionindex)[1] == adjres - 1)
985 reveal = hiddenColumns.get(regionindex);
987 // check if the region ends just after adjres
988 else if (regionindex < hiddenColumns.size()
989 && hiddenColumns.get(regionindex)[0] == adjres + 1)
991 reveal = hiddenColumns.get(regionindex);
998 LOCK.readLock().unlock();
1003 * Return an iterator over the hidden regions
1005 public Iterator<int[]> iterator()
1009 LOCK.readLock().lock();
1010 return new HiddenColsIterator(hiddenColumns);
1013 LOCK.readLock().unlock();
1018 * Return a bounded iterator over the hidden regions
1021 * position to start from (inclusive, absolute column position)
1023 * position to end at (inclusive, absolute column position)
1026 public Iterator<int[]> getBoundedIterator(int start, int end)
1030 LOCK.readLock().lock();
1031 return new HiddenColsIterator(start, end, hiddenColumns);
1034 LOCK.readLock().unlock();
1039 * Return a bounded iterator over the *visible* start positions of hidden
1043 * position to start from (inclusive, visible column position)
1045 * position to end at (inclusive, visible column position)
1047 public Iterator<Integer> getBoundedStartIterator(int start, int end)
1051 LOCK.readLock().lock();
1053 // get absolute position of column in alignment
1054 int absoluteStart = visibleToAbsoluteColumn(start);
1056 // Get cursor position and supply it to the iterator:
1057 // Since we want visible region start, we look for a cursor for the
1058 // (absoluteStart-1), then if absoluteStart is the start of a visible
1059 // region we'll get the cursor pointing to the region before, which is
1061 HiddenCursorPosition pos = cursor
1062 .findRegionForColumn(absoluteStart - 1, false);
1064 return new BoundedStartRegionIterator(pos, start, end,
1068 LOCK.readLock().unlock();
1073 * Return an iterator over visible *columns* (not regions) between the given
1074 * start and end boundaries
1077 * first column (inclusive)
1079 * last column (inclusive)
1081 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1085 LOCK.readLock().lock();
1086 return new VisibleColsIterator(start, end, hiddenColumns);
1089 LOCK.readLock().unlock();
1094 * return an iterator over visible segments between the given start and end
1098 * first column, inclusive from 0
1100 * last column - not inclusive
1101 * @param useVisibleCoords
1102 * if true, start and end are visible column positions, not absolute
1105 public VisibleContigsIterator getVisContigsIterator(int start,
1107 boolean useVisibleCoords)
1109 int adjstart = start;
1111 if (useVisibleCoords)
1113 adjstart = visibleToAbsoluteColumn(start);
1114 adjend = visibleToAbsoluteColumn(end);
1119 LOCK.readLock().lock();
1120 return new VisibleContigsIterator(adjstart, adjend, hiddenColumns);
1123 LOCK.readLock().unlock();