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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Dimension;
26 import java.awt.Graphics;
27 import java.awt.event.ActionEvent;
28 import java.awt.event.ActionListener;
29 import java.awt.print.PageFormat;
30 import java.awt.print.Printable;
31 import java.awt.print.PrinterException;
32 import java.awt.print.PrinterJob;
34 import javax.swing.ButtonGroup;
35 import javax.swing.JMenuItem;
36 import javax.swing.JRadioButtonMenuItem;
37 import javax.swing.event.InternalFrameAdapter;
38 import javax.swing.event.InternalFrameEvent;
40 import jalview.analysis.scoremodels.ScoreModels;
41 import jalview.api.AlignViewportI;
42 import jalview.api.analysis.ScoreModelI;
43 import jalview.api.analysis.SimilarityParamsI;
44 import jalview.bin.Console;
45 import jalview.datamodel.Alignment;
46 import jalview.datamodel.AlignmentI;
47 import jalview.datamodel.AlignmentView;
48 import jalview.datamodel.HiddenColumns;
49 import jalview.datamodel.SequenceI;
50 import jalview.gui.ImageExporter.ImageWriterI;
51 import jalview.gui.JalviewColourChooser.ColourChooserListener;
52 import jalview.jbgui.GPCAPanel;
53 import jalview.math.RotatableMatrix.Axis;
54 import jalview.util.ImageMaker;
55 import jalview.util.MessageManager;
56 import jalview.viewmodel.AlignmentViewport;
57 import jalview.viewmodel.PCAModel;
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.setFrameIcon(WindowIcons.treeIcon);
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 Desktop.addInternalFrame(this,
211 MessageManager.formatMessage("label.calc_title", "PCA",
212 getPcaModel().getScoreModelName()),
214 this.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT));
220 * Updates the PCA display after a change of component to use for x, y or z
224 protected void doDimensionChange()
231 int dim1 = getTop() - xCombobox.getSelectedIndex();
232 int dim2 = getTop() - yCombobox.getSelectedIndex();
233 int dim3 = getTop() - zCombobox.getSelectedIndex();
234 getPcaModel().updateRcView(dim1, dim2, dim3);
235 getRotatableCanvas().resetView();
239 * Sets the selected checkbox item index for PCA dimension (1, 2, 3...) for
240 * the given axis (X/Y/Z)
245 public void setSelectedDimensionIndex(int index, Axis axis)
250 xCombobox.setSelectedIndex(index);
253 yCombobox.setSelectedIndex(index);
256 zCombobox.setSelectedIndex(index);
263 protected void outputValues_actionPerformed()
265 CutAndPasteTransfer cap = new CutAndPasteTransfer();
268 cap.setText(getPcaModel().getDetails());
269 Desktop.addInternalFrame(cap,
270 MessageManager.getString("label.pca_details"), 500, 500);
271 } catch (OutOfMemoryError oom)
273 new OOMWarning("opening PCA details", oom);
279 protected void showLabels_actionPerformed()
281 getRotatableCanvas().showLabels(showLabels.getState());
285 protected void print_actionPerformed()
287 PCAPrinter printer = new PCAPrinter();
292 * If available, shows the data which formed the inputs for the PCA as a new
296 public void originalSeqData_actionPerformed()
298 // JAL-2647 disabled after load from project (until save to project done)
299 if (getPcaModel().getInputData() == null)
302 "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
305 // decide if av alignment is sufficiently different to original data to
306 // warrant a new window to be created
307 // create new alignment window with hidden regions (unhiding hidden regions
308 // yields unaligned seqs)
309 // or create a selection box around columns in alignment view
310 // test Alignment(SeqCigar[])
314 // we try to get the associated view's gap character
315 // but this may fail if the view was closed...
316 gc = av.getGapCharacter();
317 } catch (Exception ex)
321 Object[] alAndColsel = getPcaModel().getInputData()
322 .getAlignmentAndHiddenColumns(gc);
324 if (alAndColsel != null && alAndColsel[0] != null)
326 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
328 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
329 AlignmentI dataset = (av != null && av.getAlignment() != null)
330 ? av.getAlignment().getDataset()
334 al.setDataset(dataset);
340 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
341 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
343 // >>>This is a fix for the moment, until a better solution is
345 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
347 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
350 Desktop.addInternalFrame(af, MessageManager.formatMessage(
351 "label.original_data_for_params", new String[]
352 { this.title }), AlignFrame.DEFAULT_WIDTH,
353 AlignFrame.DEFAULT_HEIGHT);
357 * CutAndPasteTransfer cap = new CutAndPasteTransfer(); for (int i = 0; i <
358 * seqs.length; i++) { cap.appendText(new jalview.util.Format("%-" + 15 +
359 * "s").form( seqs[i].getName())); cap.appendText(" " + seqstrings[i] +
362 * Desktop.addInternalFrame(cap, "Original Data", 400, 400);
366 class PCAPrinter extends Thread implements Printable
371 PrinterJob printJob = PrinterJob.getPrinterJob();
372 PageFormat defaultPage = printJob.defaultPage();
373 PageFormat pf = printJob.pageDialog(defaultPage);
375 if (defaultPage == pf)
383 printJob.setPrintable(this, pf);
385 if (printJob.printDialog())
390 } catch (Exception PrintException)
392 PrintException.printStackTrace();
398 public int print(Graphics pg, PageFormat pf, int pi)
399 throws PrinterException
401 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
403 getRotatableCanvas().drawBackground(pg);
404 getRotatableCanvas().drawScene(pg);
405 if (getRotatableCanvas().drawAxes)
407 getRotatableCanvas().drawAxes(pg);
412 return Printable.PAGE_EXISTS;
416 return Printable.NO_SUCH_PAGE;
421 public void makePCAImage(ImageMaker.TYPE type)
423 int width = getRotatableCanvas().getWidth();
424 int height = getRotatableCanvas().getHeight();
425 ImageWriterI writer = new ImageWriterI()
428 public void exportImage(Graphics g) throws Exception
430 RotatableCanvas canvas = getRotatableCanvas();
431 canvas.drawBackground(g);
439 String pca = MessageManager.getString("label.pca");
440 ImageExporter exporter = new ImageExporter(writer, null, type, pca);
441 exporter.doExport(null, this, width, height, pca);
445 protected void viewMenu_menuSelected()
447 buildAssociatedViewMenu();
451 * Builds the menu showing the choice of possible views (for the associated
452 * sequence data) to which the PCA may be linked
454 void buildAssociatedViewMenu()
456 AlignmentPanel[] aps = PaintRefresher
457 .getAssociatedPanels(av.getSequenceSetId());
458 if (aps.length == 1 && getRotatableCanvas().av == aps[0].av)
460 associateViewsMenu.setVisible(false);
464 associateViewsMenu.setVisible(true);
467 .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
469 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
472 associateViewsMenu.removeAll();
474 JRadioButtonMenuItem item;
475 ButtonGroup buttonGroup = new ButtonGroup();
476 int iSize = aps.length;
478 for (int i = 0; i < iSize; i++)
480 final AlignmentPanel panel = aps[i];
481 item = new JRadioButtonMenuItem(panel.av.getViewName(),
482 panel.av == getRotatableCanvas().av);
483 buttonGroup.add(item);
484 item.addActionListener(new ActionListener()
487 public void actionPerformed(ActionEvent evt)
489 selectAssociatedView(panel);
493 associateViewsMenu.add(item);
496 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
499 buttonGroup.add(itemf);
501 itemf.setSelected(getRotatableCanvas().isApplyToAllViews());
502 itemf.addActionListener(new ActionListener()
505 public void actionPerformed(ActionEvent evt)
507 getRotatableCanvas().setApplyToAllViews(itemf.isSelected());
510 associateViewsMenu.add(itemf);
518 * jalview.jbgui.GPCAPanel#outputPoints_actionPerformed(java.awt.event.ActionEvent
522 protected void outputPoints_actionPerformed()
524 CutAndPasteTransfer cap = new CutAndPasteTransfer();
527 cap.setText(getPcaModel().getPointsasCsv(false,
528 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
529 zCombobox.getSelectedIndex()));
530 Desktop.addInternalFrame(cap, MessageManager
531 .formatMessage("label.points_for_params", new String[]
532 { this.getTitle() }), 500, 500);
533 } catch (OutOfMemoryError oom)
535 new OOMWarning("exporting PCA points", oom);
544 * jalview.jbgui.GPCAPanel#outputProjPoints_actionPerformed(java.awt.event
548 protected void outputProjPoints_actionPerformed()
550 CutAndPasteTransfer cap = new CutAndPasteTransfer();
553 cap.setText(getPcaModel().getPointsasCsv(true,
554 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
555 zCombobox.getSelectedIndex()));
556 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
557 "label.transformed_points_for_params", new String[]
558 { this.getTitle() }), 500, 500);
559 } catch (OutOfMemoryError oom)
561 new OOMWarning("exporting transformed PCA points", oom);
569 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
572 public void setProgressBar(String message, long id)
574 progressBar.setProgressBar(message, id);
575 // if (progressBars == null)
577 // progressBars = new Hashtable();
578 // progressBarHandlers = new Hashtable();
581 // JPanel progressPanel;
582 // Long lId = Long.valueOf(id);
583 // GridLayout layout = (GridLayout) statusPanel.getLayout();
584 // if (progressBars.get(lId) != null)
586 // progressPanel = (JPanel) progressBars.get(Long.valueOf(id));
587 // statusPanel.remove(progressPanel);
588 // progressBars.remove(lId);
589 // progressPanel = null;
590 // if (message != null)
592 // statusBar.setText(message);
594 // if (progressBarHandlers.contains(lId))
596 // progressBarHandlers.remove(lId);
598 // layout.setRows(layout.getRows() - 1);
602 // progressPanel = new JPanel(new BorderLayout(10, 5));
604 // JProgressBar progressBar = new JProgressBar();
605 // progressBar.setIndeterminate(true);
607 // progressPanel.add(new JLabel(message), BorderLayout.WEST);
608 // progressPanel.add(progressBar, BorderLayout.CENTER);
610 // layout.setRows(layout.getRows() + 1);
611 // statusPanel.add(progressPanel);
613 // progressBars.put(lId, progressPanel);
616 // // setMenusForViewport();
621 public void registerHandler(final long id,
622 final IProgressIndicatorHandler handler)
624 progressBar.registerHandler(id, handler);
625 // if (progressBarHandlers == null ||
626 // !progressBars.contains(Long.valueOf(id)))
629 // Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
631 // progressBarHandlers.put(Long.valueOf(id), handler);
632 // final JPanel progressPanel = (JPanel) progressBars.get(Long.valueOf(id));
633 // if (handler.canCancel())
635 // JButton cancel = new JButton(
636 // MessageManager.getString("action.cancel"));
637 // final IProgressIndicator us = this;
638 // cancel.addActionListener(new ActionListener()
642 // public void actionPerformed(ActionEvent e)
644 // handler.cancelActivity(id);
645 // us.setProgressBar(MessageManager.formatMessage("label.cancelled_params",
646 // new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
649 // progressPanel.add(cancel, BorderLayout.EAST);
655 * @return true if any progress bars are still active
658 public boolean operationInProgress()
660 return progressBar.operationInProgress();
664 protected void resetButton_actionPerformed()
667 setTop(0); // ugly - prevents dimensionChanged events from being processed
668 xCombobox.setSelectedIndex(0);
669 yCombobox.setSelectedIndex(1);
671 zCombobox.setSelectedIndex(2);
675 * Answers true if PCA calculation is in progress, else false
679 public boolean isWorking()
685 * Answers the selected checkbox item index for PCA dimension for the X, Y or
686 * Z axis of the display
691 public int getSelectedDimensionIndex(Axis axis)
696 return xCombobox.getSelectedIndex();
698 return yCombobox.getSelectedIndex();
700 return zCombobox.getSelectedIndex();
704 public void setShowLabels(boolean show)
706 showLabels.setSelected(show);
710 * Sets the input data used to calculate the PCA. This is provided for
711 * 'restore from project', which does not currently support this (AL-2647), so
712 * sets the value to null, and hides the menu option for "Input Data...". J
716 public void setInputData(AlignmentView data)
718 getPcaModel().setInputData(data);
719 originalSeqData.setVisible(data != null);
722 public AlignViewportI getAlignViewport()
727 public PCAModel getPcaModel()
732 public void setPcaModel(PCAModel pcaModel)
734 this.pcaModel = pcaModel;
737 public RotatableCanvas getRotatableCanvas()
742 public void setRotatableCanvas(RotatableCanvas rc)
752 public void setTop(int top)
758 * set the associated view for this PCA.
762 public void selectAssociatedView(AlignmentPanel panel)
764 getRotatableCanvas().setApplyToAllViews(false);
769 getRotatableCanvas().av = panel.av;
770 getRotatableCanvas().ap = panel;
771 PaintRefresher.Register(PCAPanel.this, panel.av.getSequenceSetId());