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.TreeCalculator;
25 import jalview.analysis.TreeModel;
26 import jalview.analysis.scoremodels.ScoreModels;
27 import jalview.analysis.scoremodels.SimilarityParams;
28 import jalview.api.analysis.ScoreModelI;
29 import jalview.api.analysis.SimilarityParamsI;
30 import jalview.bin.Cache;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.ext.archaeopteryx.AptxInit;
33 import jalview.util.MessageManager;
35 import java.awt.BorderLayout;
36 import java.awt.Color;
37 import java.awt.Component;
38 import java.awt.Dimension;
39 import java.awt.FlowLayout;
41 import java.awt.GridLayout;
42 import java.awt.Insets;
43 import java.awt.event.ActionEvent;
44 import java.awt.event.ActionListener;
45 import java.awt.event.FocusEvent;
46 import java.awt.event.FocusListener;
47 import java.awt.event.MouseAdapter;
48 import java.awt.event.MouseEvent;
49 import java.beans.PropertyVetoException;
50 import java.io.IOException;
51 import java.util.ArrayList;
52 import java.util.List;
54 import javax.swing.BorderFactory;
55 import javax.swing.ButtonGroup;
56 import javax.swing.DefaultComboBoxModel;
57 import javax.swing.JButton;
58 import javax.swing.JCheckBox;
59 import javax.swing.JComboBox;
60 import javax.swing.JInternalFrame;
61 import javax.swing.JLabel;
62 import javax.swing.JLayeredPane;
63 import javax.swing.JPanel;
64 import javax.swing.JRadioButton;
65 import javax.swing.event.InternalFrameAdapter;
66 import javax.swing.event.InternalFrameEvent;
69 * A dialog where a user can choose and action Tree or PCA calculation options
71 public class CalculationChooser extends JPanel
74 * flag for whether gap matches residue in the PID calculation for a Tree
75 * - true gives Jalview 2.10.1 behaviour
76 * - set to false (using Groovy) for a more correct tree
79 private static boolean treeMatchGaps = true;
81 private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
83 private static final int MIN_TREE_SELECTION = 3;
85 private static final int MIN_PCA_SELECTION = 4;
91 JRadioButton neighbourJoining;
93 JRadioButton averageDistance;
95 JComboBox<String> modelNames;
99 private JInternalFrame frame;
101 private JCheckBox includeGaps;
103 private JCheckBox matchGaps;
105 private JCheckBox includeGappedColumns;
107 private JCheckBox shorterSequence;
109 final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
111 List<String> tips = new ArrayList<>();
114 * the most recently opened PCA results panel
116 private PCAPanel pcaPanel;
123 public CalculationChooser(AlignFrame alignFrame)
125 this.af = alignFrame;
127 af.alignPanel.setCalculationDialog(this);
131 * Lays out the panel and adds it to the desktop
135 setLayout(new BorderLayout());
136 frame = new JInternalFrame();
137 frame.setContentPane(this);
138 this.setBackground(Color.white);
139 frame.addFocusListener(new FocusListener()
143 public void focusLost(FocusEvent e)
148 public void focusGained(FocusEvent e)
154 * Layout consists of 3 or 4 panels:
155 * - first with choice of PCA or tree method NJ or AV
156 * - second with choice of score model
157 * - third with score model parameter options [suppressed]
158 * - fourth with OK and Cancel
160 pca = new JRadioButton(
161 MessageManager.getString("label.principal_component_analysis"));
162 pca.setOpaque(false);
164 neighbourJoining = new JRadioButton(
165 MessageManager.getString("label.tree_calc_nj"));
166 neighbourJoining.setSelected(true);
167 neighbourJoining.setOpaque(false);
169 averageDistance = new JRadioButton(
170 MessageManager.getString("label.tree_calc_av"));
171 averageDistance.setOpaque(false);
173 JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
174 calcChoicePanel.setOpaque(false);
176 // first create the Tree calculation's border panel
177 JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
178 treePanel.setOpaque(false);
180 JvSwingUtils.createTitledBorder(treePanel,
181 MessageManager.getString("label.tree"), true);
183 // then copy the inset dimensions for the border-less PCA panel
184 JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
185 Insets b = treePanel.getBorder().getBorderInsets(treePanel);
186 pcaBorderless.setBorder(
187 BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
188 pcaBorderless.setOpaque(false);
190 pcaBorderless.add(pca, FlowLayout.LEFT);
191 calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
193 treePanel.add(neighbourJoining);
194 treePanel.add(averageDistance);
196 calcChoicePanel.add(treePanel);
198 ButtonGroup calcTypes = new ButtonGroup();
200 calcTypes.add(neighbourJoining);
201 calcTypes.add(averageDistance);
203 ActionListener calcChanged = new ActionListener()
206 public void actionPerformed(ActionEvent e)
211 pca.addActionListener(calcChanged);
212 neighbourJoining.addActionListener(calcChanged);
213 averageDistance.addActionListener(calcChanged);
216 * score models drop-down - with added tooltips!
218 modelNames = buildModelOptionsList();
220 JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
221 scoreModelPanel.setOpaque(false);
222 scoreModelPanel.add(modelNames);
225 * score model parameters
227 JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
228 paramsPanel.setOpaque(false);
229 includeGaps = new JCheckBox("Include gaps");
230 matchGaps = new JCheckBox("Match gaps");
231 includeGappedColumns = new JCheckBox("Include gapped columns");
232 shorterSequence = new JCheckBox("Match on shorter sequence");
233 paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
234 paramsPanel.add(includeGaps);
235 paramsPanel.add(matchGaps);
236 paramsPanel.add(includeGappedColumns);
237 paramsPanel.add(shorterSequence);
240 * OK / Cancel buttons
242 calculate = new JButton(MessageManager.getString("action.calculate"));
243 calculate.setFont(VERDANA_11PT);
244 calculate.addActionListener(new java.awt.event.ActionListener()
247 public void actionPerformed(ActionEvent e)
249 calculate_actionPerformed();
252 JButton close = new JButton(MessageManager.getString("action.close"));
253 close.setFont(VERDANA_11PT);
254 close.addActionListener(new java.awt.event.ActionListener()
257 public void actionPerformed(ActionEvent e)
259 close_actionPerformed();
262 JPanel actionPanel = new JPanel();
263 actionPanel.setOpaque(false);
264 actionPanel.add(calculate);
265 actionPanel.add(close);
267 boolean includeParams = false;
268 this.add(calcChoicePanel, BorderLayout.CENTER);
269 calcChoicePanel.add(scoreModelPanel);
272 scoreModelPanel.add(paramsPanel);
274 this.add(actionPanel, BorderLayout.SOUTH);
277 int height = includeParams ? 420 : 240;
279 setMinimumSize(new Dimension(325, height - 10));
280 String title = MessageManager.getString("label.choose_calculation");
281 if (af.getViewport().getViewName() != null)
283 title = title + " (" + af.getViewport().getViewName() + ")";
286 Desktop.addInternalFrame(frame, title, width, height, false);
287 calcChoicePanel.doLayout();
290 * null the AlignmentPanel's reference to the dialog when it is closed
292 frame.addInternalFrameListener(new InternalFrameAdapter()
295 public void internalFrameClosed(InternalFrameEvent evt)
297 af.alignPanel.setCalculationDialog(null);
302 frame.setLayer(JLayeredPane.PALETTE_LAYER);
306 * enable calculations applicable for the current alignment or selection.
308 protected void validateCalcTypes()
310 int size = af.getViewport().getAlignment().getHeight();
311 if (af.getViewport().getSelectionGroup() != null)
313 size = af.getViewport().getSelectionGroup().getSize();
317 * disable calc options for which there is insufficient input data
318 * return value of true means enabled and selected
320 boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
321 boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
323 boolean checkAverageDistance = checkEnabled(averageDistance, size,
326 if (checkPca || checkNeighbourJoining || checkAverageDistance)
328 calculate.setToolTipText(null);
329 calculate.setEnabled(true);
333 calculate.setEnabled(false);
335 updateScoreModels(modelNames, tips);
339 * Check the input and disable a calculation's radio button if necessary. A
340 * tooltip is shown for disabled calculations.
343 * - radio button for the calculation being validated
345 * - size of input to calculation
347 * - minimum size for calculation
348 * @return true if size >= minsize and calc.isSelected
350 private boolean checkEnabled(JRadioButton calc, int size, int minsize)
352 String ttip = MessageManager
353 .formatMessage("label.you_need_at_least_n_sequences", minsize);
355 calc.setEnabled(size >= minsize);
356 if (!calc.isEnabled())
358 calc.setToolTipText(ttip);
362 calc.setToolTipText(null);
364 if (calc.isSelected())
366 modelNames.setEnabled(calc.isEnabled());
367 if (calc.isEnabled())
373 calculate.setToolTipText(ttip);
380 * A rather elaborate helper method (blame Swing, not me) that builds a
381 * drop-down list of score models (by name) with descriptions as tooltips.
382 * There is also a tooltip shown for the currently selected item when hovering
383 * over it (without opening the list).
385 protected JComboBox<String> buildModelOptionsList()
387 final JComboBox<String> scoreModelsCombo = new JComboBox<>();
388 scoreModelsCombo.setRenderer(renderer);
391 * show tooltip on mouse over the combobox
392 * note the listener has to be on the components that make up
393 * the combobox, doesn't work if just on the combobox
395 final MouseAdapter mouseListener = new MouseAdapter()
398 public void mouseEntered(MouseEvent e)
400 scoreModelsCombo.setToolTipText(
401 tips.get(scoreModelsCombo.getSelectedIndex()));
405 public void mouseExited(MouseEvent e)
407 scoreModelsCombo.setToolTipText(null);
410 for (Component c : scoreModelsCombo.getComponents())
412 c.addMouseListener(mouseListener);
415 updateScoreModels(scoreModelsCombo, tips);
418 * set the list of tooltips on the combobox's renderer
420 renderer.setTooltips(tips);
422 return scoreModelsCombo;
425 private void updateScoreModels(JComboBox<String> comboBox,
426 List<String> toolTips)
428 Object curSel = comboBox.getSelectedItem();
430 DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
432 * select the score models applicable to the alignment type
434 boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
435 List<ScoreModelI> models = getApplicableScoreModels(nucleotide,
439 * now we can actually add entries to the combobox,
440 * remembering their descriptions for tooltips
442 boolean selectedIsPresent = false;
443 for (ScoreModelI sm : models)
445 if (curSel != null && sm.getName().equals(curSel))
447 selectedIsPresent = true;
448 curSel = sm.getName();
450 model.addElement(sm.getName());
453 * tooltip is description if provided, else text lookup with
454 * fallback on the model name
456 String tooltip = sm.getDescription();
459 tooltip = MessageManager.getStringOrReturn("label.score_model_",
462 toolTips.add(tooltip);
465 if (selectedIsPresent)
467 model.setSelectedItem(curSel);
469 // finally, update the model
470 comboBox.setModel(model);
474 * Builds a list of score models which are applicable for the alignment and
475 * calculation type (peptide or generic models for protein, nucleotide or
476 * generic models for nucleotide).
478 * As a special case, includes BLOSUM62 as an extra option for nucleotide PCA.
479 * This is for backwards compatibility with Jalview prior to 2.8 when BLOSUM62
480 * was the only score matrix supported. This is included if property
481 * BLOSUM62_PCA_FOR_NUCLEOTIDE is set to true in the Jalview properties file.
487 protected static List<ScoreModelI> getApplicableScoreModels(
488 boolean nucleotide, boolean forPca)
490 List<ScoreModelI> filtered = new ArrayList<>();
492 ScoreModels scoreModels = ScoreModels.getInstance();
493 for (ScoreModelI sm : scoreModels.getModels())
495 if (!nucleotide && sm.isProtein() || nucleotide && sm.isDNA())
502 * special case: add BLOSUM62 as last option for nucleotide PCA,
503 * for backwards compatibility with Jalview < 2.8 (JAL-2962)
505 if (nucleotide && forPca
506 && Cache.getDefault("BLOSUM62_PCA_FOR_NUCLEOTIDE", false))
508 filtered.add(scoreModels.getBlosum62());
515 * Open and calculate the selected tree or PCA on 'OK'
517 * @throws IOException
519 protected void calculate_actionPerformed()
521 boolean doPCA = pca.isSelected();
522 String substitutionMatrix = modelNames.getSelectedItem().toString();
523 SimilarityParamsI params = getSimilarityParameters(doPCA);
527 openPcaPanel(substitutionMatrix, params);
533 createTree(substitutionMatrix, params);
534 } catch (IOException e)
536 // TODO Auto-generated catch block
550 protected void createTree(String substitutionMatrix,
551 SimilarityParamsI params) throws IOException
553 String treeAlgo = determineTreeAlgo();
554 TreeCalculator treeCalculator = new TreeCalculator(treeAlgo,
555 substitutionMatrix, params);
556 TreeBuilder calculatedTree = treeCalculator.makeTree(af.getViewport());
558 // AptxInit.createInstanceFromCalculation(calculatedTree);
560 TreeModel tree = new TreeModel(calculatedTree);
561 jalview.io.NewickFile newick = new jalview.io.NewickFile(
563 String output = newick.print(tree.hasBootstrap(), tree.hasDistances(),
564 tree.hasRootDistance());
565 AptxInit.createInstanceFromNhx(af.getTitle(), output,
567 // openTreePanel(tree, treeAlgo, substitutionMatrix);
571 protected String determineTreeAlgo() // to be modified & expanded
573 String treeAlgorithm = neighbourJoining.isSelected()
574 ? TreeBuilder.NEIGHBOUR_JOINING
575 : TreeBuilder.AVERAGE_DISTANCE;
577 return treeAlgorithm;
581 protected void checkEnoughSequences(AlignViewport viewport)
583 SequenceGroup sg = viewport.getSelectionGroup();
584 if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
586 JvOptionPane.showMessageDialog(Desktop.desktop,
587 MessageManager.formatMessage(
588 "label.you_need_at_least_n_sequences",
590 MessageManager.getString("label.not_enough_sequences"),
591 JvOptionPane.WARNING_MESSAGE);
597 * Open a new Tree panel on the desktop
603 protected void openTreePanel(TreeModel tree, String treeAlgo,
604 String substitutionMatrix)
607 * gui validation shouldn't allow insufficient sequences here, but leave
608 * this check in in case this method gets exposed programmatically in future
610 checkEnoughSequences(af.getViewport());
612 af.newTreePanel(tree, treeAlgo, substitutionMatrix);
616 * Open a new PCA panel on the desktop
621 protected void openPcaPanel(String modelName, SimilarityParamsI params)
623 AlignViewport viewport = af.getViewport();
626 * gui validation shouldn't allow insufficient sequences here, but leave
627 * this check in in case this method gets exposed programmatically in future
629 if (((viewport.getSelectionGroup() != null)
630 && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
631 && (viewport.getSelectionGroup().getSize() > 0))
632 || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
634 JvOptionPane.showInternalMessageDialog(this,
635 MessageManager.formatMessage(
636 "label.you_need_at_least_n_sequences",
639 .getString("label.sequence_selection_insufficient"),
640 JvOptionPane.WARNING_MESSAGE);
645 * construct the panel and kick off its calculation thread
647 pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
648 new Thread(pcaPanel).start();
655 protected void closeFrame()
659 frame.setClosed(true);
660 } catch (PropertyVetoException ex)
666 * Returns a data bean holding parameters for similarity (or distance) model
672 protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
674 // commented out: parameter choices read from gui widgets
675 // SimilarityParamsI params = new SimilarityParams(
676 // includeGappedColumns.isSelected(), matchGaps.isSelected(),
677 // includeGaps.isSelected(), shorterSequence.isSelected());
679 boolean includeGapGap = true;
680 boolean includeGapResidue = true;
681 boolean matchOnShortestLength = false;
684 * 'matchGaps' flag is only used in the PID calculation
685 * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
686 * - set to true for Tree to reproduce Jalview 2.10.1 calculation
687 * - set to false for Tree for a more correct calculation (JAL-374)
689 boolean matchGap = doPCA ? false : treeMatchGaps;
691 return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
692 matchOnShortestLength);
696 * Closes dialog on Close button press
698 protected void close_actionPerformed()
702 frame.setClosed(true);
703 } catch (Exception ex)
708 public PCAPanel getPcaPanel()