2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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.datamodel.Alignment;
24 import jalview.datamodel.AlignmentView;
25 import jalview.datamodel.ColumnSelection;
26 import jalview.datamodel.SeqCigar;
27 import jalview.datamodel.SequenceI;
28 import jalview.jbgui.GPCAPanel;
29 import jalview.schemes.ResidueProperties;
30 import jalview.util.MessageManager;
31 import jalview.viewmodel.PCAModel;
33 import java.awt.BorderLayout;
34 import java.awt.Color;
35 import java.awt.Graphics;
36 import java.awt.GridLayout;
37 import java.awt.event.ActionEvent;
38 import java.awt.event.ActionListener;
39 import java.awt.print.PageFormat;
40 import java.awt.print.Printable;
41 import java.awt.print.PrinterException;
42 import java.awt.print.PrinterJob;
43 import java.util.Hashtable;
45 import javax.swing.ButtonGroup;
46 import javax.swing.JButton;
47 import javax.swing.JCheckBoxMenuItem;
48 import javax.swing.JColorChooser;
49 import javax.swing.JLabel;
50 import javax.swing.JMenuItem;
51 import javax.swing.JOptionPane;
52 import javax.swing.JPanel;
53 import javax.swing.JProgressBar;
54 import javax.swing.JRadioButtonMenuItem;
62 public class PCAPanel extends GPCAPanel implements Runnable,
77 * Creates a new PCAPanel object.
84 public PCAPanel(AlignmentPanel ap)
89 boolean sameLength = true;
90 boolean selected = av.getSelectionGroup() != null
91 && av.getSelectionGroup().getSize() > 0;
92 AlignmentView seqstrings = av.getAlignmentView(selected);
93 boolean nucleotide = av.getAlignment().isNucleotide();
97 seqs = av.getAlignment().getSequencesArray();
101 seqs = av.getSelectionGroup().getSequencesInOrder(av.getAlignment());
103 SeqCigar sq[] = seqstrings.getSequences();
104 int length = sq[0].getWidth();
106 for (int i = 0; i < seqs.length; i++)
108 if (sq[i].getWidth() != length)
120 MessageManager.getString("label.pca_sequences_not_aligned"),
121 MessageManager.getString("label.sequences_not_aligned"), JOptionPane.WARNING_MESSAGE);
125 pcaModel = new PCAModel(seqstrings, seqs, nucleotide);
126 PaintRefresher.Register(this, av.getSequenceSetId());
128 rc = new RotatableCanvas(ap);
129 this.getContentPane().add(rc, BorderLayout.CENTER);
130 Thread worker = new Thread(this);
135 protected void scoreMatrix_menuSelected()
137 scoreMatrixMenu.removeAll();
138 for (final String sm : ResidueProperties.scoreMatrices.keySet())
140 if (ResidueProperties.getScoreMatrix(sm) != null)
142 // create an entry for this score matrix for use in PCA
143 JCheckBoxMenuItem jm = new JCheckBoxMenuItem();
144 jm.setText(MessageManager
145 .getStringOrReturn("label.score_model", sm));
146 jm.setSelected(pcaModel.getScore_matrix().equals(sm));
147 if ((ResidueProperties.scoreMatrices.get(sm).isDNA() && ResidueProperties.scoreMatrices
148 .get(sm).isProtein())
149 || pcaModel.isNucleotide() == ResidueProperties.scoreMatrices
152 final PCAPanel us = this;
153 jm.addActionListener(new ActionListener()
156 public void actionPerformed(ActionEvent e)
158 if (!pcaModel.getScore_matrix().equals(sm))
160 pcaModel.setScore_matrix(sm);
161 Thread worker = new Thread(us);
166 scoreMatrixMenu.add(jm);
172 public void bgcolour_actionPerformed(ActionEvent e)
174 Color col = JColorChooser.showDialog(this, MessageManager.getString("label.select_backgroud_colour"),
189 long progId = System.currentTimeMillis();
190 IProgressIndicator progress = this;
191 String message = MessageManager.getString("label.pca_recalculating");
192 if (getParent() == null)
194 progress = ap.alignFrame;
195 message = MessageManager.getString("label.pca_calculating");
197 progress.setProgressBar(message, progId);
200 calcSettings.setEnabled(false);
203 xCombobox.setSelectedIndex(0);
204 yCombobox.setSelectedIndex(1);
205 zCombobox.setSelectedIndex(2);
207 pcaModel.updateRc(rc);
209 nuclSetting.setSelected(pcaModel.isNucleotide());
210 protSetting.setSelected(!pcaModel.isNucleotide());
211 jvVersionSetting.setSelected(pcaModel.isJvCalcMode());
212 top = pcaModel.getTop();
214 } catch (OutOfMemoryError er)
216 new OOMWarning("calculating PCA", er);
220 progress.setProgressBar("", progId);
222 calcSettings.setEnabled(true);
224 if (getParent() == null)
227 Desktop.addInternalFrame(this, MessageManager
228 .getString("label.principal_component_analysis"), 475, 450);
233 protected void nuclSetting_actionPerfomed(ActionEvent arg0)
235 if (!pcaModel.isNucleotide())
237 pcaModel.setNucleotide(true);
238 pcaModel.setScore_matrix("DNA");
239 Thread worker = new Thread(this);
246 protected void protSetting_actionPerfomed(ActionEvent arg0)
249 if (pcaModel.isNucleotide())
251 pcaModel.setNucleotide(false);
252 pcaModel.setScore_matrix("BLOSUM62");
253 Thread worker = new Thread(this);
259 protected void jvVersionSetting_actionPerfomed(ActionEvent arg0)
261 pcaModel.setJvCalcMode(jvVersionSetting.isSelected());
262 Thread worker = new Thread(this);
269 void doDimensionChange()
276 int dim1 = top - xCombobox.getSelectedIndex();
277 int dim2 = top - yCombobox.getSelectedIndex();
278 int dim3 = top - zCombobox.getSelectedIndex();
279 pcaModel.updateRcView(dim1, dim2, dim3);
281 rc.rotmat.setIdentity();
283 rc.paint(rc.getGraphics());
292 protected void xCombobox_actionPerformed(ActionEvent e)
303 protected void yCombobox_actionPerformed(ActionEvent e)
314 protected void zCombobox_actionPerformed(ActionEvent e)
319 public void outputValues_actionPerformed(ActionEvent e)
321 CutAndPasteTransfer cap = new CutAndPasteTransfer();
324 cap.setText(pcaModel.getDetails());
325 Desktop.addInternalFrame(cap,
326 MessageManager.getString("label.pca_details"), 500, 500);
327 } catch (OutOfMemoryError oom)
329 new OOMWarning("opening PCA details", oom);
334 public void showLabels_actionPerformed(ActionEvent e)
336 rc.showLabels(showLabels.getState());
339 public void print_actionPerformed(ActionEvent e)
341 PCAPrinter printer = new PCAPrinter();
345 public void originalSeqData_actionPerformed(ActionEvent e)
347 // this was cut'n'pasted from the equivalent TreePanel method - we should
348 // make this an abstract function of all jalview analysis windows
349 if (pcaModel.getSeqtrings() == null)
351 jalview.bin.Cache.log
352 .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
355 // decide if av alignment is sufficiently different to original data to
356 // warrant a new window to be created
357 // create new alignmnt window with hidden regions (unhiding hidden regions
358 // yields unaligned seqs)
359 // or create a selection box around columns in alignment view
360 // test Alignment(SeqCigar[])
364 // we try to get the associated view's gap character
365 // but this may fail if the view was closed...
366 gc = av.getGapCharacter();
367 } catch (Exception ex)
371 Object[] alAndColsel = pcaModel.getSeqtrings()
372 .getAlignmentAndColumnSelection(gc);
374 if (alAndColsel != null && alAndColsel[0] != null)
376 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
378 Alignment al = new Alignment((SequenceI[]) alAndColsel[0]);
379 Alignment dataset = (av != null && av.getAlignment() != null) ? av
380 .getAlignment().getDataset() : null;
383 al.setDataset(dataset);
389 AlignFrame af = new AlignFrame(al,
390 (ColumnSelection) alAndColsel[1], AlignFrame.DEFAULT_WIDTH,
391 AlignFrame.DEFAULT_HEIGHT);
393 // >>>This is a fix for the moment, until a better solution is
395 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
397 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
400 Desktop.addInternalFrame(af, MessageManager.formatMessage(
401 "label.original_data_for_params", new String[]
402 { this.title }), AlignFrame.DEFAULT_WIDTH,
403 AlignFrame.DEFAULT_HEIGHT);
407 * CutAndPasteTransfer cap = new CutAndPasteTransfer(); for (int i = 0; i <
408 * seqs.length; i++) { cap.appendText(new jalview.util.Format("%-" + 15 +
409 * "s").form( seqs[i].getName())); cap.appendText(" " + seqstrings[i] +
412 * Desktop.addInternalFrame(cap, "Original Data", 400, 400);
416 class PCAPrinter extends Thread implements Printable
420 PrinterJob printJob = PrinterJob.getPrinterJob();
421 PageFormat pf = printJob.pageDialog(printJob.defaultPage());
423 printJob.setPrintable(this, pf);
425 if (printJob.printDialog())
430 } catch (Exception PrintException)
432 PrintException.printStackTrace();
437 public int print(Graphics pg, PageFormat pf, int pi)
438 throws PrinterException
440 pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
442 rc.drawBackground(pg, rc.bgColour);
444 if (rc.drawAxes == true)
451 return Printable.PAGE_EXISTS;
455 return Printable.NO_SUCH_PAGE;
466 public void eps_actionPerformed(ActionEvent e)
468 makePCAImage(jalview.util.ImageMaker.TYPE.EPS);
477 public void png_actionPerformed(ActionEvent e)
479 makePCAImage(jalview.util.ImageMaker.TYPE.PNG);
482 void makePCAImage(jalview.util.ImageMaker.TYPE type)
484 int width = rc.getWidth();
485 int height = rc.getHeight();
487 jalview.util.ImageMaker im;
489 if (type == jalview.util.ImageMaker.TYPE.PNG)
491 im = new jalview.util.ImageMaker(this,
492 jalview.util.ImageMaker.TYPE.PNG,
493 "Make PNG image from PCA", width, height, null, null);
495 else if (type == jalview.util.ImageMaker.TYPE.EPS)
497 im = new jalview.util.ImageMaker(this,
498 jalview.util.ImageMaker.TYPE.EPS,
499 "Make EPS file from PCA", width, height, null,
504 im = new jalview.util.ImageMaker(this,
505 jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
506 width, height, null, this.getTitle());
510 if (im.getGraphics() != null)
512 rc.drawBackground(im.getGraphics(), Color.black);
513 rc.drawScene(im.getGraphics());
514 if (rc.drawAxes == true)
516 rc.drawAxes(im.getGraphics());
522 public void viewMenu_menuSelected()
524 buildAssociatedViewMenu();
527 void buildAssociatedViewMenu()
529 AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
530 .getSequenceSetId());
531 if (aps.length == 1 && rc.av == aps[0].av)
533 associateViewsMenu.setVisible(false);
537 associateViewsMenu.setVisible(true);
539 if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
541 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
544 associateViewsMenu.removeAll();
546 JRadioButtonMenuItem item;
547 ButtonGroup buttonGroup = new ButtonGroup();
548 int i, iSize = aps.length;
549 final PCAPanel thisPCAPanel = this;
550 for (i = 0; i < iSize; i++)
552 final AlignmentPanel ap = aps[i];
553 item = new JRadioButtonMenuItem(ap.av.viewName, ap.av == rc.av);
554 buttonGroup.add(item);
555 item.addActionListener(new ActionListener()
557 public void actionPerformed(ActionEvent evt)
559 rc.applyToAllViews = false;
562 PaintRefresher.Register(thisPCAPanel, ap.av.getSequenceSetId());
566 associateViewsMenu.add(item);
569 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem("All Views");
571 buttonGroup.add(itemf);
573 itemf.setSelected(rc.applyToAllViews);
574 itemf.addActionListener(new ActionListener()
576 public void actionPerformed(ActionEvent evt)
578 rc.applyToAllViews = itemf.isSelected();
581 associateViewsMenu.add(itemf);
589 * jalview.jbgui.GPCAPanel#outputPoints_actionPerformed(java.awt.event.ActionEvent
592 protected void outputPoints_actionPerformed(ActionEvent e)
594 CutAndPasteTransfer cap = new CutAndPasteTransfer();
597 cap.setText(pcaModel.getPointsasCsv(false,
598 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
599 zCombobox.getSelectedIndex()));
600 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
601 "label.points_for_params", new String[]
602 { this.getTitle() }), 500, 500);
603 } catch (OutOfMemoryError oom)
605 new OOMWarning("exporting PCA points", oom);
614 * jalview.jbgui.GPCAPanel#outputProjPoints_actionPerformed(java.awt.event
617 protected void outputProjPoints_actionPerformed(ActionEvent e)
619 CutAndPasteTransfer cap = new CutAndPasteTransfer();
622 cap.setText(pcaModel.getPointsasCsv(true,
623 xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
624 zCombobox.getSelectedIndex()));
625 Desktop.addInternalFrame(cap, MessageManager.formatMessage(
626 "label.transformed_points_for_params", new String[]
627 { this.getTitle() }), 500, 500);
628 } catch (OutOfMemoryError oom)
630 new OOMWarning("exporting transformed PCA points", oom);
635 // methods for implementing IProgressIndicator
636 // need to refactor to a reusable stub class
637 Hashtable progressBars, progressBarHandlers;
642 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
645 public void setProgressBar(String message, long id)
647 if (progressBars == null)
649 progressBars = new Hashtable();
650 progressBarHandlers = new Hashtable();
653 JPanel progressPanel;
654 Long lId = new Long(id);
655 GridLayout layout = (GridLayout) statusPanel.getLayout();
656 if (progressBars.get(lId) != null)
658 progressPanel = (JPanel) progressBars.get(new Long(id));
659 statusPanel.remove(progressPanel);
660 progressBars.remove(lId);
661 progressPanel = null;
664 statusBar.setText(message);
666 if (progressBarHandlers.contains(lId))
668 progressBarHandlers.remove(lId);
670 layout.setRows(layout.getRows() - 1);
674 progressPanel = new JPanel(new BorderLayout(10, 5));
676 JProgressBar progressBar = new JProgressBar();
677 progressBar.setIndeterminate(true);
679 progressPanel.add(new JLabel(message), BorderLayout.WEST);
680 progressPanel.add(progressBar, BorderLayout.CENTER);
682 layout.setRows(layout.getRows() + 1);
683 statusPanel.add(progressPanel);
685 progressBars.put(lId, progressPanel);
688 // setMenusForViewport();
693 public void registerHandler(final long id,
694 final IProgressIndicatorHandler handler)
696 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
698 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
700 progressBarHandlers.put(new Long(id), handler);
701 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
702 if (handler.canCancel())
704 JButton cancel = new JButton(
705 MessageManager.getString("action.cancel"));
706 final IProgressIndicator us = this;
707 cancel.addActionListener(new ActionListener()
711 public void actionPerformed(ActionEvent e)
713 handler.cancelActivity(id);
714 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
717 progressPanel.add(cancel, BorderLayout.EAST);
723 * @return true if any progress bars are still active
726 public boolean operationInProgress()
728 if (progressBars != null && progressBars.size() > 0)
736 protected void resetButton_actionPerformed(ActionEvent e)
739 top = 0; // ugly - prevents dimensionChanged events from being processed
740 xCombobox.setSelectedIndex(0);
741 yCombobox.setSelectedIndex(1);
743 zCombobox.setSelectedIndex(2);