d126cc37fcd281e02a473776677083083f476f80
[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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Dimension;
27 import java.awt.FlowLayout;
28 import java.awt.Font;
29 import java.awt.GridLayout;
30 import java.awt.Insets;
31 import java.awt.event.ActionEvent;
32 import java.awt.event.ActionListener;
33 import java.awt.event.FocusEvent;
34 import java.awt.event.FocusListener;
35 import java.awt.event.MouseAdapter;
36 import java.awt.event.MouseEvent;
37 import java.beans.PropertyVetoException;
38 import java.util.ArrayList;
39 import java.util.List;
40
41 import javax.swing.BorderFactory;
42 import javax.swing.ButtonGroup;
43 import javax.swing.DefaultComboBoxModel;
44 import javax.swing.JButton;
45 import javax.swing.JCheckBox;
46 import javax.swing.JComboBox;
47 import javax.swing.JInternalFrame;
48 import javax.swing.JLabel;
49 import javax.swing.JLayeredPane;
50 import javax.swing.JPanel;
51 import javax.swing.JRadioButton;
52 import javax.swing.event.InternalFrameAdapter;
53 import javax.swing.event.InternalFrameEvent;
54
55 import jalview.analysis.TreeBuilder;
56 import jalview.analysis.scoremodels.ScoreModels;
57 import jalview.analysis.scoremodels.SimilarityParams;
58 import jalview.api.analysis.ScoreModelI;
59 import jalview.api.analysis.SimilarityParamsI;
60 import jalview.bin.Cache;
61 import jalview.datamodel.AlignmentAnnotation;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.util.MessageManager;
64
65 /**
66  * A dialog where a user can choose and action Tree or PCA calculation options
67  */
68 public class CalculationChooser extends JPanel
69 {
70   /*
71    * flag for whether gap matches residue in the PID calculation for a Tree
72    * - true gives Jalview 2.10.1 behaviour
73    * - set to false (using Groovy) for a more correct tree
74    * (JAL-374)
75    */
76   private static boolean treeMatchGaps = true;
77
78   private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
79
80   private static final int MIN_TREE_SELECTION = 3;
81
82   private static final int MIN_PCA_SELECTION = 4;
83   
84   private static final String SS_ANNOTATION_LABEL = "Secondary Structure";
85   
86   private static final String SS_ANNOTATION_FROM_JPRED_LABEL = "jnetpred";
87
88   AlignFrame af;
89
90   JRadioButton pca;
91
92   JRadioButton neighbourJoining;
93
94   JRadioButton averageDistance;
95
96   JComboBox<String> modelNames;
97   
98   JComboBox<String> ssSourceDropdown;
99
100   JButton calculate;
101
102   private JInternalFrame frame;
103
104   private JCheckBox includeGaps;
105
106   private JCheckBox matchGaps;
107
108   private JCheckBox includeGappedColumns;
109
110   private JCheckBox shorterSequence;
111
112   final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
113
114   List<String> tips = new ArrayList<>();
115
116   /*
117    * the most recently opened PCA results panel
118    */
119   private PCAPanel pcaPanel;
120
121   /**
122    * Constructor
123    * 
124    * @param af
125    */
126   public CalculationChooser(AlignFrame alignFrame)
127   {
128     this.af = alignFrame;
129     init();
130     af.alignPanel.setCalculationDialog(this);
131   }
132
133   /**
134    * Lays out the panel and adds it to the desktop
135    */
136   void init()
137   {
138     setLayout(new BorderLayout());
139     frame = new JInternalFrame();
140     frame.setFrameIcon(null);
141     frame.setContentPane(this);
142     this.setBackground(Color.white);
143     frame.addFocusListener(new FocusListener()
144     {
145
146       @Override
147       public void focusLost(FocusEvent e)
148       {
149       }
150
151       @Override
152       public void focusGained(FocusEvent e)
153       {
154         validateCalcTypes();
155       }
156     });
157     /*
158      * Layout consists of 3 or 4 panels:
159      * - first with choice of PCA or tree method NJ or AV
160      * - second with choice of score model
161      * - third with score model parameter options [suppressed]
162      * - fourth with OK and Cancel
163      */
164     pca = new JRadioButton(
165             MessageManager.getString("label.principal_component_analysis"));
166     pca.setOpaque(false);
167
168     neighbourJoining = new JRadioButton(
169             MessageManager.getString("label.tree_calc_nj"));
170     neighbourJoining.setSelected(true);
171     neighbourJoining.setOpaque(false);
172
173     averageDistance = new JRadioButton(
174             MessageManager.getString("label.tree_calc_av"));
175     averageDistance.setOpaque(false);
176
177     JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
178     calcChoicePanel.setOpaque(false);
179
180     // first create the Tree calculation's border panel
181     JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
182     treePanel.setOpaque(false);
183
184     JvSwingUtils.createTitledBorder(treePanel,
185             MessageManager.getString("label.tree"), true);
186
187     // then copy the inset dimensions for the border-less PCA panel
188     JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
189     Insets b = treePanel.getBorder().getBorderInsets(treePanel);
190     pcaBorderless.setBorder(
191             BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
192     pcaBorderless.setOpaque(false);
193
194     pcaBorderless.add(pca, FlowLayout.LEFT);
195     calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
196
197     treePanel.add(neighbourJoining);
198     treePanel.add(averageDistance);
199
200     calcChoicePanel.add(treePanel);
201
202     ButtonGroup calcTypes = new ButtonGroup();
203     calcTypes.add(pca);
204     calcTypes.add(neighbourJoining);
205     calcTypes.add(averageDistance);
206
207     ActionListener calcChanged = new ActionListener()
208     {
209       @Override
210       public void actionPerformed(ActionEvent e)
211       {
212         validateCalcTypes();
213       }
214     };
215     pca.addActionListener(calcChanged);
216     neighbourJoining.addActionListener(calcChanged);
217     averageDistance.addActionListener(calcChanged);
218     
219     
220     //to do    
221     ssSourceDropdown = buildSSSourcesOptionsList();
222     ssSourceDropdown.setVisible(false); // Initially hide the dropdown
223
224     /*
225      * score models drop-down - with added tooltips!
226      */
227     modelNames = buildModelOptionsList();
228     // Step 3: Show or Hide Dropdown Based on Selection
229     modelNames.addActionListener(new ActionListener() {
230         @Override
231         public void actionPerformed(ActionEvent e) {
232             String selectedModel = modelNames.getSelectedItem().toString();
233             if (selectedModel.equals("Secondary Structure Similarity")) {
234               ssSourceDropdown.setVisible(true);
235             } else {
236               ssSourceDropdown.setVisible(false);
237             }
238         }
239     });
240
241     JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
242     scoreModelPanel.setOpaque(false);
243     scoreModelPanel.add(modelNames);
244     scoreModelPanel.add(ssSourceDropdown);
245     
246     /*
247      * score model parameters
248      */
249     JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
250     paramsPanel.setOpaque(false);
251     includeGaps = new JCheckBox("Include gaps");
252     matchGaps = new JCheckBox("Match gaps");
253     includeGappedColumns = new JCheckBox("Include gapped columns");
254     shorterSequence = new JCheckBox("Match on shorter sequence");
255     paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
256     paramsPanel.add(includeGaps);
257     paramsPanel.add(matchGaps);
258     paramsPanel.add(includeGappedColumns);
259     paramsPanel.add(shorterSequence);
260     
261     /*
262      * OK / Cancel buttons
263      */
264     calculate = new JButton(MessageManager.getString("action.calculate"));
265     calculate.setFont(VERDANA_11PT);
266     calculate.addActionListener(new java.awt.event.ActionListener()
267     {
268       @Override
269       public void actionPerformed(ActionEvent e)
270       {
271         calculate_actionPerformed();
272       }
273     });
274     JButton close = new JButton(MessageManager.getString("action.close"));
275     close.setFont(VERDANA_11PT);
276     close.addActionListener(new java.awt.event.ActionListener()
277     {
278       @Override
279       public void actionPerformed(ActionEvent e)
280       {
281         close_actionPerformed();
282       }
283     });
284     JPanel actionPanel = new JPanel();
285     actionPanel.setOpaque(false);
286     actionPanel.add(calculate);
287     actionPanel.add(close);
288
289     boolean includeParams = false;
290     this.add(calcChoicePanel, BorderLayout.CENTER);
291     calcChoicePanel.add(scoreModelPanel);
292     if (includeParams)
293     {
294       scoreModelPanel.add(paramsPanel);
295     }
296     this.add(actionPanel, BorderLayout.SOUTH);
297
298     int width = 365;
299     int height = includeParams ? 420 : 240;
300
301     setMinimumSize(new Dimension(325, height - 10));
302     String title = MessageManager.getString("label.choose_calculation");
303     if (af.getViewport().getViewName() != null)
304     {
305       title = title + " (" + af.getViewport().getViewName() + ")";
306     }
307
308     Desktop.addInternalFrame(frame, title, width, height, false);
309     calcChoicePanel.doLayout();
310     revalidate();
311     /*
312      * null the AlignmentPanel's reference to the dialog when it is closed
313      */
314     frame.addInternalFrameListener(new InternalFrameAdapter()
315     {
316       @Override
317       public void internalFrameClosed(InternalFrameEvent evt)
318       {
319         af.alignPanel.setCalculationDialog(null);
320       };
321     });
322
323     validateCalcTypes();
324     frame.setLayer(JLayeredPane.PALETTE_LAYER);
325   }
326
327   /**
328    * enable calculations applicable for the current alignment or selection.
329    */
330   protected void validateCalcTypes()
331   {
332     int size = af.getViewport().getAlignment().getHeight();
333     if (af.getViewport().getSelectionGroup() != null)
334     {
335       size = af.getViewport().getSelectionGroup().getSize();
336     }
337
338     /*
339      * disable calc options for which there is insufficient input data
340      * return value of true means enabled and selected
341      */
342     boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
343     boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
344             MIN_TREE_SELECTION);
345     boolean checkAverageDistance = checkEnabled(averageDistance, size,
346             MIN_TREE_SELECTION);
347
348     if (checkPca || checkNeighbourJoining || checkAverageDistance)
349     {
350       calculate.setToolTipText(null);
351       calculate.setEnabled(true);
352     }
353     else
354     {
355       calculate.setEnabled(false);
356     }
357     updateScoreModels(modelNames, tips);
358   }
359
360   /**
361    * Check the input and disable a calculation's radio button if necessary. A
362    * tooltip is shown for disabled calculations.
363    * 
364    * @param calc
365    *          - radio button for the calculation being validated
366    * @param size
367    *          - size of input to calculation
368    * @param minsize
369    *          - minimum size for calculation
370    * @return true if size >= minsize and calc.isSelected
371    */
372   private boolean checkEnabled(JRadioButton calc, int size, int minsize)
373   {
374     String ttip = MessageManager
375             .formatMessage("label.you_need_at_least_n_sequences", minsize);
376
377     calc.setEnabled(size >= minsize);
378     if (!calc.isEnabled())
379     {
380       calc.setToolTipText(ttip);
381     }
382     else
383     {
384       calc.setToolTipText(null);
385     }
386     if (calc.isSelected())
387     {
388       modelNames.setEnabled(calc.isEnabled());
389       if (calc.isEnabled())
390       {
391         return true;
392       }
393       else
394       {
395         calculate.setToolTipText(ttip);
396       }
397     }
398     return false;
399   }
400
401   /**
402    * A rather elaborate helper method (blame Swing, not me) that builds a
403    * drop-down list of score models (by name) with descriptions as tooltips.
404    * There is also a tooltip shown for the currently selected item when hovering
405    * over it (without opening the list).
406    */
407   protected JComboBox<String> buildModelOptionsList()
408   {
409     final JComboBox<String> scoreModelsCombo = new JComboBox<>();
410     scoreModelsCombo.setRenderer(renderer);
411
412     /*
413      * show tooltip on mouse over the combobox
414      * note the listener has to be on the components that make up
415      * the combobox, doesn't work if just on the combobox
416      */
417     final MouseAdapter mouseListener = new MouseAdapter()
418     {
419       @Override
420       public void mouseEntered(MouseEvent e)
421       {
422         scoreModelsCombo.setToolTipText(
423                 tips.get(scoreModelsCombo.getSelectedIndex()));
424       }
425
426       @Override
427       public void mouseExited(MouseEvent e)
428       {
429         scoreModelsCombo.setToolTipText(null);
430       }
431     };
432     for (Component c : scoreModelsCombo.getComponents())
433     {
434       c.addMouseListener(mouseListener);
435     }
436
437     updateScoreModels(scoreModelsCombo, tips);
438
439     /*
440      * set the list of tooltips on the combobox's renderer
441      */
442     renderer.setTooltips(tips);
443
444     return scoreModelsCombo;
445   }
446   
447
448   private JComboBox<String> buildSSSourcesOptionsList()
449   {
450     final JComboBox<String> comboBox = new JComboBox<>();
451     Object curSel = comboBox.getSelectedItem();
452     DefaultComboBoxModel<String> sourcesModel = new DefaultComboBoxModel<>();
453
454     List<String> ssSources = getApplicableSecondaryStructureSources();
455
456     boolean selectedIsPresent = false;
457     for (String source : ssSources)
458     {
459       if (curSel != null && source.equals(curSel))
460       {
461         selectedIsPresent = true;
462         curSel = source;
463       }
464       sourcesModel.addElement(source);
465       
466     }
467
468     if (selectedIsPresent)
469     {
470       sourcesModel.setSelectedItem(curSel);
471     }
472     comboBox.setModel(sourcesModel);
473     
474     return comboBox;
475   }
476   
477   
478   private void updateScoreModels(JComboBox<String> comboBox,
479           List<String> toolTips)
480   {
481     Object curSel = comboBox.getSelectedItem();
482     toolTips.clear();
483     DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
484
485     /*
486      * select the score models applicable to the alignment type
487      */
488     boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
489     AlignmentAnnotation[] alignmentAnnotation = af.getViewport().getAlignment().getAlignmentAnnotation();
490
491     boolean ssPresent = false;
492
493     for (AlignmentAnnotation aa : alignmentAnnotation)
494
495     {
496       if(ssPresent) {
497         break;
498       }     
499
500       if (aa.label.equals("Secondary Structure") || aa.label.equals("jnetpred"))
501
502       {
503         ssPresent = true;
504         break;
505       }
506     }
507
508     List<ScoreModelI> models = getApplicableScoreModels(nucleotide, pca.isSelected(),
509             ssPresent);
510
511     /*
512      * now we can actually add entries to the combobox,
513      * remembering their descriptions for tooltips
514      */
515     boolean selectedIsPresent = false;
516     for (ScoreModelI sm : models)
517     {
518       if (curSel != null && sm.getName().equals(curSel))
519       {
520         selectedIsPresent = true;
521         curSel = sm.getName();
522       }
523       model.addElement(sm.getName());
524
525       /*
526        * tooltip is description if provided, else text lookup with
527        * fallback on the model name
528        */
529       String tooltip = sm.getDescription();
530       if (tooltip == null)
531       {
532         tooltip = MessageManager.getStringOrReturn("label.score_model_",
533                 sm.getName());
534       }
535       toolTips.add(tooltip);
536     }
537
538     if (selectedIsPresent)
539     {
540       model.setSelectedItem(curSel);
541     }
542     // finally, update the model
543     comboBox.setModel(model);
544   }
545
546   /**
547    * Builds a list of score models which are applicable for the alignment and
548    * calculation type (peptide or generic models for protein, nucleotide or
549    * generic models for nucleotide).
550    * <p>
551    * As a special case, includes BLOSUM62 as an extra option for nucleotide PCA.
552    * This is for backwards compatibility with Jalview prior to 2.8 when BLOSUM62
553    * was the only score matrix supported. This is included if property
554    * BLOSUM62_PCA_FOR_NUCLEOTIDE is set to true in the Jalview properties file.
555    * 
556    * @param nucleotide
557    * @param forPca
558    * @return
559    */
560   protected static List<ScoreModelI> getApplicableScoreModels(
561           boolean nucleotide, boolean forPca, boolean ssPresent)
562   {
563     List<ScoreModelI> filtered = new ArrayList<>();
564
565     ScoreModels scoreModels = ScoreModels.getInstance();
566     for (ScoreModelI sm : scoreModels.getModels())
567     {
568       if (!nucleotide && sm.isProtein() || nucleotide && sm.isDNA() 
569               || ssPresent && sm.isSecondaryStructure())
570       {
571         filtered.add(sm);
572       }
573     }
574
575     /*
576      * special case: add BLOSUM62 as last option for nucleotide PCA, 
577      * for backwards compatibility with Jalview < 2.8 (JAL-2962)
578      */
579     if (nucleotide && forPca
580             && Cache.getDefault("BLOSUM62_PCA_FOR_NUCLEOTIDE", false))
581     {
582       filtered.add(scoreModels.getBlosum62());
583     }
584     
585     return filtered;
586   }
587
588   
589   protected List<String> getApplicableSecondaryStructureSources()
590   {
591     List<String> ssSources = new ArrayList<>();
592     
593     AlignmentAnnotation[] annotations = af.getViewport().getAlignment().getAlignmentAnnotation();
594     boolean has3DStructure = false, hasJPred = false;
595     if(annotations.length > 0) {
596       
597       for (AlignmentAnnotation annotation : annotations) {
598         has3DStructure |= SS_ANNOTATION_LABEL.equals(annotation.label);
599         hasJPred |= SS_ANNOTATION_FROM_JPRED_LABEL.equals(annotation.label);
600         
601         if (has3DStructure && hasJPred)
602           break;
603       }
604     }
605     if(has3DStructure)
606       ssSources.add("3D Structures");
607     if(hasJPred)
608       ssSources.add("JPred");
609                  
610     return ssSources;
611   }
612   
613   /**
614    * Open and calculate the selected tree or PCA on 'OK'
615    */
616   protected void calculate_actionPerformed()
617   {
618     boolean doPCA = pca.isSelected();
619     String modelName = modelNames.getSelectedItem().toString();
620     String ssSource = ssSourceDropdown.getSelectedItem().toString();
621     SimilarityParams params = getSimilarityParameters(doPCA);
622     if(ssSource.length()>0)
623       params.setSecondaryStructureSource(ssSource);
624     if (doPCA)
625     {
626       openPcaPanel(modelName, params);
627     }
628     else
629     {
630       openTreePanel(modelName, params);
631     }
632
633     // closeFrame();
634   }
635
636   /**
637    * Open a new Tree panel on the desktop
638    * 
639    * @param modelName
640    * @param params
641    */
642   protected void openTreePanel(String modelName, SimilarityParamsI params)
643   {
644     /*
645      * gui validation shouldn't allow insufficient sequences here, but leave
646      * this check in in case this method gets exposed programmatically in future
647      */
648     AlignViewport viewport = af.getViewport();
649     SequenceGroup sg = viewport.getSelectionGroup();
650     if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
651     {
652       JvOptionPane.showMessageDialog(Desktop.desktop,
653               MessageManager.formatMessage(
654                       "label.you_need_at_least_n_sequences",
655                       MIN_TREE_SELECTION),
656               MessageManager.getString("label.not_enough_sequences"),
657               JvOptionPane.WARNING_MESSAGE);
658       return;
659     }
660
661     String treeType = neighbourJoining.isSelected()
662             ? TreeBuilder.NEIGHBOUR_JOINING
663             : TreeBuilder.AVERAGE_DISTANCE;
664     af.newTreePanel(treeType, modelName, params);
665   }
666
667   /**
668    * Open a new PCA panel on the desktop
669    * 
670    * @param modelName
671    * @param params
672    */
673   protected void openPcaPanel(String modelName, SimilarityParamsI params)
674   {
675     AlignViewport viewport = af.getViewport();
676
677     /*
678      * gui validation shouldn't allow insufficient sequences here, but leave
679      * this check in in case this method gets exposed programmatically in future
680      */
681     if (((viewport.getSelectionGroup() != null)
682             && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
683             && (viewport.getSelectionGroup().getSize() > 0))
684             || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
685     {
686       JvOptionPane.showInternalMessageDialog(this,
687               MessageManager.formatMessage(
688                       "label.you_need_at_least_n_sequences",
689                       MIN_PCA_SELECTION),
690               MessageManager
691                       .getString("label.sequence_selection_insufficient"),
692               JvOptionPane.WARNING_MESSAGE);
693       return;
694     }
695
696     /*
697      * construct the panel and kick off its calculation thread
698      */
699     pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
700     new Thread(pcaPanel).start();
701
702   }
703
704   /**
705    * 
706    */
707   protected void closeFrame()
708   {
709     try
710     {
711       frame.setClosed(true);
712     } catch (PropertyVetoException ex)
713     {
714     }
715   }
716
717   /**
718    * Returns a data bean holding parameters for similarity (or distance) model
719    * calculation
720    * 
721    * @param doPCA
722    * @return
723    */
724   protected SimilarityParams getSimilarityParameters(boolean doPCA)
725   {
726     // commented out: parameter choices read from gui widgets
727     // SimilarityParamsI params = new SimilarityParams(
728     // includeGappedColumns.isSelected(), matchGaps.isSelected(),
729     // includeGaps.isSelected(), shorterSequence.isSelected());
730
731     boolean includeGapGap = true;
732     boolean includeGapResidue = true;
733     boolean matchOnShortestLength = false;
734
735     /*
736      * 'matchGaps' flag is only used in the PID calculation
737      * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
738      * - set to true for Tree to reproduce Jalview 2.10.1 calculation
739      * - set to false for Tree for a more correct calculation (JAL-374)
740      */
741     boolean matchGap = doPCA ? false : treeMatchGaps;
742
743     return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
744             matchOnShortestLength);
745   }
746
747   /**
748    * Closes dialog on Close button press
749    */
750   protected void close_actionPerformed()
751   {
752     try
753     {
754       frame.setClosed(true);
755     } catch (Exception ex)
756     {
757     }
758   }
759
760   public PCAPanel getPcaPanel()
761   {
762     return pcaPanel;
763   }
764 }