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 jalview.analysis.TreeBuilder;
24 import jalview.analysis.scoremodels.ScoreModels;
25 import jalview.analysis.scoremodels.SimilarityParams;
26 import jalview.api.analysis.ScoreModelI;
27 import jalview.api.analysis.SimilarityParamsI;
28 import jalview.bin.Cache;
29 import jalview.datamodel.SequenceGroup;
30 import jalview.util.MessageManager;
31 import jalview.viewmodel.AlignmentViewport;
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;
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;
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;
64 import jalview.analysis.AlignmentUtils;
65 import jalview.analysis.TreeBuilder;
66 import jalview.analysis.scoremodels.ScoreModels;
67 import jalview.analysis.scoremodels.SimilarityParams;
68 import jalview.api.analysis.ScoreModelI;
69 import jalview.api.analysis.SimilarityParamsI;
70 import jalview.bin.Cache;
71 import jalview.datamodel.AlignmentAnnotation;
72 import jalview.datamodel.SequenceGroup;
73 import jalview.util.MessageManager;
76 * A dialog where a user can choose and action Tree or PCA calculation options
78 public class CalculationChooser extends JPanel
81 * flag for whether gap matches residue in the PID calculation for a Tree
82 * - true gives Jalview 2.10.1 behaviour
83 * - set to false (using Groovy) for a more correct tree
86 private static boolean treeMatchGaps = true;
88 private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
90 private static final int MIN_TREE_SELECTION = 3;
92 private static final int MIN_PCA_SELECTION = 4;
94 private String secondaryStructureModelName;
96 private void getSecondaryStructureModelName() {
98 ScoreModels scoreModels = ScoreModels.getInstance();
99 for (ScoreModelI sm : scoreModels.getModels())
101 if (sm.isSecondaryStructure())
103 secondaryStructureModelName = sm.getName();
109 private static final int MIN_PASIMAP_SELECTION = 8;
115 JRadioButton pasimap;
117 JRadioButton neighbourJoining;
119 JRadioButton averageDistance;
121 JComboBox<String> modelNames;
123 JComboBox<String> ssSourceDropdown;
127 private JInternalFrame frame;
129 private JCheckBox includeGaps;
131 private JCheckBox matchGaps;
133 private JCheckBox includeGappedColumns;
135 private JCheckBox shorterSequence;
137 final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
139 List<String> tips = new ArrayList<>();
142 * the most recently opened PCA results panel
144 private PCAPanel pcaPanel;
146 private PaSiMapPanel pasimapPanel;
153 public CalculationChooser(AlignFrame alignFrame)
155 this.af = alignFrame;
157 af.alignPanel.setCalculationDialog(this);
162 * Lays out the panel and adds it to the desktop
166 getSecondaryStructureModelName();
167 setLayout(new BorderLayout());
168 frame = new JInternalFrame();
169 frame.setFrameIcon(null);
170 frame.setContentPane(this);
171 this.setBackground(Color.white);
172 frame.addFocusListener(new FocusListener()
176 public void focusLost(FocusEvent e)
181 public void focusGained(FocusEvent e)
187 * Layout consists of 3 or 4 panels:
188 * - first with choice of PCA or tree method NJ or AV
189 * - second with choice of score model
190 * - third with score model parameter options [suppressed]
191 * - fourth with OK and Cancel
193 pca = new JRadioButton(
194 MessageManager.getString("label.principal_component_analysis"));
195 pca.setOpaque(false);
197 pasimap = new JRadioButton( // create the JRadioButton for pasimap with label.pasimap as its text
198 MessageManager.getString("label.pasimap"));
199 pasimap.setOpaque(false);
201 neighbourJoining = new JRadioButton(
202 MessageManager.getString("label.tree_calc_nj"));
203 neighbourJoining.setSelected(true);
204 neighbourJoining.setOpaque(false);
206 averageDistance = new JRadioButton(
207 MessageManager.getString("label.tree_calc_av"));
208 averageDistance.setOpaque(false);
210 JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
211 calcChoicePanel.setOpaque(false);
213 // first create the Tree calculation's border panel
214 JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
215 treePanel.setOpaque(false);
217 JvSwingUtils.createTitledBorder(treePanel,
218 MessageManager.getString("label.tree"), true);
220 // then copy the inset dimensions for the border-less PCA panel
221 JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
222 Insets b = treePanel.getBorder().getBorderInsets(treePanel);
223 pcaBorderless.setBorder(
224 BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
225 pcaBorderless.setOpaque(false);
227 pcaBorderless.add(pca, FlowLayout.LEFT);
228 calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
230 // create pasimap panel
231 JPanel pasimapBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT)); // create new JPanel (button) for pasimap
232 pasimapBorderless.setBorder(
233 BorderFactory.createEmptyBorder(2, b.left, 2, b.right)); // set border (margin) for button (same as treePanel and pca)
234 pasimapBorderless.setOpaque(false); // false -> stops every pixel inside border from being painted
235 pasimapBorderless.add(pasimap, FlowLayout.LEFT); // add pasimap button to the JPanel
236 calcChoicePanel.add(pasimapBorderless, FlowLayout.LEFT); // add button with border and everything to the overall ChoicePanel
238 treePanel.add(neighbourJoining);
239 treePanel.add(averageDistance);
241 calcChoicePanel.add(treePanel);
243 ButtonGroup calcTypes = new ButtonGroup();
245 calcTypes.add(pasimap);
246 calcTypes.add(neighbourJoining);
247 calcTypes.add(averageDistance);
249 ActionListener calcChanged = new ActionListener()
252 public void actionPerformed(ActionEvent e)
257 pca.addActionListener(calcChanged);
258 pasimap.addActionListener(calcChanged); // add the calcChanged ActionListener to pasimap --> <++> idk
259 neighbourJoining.addActionListener(calcChanged);
260 averageDistance.addActionListener(calcChanged);
264 ssSourceDropdown = buildSSSourcesOptionsList();
265 ssSourceDropdown.setVisible(false); // Initially hide the dropdown
268 * score models drop-down - with added tooltips!
270 modelNames = buildModelOptionsList();
272 // Step 3: Show or Hide Dropdown Based on Selection
273 modelNames.addActionListener(new ActionListener() {
275 public void actionPerformed(ActionEvent e) {
276 String selectedModel = modelNames.getSelectedItem().toString();
278 if (selectedModel.equals(secondaryStructureModelName)) {
279 ssSourceDropdown.setVisible(true);
281 ssSourceDropdown.setVisible(false);
287 JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
288 scoreModelPanel.setOpaque(false);
289 scoreModelPanel.add(modelNames);
290 scoreModelPanel.add(ssSourceDropdown);
293 * score model parameters
295 JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
296 paramsPanel.setOpaque(false);
297 includeGaps = new JCheckBox("Include gaps");
298 matchGaps = new JCheckBox("Match gaps");
299 includeGappedColumns = new JCheckBox("Include gapped columns");
300 shorterSequence = new JCheckBox("Match on shorter sequence");
301 paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
302 paramsPanel.add(includeGaps);
303 paramsPanel.add(matchGaps);
304 paramsPanel.add(includeGappedColumns);
305 paramsPanel.add(shorterSequence);
308 * OK / Cancel buttons
310 calculate = new JButton(MessageManager.getString("action.calculate"));
311 calculate.setFont(VERDANA_11PT);
312 calculate.addActionListener(new java.awt.event.ActionListener()
315 public void actionPerformed(ActionEvent e)
317 calculate_actionPerformed();
320 JButton close = new JButton(MessageManager.getString("action.close"));
321 close.setFont(VERDANA_11PT);
322 close.addActionListener(new java.awt.event.ActionListener()
325 public void actionPerformed(ActionEvent e)
327 close_actionPerformed();
330 JPanel actionPanel = new JPanel();
331 actionPanel.setOpaque(false);
332 actionPanel.add(calculate);
333 actionPanel.add(close);
335 boolean includeParams = false;
336 this.add(calcChoicePanel, BorderLayout.CENTER);
337 calcChoicePanel.add(scoreModelPanel);
340 scoreModelPanel.add(paramsPanel);
342 this.add(actionPanel, BorderLayout.SOUTH);
345 int height = includeParams ? 420 : 240;
347 setMinimumSize(new Dimension(325, height - 10));
348 String title = MessageManager.getString("label.choose_calculation");
349 if (af.getViewport().getViewName() != null)
351 title = title + " (" + af.getViewport().getViewName() + ")";
354 Desktop.addInternalFrame(frame, title, width, height, false);
355 calcChoicePanel.doLayout();
358 * null the AlignmentPanel's reference to the dialog when it is closed
360 frame.addInternalFrameListener(new InternalFrameAdapter()
363 public void internalFrameClosed(InternalFrameEvent evt)
365 af.alignPanel.setCalculationDialog(null);
370 frame.setLayer(JLayeredPane.PALETTE_LAYER);
374 * enable calculations applicable for the current alignment or selection.
376 protected void validateCalcTypes()
378 int size = af.getViewport().getAlignment().getHeight();
379 if (af.getViewport().getSelectionGroup() != null)
381 size = af.getViewport().getSelectionGroup().getSize();
385 * disable calc options for which there is insufficient input data
386 * return value of true means enabled and selected
388 boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
389 boolean checkPasimap = checkEnabled(pasimap, size, MIN_PASIMAP_SELECTION); // check if pasimap is enabled and min_size is fulfilled
390 boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
392 boolean checkAverageDistance = checkEnabled(averageDistance, size,
395 if (checkPca || checkPasimap || checkNeighbourJoining || checkAverageDistance)
397 calculate.setToolTipText(null);
398 calculate.setEnabled(true);
402 calculate.setEnabled(false);
404 updateScoreModels(modelNames, tips);
408 * Check the input and disable a calculation's radio button if necessary. A
409 * tooltip is shown for disabled calculations.
412 * - radio button for the calculation being validated
414 * - size of input to calculation
416 * - minimum size for calculation
417 * @return true if size >= minsize and calc.isSelected
419 private boolean checkEnabled(JRadioButton calc, int size, int minsize)
421 String ttip = MessageManager
422 .formatMessage("label.you_need_at_least_n_sequences", minsize);
424 calc.setEnabled(size >= minsize);
425 if (!calc.isEnabled())
427 calc.setToolTipText(ttip);
431 calc.setToolTipText(null);
433 if (calc.isSelected())
435 modelNames.setEnabled(calc.isEnabled());
436 if (calc.isEnabled())
442 calculate.setToolTipText(ttip);
449 * A rather elaborate helper method (blame Swing, not me) that builds a
450 * drop-down list of score models (by name) with descriptions as tooltips.
451 * There is also a tooltip shown for the currently selected item when hovering
452 * over it (without opening the list).
454 protected JComboBox<String> buildModelOptionsList()
456 final JComboBox<String> scoreModelsCombo = new JComboBox<>();
457 scoreModelsCombo.setRenderer(renderer);
460 * show tooltip on mouse over the combobox
461 * note the listener has to be on the components that make up
462 * the combobox, doesn't work if just on the combobox
464 final MouseAdapter mouseListener = new MouseAdapter()
467 public void mouseEntered(MouseEvent e)
469 scoreModelsCombo.setToolTipText(
470 tips.get(scoreModelsCombo.getSelectedIndex()));
474 public void mouseExited(MouseEvent e)
476 scoreModelsCombo.setToolTipText(null);
479 for (Component c : scoreModelsCombo.getComponents())
481 c.addMouseListener(mouseListener);
484 updateScoreModels(scoreModelsCombo, tips);
487 * set the list of tooltips on the combobox's renderer
489 renderer.setTooltips(tips);
491 return scoreModelsCombo;
495 private JComboBox<String> buildSSSourcesOptionsList()
497 final JComboBox<String> comboBox = new JComboBox<>();
498 Object curSel = comboBox.getSelectedItem();
499 DefaultComboBoxModel<String> sourcesModel = new DefaultComboBoxModel<>();
501 List<String> ssSources = getApplicableSecondaryStructureSources();
503 boolean selectedIsPresent = false;
504 for (String source : ssSources)
506 if (curSel != null && source.equals(curSel))
508 selectedIsPresent = true;
511 sourcesModel.addElement(source);
515 if (selectedIsPresent)
517 sourcesModel.setSelectedItem(curSel);
519 comboBox.setModel(sourcesModel);
525 private void updateScoreModels(JComboBox<String> comboBox,
526 List<String> toolTips)
528 Object curSel = comboBox.getSelectedItem();
530 DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
533 * select the score models applicable to the alignment type
535 boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
536 AlignmentAnnotation[] alignmentAnnotations = af.getViewport().getAlignment().getAlignmentAnnotation();
538 boolean ssPresent = AlignmentUtils.isSecondaryStructurePresent(alignmentAnnotations);
540 List<ScoreModelI> models = getApplicableScoreModels(nucleotide, pca.isSelected(),
541 ssPresent, pasimap.isSelected());
544 * now we can actually add entries to the combobox,
545 * remembering their descriptions for tooltips
547 boolean selectedIsPresent = false;
548 for (ScoreModelI sm : models)
550 if (curSel != null && sm.getName().equals(curSel))
552 selectedIsPresent = true;
553 curSel = sm.getName();
555 model.addElement(sm.getName());
558 * tooltip is description if provided, else text lookup with
559 * fallback on the model name
561 String tooltip = sm.getDescription();
564 tooltip = MessageManager.getStringOrReturn("label.score_model_",
567 toolTips.add(tooltip);
570 if (selectedIsPresent)
572 model.setSelectedItem(curSel);
574 // finally, update the model
575 comboBox.setModel(model);
580 * Builds a list of score models which are applicable for the alignment and
581 * calculation type (peptide or generic models for protein, nucleotide or
582 * generic models for nucleotide).
584 * As a special case, includes BLOSUM62 as an extra option for nucleotide PCA.
585 * This is for backwards compatibility with Jalview prior to 2.8 when BLOSUM62
586 * was the only score matrix supported. This is included if property
587 * BLOSUM62_PCA_FOR_NUCLEOTIDE is set to true in the Jalview properties file.
593 protected static List<ScoreModelI> getApplicableScoreModels(
594 boolean nucleotide, boolean forPca, boolean ssPresent, boolean forPasimap)
596 List<ScoreModelI> filtered = new ArrayList<>();
598 ScoreModels scoreModels = ScoreModels.getInstance();
599 for (ScoreModelI sm : scoreModels.getModels())
601 if (!forPasimap && (!nucleotide && sm.isProtein() || nucleotide && sm.isDNA()
602 || sm.isSecondaryStructure() && ssPresent))
610 * special case: add BLOSUM62 as last option for nucleotide PCA,
611 * for backwards compatibility with Jalview < 2.8 (JAL-2962)
613 if (!forPasimap && nucleotide && forPca
614 && Cache.getDefault("BLOSUM62_PCA_FOR_NUCLEOTIDE", false))
616 filtered.add(scoreModels.getBlosum62());
623 protected List<String> getApplicableSecondaryStructureSources()
625 AlignmentAnnotation[] annotations = af.getViewport().getAlignment().getAlignmentAnnotation();
627 List<String> ssSources = AlignmentUtils.getSecondaryStructureSources(annotations);
628 //List<String> ssSources = AlignmentUtils.extractSSSourceInAlignmentAnnotation(annotations);
635 * Open and calculate the selected tree or PCA on 'OK'
637 protected void calculate_actionPerformed()
639 boolean doPCA = pca.isSelected();
640 boolean doPaSiMap = pasimap.isSelected();
641 String modelName = modelNames.getSelectedItem() == null ? "" : modelNames.getSelectedItem().toString();
642 String ssSource = "";
643 Object selectedItem = ssSourceDropdown.getSelectedItem();
644 if (selectedItem != null) {
645 ssSource = selectedItem.toString();
647 SimilarityParams params = getSimilarityParameters(doPCA);
648 if(ssSource.length()>0)
650 params.setSecondaryStructureSource(ssSource);
653 if (doPCA && !doPaSiMap)
655 openPcaPanel(modelName, params);
657 else if (doPaSiMap && !doPCA)
659 openPasimapPanel(modelName, params);
663 openTreePanel(modelName, params);
670 * Open a new Tree panel on the desktop
675 protected void openTreePanel(String modelName, SimilarityParamsI params)
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 AlignViewport viewport = af.getViewport();
682 SequenceGroup sg = viewport.getSelectionGroup();
683 if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
685 JvOptionPane.showMessageDialog(Desktop.desktop,
686 MessageManager.formatMessage(
687 "label.you_need_at_least_n_sequences",
689 MessageManager.getString("label.not_enough_sequences"),
690 JvOptionPane.WARNING_MESSAGE);
694 String treeType = neighbourJoining.isSelected()
695 ? TreeBuilder.NEIGHBOUR_JOINING
696 : TreeBuilder.AVERAGE_DISTANCE;
697 af.newTreePanel(treeType, modelName, params);
701 * Open a new PCA panel on the desktop
706 protected void openPcaPanel(String modelName, SimilarityParamsI params)
708 AlignViewport viewport = af.getViewport();
711 * gui validation shouldn't allow insufficient sequences here, but leave
712 * this check in in case this method gets exposed programmatically in future
714 if (((viewport.getSelectionGroup() != null)
715 && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
716 && (viewport.getSelectionGroup().getSize() > 0))
717 || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
719 JvOptionPane.showInternalMessageDialog(this,
720 MessageManager.formatMessage(
721 "label.you_need_at_least_n_sequences",
724 .getString("label.sequence_selection_insufficient"),
725 JvOptionPane.WARNING_MESSAGE);
730 * construct the panel and kick off its calculation thread
732 pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
733 new Thread(pcaPanel).start();
738 * Open a new PaSiMap panel on the desktop
743 protected void openPasimapPanel(String modelName, SimilarityParamsI params)
745 AlignViewport viewport = af.getViewport();
748 * gui validation shouldn't allow insufficient sequences here, but leave
749 * this check in in case this method gets exposed programmatically in future
751 if (((viewport.getSelectionGroup() != null)
752 && (viewport.getSelectionGroup().getSize() < MIN_PASIMAP_SELECTION)
753 && (viewport.getSelectionGroup().getSize() > 0))
754 || (viewport.getAlignment().getHeight() < MIN_PASIMAP_SELECTION))
756 JvOptionPane.showInternalMessageDialog(this,
757 MessageManager.formatMessage(
758 "label.you_need_at_least_n_sequences",
759 MIN_PASIMAP_SELECTION),
761 .getString("label.sequence_selection_insufficient"),
762 JvOptionPane.WARNING_MESSAGE);
767 * construct the panel and kick off its calculation thread
769 pasimapPanel = new PaSiMapPanel(af.alignPanel, modelName, params);
770 new Thread(pasimapPanel).start();
777 protected void closeFrame()
781 frame.setClosed(true);
782 } catch (PropertyVetoException ex)
788 * Returns a data bean holding parameters for similarity (or distance) model
794 protected SimilarityParams getSimilarityParameters(boolean doPCA)
796 // commented out: parameter choices read from gui widgets
797 // SimilarityParamsI params = new SimilarityParams(
798 // includeGappedColumns.isSelected(), matchGaps.isSelected(),
799 // includeGaps.isSelected(), shorterSequence.isSelected());
801 boolean includeGapGap = true;
802 boolean includeGapResidue = true;
803 boolean matchOnShortestLength = false;
806 * 'matchGaps' flag is only used in the PID calculation
807 * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
808 * - set to true for Tree to reproduce Jalview 2.10.1 calculation
809 * - set to false for Tree for a more correct calculation (JAL-374)
811 boolean matchGap = doPCA ? false : treeMatchGaps;
813 return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
814 matchOnShortestLength);
818 * Closes dialog on Close button press
820 protected void close_actionPerformed()
824 frame.setClosed(true);
825 } catch (Exception ex)
830 public PCAPanel getPcaPanel()