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