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