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.Console;
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.util.Platform;
40 import jalview.viewmodel.AlignmentViewport;
41 import jalview.viewmodel.PCAModel;
43 import java.awt.BorderLayout;
44 import java.awt.Color;
45 import java.awt.Dimension;
46 import java.awt.Graphics;
47 import java.awt.event.ActionEvent;
48 import java.awt.event.ActionListener;
49 import java.awt.print.PageFormat;
50 import java.awt.print.Printable;
51 import java.awt.print.PrinterException;
52 import java.awt.print.PrinterJob;
54 import javax.swing.ButtonGroup;
55 import javax.swing.JMenuItem;
56 import javax.swing.JRadioButtonMenuItem;
57 import javax.swing.event.InternalFrameAdapter;
58 import javax.swing.event.InternalFrameEvent;
61 * The panel holding the Principal Component Analysis 3-D visualisation
63 public class PCAPanel extends GPCAPanel
64 implements Runnable, IProgressIndicator
66 private static final int MIN_WIDTH = 470;
68 private static final int MIN_HEIGHT = 250;
70 private RotatableCanvas rc;
76 private PCAModel pcaModel;
80 private IProgressIndicator progressBar;
82 private boolean working;
85 * Constructor given sequence data, a similarity (or distance) score model
86 * name, and score calculation parameters
92 public PCAPanel(AlignmentPanel alignPanel, String modelName,
93 SimilarityParamsI params)
96 this.av = alignPanel.av;
98 boolean nucleotide = av.getAlignment().isNucleotide();
100 progressBar = new ProgressBar(statusPanel, statusBar);
102 addInternalFrameListener(new InternalFrameAdapter()
105 public void internalFrameClosed(InternalFrameEvent e)
107 close_actionPerformed();
111 boolean selected = av.getSelectionGroup() != null
112 && av.getSelectionGroup().getSize() > 0;
113 AlignmentView seqstrings = av.getAlignmentView(selected);
117 seqs = av.getAlignment().getSequencesArray();
121 seqs = av.getSelectionGroup().getSequencesInOrder(av.getAlignment());
124 ScoreModelI scoreModel = ScoreModels.getInstance()
125 .getScoreModel(modelName, ap);
127 new PCAModel(seqstrings, seqs, nucleotide, scoreModel, params));
128 PaintRefresher.Register(this, av.getSequenceSetId());
130 setRotatableCanvas(new RotatableCanvas(alignPanel));
131 this.getContentPane().add(getRotatableCanvas(), BorderLayout.CENTER);
133 addKeyListener(getRotatableCanvas());
138 * Ensure references to potentially very large objects (the PCA matrices) are
139 * nulled when the frame is closed
141 protected void close_actionPerformed()
146 this.rc.sequencePoints = null;
147 this.rc.setAxisEndPoints(null);
153 protected void bgcolour_actionPerformed()
155 String ttl = MessageManager.getString("label.select_background_colour");
156 ColourChooserListener listener = new ColourChooserListener()
159 public void colourSelected(Color c)
165 JalviewColourChooser.showColourChooser(this, ttl, rc.getBgColour(),
170 * Calculates the PCA and displays the results
176 long progId = System.currentTimeMillis();
177 IProgressIndicator progress = this;
178 String message = MessageManager.getString("label.pca_recalculating");
179 if (getParent() == null)
181 progress = ap.alignFrame;
182 message = MessageManager.getString("label.pca_calculating");
184 progress.setProgressBar(message, progId);
187 getPcaModel().calculate();
189 xCombobox.setSelectedIndex(0);
190 yCombobox.setSelectedIndex(1);
191 zCombobox.setSelectedIndex(2);
193 getPcaModel().updateRc(getRotatableCanvas());
195 setTop(getPcaModel().getTop());
197 } catch (OutOfMemoryError er)
199 new OOMWarning("calculating PCA", er);
204 progress.setProgressBar("", progId);
208 if (getParent() == null)
210 addToDesktop(this, getPcaModel().getScoreModelName());
211 this.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
217 * Updates the PCA display after a change of component to use for x, y or z
221 protected void doDimensionChange()
228 int dim1 = getTop() - xCombobox.getSelectedIndex();
229 int dim2 = getTop() - yCombobox.getSelectedIndex();
230 int dim3 = getTop() - zCombobox.getSelectedIndex();
231 getPcaModel().updateRcView(dim1, dim2, dim3);
232 getRotatableCanvas().resetView();
236 * Sets the selected checkbox item index for PCA dimension (1, 2, 3...) for
237 * the given axis (X/Y/Z)
242 public void setSelectedDimensionIndex(int index, Axis axis)
247 xCombobox.setSelectedIndex(index);
250 yCombobox.setSelectedIndex(index);
253 zCombobox.setSelectedIndex(index);
260 protected void outputValues_actionPerformed()
262 CutAndPasteTransfer cap = new CutAndPasteTransfer();
265 cap.setText(getPcaModel().getDetails());
266 Desktop.addInternalFrame(cap,
267 MessageManager.getString("label.pca_details"), 500, 500);
268 } catch (OutOfMemoryError oom)
270 new OOMWarning("opening PCA details", oom);
276 protected void showLabels_actionPerformed()
278 getRotatableCanvas().showLabels(showLabels.getState());
282 protected void print_actionPerformed()
284 PCAPrinter printer = new PCAPrinter();
289 * If available, shows the data which formed the inputs for the PCA as a new
293 public void originalSeqData_actionPerformed()
295 // JAL-2647 disabled after load from project (until save to project done)
296 if (getPcaModel().getInputData() == null)
299 "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
302 // decide if av alignment is sufficiently different to original data to
303 // warrant a new window to be created
304 // create new alignment window with hidden regions (unhiding hidden regions
305 // yields unaligned seqs)
306 // or create a selection box around columns in alignment view
307 // test Alignment(SeqCigar[])
311 // we try to get the associated view's gap character
312 // but this may fail if the view was closed...
313 gc = av.getGapCharacter();
314 } catch (Exception ex)
318 Object[] alAndColsel = getPcaModel().getInputData()
319 .getAlignmentAndHiddenColumns(gc);
321 if (alAndColsel != null && alAndColsel[0] != null)
323 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
325 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
326 AlignmentI dataset = (av != null && av.getAlignment() != null)
327 ? av.getAlignment().getDataset()
331 al.setDataset(dataset);
337 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
338 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
340 // >>>This is a fix for the moment, until a better solution is
342 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
344 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
347 Desktop.addInternalFrame(af, MessageManager.formatMessage(
348 "label.original_data_for_params", new String[]
349 { this.title }), AlignFrame.DEFAULT_WIDTH,
350 AlignFrame.DEFAULT_HEIGHT);
354 * CutAndPasteTransfer cap = new CutAndPasteTransfer(); for (int i = 0; i <
355 * seqs.length; i++) { cap.appendText(new jalview.util.Format("%-" + 15 +
356 * "s").form( seqs[i].getName())); cap.appendText(" " + seqstrings[i] +
359 * Desktop.addInternalFrame(cap, "Original Data", 400, 400);
363 class PCAPrinter extends Thread implements Printable
368 PrinterJob printJob = PrinterJob.getPrinterJob();
369 PageFormat defaultPage = printJob.defaultPage();
370 PageFormat pf = printJob.pageDialog(defaultPage);
372 if (defaultPage == pf)
380 printJob.setPrintable(this, pf);
382 if (printJob.printDialog())
387 } catch (Exception PrintException)
389 PrintException.printStackTrace();
395 public int print(Graphics pg, PageFormat pf, int pi)
396 throws PrinterException
398 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
400 getRotatableCanvas().drawBackground(pg);
401 getRotatableCanvas().drawScene(pg);
402 if (getRotatableCanvas().drawAxes)
404 getRotatableCanvas().drawAxes(pg);
409 return Printable.PAGE_EXISTS;
413 return Printable.NO_SUCH_PAGE;
418 public void makePCAImage(ImageMaker.TYPE type)
420 int width = getRotatableCanvas().getWidth();
421 int height = getRotatableCanvas().getHeight();
422 ImageWriterI writer = new ImageWriterI()
425 public void exportImage(Graphics g) throws Exception
427 RotatableCanvas canvas = getRotatableCanvas();
428 canvas.drawBackground(g);
436 String pca = MessageManager.getString("label.pca");
437 ImageExporter exporter = new ImageExporter(writer, null, type, pca);
438 exporter.doExport(null, this, width, height, pca);
442 protected void viewMenu_menuSelected()
444 buildAssociatedViewMenu();
448 * Builds the menu showing the choice of possible views (for the associated
449 * sequence data) to which the PCA may be linked
451 void buildAssociatedViewMenu()
453 AlignmentPanel[] aps = PaintRefresher
454 .getAssociatedPanels(av.getSequenceSetId());
455 if (aps.length == 1 && getRotatableCanvas().av == aps[0].av)
457 associateViewsMenu.setVisible(false);
461 associateViewsMenu.setVisible(true);
464 .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
466 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
469 associateViewsMenu.removeAll();
471 JRadioButtonMenuItem item;
472 ButtonGroup buttonGroup = new ButtonGroup();
473 int iSize = aps.length;
475 for (int i = 0; i < iSize; i++)
477 final AlignmentPanel panel = aps[i];
478 item = new JRadioButtonMenuItem(panel.av.getViewName(),
479 panel.av == getRotatableCanvas().av);
480 buttonGroup.add(item);
481 item.addActionListener(new ActionListener()
484 public void actionPerformed(ActionEvent evt)
486 selectAssociatedView(panel);
490 associateViewsMenu.add(item);
493 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
496 buttonGroup.add(itemf);
498 itemf.setSelected(getRotatableCanvas().isApplyToAllViews());
499 itemf.addActionListener(new ActionListener()
502 public void actionPerformed(ActionEvent evt)
504 getRotatableCanvas().setApplyToAllViews(itemf.isSelected());
507 associateViewsMenu.add(itemf);
515 * jalview.jbgui.GPCAPanel#outputPoints_actionPerformed(java.awt.event.ActionEvent
519 protected void outputPoints_actionPerformed()
521 CutAndPasteTransfer cap = new CutAndPasteTransfer();
524 cap.setText(getPcaModel().getPointsasCsv(false,
525 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
526 zCombobox.getSelectedIndex()));
527 Desktop.addInternalFrame(cap, MessageManager
528 .formatMessage("label.points_for_params", new String[]
529 { this.getTitle() }), 500, 500);
530 } catch (OutOfMemoryError oom)
532 new OOMWarning("exporting PCA points", oom);
541 * jalview.jbgui.GPCAPanel#outputProjPoints_actionPerformed(java.awt.event
545 protected void outputProjPoints_actionPerformed()
547 CutAndPasteTransfer cap = new CutAndPasteTransfer();
550 cap.setText(getPcaModel().getPointsasCsv(true,
551 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
552 zCombobox.getSelectedIndex()));
553 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
554 "label.transformed_points_for_params", new String[]
555 { this.getTitle() }), 500, 500);
556 } catch (OutOfMemoryError oom)
558 new OOMWarning("exporting transformed PCA points", oom);
566 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
569 public void setProgressBar(String message, long id)
571 progressBar.setProgressBar(message, id);
572 // if (progressBars == null)
574 // progressBars = new Hashtable();
575 // progressBarHandlers = new Hashtable();
578 // JPanel progressPanel;
579 // Long lId = Long.valueOf(id);
580 // GridLayout layout = (GridLayout) statusPanel.getLayout();
581 // if (progressBars.get(lId) != null)
583 // progressPanel = (JPanel) progressBars.get(Long.valueOf(id));
584 // statusPanel.remove(progressPanel);
585 // progressBars.remove(lId);
586 // progressPanel = null;
587 // if (message != null)
589 // statusBar.setText(message);
591 // if (progressBarHandlers.contains(lId))
593 // progressBarHandlers.remove(lId);
595 // layout.setRows(layout.getRows() - 1);
599 // progressPanel = new JPanel(new BorderLayout(10, 5));
601 // JProgressBar progressBar = new JProgressBar();
602 // progressBar.setIndeterminate(true);
604 // progressPanel.add(new JLabel(message), BorderLayout.WEST);
605 // progressPanel.add(progressBar, BorderLayout.CENTER);
607 // layout.setRows(layout.getRows() + 1);
608 // statusPanel.add(progressPanel);
610 // progressBars.put(lId, progressPanel);
613 // // setMenusForViewport();
618 public void addProgressBar(long id, String message)
620 progressBar.addProgressBar(id, message);
624 public void removeProgressBar(long id)
626 progressBar.removeProgressBar(id);
630 public void registerHandler(final long id,
631 final IProgressIndicatorHandler handler)
633 progressBar.registerHandler(id, handler);
634 // if (progressBarHandlers == null ||
635 // !progressBars.contains(Long.valueOf(id)))
638 // Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
640 // progressBarHandlers.put(Long.valueOf(id), handler);
641 // final JPanel progressPanel = (JPanel) progressBars.get(Long.valueOf(id));
642 // if (handler.canCancel())
644 // JButton cancel = new JButton(
645 // MessageManager.getString("action.cancel"));
646 // final IProgressIndicator us = this;
647 // cancel.addActionListener(new ActionListener()
651 // public void actionPerformed(ActionEvent e)
653 // handler.cancelActivity(id);
654 // us.setProgressBar(MessageManager.formatMessage("label.cancelled_params",
655 // new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
658 // progressPanel.add(cancel, BorderLayout.EAST);
664 * @return true if any progress bars are still active
667 public boolean operationInProgress()
669 return progressBar.operationInProgress();
673 protected void resetButton_actionPerformed()
676 setTop(0); // ugly - prevents dimensionChanged events from being processed
677 xCombobox.setSelectedIndex(0);
678 yCombobox.setSelectedIndex(1);
680 zCombobox.setSelectedIndex(2);
684 * Answers true if PCA calculation is in progress, else false
688 public boolean isWorking()
694 * Answers the selected checkbox item index for PCA dimension for the X, Y or
695 * Z axis of the display
700 public int getSelectedDimensionIndex(Axis axis)
705 return xCombobox.getSelectedIndex();
707 return yCombobox.getSelectedIndex();
709 return zCombobox.getSelectedIndex();
713 public void setShowLabels(boolean show)
715 showLabels.setSelected(show);
719 * Sets the input data used to calculate the PCA. This is provided for
720 * 'restore from project', which does not currently support this (AL-2647), so
721 * sets the value to null, and hides the menu option for "Input Data...". J
725 public void setInputData(AlignmentView data)
727 getPcaModel().setInputData(data);
728 originalSeqData.setVisible(data != null);
731 public AlignViewportI getAlignViewport()
736 public PCAModel getPcaModel()
741 public void setPcaModel(PCAModel pcaModel)
743 this.pcaModel = pcaModel;
746 public RotatableCanvas getRotatableCanvas()
751 public void setRotatableCanvas(RotatableCanvas rc)
761 public void setTop(int top)
767 * set the associated view for this PCA.
771 public void selectAssociatedView(AlignmentPanel panel)
773 getRotatableCanvas().setApplyToAllViews(false);
778 getRotatableCanvas().av = panel.av;
779 getRotatableCanvas().ap = panel;
780 PaintRefresher.Register(PCAPanel.this, panel.av.getSequenceSetId());
783 public static void addToDesktop(PCAPanel panel, String modelName)
785 Dimension dim = Platform.getDimIfEmbedded(panel, 475, 450);
786 Desktop.addInternalFrame(panel, MessageManager.formatMessage(
787 "label.calc_title", "PCA", modelName), dim.width,