Merge branch 'develop' into features/JAL-4134_use_annotation_row_for_colours_and_groups
[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    * add a series of start,end (inclusive) ranges to the column selection
282    * 
283    * @param rng
284    *          [start_0, end_0, start_1, end_1, ... ]
285    * @param baseOne
286    *          - when true, ranges are base 1 and will be mapped to base 0
287    */
288   public void addRangeOfElements(int[] rng, boolean baseOne)
289   {
290     int base = baseOne ? -1 : 0;
291     for (int c = 0; c < rng.length; c += 2)
292     {
293       for (int p = rng[c]; p <= rng[c + 1]; p++)
294       {
295         selection.add(base + p);
296       }
297     }
298
299   }
300
301   /**
302    * clears column selection
303    */
304   public void clear()
305   {
306     selection.clear();
307   }
308
309   /**
310    * Removes value 'col' from the selection (not the col'th item)
311    * 
312    * @param col
313    *          index of column to be removed
314    */
315   public void removeElement(int col)
316   {
317     selection.remove(col);
318   }
319
320   /**
321    * removes a range of columns from the selection
322    * 
323    * @param start
324    *          int - first column in range to be removed
325    * @param end
326    *          int - last col
327    */
328   public void removeElements(int start, int end)
329   {
330     Integer colInt;
331     for (int i = start; i < end; i++)
332     {
333       colInt = Integer.valueOf(i);
334       if (selection.contains(colInt))
335       {
336         selection.remove(colInt);
337       }
338     }
339   }
340
341   /**
342    * Returns a read-only view of the (possibly empty) list of selected columns
343    * <p>
344    * The list contains no duplicates but is not necessarily ordered. It also may
345    * include columns hidden from the current view. To modify (for example sort)
346    * the list, you should first make a copy.
347    * <p>
348    * The list is not thread-safe: iterating over it could result in
349    * ConcurrentModificationException if it is modified by another thread.
350    */
351   public List<Integer> getSelected()
352   {
353     return selection.getList();
354   }
355
356   /**
357    * @return list of int arrays containing start and end column position for
358    *         runs of selected columns ordered from right to left.
359    */
360   public List<int[]> getSelectedRanges()
361   {
362     return selection.getRanges();
363   }
364
365   /**
366    * 
367    * @param col
368    *          index to search for in column selection
369    * 
370    * @return true if col is selected
371    */
372   public boolean contains(int col)
373   {
374     return (col > -1) ? selection.isSelected(col) : false;
375   }
376
377   /**
378    * 
379    */
380   public boolean intersects(int from, int to)
381   {
382     // TODO: do this in a more efficient bitwise way
383     for (int f = from; f <= to; f++)
384     {
385       if (selection.isSelected(f))
386       {
387         return true;
388       }
389     }
390     return false;
391   }
392
393   /**
394    * Answers true if no columns are selected, else false
395    */
396   public boolean isEmpty()
397   {
398     return selection == null || selection.isEmpty();
399   }
400
401   /**
402    * rightmost selected column
403    * 
404    * @return rightmost column in alignment that is selected
405    */
406   public int getMax()
407   {
408     if (selection.isEmpty())
409     {
410       return -1;
411     }
412     return selection.getMaxColumn();
413   }
414
415   /**
416    * Leftmost column in selection
417    * 
418    * @return column index of leftmost column in selection
419    */
420   public int getMin()
421   {
422     if (selection.isEmpty())
423     {
424       return 1000000000;
425     }
426     return selection.getMinColumn();
427   }
428
429   public void hideSelectedColumns(AlignmentI al)
430   {
431     synchronized (selection)
432     {
433       for (int[] selregions : selection.getRanges())
434       {
435         al.getHiddenColumns().hideColumns(selregions[0], selregions[1]);
436       }
437       selection.clear();
438     }
439
440   }
441
442   /**
443    * Hides the specified column and any adjacent selected columns
444    * 
445    * @param res
446    *          int
447    */
448   public void hideSelectedColumns(int col, HiddenColumns hidden)
449   {
450     /*
451      * deselect column (whether selected or not!)
452      */
453     removeElement(col);
454
455     /*
456      * find adjacent selected columns
457      */
458     int min = col - 1, max = col + 1;
459     while (contains(min))
460     {
461       removeElement(min);
462       min--;
463     }
464
465     while (contains(max))
466     {
467       removeElement(max);
468       max++;
469     }
470
471     /*
472      * min, max are now the closest unselected columns
473      */
474     min++;
475     max--;
476     if (min > max)
477     {
478       min = max;
479     }
480
481     hidden.hideColumns(min, max);
482   }
483
484   /**
485    * Copy constructor
486    * 
487    * @param copy
488    */
489   public ColumnSelection(ColumnSelection copy)
490   {
491     if (copy != null)
492     {
493       selection = new IntList(copy.selection);
494     }
495   }
496
497   /**
498    * ColumnSelection
499    */
500   public ColumnSelection()
501   {
502   }
503
504   /**
505    * Invert the column selection from first to end-1. leaves hiddenColumns
506    * untouched (and unselected)
507    * 
508    * @param first
509    * @param end
510    */
511   public void invertColumnSelection(int first, int width, AlignmentI al)
512   {
513     boolean hasHidden = al.getHiddenColumns().hasHiddenColumns();
514     for (int i = first; i < width; i++)
515     {
516       if (contains(i))
517       {
518         removeElement(i);
519       }
520       else
521       {
522         if (!hasHidden || al.getHiddenColumns().isVisible(i))
523         {
524           addElement(i);
525         }
526       }
527     }
528   }
529
530   /**
531    * set the selected columns to the given column selection, excluding any
532    * columns that are hidden.
533    * 
534    * @param colsel
535    */
536   public void setElementsFrom(ColumnSelection colsel,
537           HiddenColumns hiddenColumns)
538   {
539     selection = new IntList();
540     if (colsel.selection != null && colsel.selection.size() > 0)
541     {
542       if (hiddenColumns.hasHiddenColumns())
543       {
544         // only select visible columns in this columns selection
545         for (Integer col : colsel.getSelected())
546         {
547           if (hiddenColumns != null
548                   && hiddenColumns.isVisible(col.intValue()))
549           {
550             selection.add(col);
551           }
552         }
553       }
554       else
555       {
556         // add everything regardless
557         for (Integer col : colsel.getSelected())
558         {
559           addElement(col);
560         }
561       }
562     }
563   }
564
565   /**
566    * 
567    * @return true if there are columns marked
568    */
569   public boolean hasSelectedColumns()
570   {
571     return (selection != null && selection.size() > 0);
572   }
573
574   /**
575    * Selects columns where the given annotation matches the provided filter
576    * condition(s). Any existing column selections are first cleared. Answers the
577    * number of columns added.
578    * 
579    * @param annotations
580    * @param filterParams
581    * @return
582    */
583   public int filterAnnotations(AlignmentAnnotation ann_row,
584           AnnotationFilterParameter filterParams)
585   {
586     Annotation[] annotations = ann_row.annotations;
587     // JBPNote - this method needs to be refactored to become independent of
588     // viewmodel package
589     this.clear();
590
591     if (ann_row.graph == AlignmentAnnotation.CONTACT_MAP && (filterParams
592             .getThresholdType() == AnnotationFilterParameter.ThresholdType.ABOVE_THRESHOLD
593             || filterParams
594                     .getThresholdType() == AnnotationFilterParameter.ThresholdType.BELOW_THRESHOLD))
595     {
596       float tVal = filterParams.getThresholdValue();
597       if (ann_row.sequenceRef != null)
598       {
599         // TODO - get ContactList from AlignmentView for non-seq-ref associatd
600         for (int column = 0; column < annotations.length; column++)
601         {
602           if (ann_row.annotations[column] == null)
603           {
604             continue;
605           }
606
607           int cpos = ann_row.sequenceRef.findPosition(column) - 1;
608           ContactListI clist = ann_row.sequenceRef
609                   .getContactListFor(ann_row, cpos);
610           for (int row = column + 8, rowEnd = clist
611                   .getContactHeight(); row < rowEnd; row++)
612           {
613             if (filterParams
614                     .getThresholdType() == AnnotationFilterParameter.ThresholdType.ABOVE_THRESHOLD
615                             ? (clist.getContactAt(row) > tVal)
616                             : (clist.getContactAt(row) < tVal))
617             {
618               addElement(column);
619               break;
620               // int column_forrowpos = ann_row.sequenceRef.findIndex(row + 1);
621               // addElement(column_forrowpos);
622             }
623           }
624         }
625       }
626       return selection.size();
627     }
628
629     int addedCount = 0;
630     int column = 0;
631     do
632     {
633       Annotation ann = annotations[column];
634       if (ann != null)
635       {
636         float value = ann.value;
637         boolean matched = false;
638
639         /*
640          * filter may have multiple conditions - 
641          * these are or'd until a match is found
642          */
643         if (filterParams
644                 .getThresholdType() == AnnotationFilterParameter.ThresholdType.ABOVE_THRESHOLD
645                 && value > filterParams.getThresholdValue())
646         {
647           matched = true;
648         }
649
650         if (!matched && filterParams
651                 .getThresholdType() == AnnotationFilterParameter.ThresholdType.BELOW_THRESHOLD
652                 && value < filterParams.getThresholdValue())
653         {
654           matched = true;
655         }
656
657         if (!matched && filterParams.isFilterAlphaHelix()
658                 && ann.secondaryStructure == 'H')
659         {
660           matched = true;
661         }
662
663         if (!matched && filterParams.isFilterBetaSheet()
664                 && ann.secondaryStructure == 'E')
665         {
666           matched = true;
667         }
668
669         if (!matched && filterParams.isFilterTurn()
670                 && ann.secondaryStructure == 'S')
671         {
672           matched = true;
673         }
674
675         String regexSearchString = filterParams.getRegexString();
676         if (!matched && regexSearchString != null)
677         {
678           List<SearchableAnnotationField> fields = filterParams
679                   .getRegexSearchFields();
680           for (SearchableAnnotationField field : fields)
681           {
682             String compareTo = field == SearchableAnnotationField.DISPLAY_STRING
683                     ? ann.displayCharacter // match 'Label'
684                     : ann.description; // and/or 'Description'
685             if (compareTo != null)
686             {
687               try
688               {
689                 if (compareTo.matches(regexSearchString))
690                 {
691                   matched = true;
692                 }
693               } catch (PatternSyntaxException pse)
694               {
695                 if (compareTo.equals(regexSearchString))
696                 {
697                   matched = true;
698                 }
699               }
700               if (matched)
701               {
702                 break;
703               }
704             }
705           }
706         }
707
708         if (matched)
709         {
710           this.addElement(column);
711           addedCount++;
712         }
713       }
714       column++;
715     } while (column < annotations.length);
716
717     return addedCount;
718   }
719
720   /**
721    * Returns a hashCode built from selected columns ranges
722    */
723   @Override
724   public int hashCode()
725   {
726     return selection.hashCode();
727   }
728
729   /**
730    * Answers true if comparing to a ColumnSelection with the same selected
731    * columns and hidden columns, else false
732    */
733   @Override
734   public boolean equals(Object obj)
735   {
736     if (!(obj instanceof ColumnSelection))
737     {
738       return false;
739     }
740     ColumnSelection that = (ColumnSelection) obj;
741
742     /*
743      * check columns selected are either both null, or match
744      */
745     if (this.selection == null)
746     {
747       if (that.selection != null)
748       {
749         return false;
750       }
751     }
752     if (!this.selection.equals(that.selection))
753     {
754       return false;
755     }
756
757     return true;
758   }
759
760   /**
761    * Updates the column selection depending on the parameters, and returns true
762    * if any change was made to the selection
763    * 
764    * @param markedColumns
765    *          a set identifying marked columns (base 0)
766    * @param startCol
767    *          the first column of the range to operate over (base 0)
768    * @param endCol
769    *          the last column of the range to operate over (base 0)
770    * @param invert
771    *          if true, deselect marked columns and select unmarked
772    * @param extendCurrent
773    *          if true, extend rather than replacing the current column selection
774    * @param toggle
775    *          if true, toggle the selection state of marked columns
776    * 
777    * @return
778    */
779   public boolean markColumns(BitSet markedColumns, int startCol, int endCol,
780           boolean invert, boolean extendCurrent, boolean toggle)
781   {
782     boolean changed = false;
783     if (!extendCurrent && !toggle)
784     {
785       changed = !this.isEmpty();
786       clear();
787     }
788     if (invert)
789     {
790       // invert only in the currently selected sequence region
791       int i = markedColumns.nextClearBit(startCol);
792       int ibs = markedColumns.nextSetBit(startCol);
793       while (i >= startCol && i <= endCol)
794       {
795         if (ibs < 0 || i < ibs)
796         {
797           changed = true;
798           if (toggle && contains(i))
799           {
800             removeElement(i++);
801           }
802           else
803           {
804             addElement(i++);
805           }
806         }
807         else
808         {
809           i = markedColumns.nextClearBit(ibs);
810           ibs = markedColumns.nextSetBit(i);
811         }
812       }
813     }
814     else
815     {
816       int i = markedColumns.nextSetBit(startCol);
817       while (i >= startCol && i <= endCol)
818       {
819         changed = true;
820         if (toggle && contains(i))
821         {
822           removeElement(i);
823         }
824         else
825         {
826           addElement(i);
827         }
828         i = markedColumns.nextSetBit(i + 1);
829       }
830     }
831     return changed;
832   }
833
834   /**
835    * Adjusts column selections, and the given selection group, to match the
836    * range of a stretch (e.g. mouse drag) operation
837    * <p>
838    * Method refactored from ScalePanel.mouseDragged
839    * 
840    * @param res
841    *          current column position, adjusted for hidden columns
842    * @param sg
843    *          current selection group
844    * @param min
845    *          start position of the stretch group
846    * @param max
847    *          end position of the stretch group
848    */
849   public void stretchGroup(int res, SequenceGroup sg, int min, int max)
850   {
851     if (!contains(res))
852     {
853       addElement(res);
854     }
855
856     if (res > sg.getStartRes())
857     {
858       // expand selection group to the right
859       sg.setEndRes(res);
860     }
861     if (res < sg.getStartRes())
862     {
863       // expand selection group to the left
864       sg.setStartRes(res);
865     }
866
867     /*
868      * expand or shrink column selection to match the
869      * range of the drag operation
870      */
871     for (int col = min; col <= max; col++)
872     {
873       if (col < sg.getStartRes() || col > sg.getEndRes())
874       {
875         // shrinking drag - remove from selection
876         removeElement(col);
877       }
878       else
879       {
880         // expanding drag - add to selection
881         addElement(col);
882       }
883     }
884   }
885 }