140a3661033f9a46d496415654aa98bf3d3cb549
[jalview.git] / src / jalview / datamodel / ColumnSelection.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.Collections;
26 import java.util.List;
27 import java.util.regex.PatternSyntaxException;
28
29 import jalview.viewmodel.annotationfilter.AnnotationFilterParameter;
30 import jalview.viewmodel.annotationfilter.AnnotationFilterParameter.SearchableAnnotationField;
31
32 /**
33  * Data class holding the selected columns and hidden column ranges for a view.
34  * Ranges are base 1.
35  */
36 public class ColumnSelection
37 {
38   /**
39    * A class to hold an efficient representation of selected columns
40    */
41   private class IntList
42   {
43     /*
44      * list of selected columns (ordered by selection order, not column order)
45      */
46     private List<Integer> order;
47
48     /*
49      * an unmodifiable view of the selected columns list
50      */
51     private List<Integer> _uorder;
52
53     /**
54      * bitfield for column selection - allows quick lookup
55      */
56     private BitSet selected;
57
58     /**
59      * Constructor
60      */
61     IntList()
62     {
63       order = new ArrayList<>();
64       _uorder = Collections.unmodifiableList(order);
65       selected = new BitSet();
66     }
67
68     /**
69      * Copy constructor
70      * 
71      * @param other
72      */
73     IntList(IntList other)
74     {
75       this();
76       if (other != null)
77       {
78         int j = other.size();
79         for (int i = 0; i < j; i++)
80         {
81           add(other.elementAt(i));
82         }
83       }
84     }
85
86     /**
87      * adds a new column i to the selection - only if i is not already selected
88      * 
89      * @param i
90      */
91     void add(int i)
92     {
93       if (!selected.get(i))
94       {
95         order.add(Integer.valueOf(i));
96         selected.set(i);
97       }
98     }
99
100     void clear()
101     {
102       order.clear();
103       selected.clear();
104     }
105
106     void remove(int col)
107     {
108
109       Integer colInt = Integer.valueOf(col);
110
111       if (selected.get(col))
112       {
113         // if this ever changes to List.remove(), ensure Integer not int
114         // argument
115         // as List.remove(int i) removes the i'th item which is wrong
116         order.remove(colInt);
117         selected.clear(col);
118       }
119     }
120
121     boolean contains(Integer colInt)
122     {
123       return selected.get(colInt);
124     }
125
126     boolean isEmpty()
127     {
128       return order.isEmpty();
129     }
130
131     /**
132      * Returns a read-only view of the selected columns list
133      * 
134      * @return
135      */
136     List<Integer> getList()
137     {
138       return _uorder;
139     }
140
141     int size()
142     {
143       return order.size();
144     }
145
146     /**
147      * gets the column that was selected first, second or i'th
148      * 
149      * @param i
150      * @return
151      */
152     int elementAt(int i)
153     {
154       return order.get(i);
155     }
156
157     protected boolean pruneColumnList(final List<int[]> shifts)
158     {
159       int s = 0, t = shifts.size();
160       int[] sr = shifts.get(s++);
161       boolean pruned = false;
162       int i = 0, j = order.size();
163       while (i < j && s <= t)
164       {
165         int c = order.get(i++).intValue();
166         if (sr[0] <= c)
167         {
168           if (sr[1] + sr[0] >= c)
169           { // sr[1] -ve means inseriton.
170             order.remove(--i);
171             selected.clear(c);
172             j--;
173           }
174           else
175           {
176             if (s < t)
177             {
178               sr = shifts.get(s);
179             }
180             s++;
181           }
182         }
183       }
184       return pruned;
185     }
186
187     /**
188      * shift every selected column at or above start by change
189      * 
190      * @param start
191      *          - leftmost column to be shifted
192      * @param change
193      *          - delta for shift
194      */
195     void compensateForEdits(int start, int change)
196     {
197       BitSet mask = new BitSet();
198       for (int i = 0; i < order.size(); i++)
199       {
200         int temp = order.get(i);
201
202         if (temp >= start)
203         {
204           // clear shifted bits and update List of selected columns
205           selected.clear(temp);
206           mask.set(temp - change);
207           order.set(i, Integer.valueOf(temp - change));
208         }
209       }
210       // lastly update the bitfield all at once
211       selected.or(mask);
212     }
213
214     boolean isSelected(int column)
215     {
216       return selected.get(column);
217     }
218
219     int getMaxColumn()
220     {
221       return selected.length() - 1;
222     }
223
224     int getMinColumn()
225     {
226       return selected.get(0) ? 0 : selected.nextSetBit(0);
227     }
228
229     /**
230      * @return a series of selection intervals along the range
231      */
232     List<int[]> getRanges()
233     {
234       List<int[]> rlist = new ArrayList<>();
235       if (selected.isEmpty())
236       {
237         return rlist;
238       }
239       int next = selected.nextSetBit(0), clear = -1;
240       while (next != -1)
241       {
242         clear = selected.nextClearBit(next);
243         rlist.add(new int[] { next, clear - 1 });
244         next = selected.nextSetBit(clear);
245       }
246       return rlist;
247     }
248
249     @Override
250     public int hashCode()
251     {
252       // TODO Auto-generated method stub
253       return selected.hashCode();
254     }
255
256     @Override
257     public boolean equals(Object obj)
258     {
259       if (obj instanceof IntList)
260       {
261         return ((IntList) obj).selected.equals(selected);
262       }
263       return false;
264     }
265   }
266
267   private IntList selection = new IntList();
268
269   /**
270    * Add a column to the selection
271    * 
272    * @param col
273    *          index of column
274    */
275   public void addElement(int col)
276   {
277     selection.add(col);
278   }
279
280   /**
281    * clears column selection
282    */
283   public void clear()
284   {
285     selection.clear();
286   }
287
288   /**
289    * Removes value 'col' from the selection (not the col'th item)
290    * 
291    * @param col
292    *          index of column to be removed
293    */
294   public void removeElement(int col)
295   {
296     selection.remove(col);
297   }
298
299   /**
300    * removes a range of columns from the selection
301    * 
302    * @param start
303    *          int - first column in range to be removed
304    * @param end
305    *          int - last col
306    */
307   public void removeElements(int start, int end)
308   {
309     Integer colInt;
310     for (int i = start; i < end; i++)
311     {
312       colInt = Integer.valueOf(i);
313       if (selection.contains(colInt))
314       {
315         selection.remove(colInt);
316       }
317     }
318   }
319
320   /**
321    * Returns a read-only view of the (possibly empty) list of selected columns
322    * <p>
323    * The list contains no duplicates but is not necessarily ordered. It also may
324    * include columns hidden from the current view. To modify (for example sort)
325    * the list, you should first make a copy.
326    * <p>
327    * The list is not thread-safe: iterating over it could result in
328    * ConcurrentModificationException if it is modified by another thread.
329    */
330   public List<Integer> getSelected()
331   {
332     return selection.getList();
333   }
334
335   /**
336    * @return list of int arrays containing start and end column position for
337    *         runs of selected columns ordered from right to left.
338    */
339   public List<int[]> getSelectedRanges()
340   {
341     return selection.getRanges();
342   }
343
344   /**
345    * 
346    * @param col
347    *          index to search for in column selection
348    * 
349    * @return true if col is selected
350    */
351   public boolean contains(int col)
352   {
353     return (col > -1) ? selection.isSelected(col) : false;
354   }
355
356   /**
357    * 
358    */
359   public boolean intersects(int from, int to)
360   {
361     // TODO: do this in a more efficient bitwise way
362     for (int f = from; f <= to; f++)
363     {
364       if (selection.isSelected(f))
365       {
366         return true;
367       }
368     }
369     return false;
370   }
371
372   /**
373    * Answers true if no columns are selected, else false
374    */
375   public boolean isEmpty()
376   {
377     return selection == null || selection.isEmpty();
378   }
379
380   /**
381    * rightmost selected column
382    * 
383    * @return rightmost column in alignment that is selected
384    */
385   public int getMax()
386   {
387     if (selection.isEmpty())
388     {
389       return -1;
390     }
391     return selection.getMaxColumn();
392   }
393
394   /**
395    * Leftmost column in selection
396    * 
397    * @return column index of leftmost column in selection
398    */
399   public int getMin()
400   {
401     if (selection.isEmpty())
402     {
403       return 1000000000;
404     }
405     return selection.getMinColumn();
406   }
407
408   public void hideSelectedColumns(AlignmentI al)
409   {
410     synchronized (selection)
411     {
412       for (int[] selregions : selection.getRanges())
413       {
414         al.getHiddenColumns().hideColumns(selregions[0], selregions[1]);
415       }
416       selection.clear();
417     }
418
419   }
420
421   /**
422    * Hides the specified column and any adjacent selected columns
423    * 
424    * @param res
425    *          int
426    */
427   public void hideSelectedColumns(int col, HiddenColumns hidden)
428   {
429     /*
430      * deselect column (whether selected or not!)
431      */
432     removeElement(col);
433
434     /*
435      * find adjacent selected columns
436      */
437     int min = col - 1, max = col + 1;
438     while (contains(min))
439     {
440       removeElement(min);
441       min--;
442     }
443
444     while (contains(max))
445     {
446       removeElement(max);
447       max++;
448     }
449
450     /*
451      * min, max are now the closest unselected columns
452      */
453     min++;
454     max--;
455     if (min > max)
456     {
457       min = max;
458     }
459
460     hidden.hideColumns(min, max);
461   }
462
463   /**
464    * Copy constructor
465    * 
466    * @param copy
467    */
468   public ColumnSelection(ColumnSelection copy)
469   {
470     if (copy != null)
471     {
472       selection = new IntList(copy.selection);
473     }
474   }
475
476   /**
477    * ColumnSelection
478    */
479   public ColumnSelection()
480   {
481   }
482
483   /**
484    * Invert the column selection from first to end-1. leaves hiddenColumns
485    * untouched (and unselected)
486    * 
487    * @param first
488    * @param end
489    */
490   public void invertColumnSelection(int first, int width, AlignmentI al)
491   {
492     boolean hasHidden = al.getHiddenColumns().hasHiddenColumns();
493     for (int i = first; i < width; i++)
494     {
495       if (contains(i))
496       {
497         removeElement(i);
498       }
499       else
500       {
501         if (!hasHidden || al.getHiddenColumns().isVisible(i))
502         {
503           addElement(i);
504         }
505       }
506     }
507   }
508
509   /**
510    * set the selected columns to the given column selection, excluding any
511    * columns that are hidden.
512    * 
513    * @param colsel
514    */
515   public void setElementsFrom(ColumnSelection colsel,
516           HiddenColumns hiddenColumns)
517   {
518     selection = new IntList();
519     if (colsel.selection != null && colsel.selection.size() > 0)
520     {
521       if (hiddenColumns.hasHiddenColumns())
522       {
523         // only select visible columns in this columns selection
524         for (Integer col : colsel.getSelected())
525         {
526           if (hiddenColumns != null
527                   && hiddenColumns.isVisible(col.intValue()))
528           {
529             selection.add(col);
530           }
531         }
532       }
533       else
534       {
535         // add everything regardless
536         for (Integer col : colsel.getSelected())
537         {
538           addElement(col);
539         }
540       }
541     }
542   }
543
544   /**
545    * 
546    * @return true if there are columns marked
547    */
548   public boolean hasSelectedColumns()
549   {
550     return (selection != null && selection.size() > 0);
551   }
552
553   /**
554    * Selects columns where the given annotation matches the provided filter
555    * condition(s). Any existing column selections are first cleared. Answers the
556    * number of columns added.
557    * 
558    * @param annotations
559    * @param filterParams
560    * @return
561    */
562   public int filterAnnotations(Annotation[] annotations,
563           AnnotationFilterParameter filterParams)
564   {
565     // JBPNote - this method needs to be refactored to become independent of
566     // viewmodel package
567     this.clear();
568     int addedCount = 0;
569     int column = 0;
570     do
571     {
572       Annotation ann = annotations[column];
573       if (ann != null)
574       {
575         boolean matched = false;
576
577         /*
578          * filter may have multiple conditions - 
579          * these are or'd until a match is found
580          */
581         if (filterParams
582                 .getThresholdType() == AnnotationFilterParameter.ThresholdType.ABOVE_THRESHOLD
583                 && ann.value > filterParams.getThresholdValue())
584         {
585           matched = true;
586         }
587
588         if (!matched && filterParams
589                 .getThresholdType() == AnnotationFilterParameter.ThresholdType.BELOW_THRESHOLD
590                 && ann.value < filterParams.getThresholdValue())
591         {
592           matched = true;
593         }
594
595         if (!matched && filterParams.isFilterAlphaHelix()
596                 && ann.secondaryStructure == 'H')
597         {
598           matched = true;
599         }
600
601         if (!matched && filterParams.isFilterBetaSheet()
602                 && ann.secondaryStructure == 'E')
603         {
604           matched = true;
605         }
606
607         if (!matched && filterParams.isFilterTurn()
608                 && ann.secondaryStructure == 'S')
609         {
610           matched = true;
611         }
612
613         String regexSearchString = filterParams.getRegexString();
614         if (!matched && regexSearchString != null)
615         {
616           List<SearchableAnnotationField> fields = filterParams
617                   .getRegexSearchFields();
618           for (SearchableAnnotationField field : fields)
619           {
620             String compareTo = field == SearchableAnnotationField.DISPLAY_STRING
621                     ? ann.displayCharacter // match 'Label'
622                     : ann.description; // and/or 'Description'
623             if (compareTo != null)
624             {
625               try
626               {
627                 if (compareTo.matches(regexSearchString))
628                 {
629                   matched = true;
630                 }
631               } catch (PatternSyntaxException pse)
632               {
633                 if (compareTo.equals(regexSearchString))
634                 {
635                   matched = true;
636                 }
637               }
638               if (matched)
639               {
640                 break;
641               }
642             }
643           }
644         }
645
646         if (matched)
647         {
648           this.addElement(column);
649           addedCount++;
650         }
651       }
652       column++;
653     } while (column < annotations.length);
654
655     return addedCount;
656   }
657
658   /**
659    * Returns a hashCode built from selected columns ranges
660    */
661   @Override
662   public int hashCode()
663   {
664     return selection.hashCode();
665   }
666
667   /**
668    * Answers true if comparing to a ColumnSelection with the same selected
669    * columns and hidden columns, else false
670    */
671   @Override
672   public boolean equals(Object obj)
673   {
674     if (!(obj instanceof ColumnSelection))
675     {
676       return false;
677     }
678     ColumnSelection that = (ColumnSelection) obj;
679
680     /*
681      * check columns selected are either both null, or match
682      */
683     if (this.selection == null)
684     {
685       if (that.selection != null)
686       {
687         return false;
688       }
689     }
690     if (!this.selection.equals(that.selection))
691     {
692       return false;
693     }
694
695     return true;
696   }
697
698   /**
699    * Updates the column selection depending on the parameters, and returns true
700    * if any change was made to the selection
701    * 
702    * @param markedColumns
703    *          a set identifying marked columns (base 0)
704    * @param startCol
705    *          the first column of the range to operate over (base 0)
706    * @param endCol
707    *          the last column of the range to operate over (base 0)
708    * @param invert
709    *          if true, deselect marked columns and select unmarked
710    * @param extendCurrent
711    *          if true, extend rather than replacing the current column selection
712    * @param toggle
713    *          if true, toggle the selection state of marked columns
714    * 
715    * @return
716    */
717   public boolean markColumns(BitSet markedColumns, int startCol, int endCol,
718           boolean invert, boolean extendCurrent, boolean toggle)
719   {
720     boolean changed = false;
721     if (!extendCurrent && !toggle)
722     {
723       changed = !this.isEmpty();
724       clear();
725     }
726     if (invert)
727     {
728       // invert only in the currently selected sequence region
729       int i = markedColumns.nextClearBit(startCol);
730       int ibs = markedColumns.nextSetBit(startCol);
731       while (i >= startCol && i <= endCol)
732       {
733         if (ibs < 0 || i < ibs)
734         {
735           changed = true;
736           if (toggle && contains(i))
737           {
738             removeElement(i++);
739           }
740           else
741           {
742             addElement(i++);
743           }
744         }
745         else
746         {
747           i = markedColumns.nextClearBit(ibs);
748           ibs = markedColumns.nextSetBit(i);
749         }
750       }
751     }
752     else
753     {
754       int i = markedColumns.nextSetBit(startCol);
755       while (i >= startCol && i <= endCol)
756       {
757         changed = true;
758         if (toggle && contains(i))
759         {
760           removeElement(i);
761         }
762         else
763         {
764           addElement(i);
765         }
766         i = markedColumns.nextSetBit(i + 1);
767       }
768     }
769     return changed;
770   }
771
772   /**
773    * Adjusts column selections, and the given selection group, to match the
774    * range of a stretch (e.g. mouse drag) operation
775    * <p>
776    * Method refactored from ScalePanel.mouseDragged
777    * 
778    * @param res
779    *          current column position, adjusted for hidden columns
780    * @param sg
781    *          current selection group
782    * @param min
783    *          start position of the stretch group
784    * @param max
785    *          end position of the stretch group
786    */
787   public void stretchGroup(int res, SequenceGroup sg, int min, int max)
788   {
789     if (!contains(res))
790     {
791       addElement(res);
792     }
793
794     if (res > sg.getStartRes())
795     {
796       // expand selection group to the right
797       sg.setEndRes(res);
798     }
799     if (res < sg.getStartRes())
800     {
801       // expand selection group to the left
802       sg.setStartRes(res);
803     }
804
805     /*
806      * expand or shrink column selection to match the
807      * range of the drag operation
808      */
809     for (int col = min; col <= max; col++)
810     {
811       if (col < sg.getStartRes() || col > sg.getEndRes())
812       {
813         // shrinking drag - remove from selection
814         removeElement(col);
815       }
816       else
817       {
818         // expanding drag - add to selection
819         addElement(col);
820       }
821     }
822   }
823 }