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