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;
67 import org.forester.io.parsers.nhx.NHXParser;
70 * A dialog where a user can choose and action Tree or PCA calculation options
72 public class CalculationChooser extends JPanel
75 * flag for whether gap matches residue in the PID calculation for a Tree
76 * - true gives Jalview 2.10.1 behaviour
77 * - set to false (using Groovy) for a more correct tree
80 private static boolean treeMatchGaps = true;
82 private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
84 private static final int MIN_TREE_SELECTION = 3;
86 private static final int MIN_PCA_SELECTION = 4;
92 JRadioButton neighbourJoining;
94 JRadioButton averageDistance;
96 JComboBox<String> modelNames;
100 private JInternalFrame frame;
102 private JCheckBox includeGaps;
104 private JCheckBox matchGaps;
106 private JCheckBox includeGappedColumns;
108 private JCheckBox shorterSequence;
110 final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
112 List<String> tips = new ArrayList<>();
115 * the most recently opened PCA results panel
117 private PCAPanel pcaPanel;
124 public CalculationChooser(AlignFrame alignFrame)
126 this.af = alignFrame;
128 af.alignPanel.setCalculationDialog(this);
132 * Lays out the panel and adds it to the desktop
136 setLayout(new BorderLayout());
137 frame = new JInternalFrame();
138 frame.setContentPane(this);
139 this.setBackground(Color.white);
140 frame.addFocusListener(new FocusListener()
144 public void focusLost(FocusEvent e)
149 public void focusGained(FocusEvent e)
155 * Layout consists of 3 or 4 panels:
156 * - first with choice of PCA or tree method NJ or AV
157 * - second with choice of score model
158 * - third with score model parameter options [suppressed]
159 * - fourth with OK and Cancel
161 pca = new JRadioButton(
162 MessageManager.getString("label.principal_component_analysis"));
163 pca.setOpaque(false);
164 neighbourJoining = new JRadioButton(
165 MessageManager.getString("label.tree_calc_nj"));
166 neighbourJoining.setSelected(true);
167 averageDistance = new JRadioButton(
168 MessageManager.getString("label.tree_calc_av"));
169 neighbourJoining.setOpaque(false);
171 JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
172 calcChoicePanel.setOpaque(false);
174 // first create the Tree calculation's border panel
175 JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
176 treePanel.setOpaque(false);
178 treePanel.setBorder(BorderFactory
179 .createTitledBorder(MessageManager.getString("label.tree")));
181 // then copy the inset dimensions for the border-less PCA panel
182 JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
183 Insets b = treePanel.getBorder().getBorderInsets(treePanel);
184 pcaBorderless.setBorder(
185 BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
186 pcaBorderless.setOpaque(false);
188 pcaBorderless.add(pca, FlowLayout.LEFT);
189 calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
191 treePanel.add(neighbourJoining);
192 treePanel.add(averageDistance);
194 calcChoicePanel.add(treePanel);
196 ButtonGroup calcTypes = new ButtonGroup();
198 calcTypes.add(neighbourJoining);
199 calcTypes.add(averageDistance);
201 ActionListener calcChanged = new ActionListener()
204 public void actionPerformed(ActionEvent e)
209 pca.addActionListener(calcChanged);
210 neighbourJoining.addActionListener(calcChanged);
211 averageDistance.addActionListener(calcChanged);
214 * score models drop-down - with added tooltips!
216 modelNames = buildModelOptionsList();
218 JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
219 scoreModelPanel.setOpaque(false);
220 scoreModelPanel.add(modelNames);
223 * score model parameters
225 JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
226 paramsPanel.setOpaque(false);
227 includeGaps = new JCheckBox("Include gaps");
228 matchGaps = new JCheckBox("Match gaps");
229 includeGappedColumns = new JCheckBox("Include gapped columns");
230 shorterSequence = new JCheckBox("Match on shorter sequence");
231 paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
232 paramsPanel.add(includeGaps);
233 paramsPanel.add(matchGaps);
234 paramsPanel.add(includeGappedColumns);
235 paramsPanel.add(shorterSequence);
238 * OK / Cancel buttons
240 calculate = new JButton(MessageManager.getString("action.calculate"));
241 calculate.setFont(VERDANA_11PT);
242 calculate.addActionListener(new java.awt.event.ActionListener()
245 public void actionPerformed(ActionEvent e)
247 calculate_actionPerformed();
250 JButton close = new JButton(MessageManager.getString("action.close"));
251 close.setFont(VERDANA_11PT);
252 close.addActionListener(new java.awt.event.ActionListener()
255 public void actionPerformed(ActionEvent e)
257 close_actionPerformed();
260 JPanel actionPanel = new JPanel();
261 actionPanel.setOpaque(false);
262 actionPanel.add(calculate);
263 actionPanel.add(close);
265 boolean includeParams = false;
266 this.add(calcChoicePanel, BorderLayout.CENTER);
267 calcChoicePanel.add(scoreModelPanel);
270 scoreModelPanel.add(paramsPanel);
272 this.add(actionPanel, BorderLayout.SOUTH);
275 int height = includeParams ? 420 : 240;
277 setMinimumSize(new Dimension(325, height - 10));
278 String title = MessageManager.getString("label.choose_calculation");
279 if (af.getViewport().viewName != null)
281 title = title + " (" + af.getViewport().viewName + ")";
284 Desktop.addInternalFrame(frame, title, width, height, false);
285 calcChoicePanel.doLayout();
288 * null the AlignmentPanel's reference to the dialog when it is closed
290 frame.addInternalFrameListener(new InternalFrameAdapter()
293 public void internalFrameClosed(InternalFrameEvent evt)
295 af.alignPanel.setCalculationDialog(null);
299 frame.setLayer(JLayeredPane.PALETTE_LAYER);
303 * enable calculations applicable for the current alignment or selection.
305 protected void validateCalcTypes()
307 int size = af.getViewport().getAlignment().getHeight();
308 if (af.getViewport().getSelectionGroup() != null)
310 size = af.getViewport().getSelectionGroup().getSize();
314 * disable calc options for which there is insufficient input data
315 * return value of true means enabled and selected
317 boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
318 boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
320 boolean checkAverageDistance = checkEnabled(averageDistance, size,
323 if (checkPca || checkNeighbourJoining || checkAverageDistance)
325 calculate.setToolTipText(null);
326 calculate.setEnabled(true);
330 calculate.setEnabled(false);
332 updateScoreModels(modelNames, tips);
336 * Check the input and disable a calculation's radio button if necessary. A
337 * tooltip is shown for disabled calculations.
340 * - radio button for the calculation being validated
342 * - size of input to calculation
344 * - minimum size for calculation
345 * @return true if size >= minsize and calc.isSelected
347 private boolean checkEnabled(JRadioButton calc, int size, int minsize)
349 String ttip = MessageManager
350 .formatMessage("label.you_need_at_least_n_sequences", minsize);
352 calc.setEnabled(size >= minsize);
353 if (!calc.isEnabled())
355 calc.setToolTipText(ttip);
359 calc.setToolTipText(null);
361 if (calc.isSelected())
363 modelNames.setEnabled(calc.isEnabled());
364 if (calc.isEnabled())
370 calculate.setToolTipText(ttip);
377 * A rather elaborate helper method (blame Swing, not me) that builds a
378 * drop-down list of score models (by name) with descriptions as tooltips.
379 * There is also a tooltip shown for the currently selected item when hovering
380 * over it (without opening the list).
382 protected JComboBox<String> buildModelOptionsList()
384 final JComboBox<String> scoreModelsCombo = new JComboBox<>();
385 scoreModelsCombo.setRenderer(renderer);
388 * show tooltip on mouse over the combobox
389 * note the listener has to be on the components that make up
390 * the combobox, doesn't work if just on the combobox
392 final MouseAdapter mouseListener = new MouseAdapter()
395 public void mouseEntered(MouseEvent e)
397 scoreModelsCombo.setToolTipText(
398 tips.get(scoreModelsCombo.getSelectedIndex()));
402 public void mouseExited(MouseEvent e)
404 scoreModelsCombo.setToolTipText(null);
407 for (Component c : scoreModelsCombo.getComponents())
409 c.addMouseListener(mouseListener);
412 updateScoreModels(scoreModelsCombo, tips);
415 * set the list of tooltips on the combobox's renderer
417 renderer.setTooltips(tips);
419 return scoreModelsCombo;
422 private void updateScoreModels(JComboBox<String> comboBox,
423 List<String> toolTips)
425 Object curSel = comboBox.getSelectedItem();
427 DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
430 * now we can actually add entries to the combobox,
431 * remembering their descriptions for tooltips
433 ScoreModels scoreModels = ScoreModels.getInstance();
434 boolean selectedIsPresent = false;
435 for (ScoreModelI sm : scoreModels.getModels())
437 boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
438 if (sm.isDNA() && nucleotide || sm.isProtein() && !nucleotide)
440 if (curSel != null && sm.getName().equals(curSel))
442 selectedIsPresent = true;
443 curSel = sm.getName();
445 model.addElement(sm.getName());
448 * tooltip is description if provided, else text lookup with
449 * fallback on the model name
451 String tooltip = sm.getDescription();
454 tooltip = MessageManager.getStringOrReturn("label.score_model_",
457 toolTips.add(tooltip);
460 if (selectedIsPresent)
462 model.setSelectedItem(curSel);
464 // finally, update the model
465 comboBox.setModel(model);
469 * Open and calculate the selected tree or PCA on 'OK'
471 * @throws IOException
473 protected void calculate_actionPerformed()
475 boolean doPCA = pca.isSelected();
476 String substitutionMatrix = modelNames.getSelectedItem().toString();
477 SimilarityParamsI params = getSimilarityParameters(doPCA);
481 openPcaPanel(substitutionMatrix, params);
487 createTree(substitutionMatrix, params);
488 } catch (IOException e)
490 // TODO Auto-generated catch block
504 protected void createTree(String substitutionMatrix,
505 SimilarityParamsI params) throws IOException
507 String treeAlgo = determineTreeAlgo();
508 TreeCalculator treeCalculator = new TreeCalculator(treeAlgo,
509 substitutionMatrix, params);
510 TreeBuilder calculatedTree = treeCalculator.makeTree(af.getViewport());
512 // AptxInit.createInstanceFromCalculation(calculatedTree);
514 TreeModel tree = new TreeModel(calculatedTree);
515 jalview.io.NewickFile newick = new jalview.io.NewickFile(
517 String output = newick.print(tree.hasBootstrap(), tree.hasDistances(),
518 tree.hasRootDistance());
519 AptxInit.createInstances(af.getTitle(), output, new NHXParser(),
521 // openTreePanel(tree, treeAlgo, substitutionMatrix);
525 protected String determineTreeAlgo() // to be modified & expanded
527 String treeAlgorithm = neighbourJoining.isSelected()
528 ? TreeBuilder.NEIGHBOUR_JOINING
529 : TreeBuilder.AVERAGE_DISTANCE;
531 return treeAlgorithm;
535 protected void checkEnoughSequences(AlignViewport viewport)
537 SequenceGroup sg = viewport.getSelectionGroup();
538 if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
540 JvOptionPane.showMessageDialog(Desktop.desktop,
541 MessageManager.formatMessage(
542 "label.you_need_at_least_n_sequences",
544 MessageManager.getString("label.not_enough_sequences"),
545 JvOptionPane.WARNING_MESSAGE);
551 * Open a new Tree panel on the desktop
557 protected void openTreePanel(TreeModel tree, String treeAlgo,
558 String substitutionMatrix)
561 * gui validation shouldn't allow insufficient sequences here, but leave
562 * this check in in case this method gets exposed programmatically in future
564 checkEnoughSequences(af.getViewport());
566 af.newTreePanel(tree, treeAlgo, substitutionMatrix);
570 * Open a new PCA panel on the desktop
575 protected void openPcaPanel(String modelName, SimilarityParamsI params)
577 AlignViewport viewport = af.getViewport();
580 * gui validation shouldn't allow insufficient sequences here, but leave
581 * this check in in case this method gets exposed programmatically in future
583 if (((viewport.getSelectionGroup() != null)
584 && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
585 && (viewport.getSelectionGroup().getSize() > 0))
586 || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
588 JvOptionPane.showInternalMessageDialog(this,
589 MessageManager.formatMessage(
590 "label.you_need_at_least_n_sequences",
593 .getString("label.sequence_selection_insufficient"),
594 JvOptionPane.WARNING_MESSAGE);
597 pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
603 protected void closeFrame()
607 frame.setClosed(true);
608 } catch (PropertyVetoException ex)
614 * Returns a data bean holding parameters for similarity (or distance) model
620 protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
622 // commented out: parameter choices read from gui widgets
623 // SimilarityParamsI params = new SimilarityParams(
624 // includeGappedColumns.isSelected(), matchGaps.isSelected(),
625 // includeGaps.isSelected(), shorterSequence.isSelected());
627 boolean includeGapGap = true;
628 boolean includeGapResidue = true;
629 boolean matchOnShortestLength = false;
632 * 'matchGaps' flag is only used in the PID calculation
633 * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
634 * - set to true for Tree to reproduce Jalview 2.10.1 calculation
635 * - set to false for Tree for a more correct calculation (JAL-374)
637 boolean matchGap = doPCA ? false : treeMatchGaps;
639 return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
640 matchOnShortestLength);
644 * Closes dialog on Close button press
646 protected void close_actionPerformed()
650 frame.setClosed(true);
651 } catch (Exception ex)
656 public PCAPanel getPcaPanel()