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
80 private int numColumns = 0;
83 * list of hidden column [start, end] ranges; the list is maintained in
84 * ascending start column order
86 private List<int[]> hiddenColumns = new ArrayList<>();
91 public HiddenColumns()
99 * the HiddenColumns object to copy from
101 public HiddenColumns(HiddenColumns copy)
103 this(copy, Integer.MIN_VALUE, Integer.MAX_VALUE, 0);
107 * Copy constructor within bounds and with offset. Copies hidden column
108 * regions fully contained between start and end, and offsets positions by
109 * subtracting offset.
112 * HiddenColumns instance to copy from
114 * lower bound to copy from
116 * upper bound to copy to
118 * offset to subtract from each region boundary position
121 public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
125 LOCK.writeLock().lock();
129 Iterator<int[]> it = copy.getBoundedIterator(start, end);
132 int[] region = it.next();
133 // still need to check boundaries because iterator returns
134 // all overlapping regions and we need contained regions
135 if (region[0] >= start && region[1] <= end)
139 { region[0] - offset, region[1] - offset });
140 numColumns += region[1] - region[0] + 1;
143 cursor = new HiddenColumnsCursor(hiddenColumns);
147 LOCK.writeLock().unlock();
152 * Adds the specified column range to the hidden columns collection
155 * start of range to add (absolute position in alignment)
157 * end of range to add (absolute position in alignment)
159 public void hideColumns(int start, int end)
163 LOCK.writeLock().lock();
166 int prevHiddenCount = 0;
168 if (!hiddenColumns.isEmpty())
170 // set up cursor reset values
171 HiddenCursorPosition cursorPos = cursor.findRegionForColumn(start);
172 regionindex = cursorPos.getRegionIndex();
176 // get previous index and hidden count for updating the cursor later
177 previndex = regionindex - 1;
178 int[] prevRegion = hiddenColumns.get(previndex);
179 prevHiddenCount = cursorPos.getHiddenSoFar()
180 - (prevRegion[1] - prevRegion[0] + 1);
185 * new range follows everything else; check first to avoid looping over whole hiddenColumns collection
187 if (hiddenColumns.isEmpty()
188 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
190 hiddenColumns.add(new int[] { start, end });
195 * traverse existing hidden ranges and insert / amend / append as
198 boolean added = false;
201 added = insertRangeAtRegion(regionindex - 1, start, end);
203 if (!added && regionindex < hiddenColumns.size())
205 insertRangeAtRegion(regionindex, start, end);
209 // reset the cursor to just before our insertion point: this saves
210 // a lot of reprocessing in large alignments
211 cursor = new HiddenColumnsCursor(hiddenColumns, previndex,
214 // reset the number of columns so they will be recounted
219 LOCK.writeLock().unlock();
224 * Insert [start, range] at the region at index i in hiddenColumns, if
230 * start of range to insert
232 * end of range to insert
233 * @return true if range was successfully inserted
235 private boolean insertRangeAtRegion(int i, int start, int end)
237 boolean added = false;
239 int[] region = hiddenColumns.get(i);
240 if (end < region[0] - 1)
243 * insert discontiguous preceding range
245 hiddenColumns.add(i, new int[] { start, end });
248 else if (end <= region[1])
251 * new range overlaps existing, or is contiguous preceding it - adjust
254 region[0] = Math.min(region[0], start);
257 else if (start <= region[1] + 1)
260 * new range overlaps existing, or is contiguous following it - adjust
261 * start and end columns
263 region[0] = Math.min(region[0], start);
264 region[1] = Math.max(region[1], end);
267 * also update or remove any subsequent ranges
268 * that are overlapped
270 while (i < hiddenColumns.size() - 1)
272 int[] nextRegion = hiddenColumns.get(i + 1);
273 if (nextRegion[0] > end + 1)
276 * gap to next hidden range - no more to update
280 region[1] = Math.max(nextRegion[1], end);
282 // in theory hiddenColumns.subList(i + 1, i + 2).clear() is faster than
283 // hiddenColumns.remove(i+1) but benchmarking results a bit ambivalent
284 hiddenColumns.remove(i + 1);
292 * hide a list of ranges
296 public void hideList(List<int[]> ranges)
300 LOCK.writeLock().lock();
301 for (int[] r : ranges)
303 hideColumns(r[0], r[1]);
305 cursor = new HiddenColumnsCursor(hiddenColumns);
309 LOCK.writeLock().unlock();
314 * Unhides, and adds to the selection list, all hidden columns
316 public void revealAllHiddenColumns(ColumnSelection sel)
320 LOCK.writeLock().lock();
322 for (int[] region : hiddenColumns)
324 for (int j = region[0]; j < region[1] + 1; j++)
329 hiddenColumns.clear();
330 cursor = new HiddenColumnsCursor(hiddenColumns);
335 LOCK.writeLock().unlock();
340 * Reveals, and marks as selected, the hidden column range with the given
344 * the start column to look for
346 * the column selection to add the hidden column range to
348 public void revealHiddenColumns(int start, ColumnSelection sel)
352 LOCK.writeLock().lock();
354 if (!hiddenColumns.isEmpty())
356 int regionIndex = cursor.findRegionForColumn(start)
359 if (regionIndex != -1 && regionIndex != hiddenColumns.size())
361 // regionIndex is the region which either contains start
362 // or lies to the right of start
363 int[] region = hiddenColumns.get(regionIndex);
364 if (start == region[0])
366 for (int j = region[0]; j < region[1] + 1; j++)
370 int colsToRemove = region[1] - region[0] + 1;
371 hiddenColumns.remove(regionIndex);
373 if (hiddenColumns.isEmpty())
375 hiddenColumns.clear();
380 numColumns -= colsToRemove;
382 cursor.updateForDeletedRegion(hiddenColumns);
388 LOCK.writeLock().unlock();
393 * Output regions data as a string. String is in the format:
394 * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
397 * string to delimit regions
398 * @param betweenstring
399 * to put between start and end region values
400 * @return regions formatted according to delimiter and between strings
402 public String regionsToString(String delimiter, String between)
406 LOCK.readLock().lock();
407 StringBuilder regionBuilder = new StringBuilder();
409 boolean first = true;
410 for (int[] range : hiddenColumns)
414 regionBuilder.append(delimiter);
420 regionBuilder.append(range[0]).append(between).append(range[1]);
424 return regionBuilder.toString();
427 LOCK.readLock().unlock();
432 * Find the number of hidden columns
434 * @return number of hidden columns
440 LOCK.readLock().lock();
444 // numColumns is out of date, so recalculate
447 for (int[] range : hiddenColumns)
449 size += range[1] - range[0] + 1;
458 LOCK.readLock().unlock();
463 * Get the number of distinct hidden regions
465 * @return number of regions
467 public int getNumberOfRegions()
471 LOCK.readLock().lock();
472 return hiddenColumns.size();
475 LOCK.readLock().unlock();
480 public boolean equals(Object obj)
484 LOCK.readLock().lock();
486 if (!(obj instanceof HiddenColumns))
490 HiddenColumns that = (HiddenColumns) obj;
493 * check hidden columns are either both null, or match
496 if (that.hiddenColumns.size() != this.hiddenColumns.size())
501 Iterator<int[]> it = this.iterator();
502 Iterator<int[]> thatit = that.iterator();
505 if (!(Arrays.equals(it.next(), thatit.next())))
514 LOCK.readLock().unlock();
519 * Return absolute column index for a visible column index
522 * int column index in alignment view (count from zero)
523 * @return alignment column index for column
525 public int visibleToAbsoluteColumn(int column)
529 LOCK.readLock().lock();
532 if (!hiddenColumns.isEmpty())
534 result += cursor.findRegionForVisColumn(column).getHiddenSoFar();
540 LOCK.readLock().unlock();
545 * Use this method to find out where a column will appear in the visible
546 * alignment when hidden columns exist. If the column is not visible, then the
547 * index of the next visible column on the left will be returned (or 0 if
548 * there is no visible column on the left)
550 * @param hiddenColumn
551 * the column index in the full alignment including hidden columns
552 * @return the position of the column in the visible alignment
554 public int absoluteToVisibleColumn(int hiddenColumn)
558 LOCK.readLock().lock();
559 int result = hiddenColumn;
561 if (!hiddenColumns.isEmpty())
563 HiddenCursorPosition cursorPos = cursor
564 .findRegionForColumn(hiddenColumn);
565 int index = cursorPos.getRegionIndex();
566 int hiddenBeforeCol = cursorPos.getHiddenSoFar();
568 // just subtract hidden cols count - this works fine if column is
570 result = hiddenColumn - hiddenBeforeCol;
572 // now check in case column is hidden - it will be in the returned
574 if (index < hiddenColumns.size())
576 int[] region = hiddenColumns.get(index);
577 if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
579 // actually col is hidden, return region[0]-1
580 // unless region[0]==0 in which case return 0
587 result = region[0] - 1 - hiddenBeforeCol;
593 return result; // return the shifted position after removing hidden
597 LOCK.readLock().unlock();
602 * Find the visible column which is a given visible number of columns to the
603 * left (negative visibleDistance) or right (positive visibleDistance) of
604 * startColumn. If startColumn is not visible, we use the visible column at
605 * the left boundary of the hidden region containing startColumn.
607 * @param visibleDistance
608 * the number of visible columns to offset by (left offset = negative
609 * value; right offset = positive value)
611 * the position of the column to start from (absolute position)
612 * @return the position of the column which is <visibleDistance> away
613 * (absolute position)
615 public int offsetByVisibleColumns(int visibleDistance, int startColumn)
619 LOCK.readLock().lock();
620 int start = absoluteToVisibleColumn(startColumn);
621 return visibleToAbsoluteColumn(start + visibleDistance);
625 LOCK.readLock().unlock();
630 * This method returns the rightmost limit of a region of an alignment with
631 * hidden columns. In otherwords, the next hidden column.
634 * the absolute (visible) alignmentPosition to find the next hidden
636 * @return the index of the next hidden column, or alPos if there is no next
639 public int getNextHiddenBoundary(boolean left, int alPos)
643 LOCK.readLock().lock();
644 if (!hiddenColumns.isEmpty())
646 int index = cursor.findRegionForColumn(alPos).getRegionIndex();
648 if (left && index > 0)
650 int[] region = hiddenColumns.get(index - 1);
653 else if (!left && index < hiddenColumns.size())
655 int[] region = hiddenColumns.get(index);
656 if (alPos < region[0])
660 else if ((alPos <= region[1])
661 && (index + 1 < hiddenColumns.size()))
663 // alPos is within a hidden region, return the next one
665 region = hiddenColumns.get(index + 1);
673 LOCK.readLock().unlock();
678 * Answers if a column in the alignment is visible
681 * absolute position of column in the alignment
682 * @return true if column is visible
684 public boolean isVisible(int column)
688 LOCK.readLock().lock();
690 int regionindex = cursor.findRegionForColumn(column).getRegionIndex();
691 if (regionindex > -1 && regionindex < hiddenColumns.size())
693 int[] region = hiddenColumns.get(regionindex);
694 // already know that column <= region[1] as cursor returns containing
695 // region or region to right
696 if (column >= region[0])
705 LOCK.readLock().unlock();
711 * @return true if there are columns hidden
713 public boolean hasHiddenColumns()
717 LOCK.readLock().lock();
719 // we don't use getSize()>0 here because it has to iterate over
720 // the full hiddenColumns collection and so will be much slower
721 return (!hiddenColumns.isEmpty());
724 LOCK.readLock().unlock();
730 * @return true if there is more than one hidden column region
732 public boolean hasMultiHiddenColumnRegions()
736 LOCK.readLock().lock();
737 return !hiddenColumns.isEmpty() && hiddenColumns.size() > 1;
740 LOCK.readLock().unlock();
746 * Returns a hashCode built from hidden column ranges
749 public int hashCode()
753 LOCK.readLock().lock();
756 for (int[] hidden : hiddenColumns)
758 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
759 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
764 LOCK.readLock().unlock();
769 * Hide columns corresponding to the marked bits
772 * - columns mapped to bits starting from zero
774 public void hideColumns(BitSet inserts)
778 LOCK.writeLock().lock();
779 for (int firstSet = inserts
780 .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
781 .nextSetBit(lastSet))
783 lastSet = inserts.nextClearBit(firstSet);
784 hideColumns(firstSet, lastSet - 1);
786 cursor = new HiddenColumnsCursor(hiddenColumns);
790 LOCK.writeLock().unlock();
795 * Hide columns corresponding to the marked bits, within the range
796 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
799 * columns mapped to bits starting from zero
801 * start of range to hide columns within
803 * end of range to hide columns within
805 public void hideColumns(BitSet tohide, int start, int end)
807 clearHiddenColumnsInRange(start, end);
809 // make sure only bits between start and end are set
810 if (!tohide.isEmpty())
812 tohide.clear(0, start);
813 tohide.clear(Math.min(end + 1, tohide.length() + 1),
814 tohide.length() + 1);
821 * Make all columns in the range [start,end] visible
824 * start of range to show columns
826 * end of range to show columns
828 private void clearHiddenColumnsInRange(int start, int end)
832 LOCK.writeLock().lock();
834 if (!hiddenColumns.isEmpty())
836 HiddenCursorPosition pos = cursor.findRegionForColumn(start);
837 int index = pos.getRegionIndex();
838 int startindex = index; // first index in hiddenColumns to remove
840 if (index != -1 && index != hiddenColumns.size())
842 // regionIndex is the region which either contains start
843 // or lies to the right of start
844 int[] region = hiddenColumns.get(index);
845 if (region[0] < start && region[1] >= start)
847 // region contains start, truncate so that it ends just before start
848 region[1] = start - 1;
853 pos = cursor.findRegionForColumn(end);
854 index = pos.getRegionIndex();
855 int endindex = index - 1; // last index in hiddenColumns to remove
857 if (index != -1 && index != hiddenColumns.size())
859 // regionIndex is the region which either contains end
860 // or lies to the right of end
861 int[] region = hiddenColumns.get(index);
862 if (region[0] <= end && region[1] > end)
864 // region contains end, truncate so that it starts just after end
869 hiddenColumns.subList(startindex, endindex + 1).clear();
870 cursor = new HiddenColumnsCursor(hiddenColumns);
875 LOCK.writeLock().unlock();
882 * BitSet where hidden columns will be marked
884 protected void andNot(BitSet updates)
888 LOCK.writeLock().lock();
890 BitSet hiddenBitSet = new BitSet();
891 for (int[] range : hiddenColumns)
893 hiddenBitSet.set(range[0], range[1] + 1);
895 hiddenBitSet.andNot(updates);
896 hiddenColumns.clear();
897 hideColumns(hiddenBitSet);
900 LOCK.writeLock().unlock();
905 * Calculate the visible start and end index of an alignment.
908 * full alignment width
909 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
911 public int[] getVisibleStartAndEndIndex(int width)
915 LOCK.readLock().lock();
917 int firstVisible = 0;
918 int lastVisible = width - 1;
920 if (!hiddenColumns.isEmpty())
922 // first visible col with index 0, convert to absolute index
923 firstVisible = visibleToAbsoluteColumn(0);
925 // last visible column is either immediately to left of
926 // last hidden region, or is just the last column in the alignment
927 int[] lastregion = hiddenColumns.get(hiddenColumns.size() - 1);
928 if (lastregion[1] == width - 1)
930 // last region is at very end of alignment
931 // last visible column immediately precedes it
932 lastVisible = lastregion[0] - 1;
935 return new int[] { firstVisible, lastVisible };
939 LOCK.readLock().unlock();
944 * Finds the hidden region (if any) which starts or ends at res
947 * visible residue position, unadjusted for hidden columns
948 * @return region as [start,end] or null if no matching region is found. If
949 * res is adjacent to two regions, returns the left region.
951 public int[] getRegionWithEdgeAtRes(int res)
955 LOCK.readLock().lock();
956 int adjres = visibleToAbsoluteColumn(res);
960 if (!hiddenColumns.isEmpty())
962 // look for a region ending just before adjres
963 int regionindex = cursor.findRegionForColumn(adjres - 1)
965 if (regionindex < hiddenColumns.size()
966 && hiddenColumns.get(regionindex)[1] == adjres - 1)
968 reveal = hiddenColumns.get(regionindex);
970 // check if the region ends just after adjres
971 else if (regionindex < hiddenColumns.size()
972 && hiddenColumns.get(regionindex)[0] == adjres + 1)
974 reveal = hiddenColumns.get(regionindex);
981 LOCK.readLock().unlock();
986 * Return an iterator over the hidden regions
988 public Iterator<int[]> iterator()
992 LOCK.readLock().lock();
993 return new HiddenColsIterator(hiddenColumns);
996 LOCK.readLock().unlock();
1001 * Return a bounded iterator over the hidden regions
1004 * position to start from (inclusive, absolute column position)
1006 * position to end at (inclusive, absolute column position)
1009 public Iterator<int[]> getBoundedIterator(int start, int end)
1013 LOCK.readLock().lock();
1014 return new HiddenColsIterator(start, end, hiddenColumns);
1017 LOCK.readLock().unlock();
1022 * Return a bounded iterator over the *visible* start positions of hidden
1026 * position to start from (inclusive, visible column position)
1028 * position to end at (inclusive, visible column position)
1030 public Iterator<Integer> getBoundedStartIterator(int start, int end)
1034 LOCK.readLock().lock();
1036 // get absolute position of column in alignment
1037 int absoluteStart = visibleToAbsoluteColumn(start);
1039 // Get cursor position and supply it to the iterator:
1040 // Since we want visible region start, we look for a cursor for the
1041 // (absoluteStart-1), then if absoluteStart is the start of a visible
1042 // region we'll get the cursor pointing to the region before, which is
1044 HiddenCursorPosition pos = cursor
1045 .findRegionForColumn(absoluteStart - 1);
1047 return new BoundedStartRegionIterator(pos, start, end,
1051 LOCK.readLock().unlock();
1056 * Return an iterator over visible *columns* (not regions) between the given
1057 * start and end boundaries
1060 * first column (inclusive)
1062 * last column (inclusive)
1064 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1068 LOCK.readLock().lock();
1069 return new VisibleColsIterator(start, end, hiddenColumns);
1072 LOCK.readLock().unlock();
1077 * return an iterator over visible segments between the given start and end
1081 * first column, inclusive from 0
1083 * last column - not inclusive
1084 * @param useVisibleCoords
1085 * if true, start and end are visible column positions, not absolute
1088 public VisibleContigsIterator getVisContigsIterator(int start,
1090 boolean useVisibleCoords)
1092 int adjstart = start;
1094 if (useVisibleCoords)
1096 adjstart = visibleToAbsoluteColumn(start);
1097 adjend = visibleToAbsoluteColumn(end);
1102 LOCK.readLock().lock();
1103 return new VisibleContigsIterator(adjstart, adjend, hiddenColumns);
1106 LOCK.readLock().unlock();