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