JAL-1355
[jalview.git] / src / jalview / gui / PCAPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.gui;
22
23 import java.util.*;
24 import java.awt.*;
25 import java.awt.event.*;
26 import java.awt.print.*;
27
28 import javax.swing.*;
29
30 import jalview.datamodel.*;
31 import jalview.jbgui.*;
32 import jalview.schemes.ResidueProperties;
33 import jalview.util.MessageManager;
34 import jalview.viewmodel.PCAModel;
35
36 /**
37  * DOCUMENT ME!
38  * 
39  * @author $author$
40  * @version $Revision$
41  */
42 public class PCAPanel extends GPCAPanel implements Runnable,
43         IProgressIndicator
44 {
45
46   RotatableCanvas rc;
47
48   AlignmentPanel ap;
49
50   AlignViewport av;
51
52   PCAModel pcaModel;
53
54   int top = 0;
55
56   /**
57    * Creates a new PCAPanel object.
58    * 
59    * @param av
60    *          DOCUMENT ME!
61    * @param s
62    *          DOCUMENT ME!
63    */
64   public PCAPanel(AlignmentPanel ap)
65   {
66     this.av = ap.av;
67     this.ap = ap;
68
69     boolean sameLength = true;
70     boolean selected = av.getSelectionGroup() != null
71             && av.getSelectionGroup().getSize() > 0;
72     AlignmentView seqstrings = av.getAlignmentView(selected);
73     boolean nucleotide = av.getAlignment().isNucleotide();
74     SequenceI[] seqs;
75     if (!selected)
76     {
77       seqs = av.getAlignment().getSequencesArray();
78     }
79     else
80     {
81       seqs = av.getSelectionGroup().getSequencesInOrder(av.getAlignment());
82     }
83     SeqCigar sq[] = seqstrings.getSequences();
84     int length = sq[0].getWidth();
85
86     for (int i = 0; i < seqs.length; i++)
87     {
88       if (sq[i].getWidth() != length)
89       {
90         sameLength = false;
91         break;
92       }
93     }
94
95     if (!sameLength)
96     {
97       JOptionPane
98               .showMessageDialog(
99                       Desktop.desktop,
100                       MessageManager.getString("label.pca_sequences_not_aligned"),
101                       MessageManager.getString("label.sequences_not_aligned"), JOptionPane.WARNING_MESSAGE);
102
103       return;
104     }
105     pcaModel = new PCAModel(seqstrings, seqs, nucleotide);
106     PaintRefresher.Register(this, av.getSequenceSetId());
107
108     rc = new RotatableCanvas(ap);
109     this.getContentPane().add(rc, BorderLayout.CENTER);
110     Thread worker = new Thread(this);
111     worker.start();
112   }
113
114   @Override
115   protected void scoreMatrix_menuSelected()
116   {
117     scoreMatrixMenu.removeAll();
118     for (final String sm : ResidueProperties.scoreMatrices.keySet())
119     {
120       if (ResidueProperties.getScoreMatrix(sm) != null)
121       {
122         // create an entry for this score matrix for use in PCA
123         JCheckBoxMenuItem jm = new JCheckBoxMenuItem();
124         jm.setText(MessageManager
125                 .getStringOrReturn("label.score_model", sm));
126         jm.setSelected(pcaModel.getScore_matrix().equals(sm));
127         if ((ResidueProperties.scoreMatrices.get(sm).isDNA() && ResidueProperties.scoreMatrices
128                 .get(sm).isProtein())
129                 || pcaModel.isNucleotide() == ResidueProperties.scoreMatrices
130                         .get(sm).isDNA())
131         {
132           final PCAPanel us = this;
133           jm.addActionListener(new ActionListener()
134           {
135             @Override
136             public void actionPerformed(ActionEvent e)
137             {
138               if (!pcaModel.getScore_matrix().equals((String) sm))
139               {
140                 pcaModel.setScore_matrix((String) sm);
141                 Thread worker = new Thread(us);
142                 worker.start();
143               }
144             }
145           });
146           scoreMatrixMenu.add(jm);
147         }
148       }
149     }
150   }
151
152   public void bgcolour_actionPerformed(ActionEvent e)
153   {
154     Color col = JColorChooser.showDialog(this, "Select Background Colour",
155             rc.bgColour);
156
157     if (col != null)
158     {
159       rc.bgColour = col;
160     }
161     rc.repaint();
162   }
163
164   /**
165    * DOCUMENT ME!
166    */
167   public void run()
168   {
169     long progId = System.currentTimeMillis();
170     IProgressIndicator progress = this;
171     String message = "Recalculating PCA";
172     if (getParent() == null)
173     {
174       progress = ap.alignFrame;
175       message = "Calculating PCA";
176     }
177     progress.setProgressBar(message, progId);
178     try
179     {
180       calcSettings.setEnabled(false);
181       pcaModel.run();
182       // ////////////////
183       xCombobox.setSelectedIndex(0);
184       yCombobox.setSelectedIndex(1);
185       zCombobox.setSelectedIndex(2);
186
187       pcaModel.updateRc(rc);
188       // rc.invalidate();
189       nuclSetting.setSelected(pcaModel.isNucleotide());
190       protSetting.setSelected(!pcaModel.isNucleotide());
191       jvVersionSetting.setSelected(pcaModel.isJvCalcMode());
192       top = pcaModel.getTop();
193
194     } catch (OutOfMemoryError er)
195     {
196       new OOMWarning("calculating PCA", er);
197       return;
198     } finally
199     {
200       progress.setProgressBar("", progId);
201     }
202     calcSettings.setEnabled(true);
203     repaint();
204     if (getParent() == null)
205     {
206       addKeyListener(rc);
207       Desktop.addInternalFrame(this, MessageManager
208               .getString("label.principal_component_analysis"), 475, 450);
209     }
210   }
211
212   @Override
213   protected void nuclSetting_actionPerfomed(ActionEvent arg0)
214   {
215     if (!pcaModel.isNucleotide())
216     {
217       pcaModel.setNucleotide(true);
218       pcaModel.setScore_matrix("DNA");
219       Thread worker = new Thread(this);
220       worker.start();
221     }
222
223   }
224
225   @Override
226   protected void protSetting_actionPerfomed(ActionEvent arg0)
227   {
228
229     if (pcaModel.isNucleotide())
230     {
231       pcaModel.setNucleotide(false);
232       pcaModel.setScore_matrix("BLOSUM62");
233       Thread worker = new Thread(this);
234       worker.start();
235     }
236   }
237
238   @Override
239   protected void jvVersionSetting_actionPerfomed(ActionEvent arg0)
240   {
241     pcaModel.setJvCalcMode(jvVersionSetting.isSelected());
242     Thread worker = new Thread(this);
243     worker.start();
244   }
245
246   /**
247    * DOCUMENT ME!
248    */
249   void doDimensionChange()
250   {
251     if (top == 0)
252     {
253       return;
254     }
255
256     int dim1 = top - xCombobox.getSelectedIndex();
257     int dim2 = top - yCombobox.getSelectedIndex();
258     int dim3 = top - zCombobox.getSelectedIndex();
259     pcaModel.updateRcView(dim1, dim2, dim3);
260     rc.img = null;
261     rc.rotmat.setIdentity();
262     rc.initAxes();
263     rc.paint(rc.getGraphics());
264   }
265
266   /**
267    * DOCUMENT ME!
268    * 
269    * @param e
270    *          DOCUMENT ME!
271    */
272   protected void xCombobox_actionPerformed(ActionEvent e)
273   {
274     doDimensionChange();
275   }
276
277   /**
278    * DOCUMENT ME!
279    * 
280    * @param e
281    *          DOCUMENT ME!
282    */
283   protected void yCombobox_actionPerformed(ActionEvent e)
284   {
285     doDimensionChange();
286   }
287
288   /**
289    * DOCUMENT ME!
290    * 
291    * @param e
292    *          DOCUMENT ME!
293    */
294   protected void zCombobox_actionPerformed(ActionEvent e)
295   {
296     doDimensionChange();
297   }
298
299   public void outputValues_actionPerformed(ActionEvent e)
300   {
301     CutAndPasteTransfer cap = new CutAndPasteTransfer();
302     try
303     {
304       cap.setText(pcaModel.getDetails());
305       Desktop.addInternalFrame(cap,
306               MessageManager.getString("label.pca_details"), 500, 500);
307     } catch (OutOfMemoryError oom)
308     {
309       new OOMWarning("opening PCA details", oom);
310       cap.dispose();
311     }
312   }
313
314   public void showLabels_actionPerformed(ActionEvent e)
315   {
316     rc.showLabels(showLabels.getState());
317   }
318
319   public void print_actionPerformed(ActionEvent e)
320   {
321     PCAPrinter printer = new PCAPrinter();
322     printer.start();
323   }
324
325   public void originalSeqData_actionPerformed(ActionEvent e)
326   {
327     // this was cut'n'pasted from the equivalent TreePanel method - we should
328     // make this an abstract function of all jalview analysis windows
329     if (pcaModel.getSeqtrings() == null)
330     {
331       jalview.bin.Cache.log
332               .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
333       return;
334     }
335     // decide if av alignment is sufficiently different to original data to
336     // warrant a new window to be created
337     // create new alignmnt window with hidden regions (unhiding hidden regions
338     // yields unaligned seqs)
339     // or create a selection box around columns in alignment view
340     // test Alignment(SeqCigar[])
341     char gc = '-';
342     try
343     {
344       // we try to get the associated view's gap character
345       // but this may fail if the view was closed...
346       gc = av.getGapCharacter();
347     } catch (Exception ex)
348     {
349     }
350     ;
351     Object[] alAndColsel = pcaModel.getSeqtrings()
352             .getAlignmentAndColumnSelection(gc);
353
354     if (alAndColsel != null && alAndColsel[0] != null)
355     {
356       // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
357
358       Alignment al = new Alignment((SequenceI[]) alAndColsel[0]);
359       Alignment dataset = (av != null && av.getAlignment() != null) ? av
360               .getAlignment().getDataset() : null;
361       if (dataset != null)
362       {
363         al.setDataset(dataset);
364       }
365
366       if (true)
367       {
368         // make a new frame!
369         AlignFrame af = new AlignFrame(al,
370                 (ColumnSelection) alAndColsel[1], AlignFrame.DEFAULT_WIDTH,
371                 AlignFrame.DEFAULT_HEIGHT);
372
373         // >>>This is a fix for the moment, until a better solution is
374         // found!!<<<
375         // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
376
377         // af.addSortByOrderMenuItem(ServiceName + " Ordering",
378         // msaorder);
379
380         Desktop.addInternalFrame(af, MessageManager.formatMessage(
381                 "label.original_data_for_params", new String[]
382                 { this.title }), AlignFrame.DEFAULT_WIDTH,
383                 AlignFrame.DEFAULT_HEIGHT);
384       }
385     }
386     /*
387      * CutAndPasteTransfer cap = new CutAndPasteTransfer(); for (int i = 0; i <
388      * seqs.length; i++) { cap.appendText(new jalview.util.Format("%-" + 15 +
389      * "s").form( seqs[i].getName())); cap.appendText(" " + seqstrings[i] +
390      * "\n"); }
391      * 
392      * Desktop.addInternalFrame(cap, "Original Data", 400, 400);
393      */
394   }
395
396   class PCAPrinter extends Thread implements Printable
397   {
398     public void run()
399     {
400       PrinterJob printJob = PrinterJob.getPrinterJob();
401       PageFormat pf = printJob.pageDialog(printJob.defaultPage());
402
403       printJob.setPrintable(this, pf);
404
405       if (printJob.printDialog())
406       {
407         try
408         {
409           printJob.print();
410         } catch (Exception PrintException)
411         {
412           PrintException.printStackTrace();
413         }
414       }
415     }
416
417     public int print(Graphics pg, PageFormat pf, int pi)
418             throws PrinterException
419     {
420       pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
421
422       rc.drawBackground(pg, rc.bgColour);
423       rc.drawScene(pg);
424       if (rc.drawAxes == true)
425       {
426         rc.drawAxes(pg);
427       }
428
429       if (pi == 0)
430       {
431         return Printable.PAGE_EXISTS;
432       }
433       else
434       {
435         return Printable.NO_SUCH_PAGE;
436       }
437     }
438   }
439
440   /**
441    * DOCUMENT ME!
442    * 
443    * @param e
444    *          DOCUMENT ME!
445    */
446   public void eps_actionPerformed(ActionEvent e)
447   {
448     makePCAImage(jalview.util.ImageMaker.EPS);
449   }
450
451   /**
452    * DOCUMENT ME!
453    * 
454    * @param e
455    *          DOCUMENT ME!
456    */
457   public void png_actionPerformed(ActionEvent e)
458   {
459     makePCAImage(jalview.util.ImageMaker.PNG);
460   }
461
462   void makePCAImage(int type)
463   {
464     int width = rc.getWidth();
465     int height = rc.getHeight();
466
467     jalview.util.ImageMaker im;
468
469     if (type == jalview.util.ImageMaker.PNG)
470     {
471       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
472               "Make PNG image from PCA", width, height, null, null);
473     }
474     else
475     {
476       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
477               "Make EPS file from PCA", width, height, null,
478               this.getTitle());
479     }
480
481     if (im.getGraphics() != null)
482     {
483       rc.drawBackground(im.getGraphics(), Color.black);
484       rc.drawScene(im.getGraphics());
485       if (rc.drawAxes == true)
486       {
487         rc.drawAxes(im.getGraphics());
488       }
489       im.writeImage();
490     }
491   }
492
493   public void viewMenu_menuSelected()
494   {
495     buildAssociatedViewMenu();
496   }
497
498   void buildAssociatedViewMenu()
499   {
500     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
501             .getSequenceSetId());
502     if (aps.length == 1 && rc.av == aps[0].av)
503     {
504       associateViewsMenu.setVisible(false);
505       return;
506     }
507
508     associateViewsMenu.setVisible(true);
509
510     if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
511     {
512       viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
513     }
514
515     associateViewsMenu.removeAll();
516
517     JRadioButtonMenuItem item;
518     ButtonGroup buttonGroup = new ButtonGroup();
519     int i, iSize = aps.length;
520     final PCAPanel thisPCAPanel = this;
521     for (i = 0; i < iSize; i++)
522     {
523       final AlignmentPanel ap = aps[i];
524       item = new JRadioButtonMenuItem(ap.av.viewName, ap.av == rc.av);
525       buttonGroup.add(item);
526       item.addActionListener(new ActionListener()
527       {
528         public void actionPerformed(ActionEvent evt)
529         {
530           rc.applyToAllViews = false;
531           rc.av = ap.av;
532           rc.ap = ap;
533           PaintRefresher.Register(thisPCAPanel, ap.av.getSequenceSetId());
534         }
535       });
536
537       associateViewsMenu.add(item);
538     }
539
540     final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem("All Views");
541
542     buttonGroup.add(itemf);
543
544     itemf.setSelected(rc.applyToAllViews);
545     itemf.addActionListener(new ActionListener()
546     {
547       public void actionPerformed(ActionEvent evt)
548       {
549         rc.applyToAllViews = itemf.isSelected();
550       }
551     });
552     associateViewsMenu.add(itemf);
553
554   }
555
556   /*
557    * (non-Javadoc)
558    * 
559    * @see
560    * jalview.jbgui.GPCAPanel#outputPoints_actionPerformed(java.awt.event.ActionEvent
561    * )
562    */
563   protected void outputPoints_actionPerformed(ActionEvent e)
564   {
565     CutAndPasteTransfer cap = new CutAndPasteTransfer();
566     try
567     {
568       cap.setText(pcaModel.getPointsasCsv(false,
569               xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
570               zCombobox.getSelectedIndex()));
571       Desktop.addInternalFrame(cap, MessageManager.formatMessage(
572               "label.points_for_params", new String[]
573               { this.getTitle() }), 500, 500);
574     } catch (OutOfMemoryError oom)
575     {
576       new OOMWarning("exporting PCA points", oom);
577       cap.dispose();
578     }
579   }
580
581   /*
582    * (non-Javadoc)
583    * 
584    * @see
585    * jalview.jbgui.GPCAPanel#outputProjPoints_actionPerformed(java.awt.event
586    * .ActionEvent)
587    */
588   protected void outputProjPoints_actionPerformed(ActionEvent e)
589   {
590     CutAndPasteTransfer cap = new CutAndPasteTransfer();
591     try
592     {
593       cap.setText(pcaModel.getPointsasCsv(true,
594               xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
595               zCombobox.getSelectedIndex()));
596       Desktop.addInternalFrame(cap, MessageManager.formatMessage(
597               "label.transformed_points_for_params", new String[]
598               { this.getTitle() }), 500, 500);
599     } catch (OutOfMemoryError oom)
600     {
601       new OOMWarning("exporting transformed PCA points", oom);
602       cap.dispose();
603     }
604   }
605
606   // methods for implementing IProgressIndicator
607   // need to refactor to a reusable stub class
608   Hashtable progressBars, progressBarHandlers;
609
610   /*
611    * (non-Javadoc)
612    * 
613    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
614    */
615   @Override
616   public void setProgressBar(String message, long id)
617   {
618     if (progressBars == null)
619     {
620       progressBars = new Hashtable();
621       progressBarHandlers = new Hashtable();
622     }
623
624     JPanel progressPanel;
625     Long lId = new Long(id);
626     GridLayout layout = (GridLayout) statusPanel.getLayout();
627     if (progressBars.get(lId) != null)
628     {
629       progressPanel = (JPanel) progressBars.get(new Long(id));
630       statusPanel.remove(progressPanel);
631       progressBars.remove(lId);
632       progressPanel = null;
633       if (message != null)
634       {
635         statusBar.setText(message);
636       }
637       if (progressBarHandlers.contains(lId))
638       {
639         progressBarHandlers.remove(lId);
640       }
641       layout.setRows(layout.getRows() - 1);
642     }
643     else
644     {
645       progressPanel = new JPanel(new BorderLayout(10, 5));
646
647       JProgressBar progressBar = new JProgressBar();
648       progressBar.setIndeterminate(true);
649
650       progressPanel.add(new JLabel(message), BorderLayout.WEST);
651       progressPanel.add(progressBar, BorderLayout.CENTER);
652
653       layout.setRows(layout.getRows() + 1);
654       statusPanel.add(progressPanel);
655
656       progressBars.put(lId, progressPanel);
657     }
658     // update GUI
659     // setMenusForViewport();
660     validate();
661   }
662
663   @Override
664   public void registerHandler(final long id,
665           final IProgressIndicatorHandler handler)
666   {
667     if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
668     {
669       throw new Error(
670               "call setProgressBar before registering the progress bar's handler.");
671     }
672     progressBarHandlers.put(new Long(id), handler);
673     final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
674     if (handler.canCancel())
675     {
676       JButton cancel = new JButton(
677               MessageManager.getString("action.cancel"));
678       final IProgressIndicator us = this;
679       cancel.addActionListener(new ActionListener()
680       {
681
682         @Override
683         public void actionPerformed(ActionEvent e)
684         {
685           handler.cancelActivity(id);
686           us.setProgressBar(
687                   "Cancelled "
688                           + ((JLabel) progressPanel.getComponent(0))
689                                   .getText(), id);
690         }
691       });
692       progressPanel.add(cancel, BorderLayout.EAST);
693     }
694   }
695
696   /**
697    * 
698    * @return true if any progress bars are still active
699    */
700   @Override
701   public boolean operationInProgress()
702   {
703     if (progressBars != null && progressBars.size() > 0)
704     {
705       return true;
706     }
707     return false;
708   }
709
710   @Override
711   protected void resetButton_actionPerformed(ActionEvent e)
712   {
713     int t = top;
714     top = 0; // ugly - prevents dimensionChanged events from being processed
715     xCombobox.setSelectedIndex(0);
716     yCombobox.setSelectedIndex(1);
717     top = t;
718     zCombobox.setSelectedIndex(2);
719   }
720 }