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();
110 * minimum number of sequences needed for PASIMAP is 9 (so each has 8 connections)
112 private static final int MIN_PASIMAP_SELECTION = 9;
118 JRadioButton pasimap;
120 JRadioButton neighbourJoining;
122 JRadioButton averageDistance;
124 JComboBox<String> modelNames;
126 JComboBox<String> ssSourceDropdown;
130 private JInternalFrame frame;
132 private JCheckBox includeGaps;
134 private JCheckBox matchGaps;
136 private JCheckBox includeGappedColumns;
138 private JCheckBox shorterSequence;
140 final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
142 List<String> tips = new ArrayList<>();
145 * the most recently opened PCA results panel
147 private PCAPanel pcaPanel;
149 private PaSiMapPanel pasimapPanel;
156 public CalculationChooser(AlignFrame alignFrame)
158 this.af = alignFrame;
160 af.alignPanel.setCalculationDialog(this);
165 * Lays out the panel and adds it to the desktop
169 getSecondaryStructureModelName();
170 setLayout(new BorderLayout());
171 frame = new JInternalFrame();
172 frame.setFrameIcon(null);
173 frame.setContentPane(this);
174 this.setBackground(Color.white);
175 frame.addFocusListener(new FocusListener()
179 public void focusLost(FocusEvent e)
184 public void focusGained(FocusEvent e)
190 * Layout consists of 3 or 4 panels:
191 * - first with choice of PCA or tree method NJ or AV
192 * - second with choice of score model
193 * - third with score model parameter options [suppressed]
194 * - fourth with OK and Cancel
196 pca = new JRadioButton(
197 MessageManager.getString("label.principal_component_analysis"));
198 pca.setOpaque(false);
200 pasimap = new JRadioButton( // create the JRadioButton for pasimap with label.pasimap as its text
201 MessageManager.getString("label.pasimap"));
202 pasimap.setOpaque(false);
204 neighbourJoining = new JRadioButton(
205 MessageManager.getString("label.tree_calc_nj"));
206 neighbourJoining.setSelected(true);
207 neighbourJoining.setOpaque(false);
209 averageDistance = new JRadioButton(
210 MessageManager.getString("label.tree_calc_av"));
211 averageDistance.setOpaque(false);
213 JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
214 calcChoicePanel.setOpaque(false);
216 // first create the Tree calculation's border panel
217 JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
218 treePanel.setOpaque(false);
220 JvSwingUtils.createTitledBorder(treePanel,
221 MessageManager.getString("label.tree"), true);
223 // then copy the inset dimensions for the border-less PCA panel
224 JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
225 Insets b = treePanel.getBorder().getBorderInsets(treePanel);
226 pcaBorderless.setBorder(
227 BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
228 pcaBorderless.setOpaque(false);
230 pcaBorderless.add(pca, FlowLayout.LEFT);
231 calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
233 // create pasimap panel
234 JPanel pasimapBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT)); // create new JPanel (button) for pasimap
235 pasimapBorderless.setBorder(
236 BorderFactory.createEmptyBorder(2, b.left, 2, b.right)); // set border (margin) for button (same as treePanel and pca)
237 pasimapBorderless.setOpaque(false); // false -> stops every pixel inside border from being painted
238 pasimapBorderless.add(pasimap, FlowLayout.LEFT); // add pasimap button to the JPanel
239 calcChoicePanel.add(pasimapBorderless, FlowLayout.LEFT); // add button with border and everything to the overall ChoicePanel
241 treePanel.add(neighbourJoining);
242 treePanel.add(averageDistance);
244 calcChoicePanel.add(treePanel);
246 ButtonGroup calcTypes = new ButtonGroup();
248 calcTypes.add(pasimap);
249 calcTypes.add(neighbourJoining);
250 calcTypes.add(averageDistance);
252 ActionListener calcChanged = new ActionListener()
255 public void actionPerformed(ActionEvent e)
260 pca.addActionListener(calcChanged);
261 pasimap.addActionListener(calcChanged); // add the calcChanged ActionListener to pasimap --> <++> idk
262 neighbourJoining.addActionListener(calcChanged);
263 averageDistance.addActionListener(calcChanged);
267 ssSourceDropdown = buildSSSourcesOptionsList();
268 ssSourceDropdown.setVisible(false); // Initially hide the dropdown
271 * score models drop-down - with added tooltips!
273 modelNames = buildModelOptionsList();
275 // Step 3: Show or Hide Dropdown Based on Selection
276 modelNames.addActionListener(new ActionListener() {
278 public void actionPerformed(ActionEvent e) {
279 String selectedModel = modelNames.getSelectedItem().toString();
281 if (selectedModel.equals(secondaryStructureModelName)) {
282 ssSourceDropdown.setVisible(true);
284 ssSourceDropdown.setVisible(false);
290 JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
291 scoreModelPanel.setOpaque(false);
292 scoreModelPanel.add(modelNames);
293 scoreModelPanel.add(ssSourceDropdown);
296 * score model parameters
298 JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
299 paramsPanel.setOpaque(false);
300 includeGaps = new JCheckBox("Include gaps");
301 matchGaps = new JCheckBox("Match gaps");
302 includeGappedColumns = new JCheckBox("Include gapped columns");
303 shorterSequence = new JCheckBox("Match on shorter sequence");
304 paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
305 paramsPanel.add(includeGaps);
306 paramsPanel.add(matchGaps);
307 paramsPanel.add(includeGappedColumns);
308 paramsPanel.add(shorterSequence);
311 * OK / Cancel buttons
313 calculate = new JButton(MessageManager.getString("action.calculate"));
314 calculate.setFont(VERDANA_11PT);
315 calculate.addActionListener(new java.awt.event.ActionListener()
318 public void actionPerformed(ActionEvent e)
320 calculate_actionPerformed();
323 JButton close = new JButton(MessageManager.getString("action.close"));
324 close.setFont(VERDANA_11PT);
325 close.addActionListener(new java.awt.event.ActionListener()
328 public void actionPerformed(ActionEvent e)
330 close_actionPerformed();
333 JPanel actionPanel = new JPanel();
334 actionPanel.setOpaque(false);
335 actionPanel.add(calculate);
336 actionPanel.add(close);
338 boolean includeParams = false;
339 this.add(calcChoicePanel, BorderLayout.CENTER);
340 calcChoicePanel.add(scoreModelPanel);
343 scoreModelPanel.add(paramsPanel);
345 this.add(actionPanel, BorderLayout.SOUTH);
348 int height = includeParams ? 420 : 240;
350 setMinimumSize(new Dimension(325, height - 10));
351 String title = MessageManager.getString("label.choose_calculation");
352 if (af.getViewport().getViewName() != null)
354 title = title + " (" + af.getViewport().getViewName() + ")";
357 Desktop.addInternalFrame(frame, title, width, height, false);
358 calcChoicePanel.doLayout();
361 * null the AlignmentPanel's reference to the dialog when it is closed
363 frame.addInternalFrameListener(new InternalFrameAdapter()
366 public void internalFrameClosed(InternalFrameEvent evt)
368 af.alignPanel.setCalculationDialog(null);
373 frame.setLayer(JLayeredPane.PALETTE_LAYER);
377 * enable calculations applicable for the current alignment or selection.
379 protected void validateCalcTypes()
381 int size = af.getViewport().getAlignment().getHeight();
382 if (af.getViewport().getSelectionGroup() != null)
384 size = af.getViewport().getSelectionGroup().getSize();
388 * disable calc options for which there is insufficient input data
389 * return value of true means enabled and selected
391 boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
392 boolean checkPasimap = checkEnabled(pasimap, size, MIN_PASIMAP_SELECTION); // check if pasimap is enabled and min_size is fulfilled
393 boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
395 boolean checkAverageDistance = checkEnabled(averageDistance, size,
398 if (checkPca || checkPasimap || checkNeighbourJoining || checkAverageDistance)
400 calculate.setToolTipText(null);
401 calculate.setEnabled(true);
405 calculate.setEnabled(false);
407 updateScoreModels(modelNames, tips);
411 * Check the input and disable a calculation's radio button if necessary. A
412 * tooltip is shown for disabled calculations.
415 * - radio button for the calculation being validated
417 * - size of input to calculation
419 * - minimum size for calculation
420 * @return true if size >= minsize and calc.isSelected
422 private boolean checkEnabled(JRadioButton calc, int size, int minsize)
424 String ttip = MessageManager
425 .formatMessage("label.you_need_at_least_n_sequences", minsize);
427 calc.setEnabled(size >= minsize);
428 if (!calc.isEnabled())
430 calc.setToolTipText(ttip);
434 calc.setToolTipText(null);
436 if (calc.isSelected())
438 modelNames.setEnabled(calc.isEnabled());
439 if (calc.isEnabled())
445 calculate.setToolTipText(ttip);
452 * A rather elaborate helper method (blame Swing, not me) that builds a
453 * drop-down list of score models (by name) with descriptions as tooltips.
454 * There is also a tooltip shown for the currently selected item when hovering
455 * over it (without opening the list).
457 protected JComboBox<String> buildModelOptionsList()
459 final JComboBox<String> scoreModelsCombo = new JComboBox<>();
460 scoreModelsCombo.setRenderer(renderer);
463 * show tooltip on mouse over the combobox
464 * note the listener has to be on the components that make up
465 * the combobox, doesn't work if just on the combobox
467 final MouseAdapter mouseListener = new MouseAdapter()
470 public void mouseEntered(MouseEvent e)
472 scoreModelsCombo.setToolTipText(
473 tips.get(scoreModelsCombo.getSelectedIndex()));
477 public void mouseExited(MouseEvent e)
479 scoreModelsCombo.setToolTipText(null);
482 for (Component c : scoreModelsCombo.getComponents())
484 c.addMouseListener(mouseListener);
487 updateScoreModels(scoreModelsCombo, tips);
490 * set the list of tooltips on the combobox's renderer
492 renderer.setTooltips(tips);
494 return scoreModelsCombo;
498 private JComboBox<String> buildSSSourcesOptionsList()
500 final JComboBox<String> comboBox = new JComboBox<>();
501 Object curSel = comboBox.getSelectedItem();
502 DefaultComboBoxModel<String> sourcesModel = new DefaultComboBoxModel<>();
504 List<String> ssSources = getApplicableSecondaryStructureSources();
506 boolean selectedIsPresent = false;
507 for (String source : ssSources)
509 if (curSel != null && source.equals(curSel))
511 selectedIsPresent = true;
514 sourcesModel.addElement(source);
518 if (selectedIsPresent)
520 sourcesModel.setSelectedItem(curSel);
522 comboBox.setModel(sourcesModel);
528 private void updateScoreModels(JComboBox<String> comboBox,
529 List<String> toolTips)
531 Object curSel = comboBox.getSelectedItem();
533 DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
536 * select the score models applicable to the alignment type
538 boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
539 AlignmentAnnotation[] alignmentAnnotations = af.getViewport().getAlignment().getAlignmentAnnotation();
541 boolean ssPresent = AlignmentUtils.isSecondaryStructurePresent(alignmentAnnotations);
543 List<ScoreModelI> models = getApplicableScoreModels(nucleotide, pca.isSelected(),
544 ssPresent, pasimap.isSelected());
547 * now we can actually add entries to the combobox,
548 * remembering their descriptions for tooltips
550 boolean selectedIsPresent = false;
551 for (ScoreModelI sm : models)
553 if (curSel != null && sm.getName().equals(curSel))
555 selectedIsPresent = true;
556 curSel = sm.getName();
558 model.addElement(sm.getName());
561 * tooltip is description if provided, else text lookup with
562 * fallback on the model name
564 String tooltip = sm.getDescription();
567 tooltip = MessageManager.getStringOrReturn("label.score_model_",
570 toolTips.add(tooltip);
573 if (selectedIsPresent)
575 model.setSelectedItem(curSel);
577 // finally, update the model
578 comboBox.setModel(model);
583 * Builds a list of score models which are applicable for the alignment and
584 * calculation type (peptide or generic models for protein, nucleotide or
585 * generic models for nucleotide).
587 * As a special case, includes BLOSUM62 as an extra option for nucleotide PCA.
588 * This is for backwards compatibility with Jalview prior to 2.8 when BLOSUM62
589 * was the only score matrix supported. This is included if property
590 * BLOSUM62_PCA_FOR_NUCLEOTIDE is set to true in the Jalview properties file.
596 protected static List<ScoreModelI> getApplicableScoreModels(
597 boolean nucleotide, boolean forPca, boolean ssPresent, boolean forPasimap)
599 List<ScoreModelI> filtered = new ArrayList<>();
601 ScoreModels scoreModels = ScoreModels.getInstance();
602 for (ScoreModelI sm : scoreModels.getModels())
604 if (!forPasimap && (!nucleotide && sm.isProtein() || nucleotide && sm.isDNA()
605 || sm.isSecondaryStructure() && ssPresent))
613 * special case: add BLOSUM62 as last option for nucleotide PCA,
614 * for backwards compatibility with Jalview < 2.8 (JAL-2962)
616 if (!forPasimap && nucleotide && forPca
617 && Cache.getDefault("BLOSUM62_PCA_FOR_NUCLEOTIDE", false))
619 filtered.add(scoreModels.getBlosum62());
626 protected List<String> getApplicableSecondaryStructureSources()
628 AlignmentAnnotation[] annotations = af.getViewport().getAlignment().getAlignmentAnnotation();
630 List<String> ssSources = AlignmentUtils.getSecondaryStructureSources(annotations);
631 //List<String> ssSources = AlignmentUtils.extractSSSourceInAlignmentAnnotation(annotations);
638 * Open and calculate the selected tree or PCA on 'OK'
640 protected void calculate_actionPerformed()
642 boolean doPCA = pca.isSelected();
643 boolean doPaSiMap = pasimap.isSelected();
644 String modelName = modelNames.getSelectedItem() == null ? "" : modelNames.getSelectedItem().toString();
645 String ssSource = "";
646 Object selectedItem = ssSourceDropdown.getSelectedItem();
647 if (selectedItem != null) {
648 ssSource = selectedItem.toString();
650 SimilarityParams params = getSimilarityParameters(doPCA);
651 if(ssSource.length()>0)
653 params.setSecondaryStructureSource(ssSource);
656 if (doPCA && !doPaSiMap)
658 openPcaPanel(modelName, params);
660 else if (doPaSiMap && !doPCA)
662 openPasimapPanel(modelName, params);
666 openTreePanel(modelName, params);
673 * Open a new Tree panel on the desktop
678 protected void openTreePanel(String modelName, SimilarityParamsI params)
681 * gui validation shouldn't allow insufficient sequences here, but leave
682 * this check in in case this method gets exposed programmatically in future
684 AlignViewport viewport = af.getViewport();
685 SequenceGroup sg = viewport.getSelectionGroup();
686 if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
688 JvOptionPane.showMessageDialog(Desktop.desktop,
689 MessageManager.formatMessage(
690 "label.you_need_at_least_n_sequences",
692 MessageManager.getString("label.not_enough_sequences"),
693 JvOptionPane.WARNING_MESSAGE);
697 String treeType = neighbourJoining.isSelected()
698 ? TreeBuilder.NEIGHBOUR_JOINING
699 : TreeBuilder.AVERAGE_DISTANCE;
700 af.newTreePanel(treeType, modelName, params);
704 * Open a new PCA panel on the desktop
709 protected void openPcaPanel(String modelName, SimilarityParamsI params)
711 AlignViewport viewport = af.getViewport();
714 * gui validation shouldn't allow insufficient sequences here, but leave
715 * this check in in case this method gets exposed programmatically in future
717 if (((viewport.getSelectionGroup() != null)
718 && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
719 && (viewport.getSelectionGroup().getSize() > 0))
720 || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
722 JvOptionPane.showInternalMessageDialog(this,
723 MessageManager.formatMessage(
724 "label.you_need_at_least_n_sequences",
727 .getString("label.sequence_selection_insufficient"),
728 JvOptionPane.WARNING_MESSAGE);
733 * construct the panel and kick off its calculation thread
735 pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
736 new Thread(pcaPanel).start();
741 * Open a new PaSiMap panel on the desktop
746 protected void openPasimapPanel(String modelName, SimilarityParamsI params)
748 AlignViewport viewport = af.getViewport();
751 * gui validation shouldn't allow insufficient sequences here, but leave
752 * this check in in case this method gets exposed programmatically in future
754 if (((viewport.getSelectionGroup() != null)
755 && (viewport.getSelectionGroup().getSize() < MIN_PASIMAP_SELECTION)
756 && (viewport.getSelectionGroup().getSize() > 0))
757 || (viewport.getAlignment().getHeight() < MIN_PASIMAP_SELECTION))
759 JvOptionPane.showInternalMessageDialog(this,
760 MessageManager.formatMessage(
761 "label.you_need_at_least_n_sequences",
762 MIN_PASIMAP_SELECTION),
764 .getString("label.sequence_selection_insufficient"),
765 JvOptionPane.WARNING_MESSAGE);
770 * construct the panel and kick off its calculation thread
772 pasimapPanel = new PaSiMapPanel(af.alignPanel, modelName, params);
773 new Thread(pasimapPanel).start();
780 protected void closeFrame()
784 frame.setClosed(true);
785 } catch (PropertyVetoException ex)
791 * Returns a data bean holding parameters for similarity (or distance) model
797 protected SimilarityParams getSimilarityParameters(boolean doPCA)
799 // commented out: parameter choices read from gui widgets
800 // SimilarityParamsI params = new SimilarityParams(
801 // includeGappedColumns.isSelected(), matchGaps.isSelected(),
802 // includeGaps.isSelected(), shorterSequence.isSelected());
804 boolean includeGapGap = true;
805 boolean includeGapResidue = true;
806 boolean matchOnShortestLength = false;
809 * 'matchGaps' flag is only used in the PID calculation
810 * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
811 * - set to true for Tree to reproduce Jalview 2.10.1 calculation
812 * - set to false for Tree for a more correct calculation (JAL-374)
814 boolean matchGap = doPCA ? false : treeMatchGaps;
816 return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
817 matchOnShortestLength);
821 * Closes dialog on Close button press
823 protected void close_actionPerformed()
827 frame.setClosed(true);
828 } catch (Exception ex)
833 public PCAPanel getPcaPanel()