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,
174 regionindex = cursorPos.getRegionIndex();
178 // get previous index and hidden count for updating the cursor later
179 previndex = regionindex - 1;
180 int[] prevRegion = hiddenColumns.get(previndex);
181 prevHiddenCount = cursorPos.getHiddenSoFar()
182 - (prevRegion[1] - prevRegion[0] + 1);
186 // new range follows everything else; check first to avoid looping over
187 // whole hiddenColumns collection
188 if (hiddenColumns.isEmpty()
189 || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
191 hiddenColumns.add(new int[] { start, end });
192 numColumns += end - start + 1;
197 * traverse existing hidden ranges and insert / amend / append as
200 boolean added = false;
203 added = insertRangeAtRegion(regionindex - 1, start, end);
205 if (!added && regionindex < hiddenColumns.size())
207 insertRangeAtRegion(regionindex, start, end);
211 // reset the cursor to just before our insertion point: this saves
212 // a lot of reprocessing in large alignments
213 cursor = new HiddenColumnsCursor(hiddenColumns, previndex,
217 LOCK.writeLock().unlock();
222 * Insert [start, range] at the region at index i in hiddenColumns, if
228 * start of range to insert
230 * end of range to insert
231 * @return true if range was successfully inserted
233 private boolean insertRangeAtRegion(int i, int start, int end)
235 boolean added = false;
237 int[] region = hiddenColumns.get(i);
238 if (end < region[0] - 1)
241 * insert discontiguous preceding range
243 hiddenColumns.add(i, new int[] { start, end });
244 numColumns += end - start + 1;
247 else if (end <= region[1])
250 * new range overlaps existing, or is contiguous preceding it - adjust
253 int oldstart = region[0];
254 region[0] = Math.min(region[0], start);
255 numColumns += oldstart - region[0]; // new columns are between old and
259 else if (start <= region[1] + 1)
262 * new range overlaps existing, or is contiguous following it - adjust
263 * start and end columns
265 insertRangeAtOverlap(i, start, end, region);
272 * Insert a range whose start position overlaps an existing region and/or is
273 * contiguous to the right of the region
278 * start of range to insert
280 * end of range to insert
282 * the overlapped/continued region
284 private void insertRangeAtOverlap(int i, int start, int end, int[] region)
286 int oldstart = region[0];
287 int oldend = region[1];
288 region[0] = Math.min(region[0], start);
289 region[1] = Math.max(region[1], end);
291 numColumns += oldstart - region[0];
294 * also update or remove any subsequent ranges
295 * that are overlapped
298 while (endi < hiddenColumns.size() - 1)
300 int[] nextRegion = hiddenColumns.get(endi + 1);
301 if (nextRegion[0] > end + 1)
304 * gap to next hidden range - no more to update
308 numColumns -= nextRegion[1] - nextRegion[0] + 1;
309 region[1] = Math.max(nextRegion[1], end);
312 numColumns += region[1] - oldend;
313 hiddenColumns.subList(i + 1, endi + 1).clear();
317 * hide a list of ranges
321 public void hideList(List<int[]> ranges)
325 LOCK.writeLock().lock();
326 for (int[] r : ranges)
328 hideColumns(r[0], r[1]);
330 cursor = new HiddenColumnsCursor(hiddenColumns);
334 LOCK.writeLock().unlock();
339 * Unhides, and adds to the selection list, all hidden columns
341 public void revealAllHiddenColumns(ColumnSelection sel)
345 LOCK.writeLock().lock();
347 for (int[] region : hiddenColumns)
349 for (int j = region[0]; j < region[1] + 1; j++)
354 hiddenColumns.clear();
355 cursor = new HiddenColumnsCursor(hiddenColumns);
360 LOCK.writeLock().unlock();
365 * Reveals, and marks as selected, the hidden column range with the given
369 * the start column to look for
371 * the column selection to add the hidden column range to
373 public void revealHiddenColumns(int start, ColumnSelection sel)
377 LOCK.writeLock().lock();
379 if (!hiddenColumns.isEmpty())
381 int regionIndex = cursor.findRegionForColumn(start, false)
384 if (regionIndex != -1 && regionIndex != hiddenColumns.size())
386 // regionIndex is the region which either contains start
387 // or lies to the right of start
388 int[] region = hiddenColumns.get(regionIndex);
389 if (start == region[0])
391 for (int j = region[0]; j < region[1] + 1; j++)
395 int colsToRemove = region[1] - region[0] + 1;
396 hiddenColumns.remove(regionIndex);
397 numColumns -= colsToRemove;
403 LOCK.writeLock().unlock();
408 * Output regions data as a string. String is in the format:
409 * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
412 * string to delimit regions
413 * @param betweenstring
414 * to put between start and end region values
415 * @return regions formatted according to delimiter and between strings
417 public String regionsToString(String delimiter, String between)
421 LOCK.readLock().lock();
422 StringBuilder regionBuilder = new StringBuilder();
424 boolean first = true;
425 for (int[] range : hiddenColumns)
429 regionBuilder.append(delimiter);
435 regionBuilder.append(range[0]).append(between).append(range[1]);
439 return regionBuilder.toString();
442 LOCK.readLock().unlock();
447 * Find the number of hidden columns
449 * @return number of hidden columns
457 * Get the number of distinct hidden regions
459 * @return number of regions
461 public int getNumberOfRegions()
465 LOCK.readLock().lock();
466 return hiddenColumns.size();
469 LOCK.readLock().unlock();
474 * Answers true if obj is an instance of HiddenColumns, and holds the same
475 * array of start-end column ranges as this, else answers false
478 public boolean equals(Object obj)
482 LOCK.readLock().lock();
484 if (!(obj instanceof HiddenColumns))
488 HiddenColumns that = (HiddenColumns) obj;
491 * check hidden columns are either both null, or match
494 if (that.hiddenColumns.size() != this.hiddenColumns.size())
499 Iterator<int[]> it = this.iterator();
500 Iterator<int[]> thatit = that.iterator();
503 if (!(Arrays.equals(it.next(), thatit.next())))
512 LOCK.readLock().unlock();
517 * Return absolute column index for a visible column index
520 * int column index in alignment view (count from zero)
521 * @return alignment column index for column
523 public int visibleToAbsoluteColumn(int column)
527 LOCK.readLock().lock();
530 if (!hiddenColumns.isEmpty())
532 result += cursor.findRegionForColumn(column, true).getHiddenSoFar();
538 LOCK.readLock().unlock();
543 * Use this method to find out where a column will appear in the visible
544 * alignment when hidden columns exist. If the column is not visible, then the
545 * index of the next visible column on the left will be returned (or 0 if
546 * there is no visible column on the left)
548 * @param hiddenColumn
549 * the column index in the full alignment including hidden columns
550 * @return the position of the column in the visible alignment
552 public int absoluteToVisibleColumn(int hiddenColumn)
556 LOCK.readLock().lock();
557 int result = hiddenColumn;
559 if (!hiddenColumns.isEmpty())
561 HiddenCursorPosition cursorPos = cursor
562 .findRegionForColumn(hiddenColumn, false);
563 int index = cursorPos.getRegionIndex();
564 int hiddenBeforeCol = cursorPos.getHiddenSoFar();
566 // just subtract hidden cols count - this works fine if column is
568 result = hiddenColumn - hiddenBeforeCol;
570 // now check in case column is hidden - it will be in the returned
572 if (index < hiddenColumns.size())
574 int[] region = hiddenColumns.get(index);
575 if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
577 // actually col is hidden, return region[0]-1
578 // unless region[0]==0 in which case return 0
585 result = region[0] - 1 - hiddenBeforeCol;
591 return result; // return the shifted position after removing hidden
595 LOCK.readLock().unlock();
600 * Find the visible column which is a given visible number of columns to the
601 * left (negative visibleDistance) or right (positive visibleDistance) of
602 * startColumn. If startColumn is not visible, we use the visible column at
603 * the left boundary of the hidden region containing startColumn.
605 * @param visibleDistance
606 * the number of visible columns to offset by (left offset = negative
607 * value; right offset = positive value)
609 * the position of the column to start from (absolute position)
610 * @return the position of the column which is <visibleDistance> away
611 * (absolute position)
613 public int offsetByVisibleColumns(int visibleDistance, int startColumn)
617 LOCK.readLock().lock();
618 int start = absoluteToVisibleColumn(startColumn);
619 return visibleToAbsoluteColumn(start + visibleDistance);
623 LOCK.readLock().unlock();
628 * This method returns the rightmost limit of a region of an alignment with
629 * hidden columns. In otherwords, the next hidden column.
632 * the absolute (visible) alignmentPosition to find the next hidden
634 * @return the index of the next hidden column, or alPos if there is no next
637 public int getNextHiddenBoundary(boolean left, int alPos)
641 LOCK.readLock().lock();
642 if (!hiddenColumns.isEmpty())
644 int index = cursor.findRegionForColumn(alPos, false)
647 if (left && index > 0)
649 int[] region = hiddenColumns.get(index - 1);
652 else if (!left && index < hiddenColumns.size())
654 int[] region = hiddenColumns.get(index);
655 if (alPos < region[0])
659 else if ((alPos <= region[1])
660 && (index + 1 < hiddenColumns.size()))
662 // alPos is within a hidden region, return the next one
664 region = hiddenColumns.get(index + 1);
672 LOCK.readLock().unlock();
677 * Answers if a column in the alignment is visible
680 * absolute position of column in the alignment
681 * @return true if column is visible
683 public boolean isVisible(int column)
687 LOCK.readLock().lock();
689 if (!hiddenColumns.isEmpty())
691 int regionindex = cursor.findRegionForColumn(column, false)
693 if (regionindex > -1 && regionindex < hiddenColumns.size())
695 int[] region = hiddenColumns.get(regionindex);
696 // already know that column <= region[1] as cursor returns containing
697 // region or region to right
698 if (column >= region[0])
708 LOCK.readLock().unlock();
714 * @return true if there are columns hidden
716 public boolean hasHiddenColumns()
720 LOCK.readLock().lock();
722 // we don't use getSize()>0 here because it has to iterate over
723 // the full hiddenColumns collection and so will be much slower
724 return (!hiddenColumns.isEmpty());
727 LOCK.readLock().unlock();
733 * @return true if there is more than one hidden column region
735 public boolean hasMultiHiddenColumnRegions()
739 LOCK.readLock().lock();
740 return !hiddenColumns.isEmpty() && hiddenColumns.size() > 1;
743 LOCK.readLock().unlock();
748 * Returns a hashCode built from hidden column ranges
751 public int hashCode()
755 LOCK.readLock().lock();
758 for (int[] hidden : hiddenColumns)
760 hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
761 hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
766 LOCK.readLock().unlock();
771 * Hide columns corresponding to the marked bits
774 * - columns mapped to bits starting from zero
776 public void hideColumns(BitSet inserts)
778 hideColumns(inserts, 0, inserts.length() - 1);
782 * Hide columns corresponding to the marked bits, within the range
783 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
786 * columns mapped to bits starting from zero
788 * start of range to hide columns within
790 * end of range to hide columns within
792 private void hideColumns(BitSet tohide, int start, int end)
796 LOCK.writeLock().lock();
797 for (int firstSet = tohide
798 .nextSetBit(start), lastSet = start; firstSet >= start
799 && lastSet <= end; firstSet = tohide
800 .nextSetBit(lastSet))
802 lastSet = tohide.nextClearBit(firstSet);
805 hideColumns(firstSet, lastSet - 1);
807 else if (firstSet <= end)
809 hideColumns(firstSet, end);
812 cursor = new HiddenColumnsCursor(hiddenColumns);
815 LOCK.writeLock().unlock();
820 * Hide columns corresponding to the marked bits, within the range
821 * [start,end]. Entries in tohide which are outside [start,end] are ignored.
822 * NB Existing entries in [start,end] are cleared.
825 * columns mapped to bits starting from zero
827 * start of range to hide columns within
829 * end of range to hide columns within
831 public void clearAndHideColumns(BitSet tohide, int start, int end)
833 clearHiddenColumnsInRange(start, end);
834 hideColumns(tohide, start, end);
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();
856 if (index != -1 && index != hiddenColumns.size())
858 // regionIndex is the region which either contains start
859 // or lies to the right of start
860 int[] region = hiddenColumns.get(index);
861 if (region[0] < start && region[1] >= start)
863 // region contains start, truncate so that it ends just before start
864 numColumns -= region[1] - start + 1;
865 region[1] = start - 1;
870 while (endi < hiddenColumns.size())
872 region = hiddenColumns.get(endi);
876 if (region[0] <= end)
878 // region contains end, truncate so it starts just after end
879 numColumns -= end - region[0] + 1;
885 numColumns -= region[1] - region[0] + 1;
888 hiddenColumns.subList(index, endi).clear();
892 cursor = new HiddenColumnsCursor(hiddenColumns);
896 LOCK.writeLock().unlock();
903 * BitSet where hidden columns will be marked
905 protected void andNot(BitSet updates)
909 LOCK.writeLock().lock();
911 BitSet hiddenBitSet = new BitSet();
912 for (int[] range : hiddenColumns)
914 hiddenBitSet.set(range[0], range[1] + 1);
916 hiddenBitSet.andNot(updates);
917 hiddenColumns.clear();
918 hideColumns(hiddenBitSet);
921 LOCK.writeLock().unlock();
926 * Calculate the visible start and end index of an alignment.
929 * full alignment width
930 * @return integer array where: int[0] = startIndex, and int[1] = endIndex
932 public int[] getVisibleStartAndEndIndex(int width)
936 LOCK.readLock().lock();
938 int firstVisible = 0;
939 int lastVisible = width - 1;
941 if (!hiddenColumns.isEmpty())
943 // first visible col with index 0, convert to absolute index
944 firstVisible = visibleToAbsoluteColumn(0);
946 // last visible column is either immediately to left of
947 // last hidden region, or is just the last column in the alignment
948 int[] lastregion = hiddenColumns.get(hiddenColumns.size() - 1);
949 if (lastregion[1] == width - 1)
951 // last region is at very end of alignment
952 // last visible column immediately precedes it
953 lastVisible = lastregion[0] - 1;
956 return new int[] { firstVisible, lastVisible };
960 LOCK.readLock().unlock();
965 * Finds the hidden region (if any) which starts or ends at res
968 * visible residue position, unadjusted for hidden columns
969 * @return region as [start,end] or null if no matching region is found. If
970 * res is adjacent to two regions, returns the left region.
972 public int[] getRegionWithEdgeAtRes(int res)
976 LOCK.readLock().lock();
977 int adjres = visibleToAbsoluteColumn(res);
981 if (!hiddenColumns.isEmpty())
983 // look for a region ending just before adjres
984 int regionindex = cursor.findRegionForColumn(adjres - 1, false)
986 if (regionindex < hiddenColumns.size()
987 && hiddenColumns.get(regionindex)[1] == adjres - 1)
989 reveal = hiddenColumns.get(regionindex);
991 // check if the region ends just after adjres
992 else if (regionindex < hiddenColumns.size()
993 && hiddenColumns.get(regionindex)[0] == adjres + 1)
995 reveal = hiddenColumns.get(regionindex);
1002 LOCK.readLock().unlock();
1007 * Return an iterator over the hidden regions
1009 public Iterator<int[]> iterator()
1013 LOCK.readLock().lock();
1014 return new RangeIterator(hiddenColumns);
1017 LOCK.readLock().unlock();
1022 * Return a bounded iterator over the hidden regions
1025 * position to start from (inclusive, absolute column position)
1027 * position to end at (inclusive, absolute column position)
1030 public Iterator<int[]> getBoundedIterator(int start, int end)
1034 LOCK.readLock().lock();
1035 return new RangeIterator(start, end, hiddenColumns);
1038 LOCK.readLock().unlock();
1043 * Return a bounded iterator over the *visible* start positions of hidden
1047 * position to start from (inclusive, visible column position)
1049 * position to end at (inclusive, visible column position)
1051 public Iterator<Integer> getStartRegionIterator(int start, int end)
1055 LOCK.readLock().lock();
1057 // get absolute position of column in alignment
1058 int absoluteStart = visibleToAbsoluteColumn(start);
1060 // Get cursor position and supply it to the iterator:
1061 // Since we want visible region start, we look for a cursor for the
1062 // (absoluteStart-1), then if absoluteStart is the start of a visible
1063 // region we'll get the cursor pointing to the region before, which is
1065 HiddenCursorPosition pos = cursor
1066 .findRegionForColumn(absoluteStart - 1, false);
1068 return new StartRegionIterator(pos, start, end, hiddenColumns);
1071 LOCK.readLock().unlock();
1076 * Return an iterator over visible *columns* (not regions) between the given
1077 * start and end boundaries
1080 * first column (inclusive)
1082 * last column (inclusive)
1084 public Iterator<Integer> getVisibleColsIterator(int start, int end)
1088 LOCK.readLock().lock();
1089 return new RangeElementsIterator(
1090 new VisibleContigsIterator(start, end + 1, hiddenColumns));
1093 LOCK.readLock().unlock();
1098 * return an iterator over visible segments between the given start and end
1102 * first column, inclusive from 0
1104 * last column - not inclusive
1105 * @param useVisibleCoords
1106 * if true, start and end are visible column positions, not absolute
1109 public VisibleContigsIterator getVisContigsIterator(int start, int end,
1110 boolean useVisibleCoords)
1112 int adjstart = start;
1114 if (useVisibleCoords)
1116 adjstart = visibleToAbsoluteColumn(start);
1117 adjend = visibleToAbsoluteColumn(end);
1122 LOCK.readLock().lock();
1123 return new VisibleContigsIterator(adjstart, adjend, hiddenColumns);
1126 LOCK.readLock().unlock();