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.TreeBuilder;
56 import jalview.analysis.scoremodels.ScoreModels;
57 import jalview.analysis.scoremodels.SimilarityParams;
58 import jalview.api.analysis.ScoreModelI;
59 import jalview.api.analysis.SimilarityParamsI;
60 import jalview.bin.Cache;
61 import jalview.datamodel.AlignmentAnnotation;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.util.MessageManager;
66 * A dialog where a user can choose and action Tree or PCA calculation options
68 public class CalculationChooser extends JPanel
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
76 private static boolean treeMatchGaps = true;
78 private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
80 private static final int MIN_TREE_SELECTION = 3;
82 private static final int MIN_PCA_SELECTION = 4;
84 private static final String SS_ANNOTATION_LABEL = "Secondary Structure";
86 private static final String SS_ANNOTATION_FROM_JPRED_LABEL = "jnetpred";
92 JRadioButton neighbourJoining;
94 JRadioButton averageDistance;
96 JComboBox<String> modelNames;
98 JComboBox<String> ssSourceDropdown;
102 private JInternalFrame frame;
104 private JCheckBox includeGaps;
106 private JCheckBox matchGaps;
108 private JCheckBox includeGappedColumns;
110 private JCheckBox shorterSequence;
112 final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
114 List<String> tips = new ArrayList<>();
117 * the most recently opened PCA results panel
119 private PCAPanel pcaPanel;
126 public CalculationChooser(AlignFrame alignFrame)
128 this.af = alignFrame;
130 af.alignPanel.setCalculationDialog(this);
134 * Lays out the panel and adds it to the desktop
138 setLayout(new BorderLayout());
139 frame = new JInternalFrame();
140 frame.setFrameIcon(null);
141 frame.setContentPane(this);
142 this.setBackground(Color.white);
143 frame.addFocusListener(new FocusListener()
147 public void focusLost(FocusEvent e)
152 public void focusGained(FocusEvent e)
158 * Layout consists of 3 or 4 panels:
159 * - first with choice of PCA or tree method NJ or AV
160 * - second with choice of score model
161 * - third with score model parameter options [suppressed]
162 * - fourth with OK and Cancel
164 pca = new JRadioButton(
165 MessageManager.getString("label.principal_component_analysis"));
166 pca.setOpaque(false);
168 neighbourJoining = new JRadioButton(
169 MessageManager.getString("label.tree_calc_nj"));
170 neighbourJoining.setSelected(true);
171 neighbourJoining.setOpaque(false);
173 averageDistance = new JRadioButton(
174 MessageManager.getString("label.tree_calc_av"));
175 averageDistance.setOpaque(false);
177 JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
178 calcChoicePanel.setOpaque(false);
180 // first create the Tree calculation's border panel
181 JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
182 treePanel.setOpaque(false);
184 JvSwingUtils.createTitledBorder(treePanel,
185 MessageManager.getString("label.tree"), true);
187 // then copy the inset dimensions for the border-less PCA panel
188 JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
189 Insets b = treePanel.getBorder().getBorderInsets(treePanel);
190 pcaBorderless.setBorder(
191 BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
192 pcaBorderless.setOpaque(false);
194 pcaBorderless.add(pca, FlowLayout.LEFT);
195 calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
197 treePanel.add(neighbourJoining);
198 treePanel.add(averageDistance);
200 calcChoicePanel.add(treePanel);
202 ButtonGroup calcTypes = new ButtonGroup();
204 calcTypes.add(neighbourJoining);
205 calcTypes.add(averageDistance);
207 ActionListener calcChanged = new ActionListener()
210 public void actionPerformed(ActionEvent e)
215 pca.addActionListener(calcChanged);
216 neighbourJoining.addActionListener(calcChanged);
217 averageDistance.addActionListener(calcChanged);
221 ssSourceDropdown = buildSSSourcesOptionsList();
222 ssSourceDropdown.setVisible(false); // Initially hide the dropdown
225 * score models drop-down - with added tooltips!
227 modelNames = buildModelOptionsList();
228 // Step 3: Show or Hide Dropdown Based on Selection
229 modelNames.addActionListener(new ActionListener() {
231 public void actionPerformed(ActionEvent e) {
232 String selectedModel = modelNames.getSelectedItem().toString();
233 if (selectedModel.equals("Secondary Structure Similarity")) {
234 ssSourceDropdown.setVisible(true);
236 ssSourceDropdown.setVisible(false);
241 JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
242 scoreModelPanel.setOpaque(false);
243 scoreModelPanel.add(modelNames);
244 scoreModelPanel.add(ssSourceDropdown);
247 * score model parameters
249 JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
250 paramsPanel.setOpaque(false);
251 includeGaps = new JCheckBox("Include gaps");
252 matchGaps = new JCheckBox("Match gaps");
253 includeGappedColumns = new JCheckBox("Include gapped columns");
254 shorterSequence = new JCheckBox("Match on shorter sequence");
255 paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
256 paramsPanel.add(includeGaps);
257 paramsPanel.add(matchGaps);
258 paramsPanel.add(includeGappedColumns);
259 paramsPanel.add(shorterSequence);
262 * OK / Cancel buttons
264 calculate = new JButton(MessageManager.getString("action.calculate"));
265 calculate.setFont(VERDANA_11PT);
266 calculate.addActionListener(new java.awt.event.ActionListener()
269 public void actionPerformed(ActionEvent e)
271 calculate_actionPerformed();
274 JButton close = new JButton(MessageManager.getString("action.close"));
275 close.setFont(VERDANA_11PT);
276 close.addActionListener(new java.awt.event.ActionListener()
279 public void actionPerformed(ActionEvent e)
281 close_actionPerformed();
284 JPanel actionPanel = new JPanel();
285 actionPanel.setOpaque(false);
286 actionPanel.add(calculate);
287 actionPanel.add(close);
289 boolean includeParams = false;
290 this.add(calcChoicePanel, BorderLayout.CENTER);
291 calcChoicePanel.add(scoreModelPanel);
294 scoreModelPanel.add(paramsPanel);
296 this.add(actionPanel, BorderLayout.SOUTH);
299 int height = includeParams ? 420 : 240;
301 setMinimumSize(new Dimension(325, height - 10));
302 String title = MessageManager.getString("label.choose_calculation");
303 if (af.getViewport().getViewName() != null)
305 title = title + " (" + af.getViewport().getViewName() + ")";
308 Desktop.addInternalFrame(frame, title, width, height, false);
309 calcChoicePanel.doLayout();
312 * null the AlignmentPanel's reference to the dialog when it is closed
314 frame.addInternalFrameListener(new InternalFrameAdapter()
317 public void internalFrameClosed(InternalFrameEvent evt)
319 af.alignPanel.setCalculationDialog(null);
324 frame.setLayer(JLayeredPane.PALETTE_LAYER);
328 * enable calculations applicable for the current alignment or selection.
330 protected void validateCalcTypes()
332 int size = af.getViewport().getAlignment().getHeight();
333 if (af.getViewport().getSelectionGroup() != null)
335 size = af.getViewport().getSelectionGroup().getSize();
339 * disable calc options for which there is insufficient input data
340 * return value of true means enabled and selected
342 boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
343 boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
345 boolean checkAverageDistance = checkEnabled(averageDistance, size,
348 if (checkPca || checkNeighbourJoining || checkAverageDistance)
350 calculate.setToolTipText(null);
351 calculate.setEnabled(true);
355 calculate.setEnabled(false);
357 updateScoreModels(modelNames, tips);
361 * Check the input and disable a calculation's radio button if necessary. A
362 * tooltip is shown for disabled calculations.
365 * - radio button for the calculation being validated
367 * - size of input to calculation
369 * - minimum size for calculation
370 * @return true if size >= minsize and calc.isSelected
372 private boolean checkEnabled(JRadioButton calc, int size, int minsize)
374 String ttip = MessageManager
375 .formatMessage("label.you_need_at_least_n_sequences", minsize);
377 calc.setEnabled(size >= minsize);
378 if (!calc.isEnabled())
380 calc.setToolTipText(ttip);
384 calc.setToolTipText(null);
386 if (calc.isSelected())
388 modelNames.setEnabled(calc.isEnabled());
389 if (calc.isEnabled())
395 calculate.setToolTipText(ttip);
402 * A rather elaborate helper method (blame Swing, not me) that builds a
403 * drop-down list of score models (by name) with descriptions as tooltips.
404 * There is also a tooltip shown for the currently selected item when hovering
405 * over it (without opening the list).
407 protected JComboBox<String> buildModelOptionsList()
409 final JComboBox<String> scoreModelsCombo = new JComboBox<>();
410 scoreModelsCombo.setRenderer(renderer);
413 * show tooltip on mouse over the combobox
414 * note the listener has to be on the components that make up
415 * the combobox, doesn't work if just on the combobox
417 final MouseAdapter mouseListener = new MouseAdapter()
420 public void mouseEntered(MouseEvent e)
422 scoreModelsCombo.setToolTipText(
423 tips.get(scoreModelsCombo.getSelectedIndex()));
427 public void mouseExited(MouseEvent e)
429 scoreModelsCombo.setToolTipText(null);
432 for (Component c : scoreModelsCombo.getComponents())
434 c.addMouseListener(mouseListener);
437 updateScoreModels(scoreModelsCombo, tips);
440 * set the list of tooltips on the combobox's renderer
442 renderer.setTooltips(tips);
444 return scoreModelsCombo;
448 private JComboBox<String> buildSSSourcesOptionsList()
450 final JComboBox<String> comboBox = new JComboBox<>();
451 Object curSel = comboBox.getSelectedItem();
452 DefaultComboBoxModel<String> sourcesModel = new DefaultComboBoxModel<>();
454 List<String> ssSources = getApplicableSecondaryStructureSources();
456 boolean selectedIsPresent = false;
457 for (String source : ssSources)
459 if (curSel != null && source.equals(curSel))
461 selectedIsPresent = true;
464 sourcesModel.addElement(source);
468 if (selectedIsPresent)
470 sourcesModel.setSelectedItem(curSel);
472 comboBox.setModel(sourcesModel);
478 private void updateScoreModels(JComboBox<String> comboBox,
479 List<String> toolTips)
481 Object curSel = comboBox.getSelectedItem();
483 DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
486 * select the score models applicable to the alignment type
488 boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
489 AlignmentAnnotation[] alignmentAnnotation = af.getViewport().getAlignment().getAlignmentAnnotation();
491 boolean ssPresent = false;
493 for (AlignmentAnnotation aa : alignmentAnnotation)
500 if (aa.label.equals("Secondary Structure") || aa.label.equals("jnetpred"))
508 List<ScoreModelI> models = getApplicableScoreModels(nucleotide, pca.isSelected(),
512 * now we can actually add entries to the combobox,
513 * remembering their descriptions for tooltips
515 boolean selectedIsPresent = false;
516 for (ScoreModelI sm : models)
518 if (curSel != null && sm.getName().equals(curSel))
520 selectedIsPresent = true;
521 curSel = sm.getName();
523 model.addElement(sm.getName());
526 * tooltip is description if provided, else text lookup with
527 * fallback on the model name
529 String tooltip = sm.getDescription();
532 tooltip = MessageManager.getStringOrReturn("label.score_model_",
535 toolTips.add(tooltip);
538 if (selectedIsPresent)
540 model.setSelectedItem(curSel);
542 // finally, update the model
543 comboBox.setModel(model);
547 * Builds a list of score models which are applicable for the alignment and
548 * calculation type (peptide or generic models for protein, nucleotide or
549 * generic models for nucleotide).
551 * As a special case, includes BLOSUM62 as an extra option for nucleotide PCA.
552 * This is for backwards compatibility with Jalview prior to 2.8 when BLOSUM62
553 * was the only score matrix supported. This is included if property
554 * BLOSUM62_PCA_FOR_NUCLEOTIDE is set to true in the Jalview properties file.
560 protected static List<ScoreModelI> getApplicableScoreModels(
561 boolean nucleotide, boolean forPca, boolean ssPresent)
563 List<ScoreModelI> filtered = new ArrayList<>();
565 ScoreModels scoreModels = ScoreModels.getInstance();
566 for (ScoreModelI sm : scoreModels.getModels())
568 if (!nucleotide && sm.isProtein() || nucleotide && sm.isDNA()
569 || ssPresent && sm.isSecondaryStructure())
576 * special case: add BLOSUM62 as last option for nucleotide PCA,
577 * for backwards compatibility with Jalview < 2.8 (JAL-2962)
579 if (nucleotide && forPca
580 && Cache.getDefault("BLOSUM62_PCA_FOR_NUCLEOTIDE", false))
582 filtered.add(scoreModels.getBlosum62());
589 protected List<String> getApplicableSecondaryStructureSources()
591 List<String> ssSources = new ArrayList<>();
593 AlignmentAnnotation[] annotations = af.getViewport().getAlignment().getAlignmentAnnotation();
594 boolean has3DStructure = false, hasJPred = false;
595 if(annotations.length > 0) {
597 for (AlignmentAnnotation annotation : annotations) {
598 has3DStructure |= SS_ANNOTATION_LABEL.equals(annotation.label);
599 hasJPred |= SS_ANNOTATION_FROM_JPRED_LABEL.equals(annotation.label);
601 if (has3DStructure && hasJPred)
606 ssSources.add("3D Structures");
608 ssSources.add("JPred");
614 * Open and calculate the selected tree or PCA on 'OK'
616 protected void calculate_actionPerformed()
618 boolean doPCA = pca.isSelected();
619 String modelName = modelNames.getSelectedItem().toString();
620 String ssSource = ssSourceDropdown.getSelectedItem().toString();
621 SimilarityParams params = getSimilarityParameters(doPCA);
622 if(ssSource.length()>0)
623 params.setSecondaryStructureSource(ssSource);
626 openPcaPanel(modelName, params);
630 openTreePanel(modelName, params);
637 * Open a new Tree panel on the desktop
642 protected void openTreePanel(String modelName, SimilarityParamsI params)
645 * gui validation shouldn't allow insufficient sequences here, but leave
646 * this check in in case this method gets exposed programmatically in future
648 AlignViewport viewport = af.getViewport();
649 SequenceGroup sg = viewport.getSelectionGroup();
650 if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
652 JvOptionPane.showMessageDialog(Desktop.desktop,
653 MessageManager.formatMessage(
654 "label.you_need_at_least_n_sequences",
656 MessageManager.getString("label.not_enough_sequences"),
657 JvOptionPane.WARNING_MESSAGE);
661 String treeType = neighbourJoining.isSelected()
662 ? TreeBuilder.NEIGHBOUR_JOINING
663 : TreeBuilder.AVERAGE_DISTANCE;
664 af.newTreePanel(treeType, modelName, params);
668 * Open a new PCA panel on the desktop
673 protected void openPcaPanel(String modelName, SimilarityParamsI params)
675 AlignViewport viewport = af.getViewport();
678 * gui validation shouldn't allow insufficient sequences here, but leave
679 * this check in in case this method gets exposed programmatically in future
681 if (((viewport.getSelectionGroup() != null)
682 && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
683 && (viewport.getSelectionGroup().getSize() > 0))
684 || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
686 JvOptionPane.showInternalMessageDialog(this,
687 MessageManager.formatMessage(
688 "label.you_need_at_least_n_sequences",
691 .getString("label.sequence_selection_insufficient"),
692 JvOptionPane.WARNING_MESSAGE);
697 * construct the panel and kick off its calculation thread
699 pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
700 new Thread(pcaPanel).start();
707 protected void closeFrame()
711 frame.setClosed(true);
712 } catch (PropertyVetoException ex)
718 * Returns a data bean holding parameters for similarity (or distance) model
724 protected SimilarityParams getSimilarityParameters(boolean doPCA)
726 // commented out: parameter choices read from gui widgets
727 // SimilarityParamsI params = new SimilarityParams(
728 // includeGappedColumns.isSelected(), matchGaps.isSelected(),
729 // includeGaps.isSelected(), shorterSequence.isSelected());
731 boolean includeGapGap = true;
732 boolean includeGapResidue = true;
733 boolean matchOnShortestLength = false;
736 * 'matchGaps' flag is only used in the PID calculation
737 * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
738 * - set to true for Tree to reproduce Jalview 2.10.1 calculation
739 * - set to false for Tree for a more correct calculation (JAL-374)
741 boolean matchGap = doPCA ? false : treeMatchGaps;
743 return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
744 matchOnShortestLength);
748 * Closes dialog on Close button press
750 protected void close_actionPerformed()
754 frame.setClosed(true);
755 } catch (Exception ex)
760 public PCAPanel getPcaPanel()