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()
146 protected void bgcolour_actionPerformed()
148 String ttl = MessageManager.getString("label.select_background_colour");
149 ColourChooserListener listener = new ColourChooserListener()
152 public void colourSelected(Color c)
158 JalviewColourChooser.showColourChooser(this, ttl, rc.getBgColour(),
163 * Calculates the PCA and displays the results
169 long progId = System.currentTimeMillis();
170 IProgressIndicator progress = this;
171 String message = MessageManager.getString("label.pca_recalculating");
172 if (getParent() == null)
174 progress = ap.alignFrame;
175 message = MessageManager.getString("label.pca_calculating");
177 progress.setProgressBar(message, progId);
180 getPcaModel().calculate();
182 xCombobox.setSelectedIndex(0);
183 yCombobox.setSelectedIndex(1);
184 zCombobox.setSelectedIndex(2);
186 getPcaModel().updateRc(getRotatableCanvas());
188 setTop(getPcaModel().getTop());
190 } catch (OutOfMemoryError er)
192 new OOMWarning("calculating PCA", er);
197 progress.setProgressBar("", progId);
201 if (getParent() == null)
203 Desktop.addInternalFrame(this,
204 MessageManager.formatMessage("label.calc_title", "PCA",
205 getPcaModel().getScoreModelName()),
207 this.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
213 * Updates the PCA display after a change of component to use for x, y or z
217 protected void doDimensionChange()
224 int dim1 = getTop() - xCombobox.getSelectedIndex();
225 int dim2 = getTop() - yCombobox.getSelectedIndex();
226 int dim3 = getTop() - zCombobox.getSelectedIndex();
227 getPcaModel().updateRcView(dim1, dim2, dim3);
228 getRotatableCanvas().resetView();
232 * Sets the selected checkbox item index for PCA dimension (1, 2, 3...) for
233 * the given axis (X/Y/Z)
238 public void setSelectedDimensionIndex(int index, Axis axis)
243 xCombobox.setSelectedIndex(index);
246 yCombobox.setSelectedIndex(index);
249 zCombobox.setSelectedIndex(index);
256 protected void outputValues_actionPerformed()
258 CutAndPasteTransfer cap = new CutAndPasteTransfer();
261 cap.setText(getPcaModel().getDetails());
262 Desktop.addInternalFrame(cap,
263 MessageManager.getString("label.pca_details"), 500, 500);
264 } catch (OutOfMemoryError oom)
266 new OOMWarning("opening PCA details", oom);
272 protected void showLabels_actionPerformed()
274 getRotatableCanvas().showLabels(showLabels.getState());
278 protected void print_actionPerformed()
280 PCAPrinter printer = new PCAPrinter();
285 * If available, shows the data which formed the inputs for the PCA as a new
289 public void originalSeqData_actionPerformed()
291 // JAL-2647 disabled after load from project (until save to project done)
292 if (getPcaModel().getInputData() == null)
295 "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
298 // decide if av alignment is sufficiently different to original data to
299 // warrant a new window to be created
300 // create new alignment window with hidden regions (unhiding hidden regions
301 // yields unaligned seqs)
302 // or create a selection box around columns in alignment view
303 // test Alignment(SeqCigar[])
307 // we try to get the associated view's gap character
308 // but this may fail if the view was closed...
309 gc = av.getGapCharacter();
310 } catch (Exception ex)
314 Object[] alAndColsel = getPcaModel().getInputData()
315 .getAlignmentAndHiddenColumns(gc);
317 if (alAndColsel != null && alAndColsel[0] != null)
319 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
321 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
322 AlignmentI dataset = (av != null && av.getAlignment() != null)
323 ? av.getAlignment().getDataset()
327 al.setDataset(dataset);
333 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
334 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
336 // >>>This is a fix for the moment, until a better solution is
338 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
340 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
343 Desktop.addInternalFrame(af, MessageManager.formatMessage(
344 "label.original_data_for_params", new String[]
345 { this.title }), AlignFrame.DEFAULT_WIDTH,
346 AlignFrame.DEFAULT_HEIGHT);
350 * CutAndPasteTransfer cap = new CutAndPasteTransfer(); for (int i = 0; i <
351 * seqs.length; i++) { cap.appendText(new jalview.util.Format("%-" + 15 +
352 * "s").form( seqs[i].getName())); cap.appendText(" " + seqstrings[i] +
355 * Desktop.addInternalFrame(cap, "Original Data", 400, 400);
359 class PCAPrinter extends Thread implements Printable
364 PrinterJob printJob = PrinterJob.getPrinterJob();
365 PageFormat defaultPage = printJob.defaultPage();
366 PageFormat pf = printJob.pageDialog(defaultPage);
368 if (defaultPage == pf)
376 printJob.setPrintable(this, pf);
378 if (printJob.printDialog())
383 } catch (Exception PrintException)
385 PrintException.printStackTrace();
391 public int print(Graphics pg, PageFormat pf, int pi)
392 throws PrinterException
394 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
396 getRotatableCanvas().drawBackground(pg);
397 getRotatableCanvas().drawScene(pg);
398 if (getRotatableCanvas().drawAxes)
400 getRotatableCanvas().drawAxes(pg);
405 return Printable.PAGE_EXISTS;
409 return Printable.NO_SUCH_PAGE;
414 public void makePCAImage(ImageMaker.TYPE type)
416 int width = getRotatableCanvas().getWidth();
417 int height = getRotatableCanvas().getHeight();
418 ImageWriterI writer = new ImageWriterI()
421 public void exportImage(Graphics g) throws Exception
423 RotatableCanvas canvas = getRotatableCanvas();
424 canvas.drawBackground(g);
432 String pca = MessageManager.getString("label.pca");
433 ImageExporter exporter = new ImageExporter(writer, null, type, pca);
434 exporter.doExport(null, this, width, height, pca);
438 protected void viewMenu_menuSelected()
440 buildAssociatedViewMenu();
444 * Builds the menu showing the choice of possible views (for the associated
445 * sequence data) to which the PCA may be linked
447 void buildAssociatedViewMenu()
449 AlignmentPanel[] aps = PaintRefresher
450 .getAssociatedPanels(av.getSequenceSetId());
451 if (aps.length == 1 && getRotatableCanvas().av == aps[0].av)
453 associateViewsMenu.setVisible(false);
457 associateViewsMenu.setVisible(true);
460 .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
462 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
465 associateViewsMenu.removeAll();
467 JRadioButtonMenuItem item;
468 ButtonGroup buttonGroup = new ButtonGroup();
469 int iSize = aps.length;
471 for (int i = 0; i < iSize; i++)
473 final AlignmentPanel panel = aps[i];
474 item = new JRadioButtonMenuItem(panel.av.getViewName(),
475 panel.av == getRotatableCanvas().av);
476 buttonGroup.add(item);
477 item.addActionListener(new ActionListener()
480 public void actionPerformed(ActionEvent evt)
482 selectAssociatedView(panel);
486 associateViewsMenu.add(item);
489 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
492 buttonGroup.add(itemf);
494 itemf.setSelected(getRotatableCanvas().isApplyToAllViews());
495 itemf.addActionListener(new ActionListener()
498 public void actionPerformed(ActionEvent evt)
500 getRotatableCanvas().setApplyToAllViews(itemf.isSelected());
503 associateViewsMenu.add(itemf);
511 * jalview.jbgui.GPCAPanel#outputPoints_actionPerformed(java.awt.event.ActionEvent
515 protected void outputPoints_actionPerformed()
517 CutAndPasteTransfer cap = new CutAndPasteTransfer();
520 cap.setText(getPcaModel().getPointsasCsv(false,
521 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
522 zCombobox.getSelectedIndex()));
523 Desktop.addInternalFrame(cap, MessageManager
524 .formatMessage("label.points_for_params", new String[]
525 { this.getTitle() }), 500, 500);
526 } catch (OutOfMemoryError oom)
528 new OOMWarning("exporting PCA points", oom);
537 * jalview.jbgui.GPCAPanel#outputProjPoints_actionPerformed(java.awt.event
541 protected void outputProjPoints_actionPerformed()
543 CutAndPasteTransfer cap = new CutAndPasteTransfer();
546 cap.setText(getPcaModel().getPointsasCsv(true,
547 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
548 zCombobox.getSelectedIndex()));
549 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
550 "label.transformed_points_for_params", new String[]
551 { this.getTitle() }), 500, 500);
552 } catch (OutOfMemoryError oom)
554 new OOMWarning("exporting transformed PCA points", oom);
562 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
565 public void setProgressBar(String message, long id)
567 progressBar.setProgressBar(message, id);
568 // if (progressBars == null)
570 // progressBars = new Hashtable();
571 // progressBarHandlers = new Hashtable();
574 // JPanel progressPanel;
575 // Long lId = Long.valueOf(id);
576 // GridLayout layout = (GridLayout) statusPanel.getLayout();
577 // if (progressBars.get(lId) != null)
579 // progressPanel = (JPanel) progressBars.get(Long.valueOf(id));
580 // statusPanel.remove(progressPanel);
581 // progressBars.remove(lId);
582 // progressPanel = null;
583 // if (message != null)
585 // statusBar.setText(message);
587 // if (progressBarHandlers.contains(lId))
589 // progressBarHandlers.remove(lId);
591 // layout.setRows(layout.getRows() - 1);
595 // progressPanel = new JPanel(new BorderLayout(10, 5));
597 // JProgressBar progressBar = new JProgressBar();
598 // progressBar.setIndeterminate(true);
600 // progressPanel.add(new JLabel(message), BorderLayout.WEST);
601 // progressPanel.add(progressBar, BorderLayout.CENTER);
603 // layout.setRows(layout.getRows() + 1);
604 // statusPanel.add(progressPanel);
606 // progressBars.put(lId, progressPanel);
609 // // setMenusForViewport();
614 public void registerHandler(final long id,
615 final IProgressIndicatorHandler handler)
617 progressBar.registerHandler(id, handler);
618 // if (progressBarHandlers == null || !progressBars.contains(Long.valueOf(id)))
621 // Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
623 // progressBarHandlers.put(Long.valueOf(id), handler);
624 // final JPanel progressPanel = (JPanel) progressBars.get(Long.valueOf(id));
625 // if (handler.canCancel())
627 // JButton cancel = new JButton(
628 // MessageManager.getString("action.cancel"));
629 // final IProgressIndicator us = this;
630 // cancel.addActionListener(new ActionListener()
634 // public void actionPerformed(ActionEvent e)
636 // handler.cancelActivity(id);
637 // us.setProgressBar(MessageManager.formatMessage("label.cancelled_params",
638 // new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
641 // progressPanel.add(cancel, BorderLayout.EAST);
647 * @return true if any progress bars are still active
650 public boolean operationInProgress()
652 return progressBar.operationInProgress();
656 protected void resetButton_actionPerformed()
659 setTop(0); // ugly - prevents dimensionChanged events from being processed
660 xCombobox.setSelectedIndex(0);
661 yCombobox.setSelectedIndex(1);
663 zCombobox.setSelectedIndex(2);
667 * Answers true if PCA calculation is in progress, else false
671 public boolean isWorking()
677 * Answers the selected checkbox item index for PCA dimension for the X, Y or
678 * Z axis of the display
683 public int getSelectedDimensionIndex(Axis axis)
688 return xCombobox.getSelectedIndex();
690 return yCombobox.getSelectedIndex();
692 return zCombobox.getSelectedIndex();
696 public void setShowLabels(boolean show)
698 showLabels.setSelected(show);
702 * Sets the input data used to calculate the PCA. This is provided for
703 * 'restore from project', which does not currently support this (AL-2647), so
704 * sets the value to null, and hides the menu option for "Input Data...". J
708 public void setInputData(AlignmentView data)
710 getPcaModel().setInputData(data);
711 originalSeqData.setVisible(data != null);
714 public AlignViewportI getAlignViewport()
719 public PCAModel getPcaModel()
724 public void setPcaModel(PCAModel pcaModel)
726 this.pcaModel = pcaModel;
729 public RotatableCanvas getRotatableCanvas()
734 public void setRotatableCanvas(RotatableCanvas rc)
744 public void setTop(int top)
750 * set the associated view for this PCA.
754 public void selectAssociatedView(AlignmentPanel panel)
756 getRotatableCanvas().setApplyToAllViews(false);
761 getRotatableCanvas().av = panel.av;
762 getRotatableCanvas().ap = panel;
763 PaintRefresher.Register(PCAPanel.this, panel.av.getSequenceSetId());