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