2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import jalview.analysis.scoremodels.ScoreModels;
24 import jalview.api.AlignViewportI;
25 import jalview.api.analysis.ScoreModelI;
26 import jalview.api.analysis.SimilarityParamsI;
27 import jalview.bin.Cache;
28 import jalview.datamodel.Alignment;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.AlignmentView;
31 import jalview.datamodel.HiddenColumns;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.ImageExporter.ImageWriterI;
34 import jalview.gui.JalviewColourChooser.ColourChooserListener;
35 import jalview.jbgui.GPCAPanel;
36 import jalview.math.RotatableMatrix.Axis;
37 import jalview.util.ImageMaker;
38 import jalview.util.MessageManager;
39 import jalview.viewmodel.AlignmentViewport;
40 import jalview.viewmodel.PCAModel;
42 import java.awt.BorderLayout;
43 import java.awt.Color;
44 import java.awt.Dimension;
45 import java.awt.Graphics;
46 import java.awt.event.ActionEvent;
47 import java.awt.event.ActionListener;
48 import java.awt.print.PageFormat;
49 import java.awt.print.Printable;
50 import java.awt.print.PrinterException;
51 import java.awt.print.PrinterJob;
53 import javax.swing.ButtonGroup;
54 import javax.swing.JMenuItem;
55 import javax.swing.JRadioButtonMenuItem;
56 import javax.swing.event.InternalFrameAdapter;
57 import javax.swing.event.InternalFrameEvent;
60 * The panel holding the Principal Component Analysis 3-D visualisation
62 public class PCAPanel extends GPCAPanel
63 implements Runnable, IProgressIndicator
65 private static final int MIN_WIDTH = 470;
67 private static final int MIN_HEIGHT = 250;
69 private RotatableCanvas rc;
75 private PCAModel pcaModel;
79 private IProgressIndicator progressBar;
81 private boolean working;
84 * Constructor given sequence data, a similarity (or distance) score model
85 * name, and score calculation parameters
91 public PCAPanel(AlignmentPanel alignPanel, String modelName,
92 SimilarityParamsI params)
95 this.av = alignPanel.av;
97 boolean nucleotide = av.getAlignment().isNucleotide();
99 progressBar = new ProgressBar(statusPanel, statusBar);
101 addInternalFrameListener(new InternalFrameAdapter()
104 public void internalFrameClosed(InternalFrameEvent e)
106 close_actionPerformed();
110 boolean selected = av.getSelectionGroup() != null
111 && av.getSelectionGroup().getSize() > 0;
112 AlignmentView seqstrings = av.getAlignmentView(selected);
116 seqs = av.getAlignment().getSequencesArray();
120 seqs = av.getSelectionGroup().getSequencesInOrder(av.getAlignment());
123 ScoreModelI scoreModel = ScoreModels.getInstance()
124 .getScoreModel(modelName, ap);
125 setPcaModel(new PCAModel(seqstrings, seqs, nucleotide, scoreModel,
127 PaintRefresher.Register(this, av.getSequenceSetId());
129 setRotatableCanvas(new RotatableCanvas(alignPanel));
130 this.getContentPane().add(getRotatableCanvas(), BorderLayout.CENTER);
132 addKeyListener(getRotatableCanvas());
137 * Ensure references to potentially very large objects (the PCA matrices) are
138 * nulled when the frame is closed
140 protected void close_actionPerformed()
145 this.rc.sequencePoints = null;
146 this.rc.setAxisEndPoints(null);
152 protected void bgcolour_actionPerformed()
154 String ttl = MessageManager.getString("label.select_background_colour");
155 ColourChooserListener listener = new ColourChooserListener()
158 public void colourSelected(Color c)
164 JalviewColourChooser.showColourChooser(this, ttl, rc.getBgColour(),
169 * Calculates the PCA and displays the results
175 long progId = System.currentTimeMillis();
176 IProgressIndicator progress = this;
177 String message = MessageManager.getString("label.pca_recalculating");
178 if (getParent() == null)
180 progress = ap.alignFrame;
181 message = MessageManager.getString("label.pca_calculating");
183 progress.setProgressBar(message, progId);
186 getPcaModel().calculate();
188 xCombobox.setSelectedIndex(0);
189 yCombobox.setSelectedIndex(1);
190 zCombobox.setSelectedIndex(2);
192 getPcaModel().updateRc(getRotatableCanvas());
194 setTop(getPcaModel().getTop());
196 } catch (OutOfMemoryError er)
198 new OOMWarning("calculating PCA", er);
203 progress.setProgressBar("", progId);
207 if (getParent() == null)
209 Desktop.addInternalFrame(this,
210 MessageManager.formatMessage("label.calc_title", "PCA",
211 getPcaModel().getScoreModelName()),
213 this.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
219 * Updates the PCA display after a change of component to use for x, y or z
223 protected void doDimensionChange()
230 int dim1 = getTop() - xCombobox.getSelectedIndex();
231 int dim2 = getTop() - yCombobox.getSelectedIndex();
232 int dim3 = getTop() - zCombobox.getSelectedIndex();
233 getPcaModel().updateRcView(dim1, dim2, dim3);
234 getRotatableCanvas().resetView();
238 * Sets the selected checkbox item index for PCA dimension (1, 2, 3...) for
239 * the given axis (X/Y/Z)
244 public void setSelectedDimensionIndex(int index, Axis axis)
249 xCombobox.setSelectedIndex(index);
252 yCombobox.setSelectedIndex(index);
255 zCombobox.setSelectedIndex(index);
262 protected void outputValues_actionPerformed()
264 CutAndPasteTransfer cap = new CutAndPasteTransfer();
267 cap.setText(getPcaModel().getDetails());
268 Desktop.addInternalFrame(cap,
269 MessageManager.getString("label.pca_details"), 500, 500);
270 } catch (OutOfMemoryError oom)
272 new OOMWarning("opening PCA details", oom);
278 protected void showLabels_actionPerformed()
280 getRotatableCanvas().showLabels(showLabels.getState());
284 protected void print_actionPerformed()
286 PCAPrinter printer = new PCAPrinter();
291 * If available, shows the data which formed the inputs for the PCA as a new
295 public void originalSeqData_actionPerformed()
297 // JAL-2647 disabled after load from project (until save to project done)
298 if (getPcaModel().getInputData() == null)
301 "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
304 // decide if av alignment is sufficiently different to original data to
305 // warrant a new window to be created
306 // create new alignment window with hidden regions (unhiding hidden regions
307 // yields unaligned seqs)
308 // or create a selection box around columns in alignment view
309 // test Alignment(SeqCigar[])
313 // we try to get the associated view's gap character
314 // but this may fail if the view was closed...
315 gc = av.getGapCharacter();
316 } catch (Exception ex)
320 Object[] alAndColsel = getPcaModel().getInputData()
321 .getAlignmentAndHiddenColumns(gc);
323 if (alAndColsel != null && alAndColsel[0] != null)
325 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
327 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
328 AlignmentI dataset = (av != null && av.getAlignment() != null)
329 ? av.getAlignment().getDataset()
333 al.setDataset(dataset);
339 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
340 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
342 // >>>This is a fix for the moment, until a better solution is
344 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
346 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
349 Desktop.addInternalFrame(af, MessageManager.formatMessage(
350 "label.original_data_for_params", new String[]
351 { this.title }), AlignFrame.DEFAULT_WIDTH,
352 AlignFrame.DEFAULT_HEIGHT);
356 * CutAndPasteTransfer cap = new CutAndPasteTransfer(); for (int i = 0; i <
357 * seqs.length; i++) { cap.appendText(new jalview.util.Format("%-" + 15 +
358 * "s").form( seqs[i].getName())); cap.appendText(" " + seqstrings[i] +
361 * Desktop.addInternalFrame(cap, "Original Data", 400, 400);
365 class PCAPrinter extends Thread implements Printable
370 PrinterJob printJob = PrinterJob.getPrinterJob();
371 PageFormat defaultPage = printJob.defaultPage();
372 PageFormat pf = printJob.pageDialog(defaultPage);
374 if (defaultPage == pf)
382 printJob.setPrintable(this, pf);
384 if (printJob.printDialog())
389 } catch (Exception PrintException)
391 PrintException.printStackTrace();
397 public int print(Graphics pg, PageFormat pf, int pi)
398 throws PrinterException
400 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
402 getRotatableCanvas().drawBackground(pg);
403 getRotatableCanvas().drawScene(pg);
404 if (getRotatableCanvas().drawAxes)
406 getRotatableCanvas().drawAxes(pg);
411 return Printable.PAGE_EXISTS;
415 return Printable.NO_SUCH_PAGE;
420 public void makePCAImage(ImageMaker.TYPE type)
422 int width = getRotatableCanvas().getWidth();
423 int height = getRotatableCanvas().getHeight();
424 ImageWriterI writer = new ImageWriterI()
427 public void exportImage(Graphics g) throws Exception
429 RotatableCanvas canvas = getRotatableCanvas();
430 canvas.drawBackground(g);
438 String pca = MessageManager.getString("label.pca");
439 ImageExporter exporter = new ImageExporter(writer, null, type, pca);
440 exporter.doExport(null, this, width, height, pca);
444 protected void viewMenu_menuSelected()
446 buildAssociatedViewMenu();
450 * Builds the menu showing the choice of possible views (for the associated
451 * sequence data) to which the PCA may be linked
453 void buildAssociatedViewMenu()
455 AlignmentPanel[] aps = PaintRefresher
456 .getAssociatedPanels(av.getSequenceSetId());
457 if (aps.length == 1 && getRotatableCanvas().av == aps[0].av)
459 associateViewsMenu.setVisible(false);
463 associateViewsMenu.setVisible(true);
466 .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
468 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
471 associateViewsMenu.removeAll();
473 JRadioButtonMenuItem item;
474 ButtonGroup buttonGroup = new ButtonGroup();
475 int iSize = aps.length;
477 for (int i = 0; i < iSize; i++)
479 final AlignmentPanel panel = aps[i];
480 item = new JRadioButtonMenuItem(panel.av.getViewName(),
481 panel.av == getRotatableCanvas().av);
482 buttonGroup.add(item);
483 item.addActionListener(new ActionListener()
486 public void actionPerformed(ActionEvent evt)
488 selectAssociatedView(panel);
492 associateViewsMenu.add(item);
495 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
498 buttonGroup.add(itemf);
500 itemf.setSelected(getRotatableCanvas().isApplyToAllViews());
501 itemf.addActionListener(new ActionListener()
504 public void actionPerformed(ActionEvent evt)
506 getRotatableCanvas().setApplyToAllViews(itemf.isSelected());
509 associateViewsMenu.add(itemf);
517 * jalview.jbgui.GPCAPanel#outputPoints_actionPerformed(java.awt.event.ActionEvent
521 protected void outputPoints_actionPerformed()
523 CutAndPasteTransfer cap = new CutAndPasteTransfer();
526 cap.setText(getPcaModel().getPointsasCsv(false,
527 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
528 zCombobox.getSelectedIndex()));
529 Desktop.addInternalFrame(cap, MessageManager
530 .formatMessage("label.points_for_params", new String[]
531 { this.getTitle() }), 500, 500);
532 } catch (OutOfMemoryError oom)
534 new OOMWarning("exporting PCA points", oom);
543 * jalview.jbgui.GPCAPanel#outputProjPoints_actionPerformed(java.awt.event
547 protected void outputProjPoints_actionPerformed()
549 CutAndPasteTransfer cap = new CutAndPasteTransfer();
552 cap.setText(getPcaModel().getPointsasCsv(true,
553 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
554 zCombobox.getSelectedIndex()));
555 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
556 "label.transformed_points_for_params", new String[]
557 { this.getTitle() }), 500, 500);
558 } catch (OutOfMemoryError oom)
560 new OOMWarning("exporting transformed PCA points", oom);
568 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
571 public void setProgressBar(String message, long id)
573 progressBar.setProgressBar(message, id);
574 // if (progressBars == null)
576 // progressBars = new Hashtable();
577 // progressBarHandlers = new Hashtable();
580 // JPanel progressPanel;
581 // Long lId = Long.valueOf(id);
582 // GridLayout layout = (GridLayout) statusPanel.getLayout();
583 // if (progressBars.get(lId) != null)
585 // progressPanel = (JPanel) progressBars.get(Long.valueOf(id));
586 // statusPanel.remove(progressPanel);
587 // progressBars.remove(lId);
588 // progressPanel = null;
589 // if (message != null)
591 // statusBar.setText(message);
593 // if (progressBarHandlers.contains(lId))
595 // progressBarHandlers.remove(lId);
597 // layout.setRows(layout.getRows() - 1);
601 // progressPanel = new JPanel(new BorderLayout(10, 5));
603 // JProgressBar progressBar = new JProgressBar();
604 // progressBar.setIndeterminate(true);
606 // progressPanel.add(new JLabel(message), BorderLayout.WEST);
607 // progressPanel.add(progressBar, BorderLayout.CENTER);
609 // layout.setRows(layout.getRows() + 1);
610 // statusPanel.add(progressPanel);
612 // progressBars.put(lId, progressPanel);
615 // // setMenusForViewport();
620 public void registerHandler(final long id,
621 final IProgressIndicatorHandler handler)
623 progressBar.registerHandler(id, handler);
624 // if (progressBarHandlers == null || !progressBars.contains(Long.valueOf(id)))
627 // Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
629 // progressBarHandlers.put(Long.valueOf(id), handler);
630 // final JPanel progressPanel = (JPanel) progressBars.get(Long.valueOf(id));
631 // if (handler.canCancel())
633 // JButton cancel = new JButton(
634 // MessageManager.getString("action.cancel"));
635 // final IProgressIndicator us = this;
636 // cancel.addActionListener(new ActionListener()
640 // public void actionPerformed(ActionEvent e)
642 // handler.cancelActivity(id);
643 // us.setProgressBar(MessageManager.formatMessage("label.cancelled_params",
644 // new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
647 // progressPanel.add(cancel, BorderLayout.EAST);
653 * @return true if any progress bars are still active
656 public boolean operationInProgress()
658 return progressBar.operationInProgress();
662 protected void resetButton_actionPerformed()
665 setTop(0); // ugly - prevents dimensionChanged events from being processed
666 xCombobox.setSelectedIndex(0);
667 yCombobox.setSelectedIndex(1);
669 zCombobox.setSelectedIndex(2);
673 * Answers true if PCA calculation is in progress, else false
677 public boolean isWorking()
683 * Answers the selected checkbox item index for PCA dimension for the X, Y or
684 * Z axis of the display
689 public int getSelectedDimensionIndex(Axis axis)
694 return xCombobox.getSelectedIndex();
696 return yCombobox.getSelectedIndex();
698 return zCombobox.getSelectedIndex();
702 public void setShowLabels(boolean show)
704 showLabels.setSelected(show);
708 * Sets the input data used to calculate the PCA. This is provided for
709 * 'restore from project', which does not currently support this (AL-2647), so
710 * sets the value to null, and hides the menu option for "Input Data...". J
714 public void setInputData(AlignmentView data)
716 getPcaModel().setInputData(data);
717 originalSeqData.setVisible(data != null);
720 public AlignViewportI getAlignViewport()
725 public PCAModel getPcaModel()
730 public void setPcaModel(PCAModel pcaModel)
732 this.pcaModel = pcaModel;
735 public RotatableCanvas getRotatableCanvas()
740 public void setRotatableCanvas(RotatableCanvas rc)
750 public void setTop(int top)
756 * set the associated view for this PCA.
760 public void selectAssociatedView(AlignmentPanel panel)
762 getRotatableCanvas().setApplyToAllViews(false);
767 getRotatableCanvas().av = panel.av;
768 getRotatableCanvas().ap = panel;
769 PaintRefresher.Register(PCAPanel.this, panel.av.getSequenceSetId());