JAL-1632 removed ‘tree’ option and changed dialog layout
[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       @Override
168       public void itemStateChanged(ItemEvent e)
169       {
170         neighbourJoining.setEnabled(tree.isSelected());
171         averageDistance.setEnabled(tree.isSelected());
172       }
173     };
174
175     /*
176      * score models drop-down - with added tooltips!
177      */
178     modelNames = buildModelOptionsList();
179
180     JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
181     scoreModelPanel.setOpaque(false);
182     scoreModelPanel.add(modelNames);
183
184     /*
185      * score model parameters
186      */
187     JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
188     paramsPanel.setOpaque(false);
189     includeGaps = new JCheckBox("Include gaps");
190     matchGaps = new JCheckBox("Match gaps");
191     includeGappedColumns = new JCheckBox("Include gapped columns");
192     shorterSequence = new JCheckBox("Match on shorter sequence");
193     paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
194     paramsPanel.add(includeGaps);
195     paramsPanel.add(matchGaps);
196     paramsPanel.add(includeGappedColumns);
197     paramsPanel.add(shorterSequence);
198
199     /*
200      * OK / Cancel buttons
201      */
202     JButton ok = new JButton(MessageManager.getString("action.ok"));
203     ok.setFont(VERDANA_11PT);
204     ok.addActionListener(new java.awt.event.ActionListener()
205     {
206       @Override
207       public void actionPerformed(ActionEvent e)
208       {
209         ok_actionPerformed();
210       }
211     });
212     JButton cancel = new JButton(MessageManager.getString("action.cancel"));
213     cancel.setFont(VERDANA_11PT);
214     cancel.addActionListener(new java.awt.event.ActionListener()
215     {
216       @Override
217       public void actionPerformed(ActionEvent e)
218       {
219         cancel_actionPerformed(e);
220       }
221     });
222     JPanel actionPanel = new JPanel();
223     actionPanel.setOpaque(false);
224     actionPanel.add(ok);
225     actionPanel.add(cancel);
226
227     boolean includeParams = false;
228     this.add(calcChoicePanel, BorderLayout.CENTER);
229     calcChoicePanel.add(scoreModelPanel);
230     if (includeParams)
231     {
232       scoreModelPanel.add(paramsPanel);
233     }
234     this.add(actionPanel, BorderLayout.SOUTH);
235
236     int width = 350;
237     int height = includeParams ? 420 : 240;
238
239     setMinimumSize(new Dimension(325, height - 10));
240     String title = MessageManager.getString("label.choose_calculation");
241     if (af.getViewport().viewName != null)
242     {
243       title = title + " (" + af.getViewport().viewName + ")";
244     }
245
246     Desktop.addInternalFrame(frame,
247             title, width,
248             height, false);
249     calcChoicePanel.doLayout();
250     revalidate();
251     /*
252      * null the AlignmentPanel's reference to the dialog when it is closed
253      */
254     frame.addInternalFrameListener(new InternalFrameAdapter()
255     {
256       @Override
257       public void internalFrameClosed(InternalFrameEvent evt)
258       {
259         af.alignPanel.setCalculationDialog(null);
260       };
261     });
262
263     frame.setLayer(JLayeredPane.PALETTE_LAYER);
264   }
265
266   /**
267    * A rather elaborate helper method (blame Swing, not me) that builds a
268    * drop-down list of score models (by name) with descriptions as tooltips.
269    * There is also a tooltip shown for the currently selected item when hovering
270    * over it (without opening the list).
271    */
272   protected JComboBox<String> buildModelOptionsList()
273   {
274     final JComboBox<String> comboBox = new JComboBox<String>();
275     ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
276     comboBox.setRenderer(renderer);
277     final List<String> tips = new ArrayList<String>();
278
279     /*
280      * show tooltip on mouse over the combobox
281      * note the listener has to be on the components that make up
282      * the combobox, doesn't work if just on the combobox
283      */
284     MouseAdapter mouseListener = new MouseAdapter()
285     {
286       @Override
287       public void mouseEntered(MouseEvent e)
288       {
289         comboBox.setToolTipText(tips.get(comboBox.getSelectedIndex()));
290       }
291
292       @Override
293       public void mouseExited(MouseEvent e)
294       {
295         comboBox.setToolTipText(null);
296       }
297     };
298     for (Component c : comboBox.getComponents())
299     {
300       c.addMouseListener(mouseListener);
301     }
302
303     /*
304      * now we can actually add entries to the combobox,
305      * remembering their descriptions for tooltips
306      */
307     ScoreModels scoreModels = ScoreModels.getInstance();
308     for (ScoreModelI sm : scoreModels.getModels())
309     {
310       boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
311       if (sm.isDNA() && nucleotide || sm.isProtein() && !nucleotide)
312       {
313         comboBox.addItem(sm.getName());
314
315         /*
316          * tooltip is description if provided, else text lookup with
317          * fallback on the model name
318          */
319         String tooltip = sm.getDescription();
320         if (tooltip == null)
321         {
322           tooltip = MessageManager.getStringOrReturn("label.score_model_",
323                   sm.getName());
324         }
325         tips.add(tooltip);
326       }
327
328       /*
329        * set the list of tooltips on the combobox's renderer
330        */
331       renderer.setTooltips(tips);
332     }
333
334     return comboBox;
335   }
336
337   /**
338    * Open and calculate the selected tree or PCA on 'OK'
339    */
340   protected void ok_actionPerformed()
341   {
342     boolean doPCA = pca.isSelected();
343     String modelName = modelNames.getSelectedItem().toString();
344     SimilarityParamsI params = getSimilarityParameters(doPCA);
345
346     if (doPCA)
347     {
348       openPcaPanel(modelName, params);
349     }
350     else
351     {
352       openTreePanel(modelName, params);
353     }
354
355     // closeFrame();
356   }
357
358   /**
359    * Open a new Tree panel on the desktop
360    * 
361    * @param modelName
362    * @param params
363    */
364   protected void openTreePanel(String modelName, SimilarityParamsI params)
365   {
366     String treeType = neighbourJoining.isSelected() ? TreeBuilder.NEIGHBOUR_JOINING
367             : TreeBuilder.AVERAGE_DISTANCE;
368     af.newTreePanel(treeType, modelName, params);
369   }
370
371   /**
372    * Open a new PCA panel on the desktop
373    * 
374    * @param modelName
375    * @param params
376    */
377   protected void openPcaPanel(String modelName, SimilarityParamsI params)
378   {
379     AlignViewport viewport = af.getViewport();
380     if (((viewport.getSelectionGroup() != null)
381             && (viewport.getSelectionGroup().getSize() < 4) && (viewport
382             .getSelectionGroup().getSize() > 0))
383             || (viewport.getAlignment().getHeight() < 4))
384     {
385       JvOptionPane
386               .showInternalMessageDialog(
387                       this,
388                       MessageManager
389                               .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
390                       MessageManager
391                               .getString("label.sequence_selection_insufficient"),
392                       JvOptionPane.WARNING_MESSAGE);
393       return;
394     }
395     new PCAPanel(af.alignPanel, modelName, params);
396   }
397
398   /**
399    * 
400    */
401   protected void closeFrame()
402   {
403     try
404     {
405       frame.setClosed(true);
406     } catch (PropertyVetoException ex)
407     {
408     }
409   }
410
411   /**
412    * Returns a data bean holding parameters for similarity (or distance) model
413    * calculation
414    * 
415    * @param doPCA
416    * @return
417    */
418   protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
419   {
420     // commented out: parameter choices read from gui widgets
421     // SimilarityParamsI params = new SimilarityParams(
422     // includeGappedColumns.isSelected(), matchGaps.isSelected(),
423     // includeGaps.isSelected(), shorterSequence.isSelected());
424
425     boolean includeGapGap = true;
426     boolean includeGapResidue = true;
427     boolean matchOnShortestLength = false;
428
429     /*
430      * 'matchGaps' flag is only used in the PID calculation
431      * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
432      * - set to true for Tree to reproduce Jalview 2.10.1 calculation
433      * - set to false for Tree for a more correct calculation (JAL-374)
434      */
435     boolean matchGap = doPCA ? false : treeMatchGaps;
436
437     return new SimilarityParams(includeGapGap, matchGap, includeGapResidue, matchOnShortestLength);
438   }
439
440   /**
441    * Closes dialog on cancel
442    * 
443    * @param e
444    */
445   protected void cancel_actionPerformed(ActionEvent e)
446   {
447     try
448     {
449       frame.setClosed(true);
450     } catch (Exception ex)
451     {
452     }
453   }
454 }