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