forester as submodule with InternalFrame + start of distance conversion
[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.ArchaeopteryxTreeBuilder;
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.util.ArrayList;
50 import java.util.List;
51
52 import javax.swing.BorderFactory;
53 import javax.swing.ButtonGroup;
54 import javax.swing.DefaultComboBoxModel;
55 import javax.swing.JButton;
56 import javax.swing.JCheckBox;
57 import javax.swing.JComboBox;
58 import javax.swing.JInternalFrame;
59 import javax.swing.JLabel;
60 import javax.swing.JLayeredPane;
61 import javax.swing.JPanel;
62 import javax.swing.JRadioButton;
63 import javax.swing.event.InternalFrameAdapter;
64 import javax.swing.event.InternalFrameEvent;
65
66 import org.forester.archaeopteryx.Archaeopteryx;
67 import org.forester.archaeopteryx.MainFrame;
68 import org.forester.phylogeny.Phylogeny;
69
70 /**
71  * A dialog where a user can choose and action Tree or PCA calculation options
72  */
73 public class CalculationChooser extends JPanel
74 {
75   /*
76    * flag for whether gap matches residue in the PID calculation for a Tree
77    * - true gives Jalview 2.10.1 behaviour
78    * - set to false (using Groovy) for a more correct tree
79    * (JAL-374)
80    */
81   private static boolean treeMatchGaps = true;
82
83   private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
84
85   private static final int MIN_TREE_SELECTION = 3;
86
87   private static final int MIN_PCA_SELECTION = 4;
88
89   AlignFrame af;
90
91   JRadioButton pca;
92
93   JRadioButton neighbourJoining;
94
95   JRadioButton averageDistance;
96
97   JComboBox<String> modelNames;
98
99   JButton calculate;
100
101   private JInternalFrame frame;
102
103   private JCheckBox includeGaps;
104
105   private JCheckBox matchGaps;
106
107   private JCheckBox includeGappedColumns;
108
109   private JCheckBox shorterSequence;
110
111   final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
112
113   List<String> tips = new ArrayList<>();
114
115   /**
116    * Constructor
117    * 
118    * @param af
119    */
120   public CalculationChooser(AlignFrame alignFrame)
121   {
122     this.af = alignFrame;
123     init();
124     af.alignPanel.setCalculationDialog(this);
125   }
126
127   /**
128    * Lays out the panel and adds it to the desktop
129    */
130   void init()
131   {
132     setLayout(new BorderLayout());
133     frame = new JInternalFrame();
134     frame.setContentPane(this);
135     this.setBackground(Color.white);
136     frame.addFocusListener(new FocusListener()
137     {
138
139       @Override
140       public void focusLost(FocusEvent e)
141       {
142       }
143
144       @Override
145       public void focusGained(FocusEvent e)
146       {
147         validateCalcTypes();
148       }
149     });
150     /*
151      * Layout consists of 3 or 4 panels:
152      * - first with choice of PCA or tree method NJ or AV
153      * - second with choice of score model
154      * - third with score model parameter options [suppressed]
155      * - fourth with OK and Cancel
156      */
157     pca = new JRadioButton(
158             MessageManager.getString("label.principal_component_analysis"));
159     pca.setOpaque(false);
160     neighbourJoining = new JRadioButton(
161             MessageManager.getString("label.tree_calc_nj"));
162     neighbourJoining.setSelected(true);
163     averageDistance = new JRadioButton(
164             MessageManager.getString("label.tree_calc_av"));
165     neighbourJoining.setOpaque(false);
166
167     JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
168     calcChoicePanel.setOpaque(false);
169
170     // first create the Tree calculation's border panel
171     JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
172     treePanel.setOpaque(false);
173
174     treePanel.setBorder(BorderFactory
175             .createTitledBorder(MessageManager.getString("label.tree")));
176
177     // then copy the inset dimensions for the border-less PCA panel
178     JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
179     Insets b = treePanel.getBorder().getBorderInsets(treePanel);
180     pcaBorderless.setBorder(
181             BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
182     pcaBorderless.setOpaque(false);
183
184     pcaBorderless.add(pca, FlowLayout.LEFT);
185     calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
186
187     treePanel.add(neighbourJoining);
188     treePanel.add(averageDistance);
189
190     calcChoicePanel.add(treePanel);
191
192     ButtonGroup calcTypes = new ButtonGroup();
193     calcTypes.add(pca);
194     calcTypes.add(neighbourJoining);
195     calcTypes.add(averageDistance);
196
197     ActionListener calcChanged = new ActionListener()
198     {
199       @Override
200       public void actionPerformed(ActionEvent e)
201       {
202         validateCalcTypes();
203       }
204     };
205     pca.addActionListener(calcChanged);
206     neighbourJoining.addActionListener(calcChanged);
207     averageDistance.addActionListener(calcChanged);
208
209     /*
210      * score models drop-down - with added tooltips!
211      */
212     modelNames = buildModelOptionsList();
213
214     JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
215     scoreModelPanel.setOpaque(false);
216     scoreModelPanel.add(modelNames);
217
218     /*
219      * score model parameters
220      */
221     JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
222     paramsPanel.setOpaque(false);
223     includeGaps = new JCheckBox("Include gaps");
224     matchGaps = new JCheckBox("Match gaps");
225     includeGappedColumns = new JCheckBox("Include gapped columns");
226     shorterSequence = new JCheckBox("Match on shorter sequence");
227     paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
228     paramsPanel.add(includeGaps);
229     paramsPanel.add(matchGaps);
230     paramsPanel.add(includeGappedColumns);
231     paramsPanel.add(shorterSequence);
232
233     /*
234      * OK / Cancel buttons
235      */
236     calculate = new JButton(MessageManager.getString("action.calculate"));
237     calculate.setFont(VERDANA_11PT);
238     calculate.addActionListener(new java.awt.event.ActionListener()
239     {
240       @Override
241       public void actionPerformed(ActionEvent e)
242       {
243         calculate_actionPerformed();
244       }
245     });
246     JButton close = new JButton(MessageManager.getString("action.close"));
247     close.setFont(VERDANA_11PT);
248     close.addActionListener(new java.awt.event.ActionListener()
249     {
250       @Override
251       public void actionPerformed(ActionEvent e)
252       {
253         close_actionPerformed();
254       }
255     });
256     JPanel actionPanel = new JPanel();
257     actionPanel.setOpaque(false);
258     actionPanel.add(calculate);
259     actionPanel.add(close);
260
261     boolean includeParams = false;
262     this.add(calcChoicePanel, BorderLayout.CENTER);
263     calcChoicePanel.add(scoreModelPanel);
264     if (includeParams)
265     {
266       scoreModelPanel.add(paramsPanel);
267     }
268     this.add(actionPanel, BorderLayout.SOUTH);
269
270     int width = 350;
271     int height = includeParams ? 420 : 240;
272
273     setMinimumSize(new Dimension(325, height - 10));
274     String title = MessageManager.getString("label.choose_calculation");
275     if (af.getViewport().viewName != null)
276     {
277       title = title + " (" + af.getViewport().viewName + ")";
278     }
279
280     Desktop.addInternalFrame(frame, title, width, height, false);
281     calcChoicePanel.doLayout();
282     revalidate();
283     /*
284      * null the AlignmentPanel's reference to the dialog when it is closed
285      */
286     frame.addInternalFrameListener(new InternalFrameAdapter()
287     {
288       @Override
289       public void internalFrameClosed(InternalFrameEvent evt)
290       {
291         af.alignPanel.setCalculationDialog(null);
292       };
293     });
294
295     frame.setLayer(JLayeredPane.PALETTE_LAYER);
296   }
297
298   /**
299    * enable calculations applicable for the current alignment or selection.
300    */
301   protected void validateCalcTypes()
302   {
303     int size = af.getViewport().getAlignment().getHeight();
304     if (af.getViewport().getSelectionGroup() != null)
305     {
306       size = af.getViewport().getSelectionGroup().getSize();
307     }
308
309     /*
310      * disable calc options for which there is insufficient input data
311      * return value of true means enabled and selected
312      */
313     boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
314     boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
315             MIN_TREE_SELECTION);
316     boolean checkAverageDistance = checkEnabled(averageDistance, size,
317             MIN_TREE_SELECTION);
318
319     if (checkPca || checkNeighbourJoining || checkAverageDistance)
320     {
321       calculate.setToolTipText(null);
322       calculate.setEnabled(true);
323     }
324     else
325     {
326       calculate.setEnabled(false);
327     }
328     updateScoreModels(modelNames, tips);
329   }
330
331   /**
332    * Check the input and disable a calculation's radio button if necessary. A
333    * tooltip is shown for disabled calculations.
334    * 
335    * @param calc
336    *          - radio button for the calculation being validated
337    * @param size
338    *          - size of input to calculation
339    * @param minsize
340    *          - minimum size for calculation
341    * @return true if size >= minsize and calc.isSelected
342    */
343   private boolean checkEnabled(JRadioButton calc, int size, int minsize)
344   {
345     String ttip = MessageManager
346             .formatMessage("label.you_need_at_least_n_sequences", minsize);
347
348     calc.setEnabled(size >= minsize);
349     if (!calc.isEnabled())
350     {
351       calc.setToolTipText(ttip);
352     }
353     else
354     {
355       calc.setToolTipText(null);
356     }
357     if (calc.isSelected())
358     {
359       modelNames.setEnabled(calc.isEnabled());
360       if (calc.isEnabled())
361       {
362         return true;
363       }
364       else
365       {
366         calculate.setToolTipText(ttip);
367       }
368     }
369     return false;
370   }
371
372   /**
373    * A rather elaborate helper method (blame Swing, not me) that builds a
374    * drop-down list of score models (by name) with descriptions as tooltips.
375    * There is also a tooltip shown for the currently selected item when hovering
376    * over it (without opening the list).
377    */
378   protected JComboBox<String> buildModelOptionsList()
379   {
380     final JComboBox<String> scoreModelsCombo = new JComboBox<>();
381     scoreModelsCombo.setRenderer(renderer);
382
383     /*
384      * show tooltip on mouse over the combobox
385      * note the listener has to be on the components that make up
386      * the combobox, doesn't work if just on the combobox
387      */
388     final MouseAdapter mouseListener = new MouseAdapter()
389     {
390       @Override
391       public void mouseEntered(MouseEvent e)
392       {
393         scoreModelsCombo.setToolTipText(
394                 tips.get(scoreModelsCombo.getSelectedIndex()));
395       }
396
397       @Override
398       public void mouseExited(MouseEvent e)
399       {
400         scoreModelsCombo.setToolTipText(null);
401       }
402     };
403     for (Component c : scoreModelsCombo.getComponents())
404     {
405       c.addMouseListener(mouseListener);
406     }
407
408     updateScoreModels(scoreModelsCombo, tips);
409
410     /*
411      * set the list of tooltips on the combobox's renderer
412      */
413     renderer.setTooltips(tips);
414
415     return scoreModelsCombo;
416   }
417
418   private void updateScoreModels(JComboBox<String> comboBox,
419           List<String> toolTips)
420   {
421     Object curSel = comboBox.getSelectedItem();
422     toolTips.clear();
423     DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
424
425     /*
426      * now we can actually add entries to the combobox,
427      * remembering their descriptions for tooltips
428      */
429     ScoreModels scoreModels = ScoreModels.getInstance();
430     boolean selectedIsPresent = false;
431     for (ScoreModelI sm : scoreModels.getModels())
432     {
433       boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
434       if (sm.isDNA() && nucleotide || sm.isProtein() && !nucleotide)
435       {
436         if (curSel != null && sm.getName().equals(curSel))
437         {
438           selectedIsPresent = true;
439           curSel = sm.getName();
440         }
441         model.addElement(sm.getName());
442
443         /*
444          * tooltip is description if provided, else text lookup with
445          * fallback on the model name
446          */
447         String tooltip = sm.getDescription();
448         if (tooltip == null)
449         {
450           tooltip = MessageManager.getStringOrReturn("label.score_model_",
451                   sm.getName());
452         }
453         toolTips.add(tooltip);
454       }
455     }
456     if (selectedIsPresent)
457     {
458       model.setSelectedItem(curSel);
459     }
460     // finally, update the model
461     comboBox.setModel(model);
462   }
463
464   /**
465    * Open and calculate the selected tree or PCA on 'OK'
466    */
467   protected void calculate_actionPerformed()
468   {
469     boolean doPCA = pca.isSelected();
470     String substitutionMatrix = modelNames.getSelectedItem().toString();
471     SimilarityParamsI params = getSimilarityParameters(doPCA);
472
473     if (doPCA)
474     {
475       openPcaPanel(substitutionMatrix, params);
476     }
477     else
478     {
479
480       String treeAlgo = determineTreeAlgo();
481       TreeCalculator treeCalculator = new TreeCalculator(treeAlgo,
482               substitutionMatrix, params);
483       TreeBuilder calculatedTree = treeCalculator
484               .makeTree(af.getViewport());
485       TreeModel tree = new TreeModel(calculatedTree);
486       openTreePanel(tree, treeAlgo, substitutionMatrix);
487
488       ArchaeopteryxTreeBuilder aptxTreeBuilder = new ArchaeopteryxTreeBuilder();
489       Phylogeny aptxTree = aptxTreeBuilder.buildAptxTree(calculatedTree);
490       MainFrame aptxFrame = Archaeopteryx.createApplication(aptxTree);
491
492       int width = 400;
493       int height = 550;
494       aptxFrame.setMinimumSize(new Dimension(width - 30, height - 50)); // doesn't
495                                                                         // work
496                                                                         // as it
497                                                                         // gets
498                                                                         // overridden
499                                                                         // during
500                                                                         // addInternalFrame?
501
502       Desktop.addInternalFrame(aptxFrame, "Archaeopteryx Tree View",
503               width, height, true);
504
505     }
506
507     // closeFrame();
508   }
509
510   protected String determineTreeAlgo() // to be modified & expanded
511   {
512     String treeAlgorithm = neighbourJoining.isSelected()
513             ? TreeBuilder.NEIGHBOUR_JOINING
514             : TreeBuilder.AVERAGE_DISTANCE;
515
516     return treeAlgorithm;
517
518   }
519
520   protected void checkEnoughSequences(AlignViewport viewport)
521   {
522     SequenceGroup sg = viewport.getSelectionGroup();
523     if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
524     {
525       JvOptionPane.showMessageDialog(Desktop.desktop,
526               MessageManager.formatMessage(
527                       "label.you_need_at_least_n_sequences",
528                       MIN_TREE_SELECTION),
529               MessageManager.getString("label.not_enough_sequences"),
530               JvOptionPane.WARNING_MESSAGE);
531       return;
532     }
533   }
534
535   /**
536    * Open a new Tree panel on the desktop
537    * 
538    * @param tree
539    * @param params
540    * @param treeAlgo
541    */
542   protected void openTreePanel(TreeModel tree, String treeAlgo,
543           String substitutionMatrix)
544   {
545     /*
546      * gui validation shouldn't allow insufficient sequences here, but leave
547      * this check in in case this method gets exposed programmatically in future
548      */
549     checkEnoughSequences(af.getViewport());
550
551     af.newTreePanel(tree, treeAlgo, substitutionMatrix);
552   }
553
554   /**
555    * Open a new PCA panel on the desktop
556    * 
557    * @param modelName
558    * @param params
559    */
560   protected void openPcaPanel(String modelName, SimilarityParamsI params)
561   {
562     AlignViewport viewport = af.getViewport();
563
564     /*
565      * gui validation shouldn't allow insufficient sequences here, but leave
566      * this check in in case this method gets exposed programmatically in future
567      */
568     if (((viewport.getSelectionGroup() != null)
569             && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
570             && (viewport.getSelectionGroup().getSize() > 0))
571             || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
572     {
573       JvOptionPane.showInternalMessageDialog(this,
574               MessageManager.formatMessage(
575                       "label.you_need_at_least_n_sequences",
576                       MIN_PCA_SELECTION),
577               MessageManager
578                       .getString("label.sequence_selection_insufficient"),
579               JvOptionPane.WARNING_MESSAGE);
580       return;
581     }
582     new PCAPanel(af.alignPanel, modelName, params);
583   }
584
585   /**
586    * 
587    */
588   protected void closeFrame()
589   {
590     try
591     {
592       frame.setClosed(true);
593     } catch (PropertyVetoException ex)
594     {
595     }
596   }
597
598   /**
599    * Returns a data bean holding parameters for similarity (or distance) model
600    * calculation
601    * 
602    * @param doPCA
603    * @return
604    */
605   protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
606   {
607     // commented out: parameter choices read from gui widgets
608     // SimilarityParamsI params = new SimilarityParams(
609     // includeGappedColumns.isSelected(), matchGaps.isSelected(),
610     // includeGaps.isSelected(), shorterSequence.isSelected());
611
612     boolean includeGapGap = true;
613     boolean includeGapResidue = true;
614     boolean matchOnShortestLength = false;
615
616     /*
617      * 'matchGaps' flag is only used in the PID calculation
618      * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
619      * - set to true for Tree to reproduce Jalview 2.10.1 calculation
620      * - set to false for Tree for a more correct calculation (JAL-374)
621      */
622     boolean matchGap = doPCA ? false : treeMatchGaps;
623
624
625     return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
626             matchOnShortestLength);
627   }
628
629   /**
630    * Closes dialog on Close button press
631    */
632   protected void close_actionPerformed()
633   {
634     try
635     {
636       frame.setClosed(true);
637     } catch (Exception ex)
638     {
639     }
640   }
641 }