4ef82c8a1d9ce9b246fc8bdb95479ce02ef299ae
[jalview.git] / src / jalview / gui / RedundancyPanel.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.gui;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.commands.CommandI;
25 import jalview.commands.EditCommand;
26 import jalview.commands.EditCommand.Action;
27 import jalview.datamodel.SequenceGroup;
28 import jalview.datamodel.SequenceI;
29 import jalview.jbgui.GSliderPanel;
30 import jalview.util.MessageManager;
31
32 import java.awt.event.ActionEvent;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Stack;
37 import java.util.Vector;
38
39 import javax.swing.JInternalFrame;
40 import javax.swing.JProgressBar;
41 import javax.swing.event.ChangeEvent;
42 import javax.swing.event.ChangeListener;
43 import javax.swing.event.InternalFrameAdapter;
44 import javax.swing.event.InternalFrameEvent;
45
46 /**
47  * DOCUMENT ME!
48  * 
49  * @author $author$
50  * @version $Revision$
51  */
52 public class RedundancyPanel extends GSliderPanel implements Runnable
53 {
54   AlignFrame af;
55
56   AlignmentPanel ap;
57
58   Stack<CommandI> historyList = new Stack<CommandI>();
59
60   // simpler than synching with alignFrame.
61
62   float[] redundancy;
63
64   SequenceI[] originalSequences;
65
66   JInternalFrame frame;
67
68   Vector redundantSeqs;
69
70   private SequenceI[] redreps;
71
72   /**
73    * Creates a new RedundancyPanel object.
74    * 
75    * @param ap
76    *          DOCUMENT ME!
77    * @param af
78    *          DOCUMENT ME!
79    */
80   public RedundancyPanel(final AlignmentPanel ap, AlignFrame af)
81   {
82     this.ap = ap;
83     this.af = af;
84     redundantSeqs = new Vector();
85
86     slider.addChangeListener(new ChangeListener()
87     {
88       public void stateChanged(ChangeEvent evt)
89       {
90         valueField.setText(slider.getValue() + "");
91         sliderValueChanged();
92       }
93     });
94
95     applyButton.setText(MessageManager.getString("action.hide"));
96     allGroupsCheck.setVisible(false);
97     slider.setMinimum(0);
98     slider.setMaximum(100);
99     slider.setValue(100);
100
101     Thread worker = new Thread(this);
102     worker.start();
103
104     frame = new JInternalFrame();
105     frame.setContentPane(this);
106     Desktop.addInternalFrame(frame, MessageManager
107             .getString("label.redundancy_threshold_selection"), 400, 100,
108             false);
109     frame.addInternalFrameListener(new InternalFrameAdapter()
110     {
111       public void internalFrameClosing(InternalFrameEvent evt)
112       {
113         ap.getIdPanel().getIdCanvas().setHighlighted(null);
114       }
115     });
116
117   }
118
119   /**
120    * This is a copy of remove redundancy in jalivew.datamodel.Alignment except
121    * we dont want to remove redundancy, just calculate once so we can use the
122    * slider to dynamically hide redundant sequences
123    * 
124    * @param threshold
125    *          DOCUMENT ME!
126    * @param sel
127    *          DOCUMENT ME!
128    * 
129    * @return DOCUMENT ME!
130    */
131   public void run()
132   {
133     JProgressBar progress = new JProgressBar();
134     progress.setIndeterminate(true);
135     southPanel.add(progress, java.awt.BorderLayout.SOUTH);
136
137     label.setText(MessageManager.getString("label.calculating"));
138
139     slider.setVisible(false);
140     applyButton.setEnabled(false);
141     valueField.setVisible(false);
142
143     validate();
144
145     String[] omitHidden = null;
146
147     SequenceGroup sg = ap.av.getSelectionGroup();
148     int height;
149
150     int start, end;
151
152     if ((sg != null) && (sg.getSize() >= 1))
153     {
154       originalSequences = sg.getSequencesInOrder(ap.av.getAlignment());
155       start = sg.getStartRes();
156       end = sg.getEndRes();
157     }
158     else
159     {
160       originalSequences = ap.av.getAlignment().getSequencesArray();
161       start = 0;
162       end = ap.av.getAlignment().getWidth();
163     }
164
165     height = originalSequences.length;
166     if (ap.av.hasHiddenColumns())
167     {
168       omitHidden = ap.av.getViewAsString(sg != null);
169     }
170     Object rr[] = AlignSeq.computeRedundancyMatrixWithRep(
171             originalSequences,
172             omitHidden, start, end, false);
173
174     redundancy = (float[]) rr[0];
175     redreps = (SequenceI[]) rr[1];
176
177     progress.setIndeterminate(false);
178     progress.setVisible(false);
179     progress = null;
180
181     label.setText(MessageManager
182             .getString("label.enter_redundancy_thereshold"));
183     slider.setVisible(true);
184     applyButton.setEnabled(true);
185     valueField.setVisible(true);
186
187     validate();
188     sliderValueChanged();
189     // System.out.println((System.currentTimeMillis()-start));
190   }
191
192   void sliderValueChanged()
193   {
194     if (redundancy == null)
195     {
196       return;
197     }
198
199     float value = slider.getValue();
200     List<SequenceI> redundantSequences = new ArrayList<SequenceI>();
201     for (int i = 0; i < redundancy.length; i++)
202     {
203       if (value <= redundancy[i])
204       {
205         redundantSequences.add(originalSequences[i]);
206       }
207     }
208     ap.getIdPanel().getIdCanvas().setHighlighted(redundantSequences);
209   }
210
211   /**
212    * DOCUMENT ME!
213    * 
214    * @param e
215    *          DOCUMENT ME!
216    */
217   public void applyButton_actionPerformed(ActionEvent e)
218   {
219
220     undoButton.setEnabled(true);
221
222     float value = slider.getValue();
223     SequenceGroup sg = ap.av.getSelectionGroup();
224     // delete_seqs(value, sg);
225     hide_seqs(value, sg);
226   }
227   private void hide_seqs(float value, SequenceGroup sg)
228   {
229     /**
230      * hash to look up the representative for a sequence
231      */
232     HashMap<SequenceI, SequenceI> rep = new HashMap<SequenceI, SequenceI>();
233     /**
234      * hash to collect lists of sequences represented by a sequence
235      */
236     HashMap<SequenceI, SequenceGroup> reps = new HashMap<SequenceI, SequenceGroup>();
237     for (int i = 0; i < redundancy.length; i++)
238     {
239       if (value <= redundancy[i])
240       {
241         // does this sequence represent other sequences ?
242         SequenceGroup repset;
243         // is the representative also redundant ?
244         SequenceI repForI = rep.get(redreps[i]);
245         if (repForI==null) {
246           // the representative is still in the alignment. 
247           // is it representing anything already ? 
248           repset = reps.get(redreps[i]);
249           if (repset==null)
250           {
251             repset = new SequenceGroup();
252           }
253           repset.addSequence(originalSequences[i], false);
254           rep.put(originalSequences[i], redreps[i]);
255           reps.put(redreps[i], repset);
256           // and save the representative sequence for originalSeq
257           repForI = redreps[i];
258         } else {
259           // already hidden the representative for this sequence, so look up its redundant peers
260           repset = reps.get(repForI);
261           if (repset==null)
262           {
263             throw new Error("Implementation failure for redundancy set creation");
264           }
265           // add the sequence to the peerset, and mark sequence's representative in hash
266           repset.addSequence(originalSequences[i], false);
267           rep.put(originalSequences[i], repForI);
268         }
269         // merge any sequences represented by this with its new containing group
270         SequenceGroup existingreps = reps.remove(originalSequences[i]);
271         if (existingreps!=null)
272         {
273           for (SequenceI sq:existingreps.getSequences())
274           {
275             rep.put(sq, repForI);
276             repset.addSequence(sq, false);
277           }
278         }
279       }
280     }
281     for (SequenceI repseq: reps.keySet())
282     {
283       sg = reps.get(repseq);
284       sg.addSequence(repseq, false);
285       sg.setSeqrep(repseq);
286       ap.av.hideRepSequences(repseq, sg);
287     }
288   }
289
290   private void delete_seqs(float value, SequenceGroup sg)
291   {
292     ArrayList<SequenceI> del = new ArrayList<SequenceI>();
293
294     for (int i = 0; i < redundancy.length; i++)
295     {
296       if (value <= redundancy[i])
297       {
298         del.add(originalSequences[i]);
299       }
300     }
301     // This has to be done before the restoreHistoryItem method of alignFrame
302     // will
303     // actually restore these sequences.
304     if (del.size() > 0)
305     {
306       SequenceI[] deleted = new SequenceI[del.size()];
307
308       int width = 0;
309       for (int i = 0; i < del.size(); i++)
310       {
311         deleted[i] = del.get(i);
312         if (deleted[i].getLength() > width)
313         {
314           width = deleted[i].getLength();
315         }
316       }
317
318       EditCommand cut = new EditCommand(
319               MessageManager.getString("action.remove_redundancy"),
320               Action.CUT, deleted, 0, width, ap.av.getAlignment());
321
322       for (int i = 0; i < del.size(); i++)
323       {
324         ap.av.getAlignment().deleteSequence(deleted[i]);
325         if (sg != null)
326         {
327           sg.deleteSequence(deleted[i], false);
328         }
329       }
330
331       historyList.push(cut);
332
333       ap.alignFrame.addHistoryItem(cut);
334
335       PaintRefresher.Refresh(this, ap.av.getSequenceSetId(), true, true);
336       ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
337               .getSequences());
338     }
339
340   }
341
342   /**
343    * DOCUMENT ME!
344    * 
345    * @param e
346    *          DOCUMENT ME!
347    */
348   public void undoButton_actionPerformed(ActionEvent e)
349   {
350     if (historyList == null || historyList.isEmpty())
351     {
352       undoButton.setEnabled(false);
353       return;
354     }
355
356     CommandI command = historyList.pop();
357     if (ap.av.getHistoryList().contains(command))
358     {
359       command.undoCommand(af.getViewAlignments());
360       ap.av.getHistoryList().remove(command);
361       ap.av.firePropertyChange("alignment", null, ap.av.getAlignment()
362               .getSequences());
363       af.updateEditMenuBar();
364     }
365
366     ap.paintAlignment(true);
367
368     if (historyList.size() == 0)
369     {
370       undoButton.setEnabled(false);
371     }
372   }
373
374   /**
375    * DOCUMENT ME!
376    * 
377    * @param e
378    *          DOCUMENT ME!
379    */
380   public void valueField_actionPerformed(ActionEvent e)
381   {
382     try
383     {
384       int i = Integer.parseInt(valueField.getText());
385       slider.setValue(i);
386     } catch (Exception ex)
387     {
388       valueField.setText(slider.getValue() + "");
389     }
390   }
391
392 }