JAL-1632 compare size of input against minimums for calculation and enable/disable...
[jalview.git] / src / jalview / gui / CalculationChooser.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.TreeBuilder;
24 import jalview.analysis.scoremodels.ScoreModels;
25 import jalview.analysis.scoremodels.SimilarityParams;
26 import jalview.api.analysis.ScoreModelI;
27 import jalview.api.analysis.SimilarityParamsI;
28 import jalview.util.MessageManager;
29
30 import java.awt.BorderLayout;
31 import java.awt.Color;
32 import java.awt.Component;
33 import java.awt.Dimension;
34 import java.awt.FlowLayout;
35 import java.awt.Font;
36 import java.awt.GridLayout;
37 import java.awt.Insets;
38 import java.awt.event.ActionEvent;
39 import java.awt.event.ActionListener;
40 import java.awt.event.FocusEvent;
41 import java.awt.event.FocusListener;
42 import java.awt.event.MouseAdapter;
43 import java.awt.event.MouseEvent;
44 import java.beans.PropertyVetoException;
45 import java.util.ArrayList;
46 import java.util.List;
47
48 import javax.swing.BorderFactory;
49 import javax.swing.ButtonGroup;
50 import javax.swing.JButton;
51 import javax.swing.JCheckBox;
52 import javax.swing.JComboBox;
53 import javax.swing.JInternalFrame;
54 import javax.swing.JLabel;
55 import javax.swing.JLayeredPane;
56 import javax.swing.JPanel;
57 import javax.swing.JRadioButton;
58 import javax.swing.event.InternalFrameAdapter;
59 import javax.swing.event.InternalFrameEvent;
60
61 /**
62  * A dialog where a user can choose and action Tree or PCA calculation options
63  */
64 public class CalculationChooser extends JPanel
65 {
66   /*
67    * flag for whether gap matches residue in the PID calculation for a Tree
68    * - true gives Jalview 2.10.1 behaviour
69    * - set to false (using Groovy) for a more correct tree
70    * (JAL-374)
71    */
72   private static boolean treeMatchGaps = true;
73
74   private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
75
76   AlignFrame af;
77
78   JRadioButton pca;
79
80   JRadioButton neighbourJoining;
81
82   JRadioButton averageDistance;
83
84   JComboBox<String> modelNames;
85
86   JButton ok;
87
88   private JInternalFrame frame;
89
90   private JCheckBox includeGaps;
91
92   private JCheckBox matchGaps;
93
94   private JCheckBox includeGappedColumns;
95
96   private JCheckBox shorterSequence;
97
98   /**
99    * Constructor
100    * 
101    * @param af
102    */
103   public CalculationChooser(AlignFrame alignFrame)
104   {
105     this.af = alignFrame;
106     init();
107     af.alignPanel.setCalculationDialog(this);
108   }
109
110   /**
111    * Lays out the panel and adds it to the desktop
112    */
113   void init()
114   {
115     setLayout(new BorderLayout());
116     frame = new JInternalFrame();
117     frame.setContentPane(this);
118     this.setBackground(Color.white);
119
120     /*
121      * Layout consists of 3 or 4 panels:
122      * - first with choice of PCA or tree method NJ or AV
123      * - second with choice of score model
124      * - third with score model parameter options [suppressed]
125      * - fourth with OK and Cancel
126      */
127     pca = new JRadioButton(
128             MessageManager.getString("label.principal_component_analysis"));
129     pca.setOpaque(false);
130     neighbourJoining = new JRadioButton(
131             MessageManager.getString("label.tree_calc_nj"));
132     averageDistance = new JRadioButton(
133             MessageManager.getString("label.tree_calc_av"));
134     neighbourJoining.setOpaque(false);
135
136     JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
137     calcChoicePanel.setOpaque(false);
138
139     // first create the Tree calculation's border panel
140     JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
141     treePanel.setOpaque(false);
142
143     treePanel.setBorder(BorderFactory.createTitledBorder(MessageManager
144             .getString("label.tree")));
145
146     // then copy the inset dimensions for the border-less PCA panel
147     JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
148     Insets b = treePanel.getBorder().getBorderInsets(treePanel);
149     pcaBorderless.setBorder(BorderFactory.createEmptyBorder(2, b.left, 2,
150             b.right));
151     pcaBorderless.setOpaque(false);
152
153     pcaBorderless.add(pca, FlowLayout.LEFT);
154     calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
155
156
157     treePanel.add(neighbourJoining);
158     treePanel.add(averageDistance);
159
160     calcChoicePanel.add(treePanel);
161
162     ButtonGroup calcTypes = new ButtonGroup();
163     calcTypes.add(pca);
164     calcTypes.add(neighbourJoining);
165     calcTypes.add(averageDistance);
166     
167     ActionListener calcChanged = new ActionListener()
168     {
169       @Override
170       public void actionPerformed(ActionEvent e)
171       {
172         validateCalcTypes();
173       }
174     };
175     pca.addActionListener(calcChanged);
176     neighbourJoining.addActionListener(calcChanged);
177     averageDistance.addActionListener(calcChanged);
178     /*
179      * score models drop-down - with added tooltips!
180      */
181     modelNames = buildModelOptionsList();
182
183     JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
184     scoreModelPanel.setOpaque(false);
185     scoreModelPanel.add(modelNames);
186
187     /*
188      * score model parameters
189      */
190     JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
191     paramsPanel.setOpaque(false);
192     includeGaps = new JCheckBox("Include gaps");
193     matchGaps = new JCheckBox("Match gaps");
194     includeGappedColumns = new JCheckBox("Include gapped columns");
195     shorterSequence = new JCheckBox("Match on shorter sequence");
196     paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
197     paramsPanel.add(includeGaps);
198     paramsPanel.add(matchGaps);
199     paramsPanel.add(includeGappedColumns);
200     paramsPanel.add(shorterSequence);
201
202     /*
203      * OK / Cancel buttons
204      */
205     ok = new JButton(MessageManager.getString("action.calculate"));
206     ok.setFont(VERDANA_11PT);
207     ok.addActionListener(new java.awt.event.ActionListener()
208     {
209       @Override
210       public void actionPerformed(ActionEvent e)
211       {
212         ok_actionPerformed();
213       }
214     });
215     JButton cancel = new JButton(MessageManager.getString("action.close"));
216     cancel.setFont(VERDANA_11PT);
217     cancel.addActionListener(new java.awt.event.ActionListener()
218     {
219       @Override
220       public void actionPerformed(ActionEvent e)
221       {
222         cancel_actionPerformed(e);
223       }
224     });
225     JPanel actionPanel = new JPanel();
226     actionPanel.setOpaque(false);
227     actionPanel.add(ok);
228     actionPanel.add(cancel);
229
230     boolean includeParams = false;
231     this.add(calcChoicePanel, BorderLayout.CENTER);
232     calcChoicePanel.add(scoreModelPanel);
233     if (includeParams)
234     {
235       scoreModelPanel.add(paramsPanel);
236     }
237     this.add(actionPanel, BorderLayout.SOUTH);
238
239     int width = 350;
240     int height = includeParams ? 420 : 240;
241
242     setMinimumSize(new Dimension(325, height - 10));
243     String title = MessageManager.getString("label.choose_calculation");
244     if (af.getViewport().viewName != null)
245     {
246       title = title + " (" + af.getViewport().viewName + ")";
247     }
248
249     Desktop.addInternalFrame(frame,
250             title, width,
251             height, false);
252     calcChoicePanel.doLayout();
253     revalidate();
254     /*
255      * null the AlignmentPanel's reference to the dialog when it is closed
256      */
257     frame.addInternalFrameListener(new InternalFrameAdapter()
258     {
259       @Override
260       public void internalFrameClosed(InternalFrameEvent evt)
261       {
262         af.alignPanel.setCalculationDialog(null);
263       };
264     });
265
266     frame.setLayer(JLayeredPane.PALETTE_LAYER);
267   }
268
269   /**
270    * enable calculations applicable for the current alignment or selection.
271    */
272   protected void validateCalcTypes()
273   {
274     int size = af.getViewport().getAlignment().getHeight();
275     if (af.getViewport().getSelectionGroup() != null)
276     {
277       size = af.getViewport().getSelectionGroup().getSize();
278     }
279     if (!(checkEnabled(pca, size, 4)
280             | checkEnabled(neighbourJoining, size, 3) | checkEnabled(
281               averageDistance, size, 3)))
282     {
283       ok.setToolTipText(null);
284       ok.setEnabled(true);
285     }
286     else
287     {
288       ok.setEnabled(false);
289     }
290   }
291
292   /**
293    * Check the input and disable a calculation's radio button if necessary. A
294    * tooltip is shown for disabled calculations.
295    * 
296    * @param calc
297    *          - radio button for the calculation being validated
298    * @param size
299    *          - size of input to calculation
300    * @param minsize
301    *          - minimum size for calculation
302    * @return true if size < minsize *and* calc.isSelected
303    */
304   private boolean checkEnabled(JRadioButton calc, int size, int minsize)
305   {
306     String ttip = MessageManager.formatMessage(
307             "label.you_need_more_than_n_sequences", minsize);
308
309     calc.setEnabled(size >= minsize);
310     if (!calc.isEnabled())
311     {
312       calc.setToolTipText(ttip);
313     }
314     else
315     {
316       calc.setToolTipText(null);
317     }
318     if (calc.isSelected())
319     {
320       modelNames.setEnabled(calc.isEnabled());
321       if (!calc.isEnabled())
322       {
323         ok.setEnabled(false);
324         ok.setToolTipText(ttip);
325         return true;
326       }
327     }
328     return false;
329   }
330   /**
331    * A rather elaborate helper method (blame Swing, not me) that builds a
332    * drop-down list of score models (by name) with descriptions as tooltips.
333    * There is also a tooltip shown for the currently selected item when hovering
334    * over it (without opening the list).
335    */
336   protected JComboBox<String> buildModelOptionsList()
337   {
338     final JComboBox<String> comboBox = new JComboBox<String>();
339     ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
340     comboBox.setRenderer(renderer);
341     final List<String> tips = new ArrayList<String>();
342
343     /*
344      * show tooltip on mouse over the combobox
345      * note the listener has to be on the components that make up
346      * the combobox, doesn't work if just on the combobox
347      */
348     MouseAdapter mouseListener = new MouseAdapter()
349     {
350       @Override
351       public void mouseEntered(MouseEvent e)
352       {
353         comboBox.setToolTipText(tips.get(comboBox.getSelectedIndex()));
354       }
355
356       @Override
357       public void mouseExited(MouseEvent e)
358       {
359         comboBox.setToolTipText(null);
360       }
361     };
362     for (Component c : comboBox.getComponents())
363     {
364       c.addMouseListener(mouseListener);
365     }
366
367     /*
368      * now we can actually add entries to the combobox,
369      * remembering their descriptions for tooltips
370      */
371     ScoreModels scoreModels = ScoreModels.getInstance();
372     for (ScoreModelI sm : scoreModels.getModels())
373     {
374       boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
375       if (sm.isDNA() && nucleotide || sm.isProtein() && !nucleotide)
376       {
377         comboBox.addItem(sm.getName());
378
379         /*
380          * tooltip is description if provided, else text lookup with
381          * fallback on the model name
382          */
383         String tooltip = sm.getDescription();
384         if (tooltip == null)
385         {
386           tooltip = MessageManager.getStringOrReturn("label.score_model_",
387                   sm.getName());
388         }
389         tips.add(tooltip);
390       }
391
392       /*
393        * set the list of tooltips on the combobox's renderer
394        */
395       renderer.setTooltips(tips);
396     }
397
398     return comboBox;
399   }
400
401   /**
402    * Open and calculate the selected tree or PCA on 'OK'
403    */
404   protected void ok_actionPerformed()
405   {
406     boolean doPCA = pca.isSelected();
407     String modelName = modelNames.getSelectedItem().toString();
408     SimilarityParamsI params = getSimilarityParameters(doPCA);
409
410     if (doPCA)
411     {
412       openPcaPanel(modelName, params);
413     }
414     else
415     {
416       openTreePanel(modelName, params);
417     }
418
419     // closeFrame();
420   }
421
422   /**
423    * Open a new Tree panel on the desktop
424    * 
425    * @param modelName
426    * @param params
427    */
428   protected void openTreePanel(String modelName, SimilarityParamsI params)
429   {
430     String treeType = neighbourJoining.isSelected() ? TreeBuilder.NEIGHBOUR_JOINING
431             : TreeBuilder.AVERAGE_DISTANCE;
432     af.newTreePanel(treeType, modelName, params);
433   }
434
435   /**
436    * Open a new PCA panel on the desktop
437    * 
438    * @param modelName
439    * @param params
440    */
441   protected void openPcaPanel(String modelName, SimilarityParamsI params)
442   {
443     AlignViewport viewport = af.getViewport();
444     if (((viewport.getSelectionGroup() != null)
445             && (viewport.getSelectionGroup().getSize() < 4) && (viewport
446             .getSelectionGroup().getSize() > 0))
447             || (viewport.getAlignment().getHeight() < 4))
448     {
449       JvOptionPane
450               .showInternalMessageDialog(
451                       this,
452                       MessageManager
453                               .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
454                       MessageManager
455                               .getString("label.sequence_selection_insufficient"),
456                       JvOptionPane.WARNING_MESSAGE);
457       return;
458     }
459     new PCAPanel(af.alignPanel, modelName, params);
460   }
461
462   /**
463    * 
464    */
465   protected void closeFrame()
466   {
467     try
468     {
469       frame.setClosed(true);
470     } catch (PropertyVetoException ex)
471     {
472     }
473   }
474
475   /**
476    * Returns a data bean holding parameters for similarity (or distance) model
477    * calculation
478    * 
479    * @param doPCA
480    * @return
481    */
482   protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
483   {
484     // commented out: parameter choices read from gui widgets
485     // SimilarityParamsI params = new SimilarityParams(
486     // includeGappedColumns.isSelected(), matchGaps.isSelected(),
487     // includeGaps.isSelected(), shorterSequence.isSelected());
488
489     boolean includeGapGap = true;
490     boolean includeGapResidue = true;
491     boolean matchOnShortestLength = false;
492
493     /*
494      * 'matchGaps' flag is only used in the PID calculation
495      * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
496      * - set to true for Tree to reproduce Jalview 2.10.1 calculation
497      * - set to false for Tree for a more correct calculation (JAL-374)
498      */
499     boolean matchGap = doPCA ? false : treeMatchGaps;
500
501     return new SimilarityParams(includeGapGap, matchGap, includeGapResidue, matchOnShortestLength);
502   }
503
504   /**
505    * Closes dialog on cancel
506    * 
507    * @param e
508    */
509   protected void cancel_actionPerformed(ActionEvent e)
510   {
511     try
512     {
513       frame.setClosed(true);
514     } catch (Exception ex)
515     {
516     }
517   }
518 }