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