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.datamodel.SequenceGroup;
31 import jalview.ext.archaeopteryx.AptxInit;
32 import jalview.util.MessageManager;
34 import java.awt.BorderLayout;
35 import java.awt.Color;
36 import java.awt.Component;
37 import java.awt.Dimension;
38 import java.awt.FlowLayout;
40 import java.awt.GridLayout;
41 import java.awt.Insets;
42 import java.awt.event.ActionEvent;
43 import java.awt.event.ActionListener;
44 import java.awt.event.FocusEvent;
45 import java.awt.event.FocusListener;
46 import java.awt.event.MouseAdapter;
47 import java.awt.event.MouseEvent;
48 import java.beans.PropertyVetoException;
49 import java.io.IOException;
50 import java.util.ArrayList;
51 import java.util.List;
53 import javax.swing.BorderFactory;
54 import javax.swing.ButtonGroup;
55 import javax.swing.DefaultComboBoxModel;
56 import javax.swing.JButton;
57 import javax.swing.JCheckBox;
58 import javax.swing.JComboBox;
59 import javax.swing.JInternalFrame;
60 import javax.swing.JLabel;
61 import javax.swing.JLayeredPane;
62 import javax.swing.JPanel;
63 import javax.swing.JRadioButton;
64 import javax.swing.event.InternalFrameAdapter;
65 import javax.swing.event.InternalFrameEvent;
68 * A dialog where a user can choose and action Tree or PCA calculation options
70 public class CalculationChooser extends JPanel
73 * flag for whether gap matches residue in the PID calculation for a Tree
74 * - true gives Jalview 2.10.1 behaviour
75 * - set to false (using Groovy) for a more correct tree
78 private static boolean treeMatchGaps = true;
80 private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
82 private static final int MIN_TREE_SELECTION = 3;
84 private static final int MIN_PCA_SELECTION = 4;
90 JRadioButton neighbourJoining;
92 JRadioButton averageDistance;
94 JComboBox<String> modelNames;
98 private JInternalFrame frame;
100 private JCheckBox includeGaps;
102 private JCheckBox matchGaps;
104 private JCheckBox includeGappedColumns;
106 private JCheckBox shorterSequence;
108 final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
110 List<String> tips = new ArrayList<>();
113 * the most recently opened PCA results panel
115 private PCAPanel pcaPanel;
122 public CalculationChooser(AlignFrame alignFrame)
124 this.af = alignFrame;
126 af.alignPanel.setCalculationDialog(this);
130 * Lays out the panel and adds it to the desktop
134 setLayout(new BorderLayout());
135 frame = new JInternalFrame();
136 frame.setContentPane(this);
137 this.setBackground(Color.white);
138 frame.addFocusListener(new FocusListener()
142 public void focusLost(FocusEvent e)
147 public void focusGained(FocusEvent e)
153 * Layout consists of 3 or 4 panels:
154 * - first with choice of PCA or tree method NJ or AV
155 * - second with choice of score model
156 * - third with score model parameter options [suppressed]
157 * - fourth with OK and Cancel
159 pca = new JRadioButton(
160 MessageManager.getString("label.principal_component_analysis"));
161 pca.setOpaque(false);
162 neighbourJoining = new JRadioButton(
163 MessageManager.getString("label.tree_calc_nj"));
164 neighbourJoining.setSelected(true);
165 averageDistance = new JRadioButton(
166 MessageManager.getString("label.tree_calc_av"));
167 neighbourJoining.setOpaque(false);
169 JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
170 calcChoicePanel.setOpaque(false);
172 // first create the Tree calculation's border panel
173 JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
174 treePanel.setOpaque(false);
176 treePanel.setBorder(BorderFactory
177 .createTitledBorder(MessageManager.getString("label.tree")));
179 // then copy the inset dimensions for the border-less PCA panel
180 JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
181 Insets b = treePanel.getBorder().getBorderInsets(treePanel);
182 pcaBorderless.setBorder(
183 BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
184 pcaBorderless.setOpaque(false);
186 pcaBorderless.add(pca, FlowLayout.LEFT);
187 calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
189 treePanel.add(neighbourJoining);
190 treePanel.add(averageDistance);
192 calcChoicePanel.add(treePanel);
194 ButtonGroup calcTypes = new ButtonGroup();
196 calcTypes.add(neighbourJoining);
197 calcTypes.add(averageDistance);
199 ActionListener calcChanged = new ActionListener()
202 public void actionPerformed(ActionEvent e)
207 pca.addActionListener(calcChanged);
208 neighbourJoining.addActionListener(calcChanged);
209 averageDistance.addActionListener(calcChanged);
212 * score models drop-down - with added tooltips!
214 modelNames = buildModelOptionsList();
216 JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
217 scoreModelPanel.setOpaque(false);
218 scoreModelPanel.add(modelNames);
221 * score model parameters
223 JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
224 paramsPanel.setOpaque(false);
225 includeGaps = new JCheckBox("Include gaps");
226 matchGaps = new JCheckBox("Match gaps");
227 includeGappedColumns = new JCheckBox("Include gapped columns");
228 shorterSequence = new JCheckBox("Match on shorter sequence");
229 paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
230 paramsPanel.add(includeGaps);
231 paramsPanel.add(matchGaps);
232 paramsPanel.add(includeGappedColumns);
233 paramsPanel.add(shorterSequence);
236 * OK / Cancel buttons
238 calculate = new JButton(MessageManager.getString("action.calculate"));
239 calculate.setFont(VERDANA_11PT);
240 calculate.addActionListener(new java.awt.event.ActionListener()
243 public void actionPerformed(ActionEvent e)
245 calculate_actionPerformed();
248 JButton close = new JButton(MessageManager.getString("action.close"));
249 close.setFont(VERDANA_11PT);
250 close.addActionListener(new java.awt.event.ActionListener()
253 public void actionPerformed(ActionEvent e)
255 close_actionPerformed();
258 JPanel actionPanel = new JPanel();
259 actionPanel.setOpaque(false);
260 actionPanel.add(calculate);
261 actionPanel.add(close);
263 boolean includeParams = false;
264 this.add(calcChoicePanel, BorderLayout.CENTER);
265 calcChoicePanel.add(scoreModelPanel);
268 scoreModelPanel.add(paramsPanel);
270 this.add(actionPanel, BorderLayout.SOUTH);
273 int height = includeParams ? 420 : 240;
275 setMinimumSize(new Dimension(325, height - 10));
276 String title = MessageManager.getString("label.choose_calculation");
277 if (af.getViewport().viewName != null)
279 title = title + " (" + af.getViewport().viewName + ")";
282 Desktop.addInternalFrame(frame, title, width, height, false);
283 calcChoicePanel.doLayout();
286 * null the AlignmentPanel's reference to the dialog when it is closed
288 frame.addInternalFrameListener(new InternalFrameAdapter()
291 public void internalFrameClosed(InternalFrameEvent evt)
293 af.alignPanel.setCalculationDialog(null);
297 frame.setLayer(JLayeredPane.PALETTE_LAYER);
301 * enable calculations applicable for the current alignment or selection.
303 protected void validateCalcTypes()
305 int size = af.getViewport().getAlignment().getHeight();
306 if (af.getViewport().getSelectionGroup() != null)
308 size = af.getViewport().getSelectionGroup().getSize();
312 * disable calc options for which there is insufficient input data
313 * return value of true means enabled and selected
315 boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
316 boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
318 boolean checkAverageDistance = checkEnabled(averageDistance, size,
321 if (checkPca || checkNeighbourJoining || checkAverageDistance)
323 calculate.setToolTipText(null);
324 calculate.setEnabled(true);
328 calculate.setEnabled(false);
330 updateScoreModels(modelNames, tips);
334 * Check the input and disable a calculation's radio button if necessary. A
335 * tooltip is shown for disabled calculations.
338 * - radio button for the calculation being validated
340 * - size of input to calculation
342 * - minimum size for calculation
343 * @return true if size >= minsize and calc.isSelected
345 private boolean checkEnabled(JRadioButton calc, int size, int minsize)
347 String ttip = MessageManager
348 .formatMessage("label.you_need_at_least_n_sequences", minsize);
350 calc.setEnabled(size >= minsize);
351 if (!calc.isEnabled())
353 calc.setToolTipText(ttip);
357 calc.setToolTipText(null);
359 if (calc.isSelected())
361 modelNames.setEnabled(calc.isEnabled());
362 if (calc.isEnabled())
368 calculate.setToolTipText(ttip);
375 * A rather elaborate helper method (blame Swing, not me) that builds a
376 * drop-down list of score models (by name) with descriptions as tooltips.
377 * There is also a tooltip shown for the currently selected item when hovering
378 * over it (without opening the list).
380 protected JComboBox<String> buildModelOptionsList()
382 final JComboBox<String> scoreModelsCombo = new JComboBox<>();
383 scoreModelsCombo.setRenderer(renderer);
386 * show tooltip on mouse over the combobox
387 * note the listener has to be on the components that make up
388 * the combobox, doesn't work if just on the combobox
390 final MouseAdapter mouseListener = new MouseAdapter()
393 public void mouseEntered(MouseEvent e)
395 scoreModelsCombo.setToolTipText(
396 tips.get(scoreModelsCombo.getSelectedIndex()));
400 public void mouseExited(MouseEvent e)
402 scoreModelsCombo.setToolTipText(null);
405 for (Component c : scoreModelsCombo.getComponents())
407 c.addMouseListener(mouseListener);
410 updateScoreModels(scoreModelsCombo, tips);
413 * set the list of tooltips on the combobox's renderer
415 renderer.setTooltips(tips);
417 return scoreModelsCombo;
420 private void updateScoreModels(JComboBox<String> comboBox,
421 List<String> toolTips)
423 Object curSel = comboBox.getSelectedItem();
425 DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
428 * now we can actually add entries to the combobox,
429 * remembering their descriptions for tooltips
431 ScoreModels scoreModels = ScoreModels.getInstance();
432 boolean selectedIsPresent = false;
433 for (ScoreModelI sm : scoreModels.getModels())
435 boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
436 if (sm.isDNA() && nucleotide || sm.isProtein() && !nucleotide)
438 if (curSel != null && sm.getName().equals(curSel))
440 selectedIsPresent = true;
441 curSel = sm.getName();
443 model.addElement(sm.getName());
446 * tooltip is description if provided, else text lookup with
447 * fallback on the model name
449 String tooltip = sm.getDescription();
452 tooltip = MessageManager.getStringOrReturn("label.score_model_",
455 toolTips.add(tooltip);
458 if (selectedIsPresent)
460 model.setSelectedItem(curSel);
462 // finally, update the model
463 comboBox.setModel(model);
467 * Open and calculate the selected tree or PCA on 'OK'
469 * @throws IOException
471 protected void calculate_actionPerformed()
473 boolean doPCA = pca.isSelected();
474 String substitutionMatrix = modelNames.getSelectedItem().toString();
475 SimilarityParamsI params = getSimilarityParameters(doPCA);
479 openPcaPanel(substitutionMatrix, params);
485 createTree(substitutionMatrix, params);
486 } catch (IOException e)
488 // TODO Auto-generated catch block
502 protected void createTree(String substitutionMatrix,
503 SimilarityParamsI params) throws IOException
505 String treeAlgo = determineTreeAlgo();
506 TreeCalculator treeCalculator = new TreeCalculator(treeAlgo,
507 substitutionMatrix, params);
508 TreeBuilder calculatedTree = treeCalculator.makeTree(af.getViewport());
510 // AptxInit.createInstanceFromCalculation(calculatedTree);
512 TreeModel tree = new TreeModel(calculatedTree);
513 jalview.io.NewickFile newick = new jalview.io.NewickFile(
515 String output = newick.print(tree.hasBootstrap(), tree.hasDistances(),
516 tree.hasRootDistance());
517 AptxInit.createInstanceFromNhx(af.getTitle(), output,
519 // openTreePanel(tree, treeAlgo, substitutionMatrix);
523 protected String determineTreeAlgo() // to be modified & expanded
525 String treeAlgorithm = neighbourJoining.isSelected()
526 ? TreeBuilder.NEIGHBOUR_JOINING
527 : TreeBuilder.AVERAGE_DISTANCE;
529 return treeAlgorithm;
533 protected void checkEnoughSequences(AlignViewport viewport)
535 SequenceGroup sg = viewport.getSelectionGroup();
536 if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
538 JvOptionPane.showMessageDialog(Desktop.desktop,
539 MessageManager.formatMessage(
540 "label.you_need_at_least_n_sequences",
542 MessageManager.getString("label.not_enough_sequences"),
543 JvOptionPane.WARNING_MESSAGE);
549 * Open a new Tree panel on the desktop
555 protected void openTreePanel(TreeModel tree, String treeAlgo,
556 String substitutionMatrix)
559 * gui validation shouldn't allow insufficient sequences here, but leave
560 * this check in in case this method gets exposed programmatically in future
562 checkEnoughSequences(af.getViewport());
564 af.newTreePanel(tree, treeAlgo, substitutionMatrix);
568 * Open a new PCA panel on the desktop
573 protected void openPcaPanel(String modelName, SimilarityParamsI params)
575 AlignViewport viewport = af.getViewport();
578 * gui validation shouldn't allow insufficient sequences here, but leave
579 * this check in in case this method gets exposed programmatically in future
581 if (((viewport.getSelectionGroup() != null)
582 && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
583 && (viewport.getSelectionGroup().getSize() > 0))
584 || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
586 JvOptionPane.showInternalMessageDialog(this,
587 MessageManager.formatMessage(
588 "label.you_need_at_least_n_sequences",
591 .getString("label.sequence_selection_insufficient"),
592 JvOptionPane.WARNING_MESSAGE);
595 pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
601 protected void closeFrame()
605 frame.setClosed(true);
606 } catch (PropertyVetoException ex)
612 * Returns a data bean holding parameters for similarity (or distance) model
618 protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
620 // commented out: parameter choices read from gui widgets
621 // SimilarityParamsI params = new SimilarityParams(
622 // includeGappedColumns.isSelected(), matchGaps.isSelected(),
623 // includeGaps.isSelected(), shorterSequence.isSelected());
625 boolean includeGapGap = true;
626 boolean includeGapResidue = true;
627 boolean matchOnShortestLength = false;
630 * 'matchGaps' flag is only used in the PID calculation
631 * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
632 * - set to true for Tree to reproduce Jalview 2.10.1 calculation
633 * - set to false for Tree for a more correct calculation (JAL-374)
635 boolean matchGap = doPCA ? false : treeMatchGaps;
637 return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
638 matchOnShortestLength);
642 * Closes dialog on Close button press
644 protected void close_actionPerformed()
648 frame.setClosed(true);
649 } catch (Exception ex)
654 public PCAPanel getPcaPanel()