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