JAL-1517 fix copyright for 2.8.2
[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                       "The sequences must be aligned before calculating PCA.\n"
101                               + "Try using the Pad function in the edit menu,\n"
102                               + "or one of the multiple sequence alignment web services.",
103                       "Sequences not aligned", JOptionPane.WARNING_MESSAGE);
104
105       return;
106     }
107     pcaModel = new PCAModel(seqstrings, seqs, nucleotide);
108     PaintRefresher.Register(this, av.getSequenceSetId());
109
110     rc = new RotatableCanvas(ap);
111     this.getContentPane().add(rc, BorderLayout.CENTER);
112     Thread worker = new Thread(this);
113     worker.start();
114   }
115   @Override
116   protected void scoreMatrix_menuSelected()
117   {
118     scoreMatrixMenu.removeAll();
119     for (final String sm:ResidueProperties.scoreMatrices.keySet())
120     {
121       if (ResidueProperties.getScoreMatrix(sm) != null)
122       {
123         // create an entry for this score matrix for use in PCA
124         JCheckBoxMenuItem jm = new JCheckBoxMenuItem();
125         jm.setText(MessageManager
126                 .getStringOrReturn("label.score_model", sm));
127         jm.setSelected(pcaModel.getScore_matrix().equals(sm));
128         if ((ResidueProperties.scoreMatrices.get(sm).isDNA() && ResidueProperties.scoreMatrices
129                 .get(sm).isProtein())
130                 || pcaModel.isNucleotide() == ResidueProperties.scoreMatrices
131                         .get(sm).isDNA())
132         {
133           final PCAPanel us = this;
134           jm.addActionListener(new ActionListener()
135           {
136             @Override
137             public void actionPerformed(ActionEvent e)
138             {
139               if (!pcaModel.getScore_matrix().equals((String) sm))
140               {
141                 pcaModel.setScore_matrix((String) sm);
142                 Thread worker = new Thread(us);
143                 worker.start();
144               }
145             }
146           });
147           scoreMatrixMenu.add(jm);
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.getString("label.principal_component_analysis"), 475,
208               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, MessageManager.getString("label.pca_details"), 500, 500);
306     } catch (OutOfMemoryError oom)
307     {
308       new OOMWarning("opening PCA details", oom);
309       cap.dispose();
310     }
311   }
312
313   public void showLabels_actionPerformed(ActionEvent e)
314   {
315     rc.showLabels(showLabels.getState());
316   }
317
318   public void print_actionPerformed(ActionEvent e)
319   {
320     PCAPrinter printer = new PCAPrinter();
321     printer.start();
322   }
323
324   public void originalSeqData_actionPerformed(ActionEvent e)
325   {
326     // this was cut'n'pasted from the equivalent TreePanel method - we should
327     // make this an abstract function of all jalview analysis windows
328     if (pcaModel.getSeqtrings() == null)
329     {
330       jalview.bin.Cache.log
331               .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
332       return;
333     }
334     // decide if av alignment is sufficiently different to original data to
335     // warrant a new window to be created
336     // create new alignmnt window with hidden regions (unhiding hidden regions
337     // yields unaligned seqs)
338     // or create a selection box around columns in alignment view
339     // test Alignment(SeqCigar[])
340     char gc = '-';
341     try
342     {
343       // we try to get the associated view's gap character
344       // but this may fail if the view was closed...
345       gc = av.getGapCharacter();
346     } catch (Exception ex)
347     {
348     }
349     ;
350     Object[] alAndColsel = pcaModel.getSeqtrings()
351             .getAlignmentAndColumnSelection(gc);
352
353     if (alAndColsel != null && alAndColsel[0] != null)
354     {
355       // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
356
357       Alignment al = new Alignment((SequenceI[]) alAndColsel[0]);
358       Alignment dataset = (av != null && av.getAlignment() != null) ? av
359               .getAlignment().getDataset() : null;
360       if (dataset != null)
361       {
362         al.setDataset(dataset);
363       }
364
365       if (true)
366       {
367         // make a new frame!
368         AlignFrame af = new AlignFrame(al,
369                 (ColumnSelection) alAndColsel[1], AlignFrame.DEFAULT_WIDTH,
370                 AlignFrame.DEFAULT_HEIGHT);
371
372         // >>>This is a fix for the moment, until a better solution is
373         // found!!<<<
374         // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
375
376         // af.addSortByOrderMenuItem(ServiceName + " Ordering",
377         // msaorder);
378
379         Desktop.addInternalFrame(af, MessageManager.formatMessage("label.original_data_for_params", new String[]{this.title}),
380                 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
381       }
382     }
383     /*
384      * CutAndPasteTransfer cap = new CutAndPasteTransfer(); for (int i = 0; i <
385      * seqs.length; i++) { cap.appendText(new jalview.util.Format("%-" + 15 +
386      * "s").form( seqs[i].getName())); cap.appendText(" " + seqstrings[i] +
387      * "\n"); }
388      * 
389      * Desktop.addInternalFrame(cap, "Original Data", 400, 400);
390      */
391   }
392
393   class PCAPrinter extends Thread implements Printable
394   {
395     public void run()
396     {
397       PrinterJob printJob = PrinterJob.getPrinterJob();
398       PageFormat pf = printJob.pageDialog(printJob.defaultPage());
399
400       printJob.setPrintable(this, pf);
401
402       if (printJob.printDialog())
403       {
404         try
405         {
406           printJob.print();
407         } catch (Exception PrintException)
408         {
409           PrintException.printStackTrace();
410         }
411       }
412     }
413
414     public int print(Graphics pg, PageFormat pf, int pi)
415             throws PrinterException
416     {
417       pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
418
419       rc.drawBackground(pg, rc.bgColour);
420       rc.drawScene(pg);
421       if (rc.drawAxes == true)
422       {
423         rc.drawAxes(pg);
424       }
425
426       if (pi == 0)
427       {
428         return Printable.PAGE_EXISTS;
429       }
430       else
431       {
432         return Printable.NO_SUCH_PAGE;
433       }
434     }
435   }
436
437   /**
438    * DOCUMENT ME!
439    * 
440    * @param e
441    *          DOCUMENT ME!
442    */
443   public void eps_actionPerformed(ActionEvent e)
444   {
445     makePCAImage(jalview.util.ImageMaker.EPS);
446   }
447
448   /**
449    * DOCUMENT ME!
450    * 
451    * @param e
452    *          DOCUMENT ME!
453    */
454   public void png_actionPerformed(ActionEvent e)
455   {
456     makePCAImage(jalview.util.ImageMaker.PNG);
457   }
458
459   void makePCAImage(int type)
460   {
461     int width = rc.getWidth();
462     int height = rc.getHeight();
463
464     jalview.util.ImageMaker im;
465
466     if (type == jalview.util.ImageMaker.PNG)
467     {
468       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
469               "Make PNG image from PCA", width, height, null, null);
470     }
471     else
472     {
473       im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
474               "Make EPS file from PCA", width, height, null,
475               this.getTitle());
476     }
477
478     if (im.getGraphics() != null)
479     {
480       rc.drawBackground(im.getGraphics(), Color.black);
481       rc.drawScene(im.getGraphics());
482       if (rc.drawAxes == true)
483       {
484         rc.drawAxes(im.getGraphics());
485       }
486       im.writeImage();
487     }
488   }
489
490   
491   public void viewMenu_menuSelected()
492   {
493     buildAssociatedViewMenu();
494   }
495
496   void buildAssociatedViewMenu()
497   {
498     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
499             .getSequenceSetId());
500     if (aps.length == 1 && rc.av == aps[0].av)
501     {
502       associateViewsMenu.setVisible(false);
503       return;
504     }
505
506     associateViewsMenu.setVisible(true);
507
508     if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
509     {
510       viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
511     }
512
513     associateViewsMenu.removeAll();
514
515     JRadioButtonMenuItem item;
516     ButtonGroup buttonGroup = new ButtonGroup();
517     int i, iSize = aps.length;
518     final PCAPanel thisPCAPanel = this;
519     for (i = 0; i < iSize; i++)
520     {
521       final AlignmentPanel ap = aps[i];
522       item = new JRadioButtonMenuItem(ap.av.viewName, ap.av == rc.av);
523       buttonGroup.add(item);
524       item.addActionListener(new ActionListener()
525       {
526         public void actionPerformed(ActionEvent evt)
527         {
528           rc.applyToAllViews = false;
529           rc.av = ap.av;
530           rc.ap = ap;
531           PaintRefresher.Register(thisPCAPanel, ap.av.getSequenceSetId());
532         }
533       });
534
535       associateViewsMenu.add(item);
536     }
537
538     final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem("All Views");
539
540     buttonGroup.add(itemf);
541
542     itemf.setSelected(rc.applyToAllViews);
543     itemf.addActionListener(new ActionListener()
544     {
545       public void actionPerformed(ActionEvent evt)
546       {
547         rc.applyToAllViews = itemf.isSelected();
548       }
549     });
550     associateViewsMenu.add(itemf);
551
552   }
553
554   /*
555    * (non-Javadoc)
556    * 
557    * @see
558    * jalview.jbgui.GPCAPanel#outputPoints_actionPerformed(java.awt.event.ActionEvent
559    * )
560    */
561   protected void outputPoints_actionPerformed(ActionEvent e)
562   {
563     CutAndPasteTransfer cap = new CutAndPasteTransfer();
564     try
565     {
566       cap.setText(pcaModel.getPointsasCsv(false,
567               xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
568               zCombobox.getSelectedIndex()));
569       Desktop.addInternalFrame(cap, MessageManager.formatMessage("label.points_for_params", new String[]{this.getTitle()}), 500, 500);
570     } catch (OutOfMemoryError oom)
571     {
572       new OOMWarning("exporting PCA points", oom);
573       cap.dispose();
574     }
575   }
576
577   /*
578    * (non-Javadoc)
579    * 
580    * @see
581    * jalview.jbgui.GPCAPanel#outputProjPoints_actionPerformed(java.awt.event
582    * .ActionEvent)
583    */
584   protected void outputProjPoints_actionPerformed(ActionEvent e)
585   {
586     CutAndPasteTransfer cap = new CutAndPasteTransfer();
587     try
588     {
589       cap.setText(pcaModel.getPointsasCsv(true,
590               xCombobox.getSelectedIndex(), yCombobox.getSelectedIndex(),
591               zCombobox.getSelectedIndex()));
592       Desktop.addInternalFrame(cap, MessageManager.formatMessage("label.transformed_points_for_params", new String[]{this.getTitle()}),
593               500, 500);
594     } catch (OutOfMemoryError oom)
595     {
596       new OOMWarning("exporting transformed PCA points", oom);
597       cap.dispose();
598     }
599   }
600
601   // methods for implementing IProgressIndicator
602   // need to refactor to a reusable stub class
603   Hashtable progressBars, progressBarHandlers;
604
605   /*
606    * (non-Javadoc)
607    * 
608    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
609    */
610   @Override
611   public void setProgressBar(String message, long id)
612   {
613     if (progressBars == null)
614     {
615       progressBars = new Hashtable();
616       progressBarHandlers = new Hashtable();
617     }
618
619     JPanel progressPanel;
620     Long lId = new Long(id);
621     GridLayout layout = (GridLayout) statusPanel.getLayout();
622     if (progressBars.get(lId) != null)
623     {
624       progressPanel = (JPanel) progressBars.get(new Long(id));
625       statusPanel.remove(progressPanel);
626       progressBars.remove(lId);
627       progressPanel = null;
628       if (message != null)
629       {
630         statusBar.setText(message);
631       }
632       if (progressBarHandlers.contains(lId))
633       {
634         progressBarHandlers.remove(lId);
635       }
636       layout.setRows(layout.getRows() - 1);
637     }
638     else
639     {
640       progressPanel = new JPanel(new BorderLayout(10, 5));
641
642       JProgressBar progressBar = new JProgressBar();
643       progressBar.setIndeterminate(true);
644
645       progressPanel.add(new JLabel(message), BorderLayout.WEST);
646       progressPanel.add(progressBar, BorderLayout.CENTER);
647
648       layout.setRows(layout.getRows() + 1);
649       statusPanel.add(progressPanel);
650
651       progressBars.put(lId, progressPanel);
652     }
653     // update GUI
654     // setMenusForViewport();
655     validate();
656   }
657
658   @Override
659   public void registerHandler(final long id,
660           final IProgressIndicatorHandler handler)
661   {
662     if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
663     {
664       throw new Error(
665               "call setProgressBar before registering the progress bar's handler.");
666     }
667     progressBarHandlers.put(new Long(id), handler);
668     final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
669     if (handler.canCancel())
670     {
671       JButton cancel = new JButton(MessageManager.getString("action.cancel"));
672       final IProgressIndicator us = this;
673       cancel.addActionListener(new ActionListener()
674       {
675
676         @Override
677         public void actionPerformed(ActionEvent e)
678         {
679           handler.cancelActivity(id);
680           us.setProgressBar(
681                   "Cancelled "
682                           + ((JLabel) progressPanel.getComponent(0))
683                                   .getText(), id);
684         }
685       });
686       progressPanel.add(cancel, BorderLayout.EAST);
687     }
688   }
689
690   /**
691    * 
692    * @return true if any progress bars are still active
693    */
694   @Override
695   public boolean operationInProgress()
696   {
697     if (progressBars != null && progressBars.size() > 0)
698     {
699       return true;
700     }
701     return false;
702   }
703
704   @Override
705   protected void resetButton_actionPerformed(ActionEvent e)
706   {
707     int t = top;
708     top = 0; // ugly - prevents dimensionChanged events from being processed
709     xCombobox.setSelectedIndex(0);
710     yCombobox.setSelectedIndex(1);
711     top = t;
712     zCombobox.setSelectedIndex(2);
713   }
714 }