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