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