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