JAL-2446 merged to spike branch
[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    * Constructor
110    * 
111    * @param af
112    */
113   public CalculationChooser(AlignFrame alignFrame)
114   {
115     this.af = alignFrame;
116     init();
117     af.alignPanel.setCalculationDialog(this);
118   }
119
120   /**
121    * Lays out the panel and adds it to the desktop
122    */
123   void init()
124   {
125     setLayout(new BorderLayout());
126     frame = new JInternalFrame();
127     frame.setContentPane(this);
128     this.setBackground(Color.white);
129     frame.addFocusListener(new FocusListener()
130     {
131
132       @Override
133       public void focusLost(FocusEvent e)
134       {
135       }
136
137       @Override
138       public void focusGained(FocusEvent e)
139       {
140         validateCalcTypes();
141       }
142     });
143     /*
144      * Layout consists of 3 or 4 panels:
145      * - first with choice of PCA or tree method NJ or AV
146      * - second with choice of score model
147      * - third with score model parameter options [suppressed]
148      * - fourth with OK and Cancel
149      */
150     pca = new JRadioButton(
151             MessageManager.getString("label.principal_component_analysis"));
152     pca.setOpaque(false);
153     neighbourJoining = new JRadioButton(
154             MessageManager.getString("label.tree_calc_nj"));
155     neighbourJoining.setSelected(true);
156     averageDistance = new JRadioButton(
157             MessageManager.getString("label.tree_calc_av"));
158     neighbourJoining.setOpaque(false);
159
160     JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
161     calcChoicePanel.setOpaque(false);
162
163     // first create the Tree calculation's border panel
164     JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
165     treePanel.setOpaque(false);
166
167     treePanel.setBorder(BorderFactory.createTitledBorder(MessageManager
168             .getString("label.tree")));
169
170     // then copy the inset dimensions for the border-less PCA panel
171     JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
172     Insets b = treePanel.getBorder().getBorderInsets(treePanel);
173     pcaBorderless.setBorder(BorderFactory.createEmptyBorder(2, b.left, 2,
174             b.right));
175     pcaBorderless.setOpaque(false);
176
177     pcaBorderless.add(pca, FlowLayout.LEFT);
178     calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
179
180     treePanel.add(neighbourJoining);
181     treePanel.add(averageDistance);
182
183     calcChoicePanel.add(treePanel);
184
185     ButtonGroup calcTypes = new ButtonGroup();
186     calcTypes.add(pca);
187     calcTypes.add(neighbourJoining);
188     calcTypes.add(averageDistance);
189     
190     ActionListener calcChanged = new ActionListener()
191     {
192       @Override
193       public void actionPerformed(ActionEvent e)
194       {
195         validateCalcTypes();
196       }
197     };
198     pca.addActionListener(calcChanged);
199     neighbourJoining.addActionListener(calcChanged);
200     averageDistance.addActionListener(calcChanged);
201
202     /*
203      * score models drop-down - with added tooltips!
204      */
205     modelNames = buildModelOptionsList();
206
207     JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
208     scoreModelPanel.setOpaque(false);
209     scoreModelPanel.add(modelNames);
210
211     /*
212      * score model parameters
213      */
214     JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
215     paramsPanel.setOpaque(false);
216     includeGaps = new JCheckBox("Include gaps");
217     matchGaps = new JCheckBox("Match gaps");
218     includeGappedColumns = new JCheckBox("Include gapped columns");
219     shorterSequence = new JCheckBox("Match on shorter sequence");
220     paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
221     paramsPanel.add(includeGaps);
222     paramsPanel.add(matchGaps);
223     paramsPanel.add(includeGappedColumns);
224     paramsPanel.add(shorterSequence);
225
226     /*
227      * OK / Cancel buttons
228      */
229     calculate = new JButton(MessageManager.getString("action.calculate"));
230     calculate.setFont(VERDANA_11PT);
231     calculate.addActionListener(new java.awt.event.ActionListener()
232     {
233       @Override
234       public void actionPerformed(ActionEvent e)
235       {
236         calculate_actionPerformed();
237       }
238     });
239     JButton close = new JButton(MessageManager.getString("action.close"));
240     close.setFont(VERDANA_11PT);
241     close.addActionListener(new java.awt.event.ActionListener()
242     {
243       @Override
244       public void actionPerformed(ActionEvent e)
245       {
246         close_actionPerformed();
247       }
248     });
249     JPanel actionPanel = new JPanel();
250     actionPanel.setOpaque(false);
251     actionPanel.add(calculate);
252     actionPanel.add(close);
253
254     boolean includeParams = false;
255     this.add(calcChoicePanel, BorderLayout.CENTER);
256     calcChoicePanel.add(scoreModelPanel);
257     if (includeParams)
258     {
259       scoreModelPanel.add(paramsPanel);
260     }
261     this.add(actionPanel, BorderLayout.SOUTH);
262
263     int width = 350;
264     int height = includeParams ? 420 : 240;
265
266     setMinimumSize(new Dimension(325, height - 10));
267     String title = MessageManager.getString("label.choose_calculation");
268     if (af.getViewport().viewName != null)
269     {
270       title = title + " (" + af.getViewport().viewName + ")";
271     }
272
273     Desktop.addInternalFrame(frame, title, width, height, false);
274     calcChoicePanel.doLayout();
275     revalidate();
276     /*
277      * null the AlignmentPanel's reference to the dialog when it is closed
278      */
279     frame.addInternalFrameListener(new InternalFrameAdapter()
280     {
281       @Override
282       public void internalFrameClosed(InternalFrameEvent evt)
283       {
284         af.alignPanel.setCalculationDialog(null);
285       };
286     });
287
288     frame.setLayer(JLayeredPane.PALETTE_LAYER);
289   }
290
291   /**
292    * enable calculations applicable for the current alignment or selection.
293    */
294   protected void validateCalcTypes()
295   {
296     int size = af.getViewport().getAlignment().getHeight();
297     if (af.getViewport().getSelectionGroup() != null)
298     {
299       size = af.getViewport().getSelectionGroup().getSize();
300     }
301
302     /*
303      * disable calc options for which there is insufficient input data
304      * return value of true means enabled and selected
305      */
306     boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
307     boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
308             MIN_TREE_SELECTION);
309     boolean checkAverageDistance = checkEnabled(averageDistance, size,
310             MIN_TREE_SELECTION);
311
312     if (checkPca || checkNeighbourJoining || checkAverageDistance)
313     {
314       calculate.setToolTipText(null);
315       calculate.setEnabled(true);
316     }
317     else
318     {
319       calculate.setEnabled(false);
320     }
321     updateScoreModels(modelNames, tips);
322   }
323
324   /**
325    * Check the input and disable a calculation's radio button if necessary. A
326    * tooltip is shown for disabled calculations.
327    * 
328    * @param calc
329    *          - radio button for the calculation being validated
330    * @param size
331    *          - size of input to calculation
332    * @param minsize
333    *          - minimum size for calculation
334    * @return true if size >= minsize and calc.isSelected
335    */
336   private boolean checkEnabled(JRadioButton calc, int size, int minsize)
337   {
338     String ttip = MessageManager.formatMessage(
339             "label.you_need_at_least_n_sequences", minsize);
340
341     calc.setEnabled(size >= minsize);
342     if (!calc.isEnabled())
343     {
344       calc.setToolTipText(ttip);
345     }
346     else
347     {
348       calc.setToolTipText(null);
349     }
350     if (calc.isSelected())
351     {
352       modelNames.setEnabled(calc.isEnabled());
353       if (calc.isEnabled())
354       {
355         return true;
356       }
357       else
358       {
359         calculate.setToolTipText(ttip);
360       }
361     }
362     return false;
363   }
364
365   /**
366    * A rather elaborate helper method (blame Swing, not me) that builds a
367    * drop-down list of score models (by name) with descriptions as tooltips.
368    * There is also a tooltip shown for the currently selected item when hovering
369    * over it (without opening the list).
370    */
371   protected JComboBox<String> buildModelOptionsList()
372   {
373     final JComboBox<String> scoreModelsCombo = new JComboBox<String>();
374     scoreModelsCombo.setRenderer(renderer);
375
376     /*
377      * show tooltip on mouse over the combobox
378      * note the listener has to be on the components that make up
379      * the combobox, doesn't work if just on the combobox
380      */
381     final MouseAdapter mouseListener = new MouseAdapter()
382     {
383       @Override
384       public void mouseEntered(MouseEvent e)
385       {
386         scoreModelsCombo.setToolTipText(tips.get(scoreModelsCombo.getSelectedIndex()));
387       }
388
389       @Override
390       public void mouseExited(MouseEvent e)
391       {
392         scoreModelsCombo.setToolTipText(null);
393       }
394     };
395     for (Component c : scoreModelsCombo.getComponents())
396     {
397       c.addMouseListener(mouseListener);
398     }
399
400     updateScoreModels(scoreModelsCombo, tips);
401
402     /*
403      * set the list of tooltips on the combobox's renderer
404      */
405     renderer.setTooltips(tips);
406
407     return scoreModelsCombo;
408   }
409
410   private void updateScoreModels(JComboBox<String> comboBox,
411           List<String> toolTips)
412   {
413     Object curSel = comboBox.getSelectedItem();
414     toolTips.clear();
415     DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
416
417     /*
418      * now we can actually add entries to the combobox,
419      * remembering their descriptions for tooltips
420      */
421     ScoreModels scoreModels = ScoreModels.getInstance();
422     boolean selectedIsPresent = false;
423     for (ScoreModelI sm : scoreModels.getModels())
424     {
425       boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
426       if (sm.isDNA() && nucleotide || sm.isProtein() && !nucleotide)
427       {
428         if (curSel != null && sm.getName().equals(curSel))
429         {
430           selectedIsPresent = true;
431           curSel = sm.getName();
432         }
433         model.addElement(sm.getName());
434
435         /*
436          * tooltip is description if provided, else text lookup with
437          * fallback on the model name
438          */
439         String tooltip = sm.getDescription();
440         if (tooltip == null)
441         {
442           tooltip = MessageManager.getStringOrReturn("label.score_model_",
443                   sm.getName());
444         }
445         toolTips.add(tooltip);
446       }
447     }
448     if (selectedIsPresent)
449     {
450       model.setSelectedItem(curSel);
451     }
452     // finally, update the model
453     comboBox.setModel(model);
454   }
455
456   /**
457    * Open and calculate the selected tree or PCA on 'OK'
458    */
459   protected void calculate_actionPerformed()
460   {
461     boolean doPCA = pca.isSelected();
462     String modelName = modelNames.getSelectedItem().toString();
463     SimilarityParamsI params = getSimilarityParameters(doPCA);
464
465     if (doPCA)
466     {
467       openPcaPanel(modelName, params);
468     }
469     else
470     {
471       openTreePanel(modelName, params);
472     }
473
474     // closeFrame();
475   }
476
477   /**
478    * Open a new Tree panel on the desktop
479    * 
480    * @param modelName
481    * @param params
482    */
483   protected void openTreePanel(String modelName, SimilarityParamsI params)
484   {
485     /*
486      * gui validation shouldn't allow insufficient sequences here, but leave
487      * this check in in case this method gets exposed programmatically in future
488      */
489     AlignViewport viewport = af.getViewport();
490     SequenceGroup sg = viewport.getSelectionGroup();
491     if (sg != null && sg.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 }