JAL-2795 calculated trees are now passed along as Newick strings
[jalview.git] / src / jalview / gui / CalculationChooser.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.gui;
22
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;
33
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;
39 import java.awt.Font;
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;
52
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;
66
67 import org.forester.io.parsers.nhx.NHXParser;
68
69 /**
70  * A dialog where a user can choose and action Tree or PCA calculation options
71  */
72 public class CalculationChooser extends JPanel
73 {
74   /*
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
78    * (JAL-374)
79    */
80   private static boolean treeMatchGaps = true;
81
82   private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
83
84   private static final int MIN_TREE_SELECTION = 3;
85
86   private static final int MIN_PCA_SELECTION = 4;
87
88   AlignFrame af;
89
90   JRadioButton pca;
91
92   JRadioButton neighbourJoining;
93
94   JRadioButton averageDistance;
95
96   JComboBox<String> modelNames;
97
98   JButton calculate;
99
100   private JInternalFrame frame;
101
102   private JCheckBox includeGaps;
103
104   private JCheckBox matchGaps;
105
106   private JCheckBox includeGappedColumns;
107
108   private JCheckBox shorterSequence;
109
110   final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
111
112   List<String> tips = new ArrayList<>();
113
114   /*
115    * the most recently opened PCA results panel
116    */
117   private PCAPanel pcaPanel;
118
119   /**
120    * Constructor
121    * 
122    * @param af
123    */
124   public CalculationChooser(AlignFrame alignFrame)
125   {
126     this.af = alignFrame;
127     init();
128     af.alignPanel.setCalculationDialog(this);
129   }
130
131   /**
132    * Lays out the panel and adds it to the desktop
133    */
134   void init()
135   {
136     setLayout(new BorderLayout());
137     frame = new JInternalFrame();
138     frame.setContentPane(this);
139     this.setBackground(Color.white);
140     frame.addFocusListener(new FocusListener()
141     {
142
143       @Override
144       public void focusLost(FocusEvent e)
145       {
146       }
147
148       @Override
149       public void focusGained(FocusEvent e)
150       {
151         validateCalcTypes();
152       }
153     });
154     /*
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
160      */
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);
170
171     JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
172     calcChoicePanel.setOpaque(false);
173
174     // first create the Tree calculation's border panel
175     JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
176     treePanel.setOpaque(false);
177
178     treePanel.setBorder(BorderFactory
179             .createTitledBorder(MessageManager.getString("label.tree")));
180
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);
187
188     pcaBorderless.add(pca, FlowLayout.LEFT);
189     calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
190
191     treePanel.add(neighbourJoining);
192     treePanel.add(averageDistance);
193
194     calcChoicePanel.add(treePanel);
195
196     ButtonGroup calcTypes = new ButtonGroup();
197     calcTypes.add(pca);
198     calcTypes.add(neighbourJoining);
199     calcTypes.add(averageDistance);
200
201     ActionListener calcChanged = new ActionListener()
202     {
203       @Override
204       public void actionPerformed(ActionEvent e)
205       {
206         validateCalcTypes();
207       }
208     };
209     pca.addActionListener(calcChanged);
210     neighbourJoining.addActionListener(calcChanged);
211     averageDistance.addActionListener(calcChanged);
212
213     /*
214      * score models drop-down - with added tooltips!
215      */
216     modelNames = buildModelOptionsList();
217
218     JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
219     scoreModelPanel.setOpaque(false);
220     scoreModelPanel.add(modelNames);
221
222     /*
223      * score model parameters
224      */
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);
236
237     /*
238      * OK / Cancel buttons
239      */
240     calculate = new JButton(MessageManager.getString("action.calculate"));
241     calculate.setFont(VERDANA_11PT);
242     calculate.addActionListener(new java.awt.event.ActionListener()
243     {
244       @Override
245       public void actionPerformed(ActionEvent e)
246       {
247         calculate_actionPerformed();
248       }
249     });
250     JButton close = new JButton(MessageManager.getString("action.close"));
251     close.setFont(VERDANA_11PT);
252     close.addActionListener(new java.awt.event.ActionListener()
253     {
254       @Override
255       public void actionPerformed(ActionEvent e)
256       {
257         close_actionPerformed();
258       }
259     });
260     JPanel actionPanel = new JPanel();
261     actionPanel.setOpaque(false);
262     actionPanel.add(calculate);
263     actionPanel.add(close);
264
265     boolean includeParams = false;
266     this.add(calcChoicePanel, BorderLayout.CENTER);
267     calcChoicePanel.add(scoreModelPanel);
268     if (includeParams)
269     {
270       scoreModelPanel.add(paramsPanel);
271     }
272     this.add(actionPanel, BorderLayout.SOUTH);
273
274     int width = 350;
275     int height = includeParams ? 420 : 240;
276
277     setMinimumSize(new Dimension(325, height - 10));
278     String title = MessageManager.getString("label.choose_calculation");
279     if (af.getViewport().viewName != null)
280     {
281       title = title + " (" + af.getViewport().viewName + ")";
282     }
283
284     Desktop.addInternalFrame(frame, title, width, height, false);
285     calcChoicePanel.doLayout();
286     revalidate();
287     /*
288      * null the AlignmentPanel's reference to the dialog when it is closed
289      */
290     frame.addInternalFrameListener(new InternalFrameAdapter()
291     {
292       @Override
293       public void internalFrameClosed(InternalFrameEvent evt)
294       {
295         af.alignPanel.setCalculationDialog(null);
296       };
297     });
298
299     frame.setLayer(JLayeredPane.PALETTE_LAYER);
300   }
301
302   /**
303    * enable calculations applicable for the current alignment or selection.
304    */
305   protected void validateCalcTypes()
306   {
307     int size = af.getViewport().getAlignment().getHeight();
308     if (af.getViewport().getSelectionGroup() != null)
309     {
310       size = af.getViewport().getSelectionGroup().getSize();
311     }
312
313     /*
314      * disable calc options for which there is insufficient input data
315      * return value of true means enabled and selected
316      */
317     boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
318     boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
319             MIN_TREE_SELECTION);
320     boolean checkAverageDistance = checkEnabled(averageDistance, size,
321             MIN_TREE_SELECTION);
322
323     if (checkPca || checkNeighbourJoining || checkAverageDistance)
324     {
325       calculate.setToolTipText(null);
326       calculate.setEnabled(true);
327     }
328     else
329     {
330       calculate.setEnabled(false);
331     }
332     updateScoreModels(modelNames, tips);
333   }
334
335   /**
336    * Check the input and disable a calculation's radio button if necessary. A
337    * tooltip is shown for disabled calculations.
338    * 
339    * @param calc
340    *          - radio button for the calculation being validated
341    * @param size
342    *          - size of input to calculation
343    * @param minsize
344    *          - minimum size for calculation
345    * @return true if size >= minsize and calc.isSelected
346    */
347   private boolean checkEnabled(JRadioButton calc, int size, int minsize)
348   {
349     String ttip = MessageManager
350             .formatMessage("label.you_need_at_least_n_sequences", minsize);
351
352     calc.setEnabled(size >= minsize);
353     if (!calc.isEnabled())
354     {
355       calc.setToolTipText(ttip);
356     }
357     else
358     {
359       calc.setToolTipText(null);
360     }
361     if (calc.isSelected())
362     {
363       modelNames.setEnabled(calc.isEnabled());
364       if (calc.isEnabled())
365       {
366         return true;
367       }
368       else
369       {
370         calculate.setToolTipText(ttip);
371       }
372     }
373     return false;
374   }
375
376   /**
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).
381    */
382   protected JComboBox<String> buildModelOptionsList()
383   {
384     final JComboBox<String> scoreModelsCombo = new JComboBox<>();
385     scoreModelsCombo.setRenderer(renderer);
386
387     /*
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
391      */
392     final MouseAdapter mouseListener = new MouseAdapter()
393     {
394       @Override
395       public void mouseEntered(MouseEvent e)
396       {
397         scoreModelsCombo.setToolTipText(
398                 tips.get(scoreModelsCombo.getSelectedIndex()));
399       }
400
401       @Override
402       public void mouseExited(MouseEvent e)
403       {
404         scoreModelsCombo.setToolTipText(null);
405       }
406     };
407     for (Component c : scoreModelsCombo.getComponents())
408     {
409       c.addMouseListener(mouseListener);
410     }
411
412     updateScoreModels(scoreModelsCombo, tips);
413
414     /*
415      * set the list of tooltips on the combobox's renderer
416      */
417     renderer.setTooltips(tips);
418
419     return scoreModelsCombo;
420   }
421
422   private void updateScoreModels(JComboBox<String> comboBox,
423           List<String> toolTips)
424   {
425     Object curSel = comboBox.getSelectedItem();
426     toolTips.clear();
427     DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
428
429     /*
430      * now we can actually add entries to the combobox,
431      * remembering their descriptions for tooltips
432      */
433     ScoreModels scoreModels = ScoreModels.getInstance();
434     boolean selectedIsPresent = false;
435     for (ScoreModelI sm : scoreModels.getModels())
436     {
437       boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
438       if (sm.isDNA() && nucleotide || sm.isProtein() && !nucleotide)
439       {
440         if (curSel != null && sm.getName().equals(curSel))
441         {
442           selectedIsPresent = true;
443           curSel = sm.getName();
444         }
445         model.addElement(sm.getName());
446
447         /*
448          * tooltip is description if provided, else text lookup with
449          * fallback on the model name
450          */
451         String tooltip = sm.getDescription();
452         if (tooltip == null)
453         {
454           tooltip = MessageManager.getStringOrReturn("label.score_model_",
455                   sm.getName());
456         }
457         toolTips.add(tooltip);
458       }
459     }
460     if (selectedIsPresent)
461     {
462       model.setSelectedItem(curSel);
463     }
464     // finally, update the model
465     comboBox.setModel(model);
466   }
467
468   /**
469    * Open and calculate the selected tree or PCA on 'OK'
470    * 
471    * @throws IOException
472    */
473   protected void calculate_actionPerformed()
474   {
475     boolean doPCA = pca.isSelected();
476     String substitutionMatrix = modelNames.getSelectedItem().toString();
477     SimilarityParamsI params = getSimilarityParameters(doPCA);
478
479     if (doPCA)
480     {
481       openPcaPanel(substitutionMatrix, params);
482     }
483     else
484     {
485       try
486       {
487         createTree(substitutionMatrix, params);
488       } catch (IOException e)
489       {
490         // TODO Auto-generated catch block
491         e.printStackTrace();
492       }
493
494
495
496
497
498
499     }
500
501     // closeFrame();
502   }
503
504   protected void createTree(String substitutionMatrix,
505           SimilarityParamsI params) throws IOException
506   {
507     String treeAlgo = determineTreeAlgo();
508     TreeCalculator treeCalculator = new TreeCalculator(treeAlgo,
509             substitutionMatrix, params);
510     TreeBuilder calculatedTree = treeCalculator.makeTree(af.getViewport());
511
512     // AptxInit.createInstanceFromCalculation(calculatedTree);
513
514     TreeModel tree = new TreeModel(calculatedTree);
515     jalview.io.NewickFile newick = new jalview.io.NewickFile(
516             tree.getTopNode());
517     String output = newick.print(tree.hasBootstrap(), tree.hasDistances(),
518             tree.hasRootDistance());
519     AptxInit.createInstances(af.getTitle(), output, new NHXParser(),
520             af.getViewport());
521     // openTreePanel(tree, treeAlgo, substitutionMatrix);
522   }
523
524
525   protected String determineTreeAlgo() // to be modified & expanded
526   {
527     String treeAlgorithm = neighbourJoining.isSelected()
528             ? TreeBuilder.NEIGHBOUR_JOINING
529             : TreeBuilder.AVERAGE_DISTANCE;
530
531     return treeAlgorithm;
532
533   }
534
535   protected void checkEnoughSequences(AlignViewport viewport)
536   {
537     SequenceGroup sg = viewport.getSelectionGroup();
538     if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
539     {
540       JvOptionPane.showMessageDialog(Desktop.desktop,
541               MessageManager.formatMessage(
542                       "label.you_need_at_least_n_sequences",
543                       MIN_TREE_SELECTION),
544               MessageManager.getString("label.not_enough_sequences"),
545               JvOptionPane.WARNING_MESSAGE);
546       return;
547     }
548   }
549
550   /**
551    * Open a new Tree panel on the desktop
552    * 
553    * @param tree
554    * @param params
555    * @param treeAlgo
556    */
557   protected void openTreePanel(TreeModel tree, String treeAlgo,
558           String substitutionMatrix)
559   {
560     /*
561      * gui validation shouldn't allow insufficient sequences here, but leave
562      * this check in in case this method gets exposed programmatically in future
563      */
564     checkEnoughSequences(af.getViewport());
565
566     af.newTreePanel(tree, treeAlgo, substitutionMatrix);
567   }
568
569   /**
570    * Open a new PCA panel on the desktop
571    * 
572    * @param modelName
573    * @param params
574    */
575   protected void openPcaPanel(String modelName, SimilarityParamsI params)
576   {
577     AlignViewport viewport = af.getViewport();
578
579     /*
580      * gui validation shouldn't allow insufficient sequences here, but leave
581      * this check in in case this method gets exposed programmatically in future
582      */
583     if (((viewport.getSelectionGroup() != null)
584             && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
585             && (viewport.getSelectionGroup().getSize() > 0))
586             || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
587     {
588       JvOptionPane.showInternalMessageDialog(this,
589               MessageManager.formatMessage(
590                       "label.you_need_at_least_n_sequences",
591                       MIN_PCA_SELECTION),
592               MessageManager
593                       .getString("label.sequence_selection_insufficient"),
594               JvOptionPane.WARNING_MESSAGE);
595       return;
596     }
597     pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
598   }
599
600   /**
601    * 
602    */
603   protected void closeFrame()
604   {
605     try
606     {
607       frame.setClosed(true);
608     } catch (PropertyVetoException ex)
609     {
610     }
611   }
612
613   /**
614    * Returns a data bean holding parameters for similarity (or distance) model
615    * calculation
616    * 
617    * @param doPCA
618    * @return
619    */
620   protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
621   {
622     // commented out: parameter choices read from gui widgets
623     // SimilarityParamsI params = new SimilarityParams(
624     // includeGappedColumns.isSelected(), matchGaps.isSelected(),
625     // includeGaps.isSelected(), shorterSequence.isSelected());
626
627     boolean includeGapGap = true;
628     boolean includeGapResidue = true;
629     boolean matchOnShortestLength = false;
630
631     /*
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)
636      */
637     boolean matchGap = doPCA ? false : treeMatchGaps;
638
639     return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
640             matchOnShortestLength);
641   }
642
643   /**
644    * Closes dialog on Close button press
645    */
646   protected void close_actionPerformed()
647   {
648     try
649     {
650       frame.setClosed(true);
651     } catch (Exception ex)
652     {
653     }
654   }
655
656   public PCAPanel getPcaPanel()
657   {
658     return pcaPanel;
659   }
660 }