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