a9f396634a63e9746e8ce405380ada7ec38b087e
[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
168             .createTitledBorder(MessageManager.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(
174             BorderFactory.createEmptyBorder(2, b.left, 2, 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
339             .formatMessage("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(
387                 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     SequenceGroup sg = viewport.getSelectionGroup();
492     if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
493     {
494       JvOptionPane.showMessageDialog(Desktop.desktop,
495               MessageManager.formatMessage(
496                       "label.you_need_at_least_n_sequences",
497                       MIN_TREE_SELECTION),
498               MessageManager.getString("label.not_enough_sequences"),
499               JvOptionPane.WARNING_MESSAGE);
500       return;
501     }
502
503     String treeType = neighbourJoining.isSelected()
504             ? TreeBuilder.NEIGHBOUR_JOINING
505             : TreeBuilder.AVERAGE_DISTANCE;
506     af.newTreePanel(treeType, modelName, params);
507   }
508
509   /**
510    * Open a new PCA panel on the desktop
511    * 
512    * @param modelName
513    * @param params
514    */
515   protected void openPcaPanel(String modelName, SimilarityParamsI params)
516   {
517     AlignViewport viewport = af.getViewport();
518
519     /*
520      * gui validation shouldn't allow insufficient sequences here, but leave
521      * this check in in case this method gets exposed programmatically in future
522      */
523     if (((viewport.getSelectionGroup() != null)
524             && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
525             && (viewport.getSelectionGroup().getSize() > 0))
526             || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
527     {
528       JvOptionPane.showInternalMessageDialog(this,
529               MessageManager.formatMessage(
530                       "label.you_need_at_least_n_sequences",
531                       MIN_PCA_SELECTION),
532               MessageManager
533                       .getString("label.sequence_selection_insufficient"),
534               JvOptionPane.WARNING_MESSAGE);
535       return;
536     }
537     new PCAPanel(af.alignPanel, modelName, params);
538   }
539
540   /**
541    * 
542    */
543   protected void closeFrame()
544   {
545     try
546     {
547       frame.setClosed(true);
548     } catch (PropertyVetoException ex)
549     {
550     }
551   }
552
553   /**
554    * Returns a data bean holding parameters for similarity (or distance) model
555    * calculation
556    * 
557    * @param doPCA
558    * @return
559    */
560   protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
561   {
562     // commented out: parameter choices read from gui widgets
563     // SimilarityParamsI params = new SimilarityParams(
564     // includeGappedColumns.isSelected(), matchGaps.isSelected(),
565     // includeGaps.isSelected(), shorterSequence.isSelected());
566
567     boolean includeGapGap = true;
568     boolean includeGapResidue = true;
569     boolean matchOnShortestLength = false;
570
571     /*
572      * 'matchGaps' flag is only used in the PID calculation
573      * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
574      * - set to true for Tree to reproduce Jalview 2.10.1 calculation
575      * - set to false for Tree for a more correct calculation (JAL-374)
576      */
577     boolean matchGap = doPCA ? false : treeMatchGaps;
578
579     return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
580             matchOnShortestLength);
581   }
582
583   /**
584    * Closes dialog on Close button press
585    */
586   protected void close_actionPerformed()
587   {
588     try
589     {
590       frame.setClosed(true);
591     } catch (Exception ex)
592     {
593     }
594   }
595 }