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