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