JAL-2333 corrected select columns with 'contact' feature
[jalview.git] / src / jalview / controller / AlignViewController.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.controller;
22
23 import jalview.analysis.AlignmentSorter;
24 import jalview.api.AlignViewControllerGuiI;
25 import jalview.api.AlignViewControllerI;
26 import jalview.api.AlignViewportI;
27 import jalview.api.AlignmentViewPanel;
28 import jalview.api.FeatureRenderer;
29 import jalview.commands.OrderCommand;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.ColumnSelection;
32 import jalview.datamodel.SequenceCollectionI;
33 import jalview.datamodel.SequenceFeature;
34 import jalview.datamodel.SequenceGroup;
35 import jalview.datamodel.SequenceI;
36 import jalview.io.FeaturesFile;
37 import jalview.util.MessageManager;
38
39 import java.awt.Color;
40 import java.util.BitSet;
41 import java.util.List;
42
43 public class AlignViewController implements AlignViewControllerI
44 {
45   AlignViewportI viewport = null;
46
47   AlignmentViewPanel alignPanel = null;
48
49   /**
50    * the GUI container that is handling interactions with the user
51    */
52   private AlignViewControllerGuiI avcg;
53
54   @Override
55   protected void finalize() throws Throwable
56   {
57     viewport = null;
58     alignPanel = null;
59     avcg = null;
60   };
61
62   public AlignViewController(AlignViewControllerGuiI alignFrame,
63           AlignViewportI viewport, AlignmentViewPanel alignPanel)
64   {
65     this.avcg = alignFrame;
66     this.viewport = viewport;
67     this.alignPanel = alignPanel;
68   }
69
70   @Override
71   public void setViewportAndAlignmentPanel(AlignViewportI viewport,
72           AlignmentViewPanel alignPanel)
73   {
74     this.alignPanel = alignPanel;
75     this.viewport = viewport;
76
77   }
78
79   @Override
80   public boolean makeGroupsFromSelection()
81   {
82     SequenceGroup sg = viewport.getSelectionGroup();
83     ColumnSelection cs = viewport.getColumnSelection();
84     SequenceGroup[] gps = null;
85     if (sg != null && (cs == null || cs.isEmpty()))
86     {
87       gps = jalview.analysis.Grouping.makeGroupsFrom(viewport
88               .getSequenceSelection(), viewport.getAlignmentView(true)
89               .getSequenceStrings(viewport.getGapCharacter()), viewport
90               .getAlignment().getGroups());
91     }
92     else
93     {
94       if (cs != null)
95       {
96         gps = jalview.analysis.Grouping.makeGroupsFromCols(
97                 (sg == null) ? viewport.getAlignment().getSequencesArray()
98                         : sg.getSequences().toArray(new SequenceI[0]), cs,
99                 viewport.getAlignment().getGroups());
100       }
101     }
102     if (gps != null)
103     {
104       viewport.getAlignment().deleteAllGroups();
105       viewport.clearSequenceColours();
106       viewport.setSelectionGroup(null);
107       // set view properties for each group
108       for (int g = 0; g < gps.length; g++)
109       {
110         // gps[g].setShowunconserved(viewport.getShowUnconserved());
111         gps[g].setshowSequenceLogo(viewport.isShowSequenceLogo());
112         viewport.getAlignment().addGroup(gps[g]);
113         Color col = new Color((int) (Math.random() * 255),
114                 (int) (Math.random() * 255), (int) (Math.random() * 255));
115         col = col.brighter();
116         for (SequenceI sq : gps[g].getSequences(null))
117         {
118           viewport.setSequenceColour(sq, col);
119         }
120       }
121       return true;
122     }
123     return false;
124   }
125
126   @Override
127   public boolean createGroup()
128   {
129
130     SequenceGroup sg = viewport.getSelectionGroup();
131     if (sg != null)
132     {
133       viewport.getAlignment().addGroup(sg);
134       return true;
135     }
136     return false;
137   }
138
139   @Override
140   public boolean unGroup()
141   {
142     SequenceGroup sg = viewport.getSelectionGroup();
143     if (sg != null)
144     {
145       viewport.getAlignment().deleteGroup(sg);
146       return true;
147     }
148     return false;
149   }
150
151   @Override
152   public boolean deleteGroups()
153   {
154     if (viewport.getAlignment().getGroups() != null
155             && viewport.getAlignment().getGroups().size() > 0)
156     {
157       viewport.getAlignment().deleteAllGroups();
158       viewport.clearSequenceColours();
159       viewport.setSelectionGroup(null);
160       return true;
161     }
162     return false;
163   }
164
165   @Override
166   public boolean markColumnsContainingFeatures(boolean invert,
167           boolean extendCurrent, boolean toggle, String featureType)
168   {
169     // JBPNote this routine could also mark rows, not just columns.
170     // need a decent query structure to allow all types of feature searches
171     BitSet bs = new BitSet();
172     SequenceCollectionI sqcol = (viewport.getSelectionGroup() == null || extendCurrent) ? viewport
173             .getAlignment() : viewport.getSelectionGroup();
174
175     int nseq = findColumnsWithFeature(featureType, sqcol, bs);
176
177     ColumnSelection cs = viewport.getColumnSelection();
178     if (cs == null)
179     {
180       cs = new ColumnSelection();
181     }
182
183     if (bs.cardinality() > 0 || invert)
184     {
185       boolean changed = cs.markColumns(bs, sqcol.getStartRes(),
186               sqcol.getEndRes(), invert, extendCurrent, toggle);
187       if (changed)
188       {
189         viewport.setColumnSelection(cs);
190         alignPanel.paintAlignment(true);
191         int columnCount = invert ? (sqcol.getEndRes() - sqcol.getStartRes() + 1)
192                 - bs.cardinality()
193                 : bs.cardinality();
194         avcg.setStatus(MessageManager.formatMessage(
195                 "label.view_controller_toggled_marked",
196                 new String[] {
197                     toggle ? MessageManager.getString("label.toggled")
198                             : MessageManager.getString("label.marked"),
199                     String.valueOf(columnCount),
200                     invert ? MessageManager
201                             .getString("label.not_containing")
202                             : MessageManager.getString("label.containing"),
203                     featureType, Integer.valueOf(nseq).toString() }));
204         return true;
205       }
206     }
207     else
208     {
209       avcg.setStatus(MessageManager.formatMessage(
210               "label.no_feature_of_type_found",
211               new String[] { featureType }));
212       if (!extendCurrent)
213       {
214         cs.clear();
215         alignPanel.paintAlignment(true);
216       }
217     }
218     return false;
219   }
220
221   /**
222    * Sets a bit in the BitSet for each column (base 0) in the sequence
223    * collection which includes the specified feature type. Returns the number of
224    * sequences which have the feature in the selected range.
225    * 
226    * @param featureType
227    * @param sqcol
228    * @param bs
229    * @return
230    */
231   static int findColumnsWithFeature(String featureType,
232           SequenceCollectionI sqcol, BitSet bs)
233   {
234     final int startPosition = sqcol.getStartRes() + 1; // converted to base 1
235     final int endPosition = sqcol.getEndRes() + 1;
236     List<SequenceI> seqs = sqcol.getSequences();
237     int nseq = 0;
238     for (SequenceI sq : seqs)
239     {
240       boolean sequenceHasFeature = false;
241       if (sq != null)
242       {
243         SequenceFeature[] sfs = sq.getSequenceFeatures();
244         if (sfs != null)
245         {
246           int ist = sq.findIndex(sq.getStart());
247           int iend = sq.findIndex(sq.getEnd());
248           if (iend < startPosition || ist > endPosition)
249           {
250             // sequence not in region
251             continue;
252           }
253           for (SequenceFeature sf : sfs)
254           {
255             // future functionality - featureType == null means mark columns
256             // containing all displayed features
257             if (sf != null && (featureType.equals(sf.getType())))
258             {
259               // optimisation - could consider 'spos,apos' like cursor argument
260               // - findIndex wastes time by starting from first character and
261               // counting
262
263               int sfStartCol = sq.findIndex(sf.getBegin());
264               int sfEndCol = sq.findIndex(sf.getEnd());
265
266               if (sf.isContactFeature())
267               {
268                 /*
269                  * 'contact' feature - check for 'start' or 'end'
270                  * position within the selected region
271                  */
272                 if (sfStartCol >= startPosition
273                         && sfStartCol <= endPosition)
274                 {
275                   bs.set(sfStartCol - 1);
276                   sequenceHasFeature = true;
277                 }
278                 if (sfEndCol >= startPosition && sfEndCol <= endPosition)
279                 {
280                   bs.set(sfEndCol - 1);
281                   sequenceHasFeature = true;
282                 }
283                 continue;
284               }
285
286               /*
287                * contiguous feature - select feature positions (if any) 
288                * within the selected region
289                */
290               if (sfStartCol > endPosition || sfEndCol < startPosition)
291               {
292                 // feature is outside selected region
293                 continue;
294               }
295               sequenceHasFeature = true;
296               if (sfStartCol < startPosition)
297               {
298                 sfStartCol = startPosition;
299               }
300               if (sfStartCol < ist)
301               {
302                 sfStartCol = ist;
303               }
304               if (sfEndCol > endPosition)
305               {
306                 sfEndCol = endPosition;
307               }
308               for (; sfStartCol <= sfEndCol; sfStartCol++)
309               {
310                 bs.set(sfStartCol - 1); // convert to base 0
311               }
312             }
313           }
314         }
315
316         if (sequenceHasFeature)
317         {
318           nseq++;
319         }
320       }
321     }
322     return nseq;
323   }
324
325   @Override
326   public void sortAlignmentByFeatureDensity(List<String> typ)
327   {
328     sortBy(typ, "Sort by Density", AlignmentSorter.FEATURE_DENSITY);
329   }
330
331   protected void sortBy(List<String> typ, String methodText,
332           final String method)
333   {
334     FeatureRenderer fr = alignPanel.getFeatureRenderer();
335     if (typ == null && fr != null)
336     {
337       typ = fr.getDisplayedFeatureTypes();
338     }
339     List<String> gps = null;
340     if (fr != null)
341     {
342       gps = fr.getDisplayedFeatureGroups();
343     }
344     AlignmentI al = viewport.getAlignment();
345
346     int start, stop;
347     SequenceGroup sg = viewport.getSelectionGroup();
348     if (sg != null)
349     {
350       start = sg.getStartRes();
351       stop = sg.getEndRes();
352     }
353     else
354     {
355       start = 0;
356       stop = al.getWidth();
357     }
358     SequenceI[] oldOrder = al.getSequencesArray();
359     AlignmentSorter.sortByFeature(typ, gps, start, stop, al, method);
360     avcg.addHistoryItem(new OrderCommand(methodText, oldOrder, viewport
361             .getAlignment()));
362     alignPanel.paintAlignment(true);
363
364   }
365
366   @Override
367   public void sortAlignmentByFeatureScore(List<String> typ)
368   {
369     sortBy(typ, "Sort by Feature Score", AlignmentSorter.FEATURE_SCORE);
370   }
371
372   @Override
373   public boolean parseFeaturesFile(String file, String protocol,
374           boolean relaxedIdMatching)
375   {
376     boolean featuresFile = false;
377     try
378     {
379       featuresFile = new FeaturesFile(false, file, protocol).parse(viewport
380               .getAlignment().getDataset(), alignPanel.getFeatureRenderer()
381               .getFeatureColours(), false, relaxedIdMatching);
382     } catch (Exception ex)
383     {
384       ex.printStackTrace();
385     }
386
387     if (featuresFile)
388     {
389       avcg.refreshFeatureUI(true);
390       if (alignPanel.getFeatureRenderer() != null)
391       {
392         // update the min/max ranges where necessary
393         alignPanel.getFeatureRenderer().findAllFeatures(true);
394       }
395       if (avcg.getFeatureSettingsUI() != null)
396       {
397         avcg.getFeatureSettingsUI().discoverAllFeatureData();
398       }
399       alignPanel.paintAlignment(true);
400     }
401
402     return featuresFile;
403
404   }
405 }