JAL-2759 setup hideBitSet over range for hideInsertions
[jalview.git] / src / jalview / datamodel / HiddenColumns.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.datamodel;
22
23 import java.util.ArrayList;
24 import java.util.BitSet;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.concurrent.locks.ReentrantReadWriteLock;
28
29 /**
30  * This class manages the collection of hidden columns associated with an
31  * alignment. To iterate over the collection, or over visible columns/regions,
32  * use an iterator obtained from one of:
33  * 
34  * - getBoundedIterator: iterates over the hidden regions, within some bounds,
35  * returning absolute positions
36  * 
37  * - getBoundedStartIterator: iterates over the start positions of hidden
38  * regions, within some bounds, returning visible positions
39  * 
40  * - getVisContigsIterator: iterates over visible regions in a range, returning
41  * absolute positions
42  * 
43  * - getVisibleColsIterator: iterates over the visible *columns*
44  * 
45  * For performance reasons, provide bounds where possible. Note that column
46  * numbering begins at 0 throughout this class.
47  * 
48  * @author kmourao
49  *
50  */
51 public class HiddenColumns
52 {
53   private static final int HASH_MULTIPLIER = 31;
54
55   private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
56
57   /*
58    * Cursor which tracks the last used hidden columns region, and the number 
59    * of hidden columns up to (but not including) that region.
60    */
61   private HiddenColumnsCursor cursor = new HiddenColumnsCursor();
62
63   /*
64    * cache of the number of hidden columns
65    */
66   private int numColumns = 0;
67
68   /*
69    * list of hidden column [start, end] ranges; the list is maintained in
70    * ascending start column order
71    */
72   private List<int[]> hiddenColumns = new ArrayList<>();
73
74   /**
75    * Constructor
76    */
77   public HiddenColumns()
78   {
79   }
80
81   /* 
82    * Methods which change the hiddenColumns collection. These methods should 
83    * use a writeLock to prevent other threads accessing the hiddenColumns
84    * collection while changes are being made. They should also reset the hidden
85    * columns cursor, and either update the hidden columns count, or set it to 0 
86    * (so that it will later be updated when needed).
87    */
88
89   /**
90    * Copy constructor
91    * 
92    * @param copy
93    *          the HiddenColumns object to copy from
94    */
95   public HiddenColumns(HiddenColumns copy)
96   {
97     this(copy, Integer.MIN_VALUE, Integer.MAX_VALUE, 0);
98   }
99
100   /**
101    * Copy constructor within bounds and with offset. Copies hidden column
102    * regions fully contained between start and end, and offsets positions by
103    * subtracting offset.
104    * 
105    * @param copy
106    *          HiddenColumns instance to copy from
107    * @param start
108    *          lower bound to copy from
109    * @param end
110    *          upper bound to copy to
111    * @param offset
112    *          offset to subtract from each region boundary position
113    * 
114    */
115   public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
116   {
117     try
118     {
119       LOCK.writeLock().lock();
120       if (copy != null)
121       {
122         numColumns = 0;
123         Iterator<int[]> it = copy.getBoundedIterator(start, end);
124         while (it.hasNext())
125         {
126           int[] region = it.next();
127           // still need to check boundaries because iterator returns
128           // all overlapping regions and we need contained regions
129           if (region[0] >= start && region[1] <= end)
130           {
131             hiddenColumns.add(
132                     new int[]
133             { region[0] - offset, region[1] - offset });
134             numColumns += region[1] - region[0] + 1;
135           }
136         }
137         cursor.resetCursor(hiddenColumns);
138       }
139     } finally
140     {
141       LOCK.writeLock().unlock();
142     }
143   }
144
145   /**
146    * Adds the specified column range to the hidden columns collection
147    * 
148    * @param start
149    *          start of range to add (absolute position in alignment)
150    * @param end
151    *          end of range to add (absolute position in alignment)
152    */
153   public void hideColumns(int start, int end)
154   {
155     boolean wasAlreadyLocked = false;
156     try
157     {
158       // check if the write lock was already locked by this thread,
159       // as this method can be called internally in loops within HiddenColumns
160       if (!LOCK.isWriteLockedByCurrentThread())
161       {
162         LOCK.writeLock().lock();
163       }
164       else
165       {
166         wasAlreadyLocked = true;
167       }
168
169       int previndex = 0;
170       int prevHiddenCount = 0;
171       int regionindex = 0;
172       if (!hiddenColumns.isEmpty())
173       {
174         // set up cursor reset values
175         HiddenCursorPosition cursorPos = cursor.findRegionForColumn(start);
176         regionindex = cursorPos.getRegionIndex();
177
178         if (regionindex > 0)
179         {
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);
185         }
186       }
187
188       /*
189        * new range follows everything else; check first to avoid looping over whole hiddenColumns collection
190        */
191       if (hiddenColumns.isEmpty()
192               || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
193       {
194         hiddenColumns.add(new int[] { start, end });
195       }
196       else
197       {
198         /*
199          * traverse existing hidden ranges and insert / amend / append as
200          * appropriate
201          */
202         boolean added = false;
203         if (regionindex > 0)
204         {
205           added = insertRangeAtRegion(regionindex - 1, start, end);
206         }
207         if (!added && regionindex < hiddenColumns.size())
208         {
209           insertRangeAtRegion(regionindex, start, end);
210         }
211       }
212
213       // reset the cursor to just before our insertion point: this saves
214       // a lot of reprocessing in large alignments
215       cursor.resetCursor(hiddenColumns, previndex, prevHiddenCount);
216
217       // reset the number of columns so they will be recounted
218       numColumns = 0;
219
220     } finally
221     {
222       if (!wasAlreadyLocked)
223       {
224         LOCK.writeLock().unlock();
225       }
226     }
227   }
228
229   /**
230    * Insert [start, range] at the region at index i in hiddenColumns, if
231    * feasible
232    * 
233    * @param i
234    *          index to insert at
235    * @param start
236    *          start of range to insert
237    * @param end
238    *          end of range to insert
239    * @return true if range was successfully inserted
240    */
241   private boolean insertRangeAtRegion(int i, int start, int end)
242   {
243     boolean added = false;
244
245     int[] region = hiddenColumns.get(i);
246     if (end < region[0] - 1)
247     {
248       /*
249        * insert discontiguous preceding range
250        */
251       hiddenColumns.add(i, new int[] { start, end });
252       added = true;
253     }
254     else if (end <= region[1])
255     {
256       /*
257        * new range overlaps existing, or is contiguous preceding it - adjust
258        * start column
259        */
260       region[0] = Math.min(region[0], start);
261       added = true;
262     }
263     else if (start <= region[1] + 1)
264     {
265       /*
266        * new range overlaps existing, or is contiguous following it - adjust
267        * start and end columns
268        */
269       region[0] = Math.min(region[0], start);
270       region[1] = Math.max(region[1], end);
271
272       /*
273        * also update or remove any subsequent ranges 
274        * that are overlapped
275        */
276       while (i < hiddenColumns.size() - 1)
277       {
278         int[] nextRegion = hiddenColumns.get(i + 1);
279         if (nextRegion[0] > end + 1)
280         {
281           /*
282            * gap to next hidden range - no more to update
283            */
284           break;
285         }
286         region[1] = Math.max(nextRegion[1], end);
287
288         // in theory this is faster than hiddenColumns.remove(i+1)
289         // benchmarking results a bit ambivalent
290         hiddenColumns.subList(i + 1, i + 2).clear();
291       }
292       added = true;
293     }
294     return added;
295   }
296
297   /**
298    * hide a list of ranges
299    * 
300    * @param ranges
301    */
302   public void hideList(List<int[]> ranges)
303   {
304     try
305     {
306       LOCK.writeLock().lock();
307       for (int[] r : ranges)
308       {
309         hideColumns(r[0], r[1]);
310       }
311       cursor.resetCursor(hiddenColumns);
312       numColumns = 0;
313     } finally
314     {
315       LOCK.writeLock().unlock();
316     }
317   }
318
319   /**
320    * Unhides, and adds to the selection list, all hidden columns
321    */
322   public void revealAllHiddenColumns(ColumnSelection sel)
323   {
324     try
325     {
326       LOCK.writeLock().lock();
327
328       for (int[] region : hiddenColumns)
329       {
330         for (int j = region[0]; j < region[1] + 1; j++)
331         {
332           sel.addElement(j);
333         }
334       }
335       hiddenColumns.clear();
336       cursor.resetCursor(hiddenColumns);
337       numColumns = 0;
338
339     } finally
340     {
341       LOCK.writeLock().unlock();
342     }
343   }
344
345   /**
346    * Reveals, and marks as selected, the hidden column range with the given
347    * start column
348    * 
349    * @param start
350    *          the start column to look for
351    * @param sel
352    *          the column selection to add the hidden column range to
353    */
354   public void revealHiddenColumns(int start, ColumnSelection sel)
355   {
356     try
357     {
358       LOCK.writeLock().lock();
359
360       if (!hiddenColumns.isEmpty())
361       {
362         int regionIndex = cursor.findRegionForColumn(start)
363                 .getRegionIndex();
364
365         if (regionIndex != -1 && regionIndex != hiddenColumns.size())
366         {
367           // regionIndex is the region which either contains start
368           // or lies to the right of start
369           int[] region = hiddenColumns.get(regionIndex);
370           if (start == region[0])
371           {
372             for (int j = region[0]; j < region[1] + 1; j++)
373             {
374               sel.addElement(j);
375             }
376             int colsToRemove = region[1] - region[0] + 1;
377             hiddenColumns.remove(regionIndex);
378
379             if (hiddenColumns.isEmpty())
380             {
381               hiddenColumns.clear();
382               numColumns = 0;
383             }
384             else
385             {
386               numColumns -= colsToRemove;
387             }
388             cursor.updateForDeletedRegion(hiddenColumns);
389           }
390         }
391       }
392     } finally
393     {
394       LOCK.writeLock().unlock();
395     }
396   }
397
398   /**
399    * Add gaps into the sequences aligned to profileseq under the given
400    * AlignmentView
401    * 
402    * @param profileseq
403    *          sequence in al which sequences are aligned to
404    * @param al
405    *          alignment to have gaps inserted into it
406    * @param input
407    *          alignment view where sequence corresponding to profileseq is first
408    *          entry
409    * @return new HiddenColumns for new alignment view, with insertions into
410    *         profileseq marked as hidden.
411    */
412   public static HiddenColumns propagateInsertions(SequenceI profileseq,
413           AlignmentI al, AlignmentView input)
414   {
415     int profsqpos = 0;
416
417     char gc = al.getGapCharacter();
418     Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
419     HiddenColumns nview = (HiddenColumns) alandhidden[1];
420     SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
421     nview.propagateInsertions(profileseq, al, origseq);
422     return nview;
423   }
424
425   /**
426    * 
427    * @param profileseq
428    *          sequence in al which corresponds to origseq
429    * @param al
430    *          alignment which is to have gaps inserted into it
431    * @param origseq
432    *          sequence corresponding to profileseq which defines gap map for
433    *          modifying al
434    */
435   private void propagateInsertions(SequenceI profileseq, AlignmentI al,
436           SequenceI origseq)
437   {
438     try
439     {
440       LOCK.writeLock().lock();
441
442       char gc = al.getGapCharacter();
443
444       // take the set of hidden columns, and the set of gaps in origseq,
445       // and remove all the hidden gaps from hiddenColumns
446
447       // first get the gaps as a Bitset
448       BitSet gaps = origseq.gapBitset();
449
450       // now calculate hidden ^ not(gap)
451       BitSet hidden = new BitSet();
452       markHiddenRegions(hidden);
453       hidden.andNot(gaps);
454       hiddenColumns.clear();
455       this.hideColumns(hidden);
456
457       // for each sequence in the alignment, except the profile sequence,
458       // insert gaps corresponding to each hidden region but where each hidden
459       // column region is shifted backwards by the number of preceding visible
460       // gaps update hidden columns at the same time
461       List<int[]> newhidden = new ArrayList<>();
462
463       int numGapsBefore = 0;
464       int gapPosition = 0;
465       for (int[] region : hiddenColumns)
466       {
467         // get region coordinates accounting for gaps
468         // we can rely on gaps not being *in* hidden regions because we already
469         // removed those
470         while (gapPosition < region[0])
471         {
472           gapPosition++;
473           if (gaps.get(gapPosition))
474           {
475             numGapsBefore++;
476           }
477         }
478
479         int left = region[0] - numGapsBefore;
480         int right = region[1] - numGapsBefore;
481         newhidden.add(new int[] { left, right });
482
483         // make a string with number of gaps = length of hidden region
484         StringBuilder sb = new StringBuilder();
485         for (int s = 0; s < right - left + 1; s++)
486         {
487           sb.append(gc);
488         }
489         padGaps(sb, left, profileseq, al);
490
491       }
492       hiddenColumns = newhidden;
493       cursor.resetCursor(hiddenColumns);
494       numColumns = 0;
495     } finally
496     {
497       LOCK.writeLock().unlock();
498     }
499   }
500
501   /**
502    * Pad gaps in all sequences in alignment except profileseq
503    * 
504    * @param sb
505    *          gap string to insert
506    * @param left
507    *          position to insert at
508    * @param profileseq
509    *          sequence not to pad
510    * @param al
511    *          alignment to pad sequences in
512    */
513   private void padGaps(StringBuilder sb, int pos, SequenceI profileseq,
514           AlignmentI al)
515   {
516     // loop over the sequences and pad with gaps where required
517     for (int s = 0, ns = al.getHeight(); s < ns; s++)
518     {
519       SequenceI sqobj = al.getSequenceAt(s);
520       if (sqobj != profileseq)
521       {
522         String sq = al.getSequenceAt(s).getSequenceAsString();
523         if (sq.length() <= pos)
524         {
525           // pad sequence
526           int diff = pos - sq.length() - 1;
527           if (diff > 0)
528           {
529             // pad gaps
530             sq = sq + sb;
531             while ((diff = pos - sq.length() - 1) > 0)
532             {
533               if (diff >= sb.length())
534               {
535                 sq += sb.toString();
536               }
537               else
538               {
539                 char[] buf = new char[diff];
540                 sb.getChars(0, diff, buf, 0);
541                 sq += buf.toString();
542               }
543             }
544           }
545           sq += sb.toString();
546         }
547         else
548         {
549           al.getSequenceAt(s).setSequence(
550                   sq.substring(0, pos) + sb.toString() + sq.substring(pos));
551         }
552       }
553     }
554   }
555
556   /*
557    * Methods which only need read access to the hidden columns collection. 
558    * These methods should use a readLock to prevent other threads changing
559    * the hidden columns collection while it is in use.
560    */
561
562   /**
563    * Output regions data as a string. String is in the format:
564    * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
565    * 
566    * @param delimiter
567    *          string to delimit regions
568    * @param betweenstring
569    *          to put between start and end region values
570    * @return regions formatted according to delimiter and between strings
571    */
572   public String regionsToString(String delimiter, String between)
573   {
574     try
575     {
576       LOCK.readLock().lock();
577       StringBuilder regionBuilder = new StringBuilder();
578
579       boolean first = true;
580       for (int[] range : hiddenColumns)
581       {
582         if (!first)
583         {
584           regionBuilder.append(delimiter);
585         }
586         else
587         {
588           first = false;
589         }
590         regionBuilder.append(range[0]).append(between).append(range[1]);
591
592       }
593
594       return regionBuilder.toString();
595     } finally
596     {
597       LOCK.readLock().unlock();
598     }
599   }
600
601   /**
602    * Find the number of hidden columns
603    * 
604    * @return number of hidden columns
605    */
606   public int getSize()
607   {
608     try
609     {
610       LOCK.readLock().lock();
611
612       if (numColumns == 0)
613       {
614         // numColumns is out of date, so recalculate
615         int size = 0;
616
617         for (int[] range : hiddenColumns)
618         {
619           size += range[1] - range[0] + 1;
620         }
621
622         numColumns = size;
623       }
624
625       return numColumns;
626     } finally
627     {
628       LOCK.readLock().unlock();
629     }
630   }
631
632   /**
633    * Get the number of distinct hidden regions
634    * 
635    * @return number of regions
636    */
637   public int getNumberOfRegions()
638   {
639     try
640     {
641       LOCK.readLock().lock();
642       int num = 0;
643       if (hasHiddenColumns())
644       {
645         num = hiddenColumns.size();
646       }
647       return num;
648     } finally
649     {
650       LOCK.readLock().unlock();
651     }
652   }
653
654   @Override
655   public boolean equals(Object obj)
656   {
657     try
658     {
659       LOCK.readLock().lock();
660
661       if (!(obj instanceof HiddenColumns))
662       {
663         return false;
664       }
665       HiddenColumns that = (HiddenColumns) obj;
666
667       /*
668        * check hidden columns are either both null, or match
669        */
670
671       if (that.hiddenColumns.size() != this.hiddenColumns.size())
672       {
673         return false;
674       }
675
676       Iterator<int[]> thatit = that.iterator();
677       for (int[] thisRange : hiddenColumns)
678       {
679         int[] thatRange = thatit.next();
680         if (thisRange[0] != thatRange[0] || thisRange[1] != thatRange[1])
681         {
682           return false;
683         }
684       }
685       return true;
686     } finally
687     {
688       LOCK.readLock().unlock();
689     }
690   }
691
692   /**
693    * Return absolute column index for a visible column index
694    * 
695    * @param column
696    *          int column index in alignment view (count from zero)
697    * @return alignment column index for column
698    */
699   public int visibleToAbsoluteColumn(int column)
700   {
701     try
702     {
703       LOCK.readLock().lock();
704       int result = column;
705
706       if (!hiddenColumns.isEmpty())
707       {
708         result += cursor.findRegionForVisColumn(column).getHiddenSoFar();
709       }
710
711       return result;
712     } finally
713     {
714       LOCK.readLock().unlock();
715     }
716   }
717
718   /**
719    * Use this method to find out where a column will appear in the visible
720    * alignment when hidden columns exist. If the column is not visible, then the
721    * index of the next visible column on the left will be returned (or 0 if
722    * there is no visible column on the left)
723    * 
724    * @param hiddenColumn
725    *          the column index in the full alignment including hidden columns
726    * @return the position of the column in the visible alignment
727    */
728   public int absoluteToVisibleColumn(int hiddenColumn)
729   {
730     try
731     {
732       LOCK.readLock().lock();
733       int result = hiddenColumn;
734
735       if (!hiddenColumns.isEmpty())
736       {
737         HiddenCursorPosition cursorPos = cursor
738                 .findRegionForColumn(hiddenColumn);
739         int index = cursorPos.getRegionIndex();
740         int hiddenBeforeCol = cursorPos.getHiddenSoFar();
741     
742         // just subtract hidden cols count - this works fine if column is
743         // visible
744         result = hiddenColumn - hiddenBeforeCol;
745     
746         // now check in case column is hidden - it will be in the returned
747         // hidden region
748         if (index < hiddenColumns.size())
749         {
750           int[] region = hiddenColumns.get(index);
751           if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
752           {
753             // actually col is hidden, return region[0]-1
754             // unless region[0]==0 in which case return 0
755             if (region[0] == 0)
756             {
757               result = 0;
758             }
759             else
760             {
761               result = region[0] - 1 - hiddenBeforeCol;
762             }
763           }
764         }
765       }
766
767       return result; // return the shifted position after removing hidden
768                      // columns.
769     } finally
770     {
771       LOCK.readLock().unlock();
772     }
773   }
774
775   /**
776    * Find the visible column which is a given visible number of columns to the
777    * left of another visible column. i.e. for a startColumn x, the column which
778    * is distance 1 away will be column x-1.
779    * 
780    * @param visibleDistance
781    *          the number of visible columns to offset by
782    * @param startColumn
783    *          the column to start from
784    * @return the position of the column in the visible alignment
785    */
786   public int subtractVisibleColumns(int visibleDistance, int startColumn)
787   {
788     try
789     {
790       LOCK.readLock().lock();
791       int distance = visibleDistance;
792
793       // in case startColumn is in a hidden region, move it to the left
794       int start = visibleToAbsoluteColumn(absoluteToVisibleColumn(startColumn));
795
796       Iterator<int[]> it = new ReverseRegionsIterator(0, start,
797               hiddenColumns);
798
799       while (it.hasNext() && (distance > 0))
800       {
801         int[] region = it.next();
802
803         if (start > region[1])
804         {
805           // subtract the gap to right of region from distance
806           if (start - region[1] <= distance)
807           {
808             distance -= start - region[1];
809             start = region[0] - 1;
810           }
811           else
812           {
813             start = start - distance;
814             distance = 0;
815           }
816         }
817       }
818       return start - distance;
819
820     } finally
821     {
822       LOCK.readLock().unlock();
823     }
824   }
825
826   /**
827    * This method returns the rightmost limit of a region of an alignment with
828    * hidden columns. In otherwords, the next hidden column.
829    * 
830    * @param alPos
831    *          the absolute (visible) alignmentPosition to find the next hidden
832    *          column for
833    * @return the index of the next hidden column, or alPos if there is no next
834    *         hidden column
835    */
836   public int getHiddenBoundaryRight(int alPos)
837   {
838     try
839     {
840       LOCK.readLock().lock();
841       if (!hiddenColumns.isEmpty())
842       {
843         int index = cursor.findRegionForColumn(alPos).getRegionIndex();
844         if (index < hiddenColumns.size())
845         {
846           int[] region = hiddenColumns.get(index);
847           if (alPos < region[0])
848           {
849             return region[0];
850           }
851           else if ((alPos <= region[1])
852                   && (index + 1 < hiddenColumns.size()))
853           {
854             // alPos is within a hidden region, return the next one
855             // if there is one
856             region = hiddenColumns.get(index + 1);
857             return region[0];
858           }
859         }
860       }
861       return alPos;
862     } finally
863     {
864       LOCK.readLock().unlock();
865     }
866   }
867
868   /**
869    * This method returns the leftmost limit of a region of an alignment with
870    * hidden columns. In otherwords, the previous hidden column.
871    * 
872    * @param alPos
873    *          the absolute (visible) alignmentPosition to find the previous
874    *          hidden column for
875    */
876   public int getHiddenBoundaryLeft(int alPos)
877   {
878     try
879     {
880       LOCK.readLock().lock();
881
882       if (!hiddenColumns.isEmpty())
883       {
884         int index = cursor.findRegionForColumn(alPos).getRegionIndex();
885
886         if (index > 0)
887         {
888           int[] region = hiddenColumns.get(index - 1);
889           return region[1];
890         }
891       }
892       return alPos;
893     } finally
894     {
895       LOCK.readLock().unlock();
896     }
897   }
898
899
900   /**
901    * Answers if a column in the alignment is visible
902    * 
903    * @param column
904    *          absolute position of column in the alignment
905    * @return true if column is visible
906    */
907   public boolean isVisible(int column)
908   {
909     try
910     {
911       LOCK.readLock().lock();
912
913       int regionindex = cursor.findRegionForColumn(column).getRegionIndex();
914       if (regionindex > -1 && regionindex < hiddenColumns.size())
915       {
916         int[] region = hiddenColumns.get(regionindex);
917         // already know that column <= region[1] as cursor returns containing
918         // region or region to right
919         if (column >= region[0])
920         {
921           return false;
922         }
923       }
924       return true;
925
926     } finally
927     {
928       LOCK.readLock().unlock();
929     }
930   }
931
932   /**
933    * Get the visible sections of a set of sequences
934    * 
935    * @param start
936    *          sequence position to start from
937    * @param end
938    *          sequence position to end at
939    * @param seqs
940    *          an array of sequences
941    * @return an array of strings encoding the visible parts of each sequence
942    */
943   public String[] getVisibleSequenceStrings(int start, int end,
944           SequenceI[] seqs)
945   {
946     try
947     {
948       LOCK.readLock().lock();
949       int iSize = seqs.length;
950       String[] selections = new String[iSize];
951       if (!hiddenColumns.isEmpty())
952       {
953         for (int i = 0; i < iSize; i++)
954         {
955           StringBuilder visibleSeq = new StringBuilder();
956
957           Iterator<int[]> blocks = new VisibleContigsIterator(start,
958                   end + 1, hiddenColumns);
959
960           while (blocks.hasNext())
961           {
962             int[] block = blocks.next();
963             if (blocks.hasNext())
964             {
965               visibleSeq
966                       .append(seqs[i].getSequence(block[0], block[1] + 1));
967             }
968             else
969             {
970               visibleSeq
971                       .append(seqs[i].getSequence(block[0], block[1]));
972             }
973           }
974
975           selections[i] = visibleSeq.toString();
976         }
977       }
978       else
979       {
980         for (int i = 0; i < iSize; i++)
981         {
982           selections[i] = seqs[i].getSequenceAsString(start, end);
983         }
984       }
985
986       return selections;
987     } finally
988     {
989       LOCK.readLock().unlock();
990     }
991   }
992
993   /**
994    * Locate the first position visible for this sequence. If seq isn't visible
995    * then return the position of the left side of the hidden boundary region.
996    * 
997    * @param seq
998    *          sequence to find position for
999    * @return visible start position
1000    */
1001   public int locateVisibleStartOfSequence(SequenceI seq)
1002   {
1003     try
1004     {
1005       LOCK.readLock().lock();
1006       int start = 0;
1007
1008       if (hiddenColumns.isEmpty())
1009       {
1010         return seq.findIndex(seq.getStart()) - 1;
1011       }
1012
1013       // Simply walk along the sequence whilst watching for hidden column
1014       // boundaries
1015       Iterator<int[]> regions = hiddenColumns.iterator();
1016       int hideStart = seq.getLength();
1017       int hideEnd = -1;
1018       int visPrev = 0;
1019       int visNext = 0;
1020       boolean foundStart = false;
1021
1022       // step through the non-gapped positions of the sequence
1023       for (int i = seq.getStart(); i <= seq.getEnd() && (!foundStart); i++)
1024       {
1025         // get alignment position of this residue in the sequence
1026         int p = seq.findIndex(i) - 1;
1027
1028         // update hidden region start/end
1029         while (hideEnd < p && regions.hasNext())
1030         {
1031           int[] region = regions.next();
1032           visPrev = visNext;
1033           visNext += region[0] - visPrev;
1034           hideStart = region[0];
1035           hideEnd = region[1];
1036         }
1037         if (hideEnd < p)
1038         {
1039           hideStart = seq.getLength();
1040         }
1041         // update visible boundary for sequence
1042         if (p < hideStart)
1043         {
1044           start = p;
1045           foundStart = true;
1046         }
1047       }
1048
1049       if (foundStart)
1050       {
1051         return absoluteToVisibleColumn(start);
1052       }
1053       // otherwise, sequence was completely hidden
1054       return visPrev;
1055     } finally
1056     {
1057       LOCK.readLock().unlock();
1058     }
1059   }
1060
1061
1062   /**
1063    * 
1064    * @return true if there are columns hidden
1065    */
1066   public boolean hasHiddenColumns()
1067   {
1068     try
1069     {
1070       LOCK.readLock().lock();
1071
1072       // we don't use getSize()>0 here because it has to iterate over
1073       // the full hiddenColumns collection and so will be much slower
1074       return (!hiddenColumns.isEmpty());
1075     } finally
1076     {
1077       LOCK.readLock().unlock();
1078     }
1079   }
1080
1081   /**
1082    * 
1083    * @return true if there is more than one hidden column region
1084    */
1085   public boolean hasMultiHiddenColumnRegions()
1086   {
1087     try
1088     {
1089       LOCK.readLock().lock();
1090       return !hiddenColumns.isEmpty() && hiddenColumns.size() > 1;
1091     } finally
1092     {
1093       LOCK.readLock().unlock();
1094     }
1095   }
1096
1097
1098   /**
1099    * Returns a hashCode built from hidden column ranges
1100    */
1101   @Override
1102   public int hashCode()
1103   {
1104     try
1105     {
1106       LOCK.readLock().lock();
1107       int hashCode = 1;
1108       for (int[] hidden : hiddenColumns)
1109       {
1110         hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
1111         hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
1112       }
1113       return hashCode;
1114     } finally
1115     {
1116       LOCK.readLock().unlock();
1117     }
1118   }
1119
1120   /**
1121    * Hide columns corresponding to the marked bits
1122    * 
1123    * @param inserts
1124    *          - columns mapped to bits starting from zero
1125    */
1126   public void hideColumns(BitSet inserts)
1127   {
1128     try
1129     {
1130       LOCK.writeLock().lock();
1131       for (int firstSet = inserts
1132               .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
1133                       .nextSetBit(lastSet))
1134       {
1135         lastSet = inserts.nextClearBit(firstSet);
1136         hideColumns(firstSet, lastSet - 1);
1137       }
1138       cursor.resetCursor(hiddenColumns);
1139       numColumns = 0;
1140     } finally
1141     {
1142       LOCK.writeLock().unlock();
1143     }
1144   }
1145
1146   /**
1147    * Hide columns corresponding to the marked bits, within the range
1148    * [start,end]. Entries in tohide which are outside [start,end] are ignored.
1149    * 
1150    * @param tohide
1151    *          columns mapped to bits starting from zero
1152    * @param start
1153    *          start of range to hide columns within
1154    * @param end
1155    *          end of range to hide columns within
1156    */
1157   public void hideColumns(BitSet tohide, int start, int end)
1158   {
1159     clearHiddenColumnsInRange(start, end);
1160
1161     // make sure only bits between start and end are set
1162     tohide.clear(0, start - 1);
1163     tohide.clear(Math.min(end + 1, tohide.length() - 1),
1164             tohide.length() - 1);
1165
1166     hideColumns(tohide);
1167   }
1168
1169   /**
1170    * Make all columns in the range [start,end] visible
1171    * 
1172    * @param start
1173    *          start of range to show columns
1174    * @param end
1175    *          end of range to show columns
1176    */
1177   private void clearHiddenColumnsInRange(int start, int end)
1178   {
1179     try
1180     {
1181       LOCK.writeLock().lock();
1182       
1183       HiddenCursorPosition pos = cursor.findRegionForColumn(start);
1184       int index = pos.getRegionIndex();
1185       int startindex = index; // first index in hiddenColumns to remove
1186       
1187       if (index != -1 && index != hiddenColumns.size())
1188       {
1189         // regionIndex is the region which either contains start
1190         // or lies to the right of start
1191         int[] region = hiddenColumns.get(index);
1192         if (region[0] < start && region[1] >= start)
1193         {
1194           // region contains start, truncate so that it ends just before start
1195           region[1] = start - 1;
1196           startindex++;
1197         }
1198       }
1199       
1200       pos = cursor.findRegionForColumn(end);
1201       index = pos.getRegionIndex();
1202       int endindex = index - 1; // last index in hiddenColumns to remove
1203
1204       if (index != -1 && index != hiddenColumns.size())
1205       {
1206         // regionIndex is the region which either contains end
1207         // or lies to the right of end
1208         int[] region = hiddenColumns.get(index);
1209         if (region[0] <= end && region[1] > end)
1210         {
1211           // region contains end, truncate so that it starts just after end
1212           region[0] = end + 1;
1213         }
1214       }
1215       
1216       hiddenColumns.subList(startindex, endindex + 1).clear();
1217       cursor.resetCursor(hiddenColumns);
1218       numColumns = 0;
1219     } finally
1220     {
1221       LOCK.writeLock().unlock();
1222     }
1223   }
1224
1225   /**
1226    * 
1227    * @param inserts
1228    *          BitSet where hidden columns will be marked
1229    */
1230   public void markHiddenRegions(BitSet inserts)
1231   {
1232     try
1233     {
1234       LOCK.readLock().lock();
1235
1236       for (int[] range : hiddenColumns)
1237       {
1238         inserts.set(range[0], range[1] + 1);
1239       }
1240     } finally
1241     {
1242       LOCK.readLock().unlock();
1243     }
1244   }
1245
1246   /**
1247    * Calculate the visible start and end index of an alignment.
1248    * 
1249    * @param width
1250    *          full alignment width
1251    * @return integer array where: int[0] = startIndex, and int[1] = endIndex
1252    */
1253   public int[] getVisibleStartAndEndIndex(int width)
1254   {
1255     try
1256     {
1257       LOCK.readLock().lock();
1258       int[] alignmentStartEnd = new int[] { 0, width - 1 };
1259       int startPos = alignmentStartEnd[0];
1260       int endPos = alignmentStartEnd[1];
1261
1262       int[] lowestRange = new int[] { -1, -1 };
1263       int[] higestRange = new int[] { -1, -1 };
1264
1265       if (hiddenColumns.isEmpty())
1266       {
1267         return new int[] { startPos, endPos };
1268       }
1269
1270       for (int[] range : hiddenColumns)
1271       {
1272         lowestRange = (range[0] <= startPos) ? range : lowestRange;
1273         higestRange = (range[1] >= endPos) ? range : higestRange;
1274       }
1275
1276       if (lowestRange[0] == -1) // includes (lowestRange[1] == -1)
1277       {
1278         startPos = alignmentStartEnd[0];
1279       }
1280       else
1281       {
1282         startPos = lowestRange[1] + 1;
1283       }
1284
1285       if (higestRange[0] == -1) // includes (higestRange[1] == -1)
1286       {
1287         endPos = alignmentStartEnd[1];
1288       }
1289       else
1290       {
1291         endPos = higestRange[0] - 1;
1292       }
1293       return new int[] { startPos, endPos };
1294     } finally
1295     {
1296       LOCK.readLock().unlock();
1297     }
1298   }
1299
1300   /**
1301    * Finds the hidden region (if any) which starts or ends at res
1302    * 
1303    * @param res
1304    *          visible residue position, unadjusted for hidden columns
1305    * @return region as [start,end] or null if no matching region is found. If
1306    *         res is adjacent to two regions, returns the left region.
1307    */
1308   public int[] getRegionWithEdgeAtRes(int res)
1309   {
1310     try
1311     {
1312       LOCK.readLock().lock();
1313       int adjres = visibleToAbsoluteColumn(res);
1314
1315       int[] reveal = null;
1316
1317       if (!hiddenColumns.isEmpty())
1318       {
1319         // look for a region ending just before adjres
1320         int regionindex = cursor.findRegionForColumn(adjres - 1)
1321                 .getRegionIndex();
1322         if (regionindex < hiddenColumns.size()
1323                 && hiddenColumns.get(regionindex)[1] == adjres - 1)
1324         {
1325           reveal = hiddenColumns.get(regionindex);
1326         }
1327         // check if the region ends just after adjres
1328         else if (regionindex < hiddenColumns.size()
1329                 && hiddenColumns.get(regionindex)[0] == adjres + 1)
1330         {
1331           reveal = hiddenColumns.get(regionindex);
1332         }
1333       }
1334       return reveal;
1335
1336     } finally
1337     {
1338       LOCK.readLock().unlock();
1339     }
1340   }
1341
1342   /**
1343    * Return an iterator over the hidden regions
1344    */
1345   public Iterator<int[]> iterator()
1346   {
1347     try
1348     {
1349       LOCK.readLock().lock();
1350       return new HiddenColsIterator(hiddenColumns);
1351     } finally
1352     {
1353       LOCK.readLock().unlock();
1354     }
1355   }
1356
1357   /**
1358    * Return a bounded iterator over the hidden regions
1359    * 
1360    * @param start
1361    *          position to start from (inclusive, absolute column position)
1362    * @param end
1363    *          position to end at (inclusive, absolute column position)
1364    * @return
1365    */
1366   public Iterator<int[]> getBoundedIterator(int start, int end)
1367   {
1368     try
1369     {
1370       LOCK.readLock().lock();
1371       return new HiddenColsIterator(start, end, hiddenColumns);
1372     } finally
1373     {
1374       LOCK.readLock().unlock();
1375     }
1376   }
1377
1378   /**
1379    * Return a bounded iterator over the *visible* start positions of hidden
1380    * regions
1381    * 
1382    * @param start
1383    *          position to start from (inclusive, visible column position)
1384    * @param end
1385    *          position to end at (inclusive, visible column position)
1386    */
1387   public Iterator<Integer> getBoundedStartIterator(int start, int end)
1388   {
1389     try
1390     {
1391       LOCK.readLock().lock();
1392
1393       // get absolute position of column in alignment
1394       int absoluteStart = visibleToAbsoluteColumn(start);
1395
1396       // Get cursor position and supply it to the iterator:
1397       // Since we want visible region start, we look for a cursor for the
1398       // (absoluteStart-1), then if absoluteStart is the start of a visible
1399       // region we'll get the cursor pointing to the region before, which is
1400       // what we want
1401       HiddenCursorPosition pos = cursor
1402               .findRegionForColumn(absoluteStart - 1);
1403
1404       return new BoundedStartRegionIterator(pos, start, end,
1405               hiddenColumns);
1406     } finally
1407     {
1408       LOCK.readLock().unlock();
1409     }
1410   }
1411
1412   /**
1413    * Return an iterator over visible *columns* (not regions) between the given
1414    * start and end boundaries
1415    * 
1416    * @param start
1417    *          first column (inclusive)
1418    * @param end
1419    *          last column (inclusive)
1420    */
1421   public Iterator<Integer> getVisibleColsIterator(int start, int end)
1422   {
1423     try
1424     {
1425       LOCK.readLock().lock();
1426       return new VisibleColsIterator(start, end, hiddenColumns);
1427     } finally
1428     {
1429       LOCK.readLock().unlock();
1430     }
1431   }
1432
1433   /**
1434    * return an iterator over visible segments between the given start and end
1435    * boundaries
1436    * 
1437    * @param start
1438    *          first column, inclusive from 0
1439    * @param end
1440    *          last column - not inclusive
1441    * @param useVisibleCoords
1442    *          if true, start and end are visible column positions, not absolute
1443    *          positions*
1444    */
1445   public VisibleContigsIterator getVisContigsIterator(int start,
1446           int end,
1447           boolean useVisibleCoords)
1448   {
1449     int adjstart = start;
1450     int adjend = end;
1451     if (useVisibleCoords)
1452     {
1453       adjstart = visibleToAbsoluteColumn(start);
1454       adjend = visibleToAbsoluteColumn(end);
1455     }
1456
1457     try
1458     {
1459       LOCK.readLock().lock();
1460       return new VisibleContigsIterator(adjstart, adjend, hiddenColumns);
1461     } finally
1462     {
1463       LOCK.readLock().unlock();
1464     }
1465   }
1466 }