2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
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;
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;
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;
55 import jalview.analysis.AlignmentUtils;
56 import jalview.analysis.TreeBuilder;
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.AlignmentAnnotation;
63 import jalview.datamodel.SequenceGroup;
64 import jalview.util.MessageManager;
67 * A dialog where a user can choose and action Tree or PCA calculation options
69 public class CalculationChooser extends JPanel
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
77 private static boolean treeMatchGaps = true;
79 private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
81 private static final int MIN_TREE_SELECTION = 3;
83 private static final int MIN_PCA_SELECTION = 4;
85 private String secondaryStructureModelName;
87 private void getSecondaryStructureModelName() {
89 ScoreModels scoreModels = ScoreModels.getInstance();
90 for (ScoreModelI sm : scoreModels.getModels())
92 if (sm.isSecondaryStructure())
94 secondaryStructureModelName = sm.getName();
104 JRadioButton neighbourJoining;
106 JRadioButton averageDistance;
108 JComboBox<String> modelNames;
110 JComboBox<String> ssSourceDropdown;
114 private JInternalFrame frame;
116 private JCheckBox includeGaps;
118 private JCheckBox matchGaps;
120 private JCheckBox includeGappedColumns;
122 private JCheckBox shorterSequence;
124 final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
126 List<String> tips = new ArrayList<>();
129 * the most recently opened PCA results panel
131 private PCAPanel pcaPanel;
138 public CalculationChooser(AlignFrame alignFrame)
140 this.af = alignFrame;
142 af.alignPanel.setCalculationDialog(this);
147 * Lays out the panel and adds it to the desktop
151 getSecondaryStructureModelName();
152 setLayout(new BorderLayout());
153 frame = new JInternalFrame();
154 frame.setFrameIcon(null);
155 frame.setContentPane(this);
156 this.setBackground(Color.white);
157 frame.addFocusListener(new FocusListener()
161 public void focusLost(FocusEvent e)
166 public void focusGained(FocusEvent e)
172 * Layout consists of 3 or 4 panels:
173 * - first with choice of PCA or tree method NJ or AV
174 * - second with choice of score model
175 * - third with score model parameter options [suppressed]
176 * - fourth with OK and Cancel
178 pca = new JRadioButton(
179 MessageManager.getString("label.principal_component_analysis"));
180 pca.setOpaque(false);
182 neighbourJoining = new JRadioButton(
183 MessageManager.getString("label.tree_calc_nj"));
184 neighbourJoining.setSelected(true);
185 neighbourJoining.setOpaque(false);
187 averageDistance = new JRadioButton(
188 MessageManager.getString("label.tree_calc_av"));
189 averageDistance.setOpaque(false);
191 JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
192 calcChoicePanel.setOpaque(false);
194 // first create the Tree calculation's border panel
195 JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
196 treePanel.setOpaque(false);
198 JvSwingUtils.createTitledBorder(treePanel,
199 MessageManager.getString("label.tree"), true);
201 // then copy the inset dimensions for the border-less PCA panel
202 JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
203 Insets b = treePanel.getBorder().getBorderInsets(treePanel);
204 pcaBorderless.setBorder(
205 BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
206 pcaBorderless.setOpaque(false);
208 pcaBorderless.add(pca, FlowLayout.LEFT);
209 calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
211 treePanel.add(neighbourJoining);
212 treePanel.add(averageDistance);
214 calcChoicePanel.add(treePanel);
216 ButtonGroup calcTypes = new ButtonGroup();
218 calcTypes.add(neighbourJoining);
219 calcTypes.add(averageDistance);
221 ActionListener calcChanged = new ActionListener()
224 public void actionPerformed(ActionEvent e)
229 pca.addActionListener(calcChanged);
230 neighbourJoining.addActionListener(calcChanged);
231 averageDistance.addActionListener(calcChanged);
235 ssSourceDropdown = buildSSSourcesOptionsList();
236 ssSourceDropdown.setVisible(false); // Initially hide the dropdown
239 * score models drop-down - with added tooltips!
241 modelNames = buildModelOptionsList();
243 // Step 3: Show or Hide Dropdown Based on Selection
244 modelNames.addActionListener(new ActionListener() {
246 public void actionPerformed(ActionEvent e) {
247 String selectedModel = modelNames.getSelectedItem().toString();
249 if (selectedModel.equals(secondaryStructureModelName)) {
250 ssSourceDropdown.setVisible(true);
252 ssSourceDropdown.setVisible(false);
258 JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
259 scoreModelPanel.setOpaque(false);
260 scoreModelPanel.add(modelNames);
261 scoreModelPanel.add(ssSourceDropdown);
264 * score model parameters
266 JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
267 paramsPanel.setOpaque(false);
268 includeGaps = new JCheckBox("Include gaps");
269 matchGaps = new JCheckBox("Match gaps");
270 includeGappedColumns = new JCheckBox("Include gapped columns");
271 shorterSequence = new JCheckBox("Match on shorter sequence");
272 paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
273 paramsPanel.add(includeGaps);
274 paramsPanel.add(matchGaps);
275 paramsPanel.add(includeGappedColumns);
276 paramsPanel.add(shorterSequence);
279 * OK / Cancel buttons
281 calculate = new JButton(MessageManager.getString("action.calculate"));
282 calculate.setFont(VERDANA_11PT);
283 calculate.addActionListener(new java.awt.event.ActionListener()
286 public void actionPerformed(ActionEvent e)
288 calculate_actionPerformed();
291 JButton close = new JButton(MessageManager.getString("action.close"));
292 close.setFont(VERDANA_11PT);
293 close.addActionListener(new java.awt.event.ActionListener()
296 public void actionPerformed(ActionEvent e)
298 close_actionPerformed();
301 JPanel actionPanel = new JPanel();
302 actionPanel.setOpaque(false);
303 actionPanel.add(calculate);
304 actionPanel.add(close);
306 boolean includeParams = false;
307 this.add(calcChoicePanel, BorderLayout.CENTER);
308 calcChoicePanel.add(scoreModelPanel);
311 scoreModelPanel.add(paramsPanel);
313 this.add(actionPanel, BorderLayout.SOUTH);
316 int height = includeParams ? 420 : 240;
318 setMinimumSize(new Dimension(325, height - 10));
319 String title = MessageManager.getString("label.choose_calculation");
320 if (af.getViewport().getViewName() != null)
322 title = title + " (" + af.getViewport().getViewName() + ")";
325 Desktop.addInternalFrame(frame, title, width, height, false);
326 calcChoicePanel.doLayout();
329 * null the AlignmentPanel's reference to the dialog when it is closed
331 frame.addInternalFrameListener(new InternalFrameAdapter()
334 public void internalFrameClosed(InternalFrameEvent evt)
336 af.alignPanel.setCalculationDialog(null);
341 frame.setLayer(JLayeredPane.PALETTE_LAYER);
345 * enable calculations applicable for the current alignment or selection.
347 protected void validateCalcTypes()
349 int size = af.getViewport().getAlignment().getHeight();
350 if (af.getViewport().getSelectionGroup() != null)
352 size = af.getViewport().getSelectionGroup().getSize();
356 * disable calc options for which there is insufficient input data
357 * return value of true means enabled and selected
359 boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
360 boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
362 boolean checkAverageDistance = checkEnabled(averageDistance, size,
365 if (checkPca || checkNeighbourJoining || checkAverageDistance)
367 calculate.setToolTipText(null);
368 calculate.setEnabled(true);
372 calculate.setEnabled(false);
374 updateScoreModels(modelNames, tips);
378 * Check the input and disable a calculation's radio button if necessary. A
379 * tooltip is shown for disabled calculations.
382 * - radio button for the calculation being validated
384 * - size of input to calculation
386 * - minimum size for calculation
387 * @return true if size >= minsize and calc.isSelected
389 private boolean checkEnabled(JRadioButton calc, int size, int minsize)
391 String ttip = MessageManager
392 .formatMessage("label.you_need_at_least_n_sequences", minsize);
394 calc.setEnabled(size >= minsize);
395 if (!calc.isEnabled())
397 calc.setToolTipText(ttip);
401 calc.setToolTipText(null);
403 if (calc.isSelected())
405 modelNames.setEnabled(calc.isEnabled());
406 if (calc.isEnabled())
412 calculate.setToolTipText(ttip);
419 * A rather elaborate helper method (blame Swing, not me) that builds a
420 * drop-down list of score models (by name) with descriptions as tooltips.
421 * There is also a tooltip shown for the currently selected item when hovering
422 * over it (without opening the list).
424 protected JComboBox<String> buildModelOptionsList()
426 final JComboBox<String> scoreModelsCombo = new JComboBox<>();
427 scoreModelsCombo.setRenderer(renderer);
430 * show tooltip on mouse over the combobox
431 * note the listener has to be on the components that make up
432 * the combobox, doesn't work if just on the combobox
434 final MouseAdapter mouseListener = new MouseAdapter()
437 public void mouseEntered(MouseEvent e)
439 scoreModelsCombo.setToolTipText(
440 tips.get(scoreModelsCombo.getSelectedIndex()));
444 public void mouseExited(MouseEvent e)
446 scoreModelsCombo.setToolTipText(null);
449 for (Component c : scoreModelsCombo.getComponents())
451 c.addMouseListener(mouseListener);
454 updateScoreModels(scoreModelsCombo, tips);
457 * set the list of tooltips on the combobox's renderer
459 renderer.setTooltips(tips);
461 return scoreModelsCombo;
465 private JComboBox<String> buildSSSourcesOptionsList()
467 final JComboBox<String> comboBox = new JComboBox<>();
468 Object curSel = comboBox.getSelectedItem();
469 DefaultComboBoxModel<String> sourcesModel = new DefaultComboBoxModel<>();
471 List<String> ssSources = getApplicableSecondaryStructureSources();
473 boolean selectedIsPresent = false;
474 for (String source : ssSources)
476 if (curSel != null && source.equals(curSel))
478 selectedIsPresent = true;
481 sourcesModel.addElement(source);
485 if (selectedIsPresent)
487 sourcesModel.setSelectedItem(curSel);
489 comboBox.setModel(sourcesModel);
495 private void updateScoreModels(JComboBox<String> comboBox,
496 List<String> toolTips)
498 Object curSel = comboBox.getSelectedItem();
500 DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
503 * select the score models applicable to the alignment type
505 boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
506 AlignmentAnnotation[] alignmentAnnotations = af.getViewport().getAlignment().getAlignmentAnnotation();
508 boolean ssPresent = AlignmentUtils.isSecondaryStructurePresent(alignmentAnnotations);
510 List<ScoreModelI> models = getApplicableScoreModels(nucleotide, pca.isSelected(),
514 * now we can actually add entries to the combobox,
515 * remembering their descriptions for tooltips
517 boolean selectedIsPresent = false;
518 for (ScoreModelI sm : models)
520 if (curSel != null && sm.getName().equals(curSel))
522 selectedIsPresent = true;
523 curSel = sm.getName();
525 model.addElement(sm.getName());
528 * tooltip is description if provided, else text lookup with
529 * fallback on the model name
531 String tooltip = sm.getDescription();
534 tooltip = MessageManager.getStringOrReturn("label.score_model_",
537 toolTips.add(tooltip);
540 if (selectedIsPresent)
542 model.setSelectedItem(curSel);
544 // finally, update the model
545 comboBox.setModel(model);
550 * Builds a list of score models which are applicable for the alignment and
551 * calculation type (peptide or generic models for protein, nucleotide or
552 * generic models for nucleotide).
554 * As a special case, includes BLOSUM62 as an extra option for nucleotide PCA.
555 * This is for backwards compatibility with Jalview prior to 2.8 when BLOSUM62
556 * was the only score matrix supported. This is included if property
557 * BLOSUM62_PCA_FOR_NUCLEOTIDE is set to true in the Jalview properties file.
563 protected static List<ScoreModelI> getApplicableScoreModels(
564 boolean nucleotide, boolean forPca, boolean ssPresent)
566 List<ScoreModelI> filtered = new ArrayList<>();
568 ScoreModels scoreModels = ScoreModels.getInstance();
569 for (ScoreModelI sm : scoreModels.getModels())
571 if (!nucleotide && sm.isProtein() || nucleotide && sm.isDNA()
572 || ssPresent && sm.isSecondaryStructure())
579 * special case: add BLOSUM62 as last option for nucleotide PCA,
580 * for backwards compatibility with Jalview < 2.8 (JAL-2962)
582 if (nucleotide && forPca
583 && Cache.getDefault("BLOSUM62_PCA_FOR_NUCLEOTIDE", false))
585 filtered.add(scoreModels.getBlosum62());
592 protected List<String> getApplicableSecondaryStructureSources()
594 AlignmentAnnotation[] annotations = af.getViewport().getAlignment().getAlignmentAnnotation();
596 List<String> ssSources = AlignmentUtils.getSecondaryStructureSources(annotations);
602 * Open and calculate the selected tree or PCA on 'OK'
604 protected void calculate_actionPerformed()
606 boolean doPCA = pca.isSelected();
607 String modelName = modelNames.getSelectedItem().toString();
608 String ssSource = "";
609 Object selectedItem = ssSourceDropdown.getSelectedItem();
610 if (selectedItem != null) {
611 ssSource = selectedItem.toString();
613 SimilarityParams params = getSimilarityParameters(doPCA);
614 if(ssSource.length()>0)
616 params.setSecondaryStructureSource(ssSource);
620 openPcaPanel(modelName, params);
624 openTreePanel(modelName, params);
631 * Open a new Tree panel on the desktop
636 protected void openTreePanel(String modelName, SimilarityParamsI params)
639 * gui validation shouldn't allow insufficient sequences here, but leave
640 * this check in in case this method gets exposed programmatically in future
642 AlignViewport viewport = af.getViewport();
643 SequenceGroup sg = viewport.getSelectionGroup();
644 if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
646 JvOptionPane.showMessageDialog(Desktop.desktop,
647 MessageManager.formatMessage(
648 "label.you_need_at_least_n_sequences",
650 MessageManager.getString("label.not_enough_sequences"),
651 JvOptionPane.WARNING_MESSAGE);
655 String treeType = neighbourJoining.isSelected()
656 ? TreeBuilder.NEIGHBOUR_JOINING
657 : TreeBuilder.AVERAGE_DISTANCE;
658 af.newTreePanel(treeType, modelName, params);
662 * Open a new PCA panel on the desktop
667 protected void openPcaPanel(String modelName, SimilarityParamsI params)
669 AlignViewport viewport = af.getViewport();
672 * gui validation shouldn't allow insufficient sequences here, but leave
673 * this check in in case this method gets exposed programmatically in future
675 if (((viewport.getSelectionGroup() != null)
676 && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
677 && (viewport.getSelectionGroup().getSize() > 0))
678 || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
680 JvOptionPane.showInternalMessageDialog(this,
681 MessageManager.formatMessage(
682 "label.you_need_at_least_n_sequences",
685 .getString("label.sequence_selection_insufficient"),
686 JvOptionPane.WARNING_MESSAGE);
691 * construct the panel and kick off its calculation thread
693 pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
694 new Thread(pcaPanel).start();
701 protected void closeFrame()
705 frame.setClosed(true);
706 } catch (PropertyVetoException ex)
712 * Returns a data bean holding parameters for similarity (or distance) model
718 protected SimilarityParams getSimilarityParameters(boolean doPCA)
720 // commented out: parameter choices read from gui widgets
721 // SimilarityParamsI params = new SimilarityParams(
722 // includeGappedColumns.isSelected(), matchGaps.isSelected(),
723 // includeGaps.isSelected(), shorterSequence.isSelected());
725 boolean includeGapGap = true;
726 boolean includeGapResidue = true;
727 boolean matchOnShortestLength = false;
730 * 'matchGaps' flag is only used in the PID calculation
731 * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
732 * - set to true for Tree to reproduce Jalview 2.10.1 calculation
733 * - set to false for Tree for a more correct calculation (JAL-374)
735 boolean matchGap = doPCA ? false : treeMatchGaps;
737 return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
738 matchOnShortestLength);
742 * Closes dialog on Close button press
744 protected void close_actionPerformed()
748 frame.setClosed(true);
749 } catch (Exception ex)
754 public PCAPanel getPcaPanel()