Merge branch 'features/JAL-1767pcaInProject' into bug/JAL-3171_maintain_datasets_acro...
[jalview.git] / src / jalview / gui / PCAPanel.java
index c1e935a..da1dffe 100644 (file)
 package jalview.gui;
 
 import jalview.analysis.scoremodels.ScoreModels;
-import jalview.analysis.scoremodels.SimilarityParams;
 import jalview.api.analysis.ScoreModelI;
 import jalview.api.analysis.SimilarityParamsI;
+import jalview.bin.Cache;
 import jalview.datamodel.Alignment;
 import jalview.datamodel.AlignmentI;
 import jalview.datamodel.AlignmentView;
 import jalview.datamodel.HiddenColumns;
 import jalview.datamodel.SequenceI;
 import jalview.jbgui.GPCAPanel;
+import jalview.math.RotatableMatrix.Axis;
+import jalview.util.ImageMaker;
 import jalview.util.MessageManager;
 import jalview.viewmodel.AlignmentViewport;
 import jalview.viewmodel.PCAModel;
@@ -46,7 +48,6 @@ import java.awt.print.PrinterException;
 import java.awt.print.PrinterJob;
 
 import javax.swing.ButtonGroup;
-import javax.swing.JCheckBoxMenuItem;
 import javax.swing.JColorChooser;
 import javax.swing.JMenuItem;
 import javax.swing.JRadioButtonMenuItem;
@@ -54,16 +55,14 @@ import javax.swing.event.InternalFrameAdapter;
 import javax.swing.event.InternalFrameEvent;
 
 /**
- * DOCUMENT ME!
- * 
- * @author $author$
- * @version $Revision$
+ * The panel holding the Principal Component Analysis 3-D visualisation
  */
 public class PCAPanel extends GPCAPanel
         implements Runnable, IProgressIndicator
 {
+  private static final int MIN_WIDTH = 470;
 
-  private IProgressIndicator progressBar;
+  private static final int MIN_HEIGHT = 250;
 
   RotatableCanvas rc;
 
@@ -73,28 +72,11 @@ public class PCAPanel extends GPCAPanel
 
   PCAModel pcaModel;
 
-  private static final int MIN_WIDTH = 470;
-
-  private static final int MIN_HEIGHT = 250;
-
   int top = 0;
 
-  private boolean working;
+  private IProgressIndicator progressBar;
 
-  /**
-   * Creates a new PCAPanel object using default score model and parameters
-   * 
-   * @param alignPanel
-   */
-  public PCAPanel(AlignmentPanel alignPanel)
-  {
-    this(alignPanel,
-            ScoreModels.getInstance()
-                    .getDefaultModel(
-                            !alignPanel.av.getAlignment().isNucleotide())
-                    .getName(),
-            SimilarityParams.SeqSpace);
-  }
+  private boolean working;
 
   /**
    * Constructor given sequence data, a similarity (or distance) score model
@@ -144,8 +126,11 @@ public class PCAPanel extends GPCAPanel
 
     rc = new RotatableCanvas(alignPanel);
     this.getContentPane().add(rc, BorderLayout.CENTER);
-    Thread worker = new Thread(this);
-    worker.start();
+
+    addKeyListener(rc);
+    validate();
+
+    this.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
   }
 
   /**
@@ -157,58 +142,8 @@ public class PCAPanel extends GPCAPanel
     pcaModel = null;
   }
 
-  /**
-   * Repopulate the options and actions under the score model menu when it is
-   * selected. Options will depend on whether 'nucleotide' or 'peptide'
-   * modelling is selected (and also possibly on whether any additional score
-   * models have been added).
-   */
-  @Override
-  protected void scoreModel_menuSelected()
-  {
-    scoreModelMenu.removeAll();
-    for (final ScoreModelI sm : ScoreModels.getInstance().getModels())
-    {
-      final String name = sm.getName();
-      JCheckBoxMenuItem jm = new JCheckBoxMenuItem(name);
-
-      /*
-       * if the score model doesn't provide a description, try to look one
-       * up in the text bundle, falling back on its name
-       */
-      String tooltip = sm.getDescription();
-      if (tooltip == null)
-      {
-        tooltip = MessageManager.getStringOrReturn("label.score_model_",
-                name);
-      }
-      jm.setToolTipText(tooltip);
-      jm.setSelected(pcaModel.getScoreModelName().equals(name));
-      if ((pcaModel.isNucleotide() && sm.isDNA())
-              || (!pcaModel.isNucleotide() && sm.isProtein()))
-      {
-        jm.addActionListener(new ActionListener()
-        {
-          @Override
-          public void actionPerformed(ActionEvent e)
-          {
-            if (!pcaModel.getScoreModelName().equals(name))
-            {
-              ScoreModelI sm2 = ScoreModels.getInstance()
-                      .getScoreModel(name, ap);
-              pcaModel.setScoreModel(sm2);
-              Thread worker = new Thread(PCAPanel.this);
-              worker.start();
-            }
-          }
-        });
-        scoreModelMenu.add(jm);
-      }
-    }
-  }
-
   @Override
-  public void bgcolour_actionPerformed(ActionEvent e)
+  protected void bgcolour_actionPerformed()
   {
     Color col = JColorChooser.showDialog(this,
             MessageManager.getString("label.select_background_colour"),
@@ -222,11 +157,12 @@ public class PCAPanel extends GPCAPanel
   }
 
   /**
-   * DOCUMENT ME!
+   * Calculates the PCA and displays the results
    */
   @Override
   public void run()
   {
+    working = true;
     long progId = System.currentTimeMillis();
     IProgressIndicator progress = this;
     String message = MessageManager.getString("label.pca_recalculating");
@@ -236,20 +172,16 @@ public class PCAPanel extends GPCAPanel
       message = MessageManager.getString("label.pca_calculating");
     }
     progress.setProgressBar(message, progId);
-    working = true;
     try
     {
-      calcSettings.setEnabled(false);
-      pcaModel.run();
-      // ////////////////
+      pcaModel.calculate();
+
       xCombobox.setSelectedIndex(0);
       yCombobox.setSelectedIndex(1);
       zCombobox.setSelectedIndex(2);
 
       pcaModel.updateRc(rc);
       // rc.invalidate();
-      nuclSetting.setSelected(pcaModel.isNucleotide());
-      protSetting.setSelected(!pcaModel.isNucleotide());
       top = pcaModel.getTop();
 
     } catch (OutOfMemoryError er)
@@ -261,50 +193,24 @@ public class PCAPanel extends GPCAPanel
     {
       progress.setProgressBar("", progId);
     }
-    calcSettings.setEnabled(true);
+
     repaint();
     if (getParent() == null)
     {
-      addKeyListener(rc);
-      Desktop.addInternalFrame(this, MessageManager
-              .getString("label.principal_component_analysis"), 475, 450);
-      this.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
+      Desktop.addInternalFrame(this,
+              MessageManager.formatMessage("label.calc_title", "PCA",
+                      pcaModel.getScoreModelName()),
+              475, 450);
     }
     working = false;
   }
 
-  @Override
-  protected void nuclSetting_actionPerfomed(ActionEvent arg0)
-  {
-    if (!pcaModel.isNucleotide())
-    {
-      pcaModel.setNucleotide(true);
-      pcaModel.setScoreModel(
-              ScoreModels.getInstance().getDefaultModel(false));
-      Thread worker = new Thread(this);
-      worker.start();
-    }
-
-  }
-
-  @Override
-  protected void protSetting_actionPerfomed(ActionEvent arg0)
-  {
-
-    if (pcaModel.isNucleotide())
-    {
-      pcaModel.setNucleotide(false);
-      pcaModel.setScoreModel(
-              ScoreModels.getInstance().getDefaultModel(true));
-      Thread worker = new Thread(this);
-      worker.start();
-    }
-  }
-
   /**
-   * DOCUMENT ME!
+   * Updates the PCA display after a change of component to use for x, y or z
+   * axis
    */
-  void doDimensionChange()
+  @Override
+  protected void doDimensionChange()
   {
     if (top == 0)
     {
@@ -315,50 +221,35 @@ public class PCAPanel extends GPCAPanel
     int dim2 = top - yCombobox.getSelectedIndex();
     int dim3 = top - zCombobox.getSelectedIndex();
     pcaModel.updateRcView(dim1, dim2, dim3);
-    rc.img = null;
-    rc.rotmat.setIdentity();
-    rc.initAxes();
-    rc.paint(rc.getGraphics());
+    rc.resetView();
   }
 
   /**
-   * DOCUMENT ME!
+   * Sets the selected checkbox item index for PCA dimension (1, 2, 3...) for
+   * the given axis (X/Y/Z)
    * 
-   * @param e
-   *          DOCUMENT ME!
+   * @param index
+   * @param axis
    */
-  @Override
-  protected void xCombobox_actionPerformed(ActionEvent e)
+  public void setSelectedDimensionIndex(int index, Axis axis)
   {
-    doDimensionChange();
-  }
-
-  /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
-   */
-  @Override
-  protected void yCombobox_actionPerformed(ActionEvent e)
-  {
-    doDimensionChange();
-  }
-
-  /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
-   */
-  @Override
-  protected void zCombobox_actionPerformed(ActionEvent e)
-  {
-    doDimensionChange();
+    switch (axis)
+    {
+    case X:
+      xCombobox.setSelectedIndex(index);
+      break;
+    case Y:
+      yCombobox.setSelectedIndex(index);
+      break;
+    case Z:
+      zCombobox.setSelectedIndex(index);
+      break;
+    default:
+    }
   }
 
   @Override
-  public void outputValues_actionPerformed(ActionEvent e)
+  protected void outputValues_actionPerformed()
   {
     CutAndPasteTransfer cap = new CutAndPasteTransfer();
     try
@@ -374,32 +265,35 @@ public class PCAPanel extends GPCAPanel
   }
 
   @Override
-  public void showLabels_actionPerformed(ActionEvent e)
+  protected void showLabels_actionPerformed()
   {
     rc.showLabels(showLabels.getState());
   }
 
   @Override
-  public void print_actionPerformed(ActionEvent e)
+  protected void print_actionPerformed()
   {
     PCAPrinter printer = new PCAPrinter();
     printer.start();
   }
 
+  /**
+   * If available, shows the data which formed the inputs for the PCA as a new
+   * alignment
+   */
   @Override
-  public void originalSeqData_actionPerformed(ActionEvent e)
+  public void originalSeqData_actionPerformed()
   {
-    // this was cut'n'pasted from the equivalent TreePanel method - we should
-    // make this an abstract function of all jalview analysis windows
-    if (pcaModel.getSeqtrings() == null)
+    // JAL-2647 disabled after load from project (until save to project done)
+    if (pcaModel.getInputData() == null)
     {
-      jalview.bin.Cache.log.info(
+      Cache.log.info(
               "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
       return;
     }
     // decide if av alignment is sufficiently different to original data to
     // warrant a new window to be created
-    // create new alignmnt window with hidden regions (unhiding hidden regions
+    // create new alignment window with hidden regions (unhiding hidden regions
     // yields unaligned seqs)
     // or create a selection box around columns in alignment view
     // test Alignment(SeqCigar[])
@@ -412,8 +306,8 @@ public class PCAPanel extends GPCAPanel
     } catch (Exception ex)
     {
     }
-    ;
-    Object[] alAndColsel = pcaModel.getSeqtrings()
+
+    Object[] alAndColsel = pcaModel.getInputData()
             .getAlignmentAndHiddenColumns(gc);
 
     if (alAndColsel != null && alAndColsel[0] != null)
@@ -495,9 +389,9 @@ public class PCAPanel extends GPCAPanel
     {
       pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
 
-      rc.drawBackground(pg, rc.bgColour);
+      rc.drawBackground(pg);
       rc.drawScene(pg);
-      if (rc.drawAxes == true)
+      if (rc.drawAxes)
       {
         rc.drawAxes(pg);
       }
@@ -514,61 +408,53 @@ public class PCAPanel extends GPCAPanel
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Handler for 'Save as EPS' option
    */
   @Override
-  public void eps_actionPerformed(ActionEvent e)
+  protected void eps_actionPerformed()
   {
-    makePCAImage(jalview.util.ImageMaker.TYPE.EPS);
+    makePCAImage(ImageMaker.TYPE.EPS);
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Handler for 'Save as PNG' option
    */
   @Override
-  public void png_actionPerformed(ActionEvent e)
+  protected void png_actionPerformed()
   {
-    makePCAImage(jalview.util.ImageMaker.TYPE.PNG);
+    makePCAImage(ImageMaker.TYPE.PNG);
   }
 
-  void makePCAImage(jalview.util.ImageMaker.TYPE type)
+  void makePCAImage(ImageMaker.TYPE type)
   {
     int width = rc.getWidth();
     int height = rc.getHeight();
 
-    jalview.util.ImageMaker im;
-
-    if (type == jalview.util.ImageMaker.TYPE.PNG)
-    {
-      im = new jalview.util.ImageMaker(this,
-              jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from PCA",
-              width, height, null, null, null, 0, false);
-    }
-    else if (type == jalview.util.ImageMaker.TYPE.EPS)
-    {
-      im = new jalview.util.ImageMaker(this,
-              jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from PCA",
-              width, height, null, this.getTitle(), null, 0, false);
-    }
-    else
-    {
-      im = new jalview.util.ImageMaker(this,
-              jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
-              width, height, null, this.getTitle(), null, 0, false);
-
+    ImageMaker im;
+
+    switch (type)
+    {
+    case PNG:
+      im = new ImageMaker(this, ImageMaker.TYPE.PNG,
+              "Make PNG image from PCA", width, height, null, null, null, 0,
+              false);
+      break;
+    case EPS:
+      im = new ImageMaker(this, ImageMaker.TYPE.EPS,
+              "Make EPS file from PCA", width, height, null,
+              this.getTitle(), null, 0, false);
+      break;
+    default:
+      im = new ImageMaker(this, ImageMaker.TYPE.SVG,
+              "Make SVG file from PCA", width, height, null,
+              this.getTitle(), null, 0, false);
     }
 
     if (im.getGraphics() != null)
     {
-      rc.drawBackground(im.getGraphics(), Color.black);
+      rc.drawBackground(im.getGraphics());
       rc.drawScene(im.getGraphics());
-      if (rc.drawAxes == true)
+      if (rc.drawAxes)
       {
         rc.drawAxes(im.getGraphics());
       }
@@ -577,11 +463,15 @@ public class PCAPanel extends GPCAPanel
   }
 
   @Override
-  public void viewMenu_menuSelected()
+  protected void viewMenu_menuSelected()
   {
     buildAssociatedViewMenu();
   }
 
+  /**
+   * Builds the menu showing the choice of possible views (for the associated
+   * sequence data) to which the PCA may be linked
+   */
   void buildAssociatedViewMenu()
   {
     AlignmentPanel[] aps = PaintRefresher
@@ -604,9 +494,9 @@ public class PCAPanel extends GPCAPanel
 
     JRadioButtonMenuItem item;
     ButtonGroup buttonGroup = new ButtonGroup();
-    int i, iSize = aps.length;
-    final PCAPanel thisPCAPanel = this;
-    for (i = 0; i < iSize; i++)
+    int iSize = aps.length;
+
+    for (int i = 0; i < iSize; i++)
     {
       final AlignmentPanel ap = aps[i];
       item = new JRadioButtonMenuItem(ap.av.getViewName(), ap.av == rc.av);
@@ -617,9 +507,10 @@ public class PCAPanel extends GPCAPanel
         public void actionPerformed(ActionEvent evt)
         {
           rc.applyToAllViews = false;
-          rc.av = ap.av;
-          rc.ap = ap;
-          PaintRefresher.Register(thisPCAPanel, ap.av.getSequenceSetId());
+          rc.av = panel.av;
+          rc.ap = panel;
+          PaintRefresher.Register(PCAPanel.this,
+                  panel.av.getSequenceSetId());
         }
       });
 
@@ -652,7 +543,7 @@ public class PCAPanel extends GPCAPanel
    * )
    */
   @Override
-  protected void outputPoints_actionPerformed(ActionEvent e)
+  protected void outputPoints_actionPerformed()
   {
     CutAndPasteTransfer cap = new CutAndPasteTransfer();
     try
@@ -678,7 +569,7 @@ public class PCAPanel extends GPCAPanel
    * .ActionEvent)
    */
   @Override
-  protected void outputProjPoints_actionPerformed(ActionEvent e)
+  protected void outputProjPoints_actionPerformed()
   {
     CutAndPasteTransfer cap = new CutAndPasteTransfer();
     try
@@ -793,7 +684,7 @@ public class PCAPanel extends GPCAPanel
   }
 
   @Override
-  protected void resetButton_actionPerformed(ActionEvent e)
+  protected void resetButton_actionPerformed()
   {
     int t = top;
     top = 0; // ugly - prevents dimensionChanged events from being processed
@@ -812,4 +703,42 @@ public class PCAPanel extends GPCAPanel
   {
     return working;
   }
+
+  /**
+   * Answers the selected checkbox item index for PCA dimension for the X, Y or
+   * Z axis of the display
+   * 
+   * @param axis
+   * @return
+   */
+  public int getSelectedDimensionIndex(Axis axis)
+  {
+    switch (axis)
+    {
+    case X:
+      return xCombobox.getSelectedIndex();
+    case Y:
+      return yCombobox.getSelectedIndex();
+    default:
+      return zCombobox.getSelectedIndex();
+    }
+  }
+
+  public void setShowLabels(boolean show)
+  {
+    showLabels.setSelected(show);
+  }
+
+  /**
+   * Sets the input data used to calculate the PCA. This is provided for
+   * 'restore from project', which does not currently support this (AL-2647), so
+   * sets the value to null, and hides the menu option for "Input Data...". J
+   * 
+   * @param data
+   */
+  public void setInputData(AlignmentView data)
+  {
+    pcaModel.setInputData(data);
+    originalSeqData.setVisible(data != null);
+  }
 }