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