JAL-2591 Hidden columns regions can be output to string + test
[jalview.git] / src / jalview / datamodel / HiddenColumns.java
1 package jalview.datamodel;
2
3 import jalview.util.Comparison;
4 import jalview.util.ShiftList;
5
6 import java.util.ArrayList;
7 import java.util.BitSet;
8 import java.util.Collections;
9 import java.util.Iterator;
10 import java.util.List;
11 import java.util.Vector;
12 import java.util.concurrent.locks.ReentrantReadWriteLock;
13
14 public class HiddenColumns implements Iterable<int[]>
15 {
16   private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
17   
18   /*
19    * list of hidden column [start, end] ranges; the list is maintained in
20    * ascending start column order
21    */
22   private Vector<int[]> hiddenColumns;
23
24   /**
25    * This Method is used to return all the HiddenColumn regions
26    * 
27    * @return empty list or List of hidden column intervals
28    */
29   public List<int[]> getHiddenRegions()
30   {
31     return hiddenColumns == null ? Collections.<int[]> emptyList()
32             : hiddenColumns;
33   }
34
35   /**
36    * Output regions data as a string. String is in the format:
37    * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
38    * 
39    * @param delimiter
40    *          string to delimit regions
41    * @param betweenstring
42    *          to put between start and end region values
43    * @return regions formatted according to delimiter and between strings
44    */
45   public String regionsToString(String delimiter, String between)
46   {
47     try
48     {
49       lock.readLock().lock();
50       StringBuilder regionBuilder = new StringBuilder();
51       for (int[] range : hiddenColumns)
52       {
53         regionBuilder.append(delimiter).append(range[0]).append(between)
54                 .append(range[1]);
55       }
56
57       regionBuilder.deleteCharAt(0);
58       return regionBuilder.toString();
59     } finally
60     {
61       lock.readLock().unlock();
62     }
63   }
64
65   /**
66    * Find the number of hidden columns
67    * 
68    * @return number of hidden columns
69    */
70   public int getSize()
71   {
72     try
73     {
74       lock.readLock().lock();
75       int size = 0;
76       if (hasHidden())
77       {
78         for (int[] range : hiddenColumns)
79         {
80           size += range[1] - range[0] + 1;
81         }
82       }
83       return size;
84     }
85     finally
86     {
87       lock.readLock().unlock();
88     }
89   }
90
91   /**
92    * Answers if there are any hidden columns
93    * 
94    * @return true if there are hidden columns
95    */
96   public boolean hasHidden()
97   {
98     try
99     {
100       lock.readLock().lock();
101       return (hiddenColumns != null) && (!hiddenColumns.isEmpty());
102     } finally
103     {
104       lock.readLock().unlock();
105     }
106
107   }
108
109   @Override
110   public boolean equals(Object obj)
111   {
112     try
113     {
114       lock.readLock().lock();
115
116       if (!(obj instanceof HiddenColumns))
117       {
118         return false;
119       }
120       HiddenColumns that = (HiddenColumns) obj;
121
122       /*
123        * check hidden columns are either both null, or match
124        */
125       if (this.hiddenColumns == null)
126       {
127         return (that.hiddenColumns == null);
128       }
129       if (that.hiddenColumns == null
130               || that.hiddenColumns.size() != this.hiddenColumns.size())
131       {
132         return false;
133       }
134       int i = 0;
135       for (int[] thisRange : hiddenColumns)
136       {
137         int[] thatRange = that.hiddenColumns.get(i++);
138         if (thisRange[0] != thatRange[0] || thisRange[1] != thatRange[1])
139         {
140           return false;
141         }
142       }
143       return true;
144     } finally
145     {
146       lock.readLock().unlock();
147     }
148   }
149
150   /**
151    * Return absolute column index for a visible column index
152    * 
153    * @param column
154    *          int column index in alignment view (count from zero)
155    * @return alignment column index for column
156    */
157   public int adjustForHiddenColumns(int column)
158   {
159     try
160     {
161       lock.readLock().lock();
162       int result = column;
163       if (hiddenColumns != null)
164       {
165         for (int i = 0; i < hiddenColumns.size(); i++)
166         {
167           int[] region = hiddenColumns.elementAt(i);
168           if (result >= region[0])
169           {
170             result += region[1] - region[0] + 1;
171           }
172         }
173       }
174       return result;
175     } finally
176     {
177       lock.readLock().unlock();
178     }
179   }
180
181   /**
182    * Use this method to find out where a column will appear in the visible
183    * alignment when hidden columns exist. If the column is not visible, then the
184    * left-most visible column will always be returned.
185    * 
186    * @param hiddenColumn
187    *          the column index in the full alignment including hidden columns
188    * @return the position of the column in the visible alignment
189    */
190   public int findColumnPosition(int hiddenColumn)
191   {
192     try
193     {
194       lock.readLock().lock();
195       int result = hiddenColumn;
196       if (hiddenColumns != null)
197       {
198         int index = 0;
199         int[] region;
200         do
201         {
202           region = hiddenColumns.elementAt(index++);
203           if (hiddenColumn > region[1])
204           {
205             result -= region[1] + 1 - region[0];
206           }
207         } while ((hiddenColumn > region[1])
208                 && (index < hiddenColumns.size()));
209
210         if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
211         {
212           // Here the hidden column is within a region, so
213           // we want to return the position of region[0]-1, adjusted for any
214           // earlier hidden columns.
215           // Calculate the difference between the actual hidden col position
216           // and region[0]-1, and then subtract from result to convert result
217           // from
218           // the adjusted hiddenColumn value to the adjusted region[0]-1 value
219
220           // However, if the region begins at 0 we cannot return region[0]-1
221           // just return 0
222           if (region[0] == 0)
223           {
224             return 0;
225           }
226           else
227           {
228             return result - (hiddenColumn - region[0] + 1);
229           }
230         }
231       }
232       return result; // return the shifted position after removing hidden
233                      // columns.
234     } finally
235     {
236       lock.readLock().unlock();
237     }
238   }
239
240   /**
241    * Find the visible column which is a given visible number of columns to the
242    * left of another visible column. i.e. for a startColumn x, the column which
243    * is distance 1 away will be column x-1.
244    * 
245    * @param visibleDistance
246    *          the number of visible columns to offset by
247    * @param startColumn
248    *          the column to start from
249    * @return the position of the column in the visible alignment
250    */
251   public int subtractVisibleColumns(int visibleDistance, int startColumn)
252   {
253     try
254     {
255
256       lock.readLock().lock();
257     int distance = visibleDistance;
258
259     // in case startColumn is in a hidden region, move it to the left
260     int start = adjustForHiddenColumns(findColumnPosition(startColumn));
261
262     // get index of hidden region to left of start
263     int index = getHiddenIndexLeft(start);
264     if (index == -1)
265     {
266       // no hidden regions to left of startColumn
267       return start - distance;
268     }
269
270     // walk backwards through the alignment subtracting the counts of visible
271     // columns from distance
272     int[] region;
273     int gap = 0;
274     int nextstart = start;
275
276     while ((index > -1) && (distance - gap > 0))
277     {
278       // subtract the gap to right of region from distance
279       distance -= gap;
280       start = nextstart;
281
282       // calculate the next gap
283       region = hiddenColumns.get(index);
284       gap = start - region[1];
285
286       // set start to just to left of current region
287       nextstart = region[0] - 1;
288       index--;
289     }
290
291     if (distance - gap > 0)
292     {
293       // fell out of loop because there are no more hidden regions
294       distance -= gap;
295       return nextstart - distance;
296     }
297     return start - distance;
298     } finally
299     {
300       lock.readLock().unlock();
301     }
302
303   }
304
305   /**
306    * Use this method to determine the set of hiddenRegion start positions
307    * 
308    * @return list of column number in visible view where hidden regions start
309    */
310   public List<Integer> findHiddenRegionPositions()
311   {
312     try
313     {
314       lock.readLock().lock();
315       List<Integer> positions = new ArrayList<>(
316               hiddenColumns.size());
317
318       positions.add(hiddenColumns.elementAt(0)[0]);
319       for (int i = 1; i < hiddenColumns.size(); ++i)
320       {
321
322         int result = 0;
323         if (hiddenColumns != null)
324         {
325           int index = 0;
326           int gaps = 0;
327           do
328           {
329             int[] region = hiddenColumns.elementAt(index);
330             gaps += region[1] + 1 - region[0];
331             result = region[1] + 1;
332             index++;
333           } while (index <= i);
334
335           result -= gaps;
336         }
337         positions.add(result);
338       }
339
340       return positions;
341     }
342     finally
343     {
344       lock.readLock().unlock();
345     }
346   }
347
348   /**
349    * This method returns the rightmost limit of a region of an alignment with
350    * hidden columns. In otherwords, the next hidden column.
351    * 
352    * @param index
353    *          int
354    */
355   public int getHiddenBoundaryRight(int alPos)
356   {
357     try
358     {
359       lock.readLock().lock();
360       if (hiddenColumns != null)
361       {
362         int index = 0;
363         do
364         {
365           int[] region = hiddenColumns.elementAt(index);
366           if (alPos < region[0])
367           {
368             return region[0];
369           }
370
371           index++;
372         } while (index < hiddenColumns.size());
373       }
374
375       return alPos;
376     } finally
377     {
378       lock.readLock().unlock();
379     }
380
381   }
382
383   /**
384    * This method returns the leftmost limit of a region of an alignment with
385    * hidden columns. In otherwords, the previous hidden column.
386    * 
387    * @param index
388    *          int
389    */
390   public int getHiddenBoundaryLeft(int alPos)
391   {
392     try
393     {
394       lock.readLock().lock();
395
396     if (hiddenColumns != null)
397     {
398       int index = hiddenColumns.size() - 1;
399       do
400       {
401         int[] region = hiddenColumns.elementAt(index);
402         if (alPos > region[1])
403         {
404           return region[1];
405         }
406
407         index--;
408       } while (index > -1);
409     }
410
411     return alPos;
412     } finally
413     {
414       lock.readLock().unlock();
415     }
416   }
417
418   /**
419    * This method returns the index of the hidden region to the left of a column
420    * position. If the column is in a hidden region it returns the index of the
421    * region to the left. If there is no hidden region to the left it returns -1.
422    * 
423    * @param pos
424    *          int
425    */
426   private int getHiddenIndexLeft(int pos)
427   {
428     try
429     {
430
431       lock.readLock().lock();
432     if (hiddenColumns != null)
433     {
434       int index = hiddenColumns.size() - 1;
435       do
436       {
437         int[] region = hiddenColumns.elementAt(index);
438         if (pos > region[1])
439         {
440           return index;
441         }
442
443         index--;
444       } while (index > -1);
445     }
446
447     return -1;
448     } finally
449     {
450       lock.readLock().unlock();
451     }
452
453   }
454
455   /**
456    * Adds the specified column range to the hidden columns
457    * 
458    * @param start
459    * @param end
460    */
461   public void hideColumns(int start, int end)
462   {
463     hideColumns(start, end, false);
464   }
465
466   /**
467    * Adds the specified column range to the hidden columns
468    * 
469    * @param start
470    * @param end
471    */
472   private void hideColumns(int start, int end, boolean alreadyLocked)
473   {
474     try
475     {
476
477       if (!alreadyLocked)
478       {
479         lock.writeLock().lock();
480       }
481
482     if (hiddenColumns == null)
483     {
484       hiddenColumns = new Vector<>();
485     }
486
487     /*
488      * traverse existing hidden ranges and insert / amend / append as
489      * appropriate
490      */
491     for (int i = 0; i < hiddenColumns.size(); i++)
492     {
493       int[] region = hiddenColumns.elementAt(i);
494
495       if (end < region[0] - 1)
496       {
497         /*
498          * insert discontiguous preceding range
499          */
500         hiddenColumns.insertElementAt(new int[] { start, end }, i);
501         return;
502       }
503
504       if (end <= region[1])
505       {
506         /*
507          * new range overlaps existing, or is contiguous preceding it - adjust
508          * start column
509          */
510         region[0] = Math.min(region[0], start);
511         return;
512       }
513
514       if (start <= region[1] + 1)
515       {
516         /*
517          * new range overlaps existing, or is contiguous following it - adjust
518          * start and end columns
519          */
520         region[0] = Math.min(region[0], start);
521         region[1] = Math.max(region[1], end);
522
523         /*
524          * also update or remove any subsequent ranges 
525          * that are overlapped
526          */
527         while (i < hiddenColumns.size() - 1)
528         {
529           int[] nextRegion = hiddenColumns.get(i + 1);
530           if (nextRegion[0] > end + 1)
531           {
532             /*
533              * gap to next hidden range - no more to update
534              */
535             break;
536           }
537           region[1] = Math.max(nextRegion[1], end);
538           hiddenColumns.remove(i + 1);
539         }
540         return;
541       }
542     }
543
544     /*
545      * remaining case is that the new range follows everything else
546      */
547     hiddenColumns.addElement(new int[] { start, end });
548     } finally
549     {
550       if (!alreadyLocked)
551       {
552         lock.writeLock().unlock();
553       }
554     }
555   }
556
557   public boolean isVisible(int column)
558   {
559     try
560     {
561       lock.readLock().lock();
562
563     if (hiddenColumns != null)
564     {
565       for (int[] region : hiddenColumns)
566       {
567         if (column >= region[0] && column <= region[1])
568         {
569           return false;
570         }
571       }
572     }
573
574     return true;
575     } finally
576     {
577       lock.readLock().unlock();
578     }
579   }
580
581   /**
582    * ColumnSelection
583    */
584   public HiddenColumns()
585   {
586   }
587
588   /**
589    * Copy constructor
590    * 
591    * @param copy
592    */
593   public HiddenColumns(HiddenColumns copy)
594   {
595     try
596     {
597
598       lock.readLock().lock();
599       if (copy != null)
600       {
601         if (copy.hiddenColumns != null)
602         {
603           hiddenColumns = copy.copyHiddenRegions();
604         }
605       }
606     }
607     finally
608     {
609       lock.readLock().unlock();
610     }
611   }
612
613   private Vector<int[]> copyHiddenRegions()
614   {
615     Vector<int[]> copy = new Vector<>(hiddenColumns.size());
616     for (int i = 0, j = hiddenColumns.size(); i < j; i++)
617     {
618       int[] rh, cp;
619       rh = hiddenColumns.elementAt(i);
620       if (rh != null)
621       {
622         cp = new int[rh.length];
623         System.arraycopy(rh, 0, cp, 0, rh.length);
624         copy.addElement(cp);
625       }
626     }
627     return copy;
628   }
629
630   private ArrayList<int[]> copyHiddenRegionsToArrayList()
631   {
632     ArrayList<int[]> copy = new ArrayList<>(hiddenColumns.size());
633     for (int i = 0, j = hiddenColumns.size(); i < j; i++)
634     {
635       int[] rh, cp;
636       rh = hiddenColumns.elementAt(i);
637       if (rh != null)
638       {
639         cp = new int[rh.length];
640         System.arraycopy(rh, 0, cp, 0, rh.length);
641         copy.add(cp);
642       }
643     }
644     return copy;
645   }
646
647   public void getHiddenColumnsCopy(Vector<int[]> copy)
648   {
649     try
650     {
651       lock.readLock().lock();
652       copy = copyHiddenRegions();
653     } finally
654     {
655       lock.readLock().unlock();
656     }
657   }
658
659   public void getHiddenColumnsCopy(ArrayList<int[]> copy)
660   {
661     try
662     {
663       lock.readLock().lock();
664       copy = copyHiddenRegionsToArrayList();
665     } finally
666     {
667       lock.readLock().unlock();
668     }
669   }
670
671   /**
672    * propagate shift in alignment columns to column selection
673    * 
674    * @param start
675    *          beginning of edit
676    * @param left
677    *          shift in edit (+ve for removal, or -ve for inserts)
678    */
679   public List<int[]> compensateForEdit(int start, int change,
680           ColumnSelection sel)
681   {
682     try
683     {
684       lock.writeLock().lock();
685       List<int[]> deletedHiddenColumns = null;
686
687       if (hiddenColumns != null)
688       {
689         deletedHiddenColumns = new ArrayList<>();
690         int hSize = hiddenColumns.size();
691         for (int i = 0; i < hSize; i++)
692         {
693           int[] region = hiddenColumns.elementAt(i);
694           if (region[0] > start && start + change > region[1])
695           {
696             deletedHiddenColumns.add(region);
697
698             hiddenColumns.removeElementAt(i);
699             i--;
700             hSize--;
701             continue;
702           }
703
704           if (region[0] > start)
705           {
706             region[0] -= change;
707             region[1] -= change;
708           }
709
710           if (region[0] < 0)
711           {
712             region[0] = 0;
713           }
714
715         }
716
717         this.revealHiddenColumns(0, sel);
718       }
719
720       return deletedHiddenColumns;
721     } finally
722     {
723       lock.writeLock().unlock();
724     }
725   }
726
727   /**
728    * propagate shift in alignment columns to column selection special version of
729    * compensateForEdit - allowing for edits within hidden regions
730    * 
731    * @param start
732    *          beginning of edit
733    * @param left
734    *          shift in edit (+ve for removal, or -ve for inserts)
735    */
736   public void compensateForDelEdits(int start, int change)
737   {
738     try
739     {
740       lock.writeLock().lock();
741       if (hiddenColumns != null)
742       {
743         for (int i = 0; i < hiddenColumns.size(); i++)
744         {
745           int[] region = hiddenColumns.elementAt(i);
746           if (region[0] >= start)
747           {
748             region[0] -= change;
749           }
750           if (region[1] >= start)
751           {
752             region[1] -= change;
753           }
754           if (region[1] < region[0])
755           {
756             hiddenColumns.removeElementAt(i--);
757           }
758
759           if (region[0] < 0)
760           {
761             region[0] = 0;
762           }
763           if (region[1] < 0)
764           {
765             region[1] = 0;
766           }
767         }
768       }
769     }
770     finally
771     {
772       lock.writeLock().unlock();
773     }
774   }
775
776   /**
777    * return all visible segments between the given start and end boundaries
778    * 
779    * @param start
780    *          (first column inclusive from 0)
781    * @param end
782    *          (last column - not inclusive)
783    * @return int[] {i_start, i_end, ..} where intervals lie in
784    *         start<=i_start<=i_end<end
785    */
786   public int[] getVisibleContigs(int start, int end)
787   {
788     try
789     {
790       lock.readLock().lock();
791       if (hiddenColumns != null && hiddenColumns.size() > 0)
792       {
793         List<int[]> visiblecontigs = new ArrayList<>();
794         List<int[]> regions = getHiddenRegions();
795
796         int vstart = start;
797         int[] region;
798         int hideStart, hideEnd;
799
800         for (int j = 0; vstart < end && j < regions.size(); j++)
801         {
802           region = regions.get(j);
803           hideStart = region[0];
804           hideEnd = region[1];
805
806           if (hideEnd < vstart)
807           {
808             continue;
809           }
810           if (hideStart > vstart)
811           {
812             visiblecontigs.add(new int[] { vstart, hideStart - 1 });
813           }
814           vstart = hideEnd + 1;
815         }
816
817         if (vstart < end)
818         {
819           visiblecontigs.add(new int[] { vstart, end - 1 });
820         }
821         int[] vcontigs = new int[visiblecontigs.size() * 2];
822         for (int i = 0, j = visiblecontigs.size(); i < j; i++)
823         {
824           int[] vc = visiblecontigs.get(i);
825           visiblecontigs.set(i, null);
826           vcontigs[i * 2] = vc[0];
827           vcontigs[i * 2 + 1] = vc[1];
828         }
829         visiblecontigs.clear();
830         return vcontigs;
831       }
832       else
833       {
834         return new int[] { start, end - 1 };
835       }
836     }
837     finally
838     {
839       lock.readLock().unlock();
840     }
841   }
842
843   public String[] getVisibleSequenceStrings(int start, int end,
844           SequenceI[] seqs)
845   {
846     try
847     {
848       lock.readLock().lock();
849       int i, iSize = seqs.length;
850       String selections[] = new String[iSize];
851       if (hiddenColumns != null && hiddenColumns.size() > 0)
852       {
853         for (i = 0; i < iSize; i++)
854         {
855           StringBuffer visibleSeq = new StringBuffer();
856           List<int[]> regions = getHiddenRegions();
857
858           int blockStart = start, blockEnd = end;
859           int[] region;
860           int hideStart, hideEnd;
861
862           for (int j = 0; j < regions.size(); j++)
863           {
864             region = regions.get(j);
865             hideStart = region[0];
866             hideEnd = region[1];
867
868             if (hideStart < start)
869             {
870               continue;
871             }
872
873             blockStart = Math.min(blockStart, hideEnd + 1);
874             blockEnd = Math.min(blockEnd, hideStart);
875
876             if (blockStart > blockEnd)
877             {
878               break;
879             }
880
881             visibleSeq.append(seqs[i].getSequence(blockStart, blockEnd));
882
883             blockStart = hideEnd + 1;
884             blockEnd = end;
885           }
886
887           if (end > blockStart)
888           {
889             visibleSeq.append(seqs[i].getSequence(blockStart, end));
890           }
891
892           selections[i] = visibleSeq.toString();
893         }
894       }
895       else
896       {
897         for (i = 0; i < iSize; i++)
898         {
899           selections[i] = seqs[i].getSequenceAsString(start, end);
900         }
901       }
902
903       return selections;
904     }
905     finally
906     {
907       lock.readLock().unlock();
908     }
909   }
910
911   /**
912    * Locate the first and last position visible for this sequence. if seq isn't
913    * visible then return the position of the left and right of the hidden
914    * boundary region, and the corresponding alignment column indices for the
915    * extent of the sequence
916    * 
917    * @param seq
918    * @return int[] { visible start, visible end, first seqpos, last seqpos,
919    *         alignment index for seq start, alignment index for seq end }
920    */
921   public int[] locateVisibleBoundsOfSequence(SequenceI seq)
922   {
923     try
924     {
925       lock.readLock().lock();
926       int fpos = seq.getStart(), lpos = seq.getEnd();
927       int start = 0;
928
929       if (hiddenColumns == null || hiddenColumns.size() == 0)
930       {
931         int ifpos = seq.findIndex(fpos) - 1,
932                 ilpos = seq.findIndex(lpos) - 1;
933         return new int[] { ifpos, ilpos, fpos, lpos, ifpos, ilpos };
934       }
935
936       // Simply walk along the sequence whilst watching for hidden column
937       // boundaries
938       List<int[]> regions = getHiddenRegions();
939       int spos = fpos, lastvispos = -1, rcount = 0,
940               hideStart = seq.getLength(), hideEnd = -1;
941       int visPrev = 0, visNext = 0, firstP = -1, lastP = -1;
942       boolean foundStart = false;
943       for (int p = 0, pLen = seq.getLength(); spos <= seq.getEnd()
944               && p < pLen; p++)
945       {
946         if (!Comparison.isGap(seq.getCharAt(p)))
947         {
948           // keep track of first/last column
949           // containing sequence data regardless of visibility
950           if (firstP == -1)
951           {
952             firstP = p;
953           }
954           lastP = p;
955           // update hidden region start/end
956           while (hideEnd < p && rcount < regions.size())
957           {
958             int[] region = regions.get(rcount++);
959             visPrev = visNext;
960             visNext += region[0] - visPrev;
961             hideStart = region[0];
962             hideEnd = region[1];
963           }
964           if (hideEnd < p)
965           {
966             hideStart = seq.getLength();
967           }
968           // update visible boundary for sequence
969           if (p < hideStart)
970           {
971             if (!foundStart)
972             {
973               fpos = spos;
974               start = p;
975               foundStart = true;
976             }
977             lastvispos = p;
978             lpos = spos;
979           }
980           // look for next sequence position
981           spos++;
982         }
983       }
984       if (foundStart)
985       {
986         return new int[] { findColumnPosition(start),
987             findColumnPosition(lastvispos), fpos, lpos, firstP, lastP };
988       }
989       // otherwise, sequence was completely hidden
990       return new int[] { visPrev, visNext, 0, 0, firstP, lastP };
991     }
992     finally
993     {
994       lock.readLock().unlock();
995     }
996   }
997
998   /**
999    * delete any columns in alignmentAnnotation that are hidden (including
1000    * sequence associated annotation).
1001    * 
1002    * @param alignmentAnnotation
1003    */
1004   public void makeVisibleAnnotation(AlignmentAnnotation alignmentAnnotation)
1005   {
1006     makeVisibleAnnotation(-1, -1, alignmentAnnotation);
1007   }
1008
1009   /**
1010    * delete any columns in alignmentAnnotation that are hidden (including
1011    * sequence associated annotation).
1012    * 
1013    * @param start
1014    *          remove any annotation to the right of this column
1015    * @param end
1016    *          remove any annotation to the left of this column
1017    * @param alignmentAnnotation
1018    *          the annotation to operate on
1019    */
1020   public void makeVisibleAnnotation(int start, int end,
1021           AlignmentAnnotation alignmentAnnotation)
1022   {
1023     try
1024     {
1025       lock.readLock().lock();
1026       if (alignmentAnnotation.annotations == null)
1027       {
1028         return;
1029       }
1030       if (start == end && end == -1)
1031       {
1032         start = 0;
1033         end = alignmentAnnotation.annotations.length;
1034       }
1035       if (hiddenColumns != null && hiddenColumns.size() > 0)
1036       {
1037         // then mangle the alignmentAnnotation annotation array
1038         Vector<Annotation[]> annels = new Vector<>();
1039         Annotation[] els = null;
1040         List<int[]> regions = getHiddenRegions();
1041         int blockStart = start, blockEnd = end;
1042         int[] region;
1043         int hideStart, hideEnd, w = 0;
1044
1045         for (int j = 0; j < regions.size(); j++)
1046         {
1047           region = regions.get(j);
1048           hideStart = region[0];
1049           hideEnd = region[1];
1050
1051           if (hideStart < start)
1052           {
1053             continue;
1054           }
1055
1056           blockStart = Math.min(blockStart, hideEnd + 1);
1057           blockEnd = Math.min(blockEnd, hideStart);
1058
1059           if (blockStart > blockEnd)
1060           {
1061             break;
1062           }
1063
1064           annels.addElement(els = new Annotation[blockEnd - blockStart]);
1065           System.arraycopy(alignmentAnnotation.annotations, blockStart, els,
1066                   0, els.length);
1067           w += els.length;
1068           blockStart = hideEnd + 1;
1069           blockEnd = end;
1070         }
1071
1072         if (end > blockStart)
1073         {
1074           annels.addElement(els = new Annotation[end - blockStart + 1]);
1075           if ((els.length
1076                   + blockStart) <= alignmentAnnotation.annotations.length)
1077           {
1078             // copy just the visible segment of the annotation row
1079             System.arraycopy(alignmentAnnotation.annotations, blockStart,
1080                     els, 0, els.length);
1081           }
1082           else
1083           {
1084             // copy to the end of the annotation row
1085             System.arraycopy(alignmentAnnotation.annotations, blockStart,
1086                     els, 0,
1087                     (alignmentAnnotation.annotations.length - blockStart));
1088           }
1089           w += els.length;
1090         }
1091         if (w == 0)
1092         {
1093           return;
1094         }
1095
1096         alignmentAnnotation.annotations = new Annotation[w];
1097         w = 0;
1098
1099         for (Annotation[] chnk : annels)
1100         {
1101           System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
1102                   chnk.length);
1103           w += chnk.length;
1104         }
1105       }
1106       else
1107       {
1108         alignmentAnnotation.restrict(start, end);
1109       }
1110     }
1111     finally
1112     {
1113       lock.readLock().unlock();
1114     }
1115   }
1116
1117   /**
1118    * 
1119    * @return true if there are columns hidden
1120    */
1121   public boolean hasHiddenColumns()
1122   {
1123     try
1124     {
1125       lock.readLock().lock();
1126       return hiddenColumns != null && hiddenColumns.size() > 0;
1127     } finally
1128     {
1129       lock.readLock().unlock();
1130     }
1131   }
1132
1133   /**
1134    * 
1135    * @return true if there are more than one set of columns hidden
1136    */
1137   public boolean hasManyHiddenColumns()
1138   {
1139     try
1140     {
1141       lock.readLock().lock();
1142       return hiddenColumns != null && hiddenColumns.size() > 1;
1143     } finally
1144     {
1145       lock.readLock().unlock();
1146     }
1147   }
1148
1149   /**
1150    * mark the columns corresponding to gap characters as hidden in the column
1151    * selection
1152    * 
1153    * @param sr
1154    */
1155   public void hideInsertionsFor(SequenceI sr)
1156   {
1157     try
1158     {
1159       lock.writeLock().lock();
1160       List<int[]> inserts = sr.getInsertions();
1161       for (int[] r : inserts)
1162       {
1163         hideColumns(r[0], r[1], true);
1164       }
1165     } finally
1166     {
1167       lock.writeLock().unlock();
1168     }
1169   }
1170
1171   /**
1172    * Unhides, and adds to the selection list, all hidden columns
1173    */
1174   public void revealAllHiddenColumns(ColumnSelection sel)
1175   {
1176     try
1177     {
1178       lock.writeLock().lock();
1179       if (hiddenColumns != null)
1180       {
1181         for (int i = 0; i < hiddenColumns.size(); i++)
1182         {
1183           int[] region = hiddenColumns.elementAt(i);
1184           for (int j = region[0]; j < region[1] + 1; j++)
1185           {
1186             sel.addElement(j);
1187           }
1188         }
1189       }
1190
1191       hiddenColumns = null;
1192     }
1193     finally
1194     {
1195       lock.writeLock().unlock();
1196     }
1197   }
1198
1199   /**
1200    * Reveals, and marks as selected, the hidden column range with the given
1201    * start column
1202    * 
1203    * @param start
1204    */
1205   public void revealHiddenColumns(int start, ColumnSelection sel)
1206   {
1207     try
1208     {
1209       lock.writeLock().lock();
1210       for (int i = 0; i < hiddenColumns.size(); i++)
1211       {
1212         int[] region = hiddenColumns.elementAt(i);
1213         if (start == region[0])
1214         {
1215           for (int j = region[0]; j < region[1] + 1; j++)
1216           {
1217             sel.addElement(j);
1218           }
1219
1220           hiddenColumns.removeElement(region);
1221           break;
1222         }
1223       }
1224       if (hiddenColumns.size() == 0)
1225       {
1226         hiddenColumns = null;
1227       }
1228     }
1229     finally
1230     {
1231       lock.writeLock().unlock();
1232     }
1233   }
1234
1235   /**
1236    * removes intersection of position,length ranges in deletions from the
1237    * start,end regions marked in intervals.
1238    * 
1239    * @param shifts
1240    * @param intervals
1241    * @return
1242    */
1243   private boolean pruneIntervalVector(final List<int[]> shifts,
1244           Vector<int[]> intervals)
1245   {
1246     boolean pruned = false;
1247     int i = 0, j = intervals.size() - 1, s = 0, t = shifts.size() - 1;
1248     int hr[] = intervals.elementAt(i);
1249     int sr[] = shifts.get(s);
1250     while (i <= j && s <= t)
1251     {
1252       boolean trailinghn = hr[1] >= sr[0];
1253       if (!trailinghn)
1254       {
1255         if (i < j)
1256         {
1257           hr = intervals.elementAt(++i);
1258         }
1259         else
1260         {
1261           i++;
1262         }
1263         continue;
1264       }
1265       int endshift = sr[0] + sr[1]; // deletion ranges - -ve means an insert
1266       if (endshift < hr[0] || endshift < sr[0])
1267       { // leadinghc disjoint or not a deletion
1268         if (s < t)
1269         {
1270           sr = shifts.get(++s);
1271         }
1272         else
1273         {
1274           s++;
1275         }
1276         continue;
1277       }
1278       boolean leadinghn = hr[0] >= sr[0];
1279       boolean leadinghc = hr[0] < endshift;
1280       boolean trailinghc = hr[1] < endshift;
1281       if (leadinghn)
1282       {
1283         if (trailinghc)
1284         { // deleted hidden region.
1285           intervals.removeElementAt(i);
1286           pruned = true;
1287           j--;
1288           if (i <= j)
1289           {
1290             hr = intervals.elementAt(i);
1291           }
1292           continue;
1293         }
1294         if (leadinghc)
1295         {
1296           hr[0] = endshift; // clip c terminal region
1297           leadinghn = !leadinghn;
1298           pruned = true;
1299         }
1300       }
1301       if (!leadinghn)
1302       {
1303         if (trailinghc)
1304         {
1305           if (trailinghn)
1306           {
1307             hr[1] = sr[0] - 1;
1308             pruned = true;
1309           }
1310         }
1311         else
1312         {
1313           // sr contained in hr
1314           if (s < t)
1315           {
1316             sr = shifts.get(++s);
1317           }
1318           else
1319           {
1320             s++;
1321           }
1322           continue;
1323         }
1324       }
1325     }
1326     return pruned; // true if any interval was removed or modified by
1327     // operations.
1328   }
1329
1330   /**
1331    * remove any hiddenColumns or selected columns and shift remaining based on a
1332    * series of position, range deletions.
1333    * 
1334    * @param deletions
1335    */
1336   public void pruneDeletions(List<int[]> shifts)
1337   {
1338     try
1339     {
1340       lock.writeLock().lock();
1341       // delete any intervals intersecting.
1342       if (hiddenColumns != null)
1343       {
1344         pruneIntervalVector(shifts, hiddenColumns);
1345         if (hiddenColumns != null && hiddenColumns.size() == 0)
1346         {
1347           hiddenColumns = null;
1348         }
1349       }
1350     }
1351     finally
1352     {
1353       lock.writeLock().unlock();
1354     }
1355   }
1356
1357   /**
1358    * Add gaps into the sequences aligned to profileseq under the given
1359    * AlignmentView
1360    * 
1361    * @param profileseq
1362    * @param al
1363    *          - alignment to have gaps inserted into it
1364    * @param input
1365    *          - alignment view where sequence corresponding to profileseq is
1366    *          first entry
1367    * @return new HiddenColumns for new alignment view, with insertions into
1368    *         profileseq marked as hidden.
1369    */
1370   public static HiddenColumns propagateInsertions(SequenceI profileseq,
1371           AlignmentI al, AlignmentView input)
1372   {
1373     int profsqpos = 0;
1374
1375     char gc = al.getGapCharacter();
1376     Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
1377     HiddenColumns nview = (HiddenColumns) alandhidden[1];
1378     SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
1379     nview.propagateInsertions(profileseq, al, origseq);
1380     return nview;
1381   }
1382
1383   /**
1384    * 
1385    * @param profileseq
1386    *          - sequence in al which corresponds to origseq
1387    * @param al
1388    *          - alignment which is to have gaps inserted into it
1389    * @param origseq
1390    *          - sequence corresponding to profileseq which defines gap map for
1391    *          modifying al
1392    */
1393   private void propagateInsertions(SequenceI profileseq, AlignmentI al,
1394           SequenceI origseq)
1395   {
1396     char gc = al.getGapCharacter();
1397     // recover mapping between sequence's non-gap positions and positions
1398     // mapping to view.
1399     pruneDeletions(ShiftList.parseMap(origseq.gapMap()));
1400     int[] viscontigs = al.getHiddenColumns().getVisibleContigs(0,
1401             profileseq.getLength());
1402     int spos = 0;
1403     int offset = 0;
1404
1405     // add profile to visible contigs
1406     for (int v = 0; v < viscontigs.length; v += 2)
1407     {
1408       if (viscontigs[v] > spos)
1409       {
1410         StringBuffer sb = new StringBuffer();
1411         for (int s = 0, ns = viscontigs[v] - spos; s < ns; s++)
1412         {
1413           sb.append(gc);
1414         }
1415         for (int s = 0, ns = al.getHeight(); s < ns; s++)
1416         {
1417           SequenceI sqobj = al.getSequenceAt(s);
1418           if (sqobj != profileseq)
1419           {
1420             String sq = al.getSequenceAt(s).getSequenceAsString();
1421             if (sq.length() <= spos + offset)
1422             {
1423               // pad sequence
1424               int diff = spos + offset - sq.length() - 1;
1425               if (diff > 0)
1426               {
1427                 // pad gaps
1428                 sq = sq + sb;
1429                 while ((diff = spos + offset - sq.length() - 1) > 0)
1430                 {
1431                   // sq = sq
1432                   // + ((diff >= sb.length()) ? sb.toString() : sb
1433                   // .substring(0, diff));
1434                   if (diff >= sb.length())
1435                   {
1436                     sq += sb.toString();
1437                   }
1438                   else
1439                   {
1440                     char[] buf = new char[diff];
1441                     sb.getChars(0, diff, buf, 0);
1442                     sq += buf.toString();
1443                   }
1444                 }
1445               }
1446               sq += sb.toString();
1447             }
1448             else
1449             {
1450               al.getSequenceAt(s).setSequence(
1451                       sq.substring(0, spos + offset) + sb.toString()
1452                               + sq.substring(spos + offset));
1453             }
1454           }
1455         }
1456         // offset+=sb.length();
1457       }
1458       spos = viscontigs[v + 1] + 1;
1459     }
1460     if ((offset + spos) < profileseq.getLength())
1461     {
1462       // pad the final region with gaps.
1463       StringBuffer sb = new StringBuffer();
1464       for (int s = 0, ns = profileseq.getLength() - spos - offset; s < ns; s++)
1465       {
1466         sb.append(gc);
1467       }
1468       for (int s = 0, ns = al.getHeight(); s < ns; s++)
1469       {
1470         SequenceI sqobj = al.getSequenceAt(s);
1471         if (sqobj == profileseq)
1472         {
1473           continue;
1474         }
1475         String sq = sqobj.getSequenceAsString();
1476         // pad sequence
1477         int diff = origseq.getLength() - sq.length();
1478         while (diff > 0)
1479         {
1480           // sq = sq
1481           // + ((diff >= sb.length()) ? sb.toString() : sb
1482           // .substring(0, diff));
1483           if (diff >= sb.length())
1484           {
1485             sq += sb.toString();
1486           }
1487           else
1488           {
1489             char[] buf = new char[diff];
1490             sb.getChars(0, diff, buf, 0);
1491             sq += buf.toString();
1492           }
1493           diff = origseq.getLength() - sq.length();
1494         }
1495       }
1496     }
1497   }
1498
1499   /**
1500    * remove any hiddenColumns or selected columns and shift remaining based on a
1501    * series of position, range deletions.
1502    * 
1503    * @param deletions
1504    */
1505   private void pruneDeletions(ShiftList deletions)
1506   {
1507     if (deletions != null)
1508     {
1509       final List<int[]> shifts = deletions.getShifts();
1510       if (shifts != null && shifts.size() > 0)
1511       {
1512         pruneDeletions(shifts);
1513
1514         // and shift the rest.
1515         this.compensateForEdits(deletions);
1516       }
1517     }
1518   }
1519
1520   /**
1521    * Adjust hidden column boundaries based on a series of column additions or
1522    * deletions in visible regions.
1523    * 
1524    * @param shiftrecord
1525    * @return
1526    */
1527   private ShiftList compensateForEdits(ShiftList shiftrecord)
1528   {
1529     if (shiftrecord != null)
1530     {
1531       final List<int[]> shifts = shiftrecord.getShifts();
1532       if (shifts != null && shifts.size() > 0)
1533       {
1534         int shifted = 0;
1535         for (int i = 0, j = shifts.size(); i < j; i++)
1536         {
1537           int[] sh = shifts.get(i);
1538           compensateForDelEdits(shifted + sh[0], sh[1]);
1539           shifted -= sh[1];
1540         }
1541       }
1542       return shiftrecord.getInverse();
1543     }
1544     return null;
1545   }
1546
1547   /**
1548    * Returns a hashCode built from hidden column ranges
1549    */
1550   @Override
1551   public int hashCode()
1552   {
1553     try
1554     {
1555       lock.readLock().lock();
1556       int hashCode = 1;
1557       if (hiddenColumns != null)
1558       {
1559         for (int[] hidden : hiddenColumns)
1560         {
1561           hashCode = 31 * hashCode + hidden[0];
1562           hashCode = 31 * hashCode + hidden[1];
1563         }
1564       }
1565       return hashCode;
1566     }
1567     finally
1568     {
1569       lock.readLock().unlock();
1570     }
1571   }
1572
1573   /**
1574    * Hide columns corresponding to the marked bits
1575    * 
1576    * @param inserts
1577    *          - columns map to bits starting from zero
1578    */
1579   public void hideMarkedBits(BitSet inserts)
1580   {
1581     try
1582     {
1583       lock.writeLock().lock();
1584       for (int firstSet = inserts
1585               .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
1586                       .nextSetBit(lastSet))
1587       {
1588         lastSet = inserts.nextClearBit(firstSet);
1589         hideColumns(firstSet, lastSet - 1, true);
1590       }
1591     } finally
1592     {
1593       lock.writeLock().unlock();
1594     }
1595   }
1596
1597   /**
1598    * 
1599    * @param inserts
1600    *          BitSet where hidden columns will be marked
1601    */
1602   public void markHiddenRegions(BitSet inserts)
1603   {
1604     try
1605     {
1606       lock.readLock().lock();
1607       if (hiddenColumns == null)
1608       {
1609         return;
1610       }
1611       for (int[] range : hiddenColumns)
1612       {
1613         inserts.set(range[0], range[1] + 1);
1614       }
1615     }
1616     finally
1617     {
1618       lock.readLock().unlock();
1619     }
1620   }
1621
1622   @Override
1623   public Iterator<int[]> iterator()
1624   {
1625     if (hiddenColumns == null)
1626     {
1627       return Collections.<int[]> emptyList().iterator();
1628     }
1629     return hiddenColumns.iterator();
1630   }
1631
1632 }