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