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