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