use OOMwarning to warn user when out of Memory occurs
[jalview.git] / src / jalview / gui / PCAPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3  * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import java.util.*;
22
23 import java.awt.*;
24 import java.awt.event.*;
25 import java.awt.print.*;
26 import javax.swing.*;
27
28 import jalview.analysis.*;
29 import jalview.datamodel.*;
30 import jalview.jbgui.*;
31
32 /**
33  * DOCUMENT ME!
34  *
35  * @author $author$
36  * @version $Revision$
37  */
38 public class PCAPanel
39     extends GPCAPanel implements Runnable
40 {
41   PCA pca;
42   int top;
43   RotatableCanvas rc;
44   AlignmentPanel ap;
45   AlignViewport av;
46   AlignmentView seqstrings;
47   SequenceI[] seqs;
48
49   /**
50    * Creates a new PCAPanel object.
51    *
52    * @param av DOCUMENT ME!
53    * @param s DOCUMENT ME!
54    */
55   public PCAPanel(AlignmentPanel ap)
56   {
57     this.av = ap.av;
58     this.ap = ap;
59
60     boolean sameLength = true;
61
62     seqstrings = av.getAlignmentView(av.getSelectionGroup() != null);
63     if (av.getSelectionGroup() == null)
64     {
65       seqs = av.alignment.getSequencesArray();
66     }
67     else
68     {
69       seqs = av.getSelectionGroup().getSequencesInOrder(av.alignment);
70     }
71     SeqCigar sq[] = seqstrings.getSequences();
72     int length = sq[0].getWidth();
73
74     for (int i = 0; i < seqs.length; i++)
75     {
76       if (sq[i].getWidth() != length)
77       {
78         sameLength = false;
79         break;
80       }
81     }
82
83     if (!sameLength)
84     {
85       JOptionPane.showMessageDialog(Desktop.desktop,
86                                     "The sequences must be aligned before calculating PCA.\n" +
87                                     "Try using the Pad function in the edit menu,\n" +
88                                     "or one of the multiple sequence alignment web services.",
89                                     "Sequences not aligned",
90                                     JOptionPane.WARNING_MESSAGE);
91
92       return;
93     }
94
95     Desktop.addInternalFrame(this, "Principal component analysis",
96                              400, 400);
97
98     PaintRefresher.Register(this, av.getSequenceSetId());
99
100     rc = new RotatableCanvas(ap);
101     this.getContentPane().add(rc, BorderLayout.CENTER);
102     Thread worker = new Thread(this);
103     worker.start();
104   }
105
106   public void bgcolour_actionPerformed(ActionEvent e)
107   {
108     Color col = JColorChooser.showDialog(this, "Select Background Colour",
109                                          rc.bgColour);
110
111     if (col != null)
112     {
113       rc.bgColour = col;
114     }
115     rc.repaint();
116   }
117
118   /**
119    * DOCUMENT ME!
120    */
121   public void run()
122   {
123     try
124     {
125       pca = new PCA(seqstrings.getSequenceStrings(' '));
126       pca.run();
127
128       // Now find the component coordinates
129       int ii = 0;
130
131       while ( (ii < seqs.length) && (seqs[ii] != null))
132       {
133         ii++;
134       }
135
136       double[][] comps = new double[ii][ii];
137
138       for (int i = 0; i < ii; i++)
139       {
140         if (pca.getEigenvalue(i) > 1e-4)
141         {
142           comps[i] = pca.component(i);
143         }
144       }
145
146       //////////////////
147       xCombobox.setSelectedIndex(0);
148       yCombobox.setSelectedIndex(1);
149       zCombobox.setSelectedIndex(2);
150
151       top = pca.getM().rows - 1;
152
153       Vector points = new Vector();
154       float[][] scores = pca.getComponents(top - 1, top - 2, top - 3, 100);
155
156       for (int i = 0; i < pca.getM().rows; i++)
157       {
158         SequencePoint sp = new SequencePoint(seqs[i], scores[i]);
159         points.addElement(sp);
160       }
161
162       rc.setPoints(points, pca.getM().rows);
163       rc.repaint();
164
165       addKeyListener(rc);
166
167     }
168     catch (OutOfMemoryError er)
169     {
170       new OOMWarning("calculating PCA", er);
171
172     }
173
174   }
175
176   /**
177    * DOCUMENT ME!
178    */
179   void doDimensionChange()
180   {
181     if (top == 0)
182     {
183       return;
184     }
185
186     int dim1 = top - xCombobox.getSelectedIndex();
187     int dim2 = top - yCombobox.getSelectedIndex();
188     int dim3 = top - zCombobox.getSelectedIndex();
189
190     float[][] scores = pca.getComponents(dim1, dim2, dim3, 100);
191
192     for (int i = 0; i < pca.getM().rows; i++)
193     {
194       ( (SequencePoint) rc.points.elementAt(i)).coord = scores[i];
195     }
196
197     rc.img = null;
198     rc.rotmat.setIdentity();
199     rc.initAxes();
200     rc.paint(rc.getGraphics());
201   }
202
203   /**
204    * DOCUMENT ME!
205    *
206    * @param e DOCUMENT ME!
207    */
208   protected void xCombobox_actionPerformed(ActionEvent e)
209   {
210     doDimensionChange();
211   }
212
213   /**
214    * DOCUMENT ME!
215    *
216    * @param e DOCUMENT ME!
217    */
218   protected void yCombobox_actionPerformed(ActionEvent e)
219   {
220     doDimensionChange();
221   }
222
223   /**
224    * DOCUMENT ME!
225    *
226    * @param e DOCUMENT ME!
227    */
228   protected void zCombobox_actionPerformed(ActionEvent e)
229   {
230     doDimensionChange();
231   }
232
233   public void outputValues_actionPerformed(ActionEvent e)
234   {
235     CutAndPasteTransfer cap = new CutAndPasteTransfer();
236     Desktop.addInternalFrame(cap, "PCA details", 500,
237                              500);
238
239     cap.setText(pca.getDetails());
240   }
241
242   public void showLabels_actionPerformed(ActionEvent e)
243   {
244     rc.showLabels(showLabels.getState());
245   }
246
247   public void print_actionPerformed(ActionEvent e)
248   {
249     PCAPrinter printer = new PCAPrinter();
250     printer.start();
251   }
252
253   public void originalSeqData_actionPerformed(ActionEvent e)
254   {
255     // this was cut'n'pasted from the equivalent TreePanel method - we should make this an abstract function of all jalview analysis windows
256     if (seqstrings == null)
257     {
258       jalview.bin.Cache.log.info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
259       return;
260     }
261     // decide if av alignment is sufficiently different to original data to warrant a new window to be created
262     // create new alignmnt window with hidden regions (unhiding hidden regions yields unaligned seqs)
263     // or create a selection box around columns in alignment view
264     // test Alignment(SeqCigar[])
265     char gc = '-';
266     try {
267       // we try to get the associated view's gap character
268       // but this may fail if the view was closed...
269       gc = av.
270       getGapCharacter();
271     } catch (Exception ex) {};
272     Object[] alAndColsel = seqstrings.getAlignmentAndColumnSelection(gc);
273
274     if (alAndColsel != null && alAndColsel[0] != null)
275     {
276       // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
277
278       Alignment al = new Alignment( (SequenceI[]) alAndColsel[0]);
279       Alignment dataset = (av!=null && av.getAlignment()!=null) ? av.getAlignment().getDataset() : null;
280       if (dataset != null)
281       {
282         al.setDataset(dataset);
283       }
284
285       if (true)
286       {
287         // make a new frame!
288         AlignFrame af = new AlignFrame(al, (ColumnSelection) alAndColsel[1],
289                                        AlignFrame.DEFAULT_WIDTH,
290                                        AlignFrame.DEFAULT_HEIGHT
291             );
292
293         //>>>This is a fix for the moment, until a better solution is found!!<<<
294         // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
295
296         //           af.addSortByOrderMenuItem(ServiceName + " Ordering",
297         //                                     msaorder);
298
299         Desktop.addInternalFrame(af, "Original Data for " + this.title,
300                                  AlignFrame.DEFAULT_WIDTH,
301                                  AlignFrame.DEFAULT_HEIGHT);
302       }
303     }
304     /*      CutAndPasteTransfer cap = new CutAndPasteTransfer();
305            for (int i = 0; i < seqs.length; i++)
306            {
307              cap.appendText(new jalview.util.Format("%-" + 15 + "s").form(
308       seqs[i].getName()));
309              cap.appendText(" " + seqstrings[i] + "\n");
310
311            }
312
313            Desktop.addInternalFrame(cap, "Original Data",
314                400, 400);
315      */
316   }
317
318   class PCAPrinter
319       extends Thread implements Printable
320   {
321     public void run()
322     {
323       PrinterJob printJob = PrinterJob.getPrinterJob();
324       PageFormat pf = printJob.pageDialog(printJob.defaultPage());
325
326       printJob.setPrintable(this, pf);
327
328       if (printJob.printDialog())
329       {
330         try
331         {
332           printJob.print();
333         }
334         catch (Exception PrintException)
335         {
336           PrintException.printStackTrace();
337         }
338       }
339     }
340
341     public int print(Graphics pg, PageFormat pf, int pi)
342         throws PrinterException
343     {
344       pg.translate( (int) pf.getImageableX(), (int) pf.getImageableY());
345
346       rc.drawBackground(pg, rc.bgColour);
347       rc.drawScene(pg);
348       if (rc.drawAxes == true)
349       {
350         rc.drawAxes(pg);
351       }
352
353       if (pi == 0)
354       {
355         return Printable.PAGE_EXISTS;
356       }
357       else
358       {
359         return Printable.NO_SUCH_PAGE;
360       }
361     }
362   }
363
364   /**
365    * DOCUMENT ME!
366    *
367    * @param e DOCUMENT ME!
368    */
369   public void eps_actionPerformed(ActionEvent e)
370   {
371     makePCAImage(jalview.util.ImageMaker.EPS);
372   }
373
374   /**
375    * DOCUMENT ME!
376    *
377    * @param e DOCUMENT ME!
378    */
379   public void png_actionPerformed(ActionEvent e)
380   {
381     makePCAImage(jalview.util.ImageMaker.PNG);
382   }
383
384   void makePCAImage(int type)
385   {
386     int width = rc.getWidth();
387     int height = rc.getHeight();
388
389     jalview.util.ImageMaker im;
390
391     if (type == jalview.util.ImageMaker.PNG)
392     {
393       im = new jalview.util.ImageMaker(this,
394                                        jalview.util.ImageMaker.PNG,
395                                        "Make PNG image from PCA",
396                                        width, height,
397                                        null, null);
398     }
399     else
400     {
401       im = new jalview.util.ImageMaker(this,
402                                        jalview.util.ImageMaker.EPS,
403                                        "Make EPS file from PCA",
404                                        width, height,
405                                        null, this.getTitle());
406     }
407
408     if (im.getGraphics() != null)
409     {
410       rc.drawBackground(im.getGraphics(), Color.black);
411       rc.drawScene(im.getGraphics());
412       if (rc.drawAxes == true)
413       {
414         rc.drawAxes(im.getGraphics());
415       }
416       im.writeImage();
417     }
418   }
419
420   public void viewMenu_menuSelected()
421   {
422     buildAssociatedViewMenu();
423   }
424
425   void buildAssociatedViewMenu()
426   {
427     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av.
428         getSequenceSetId());
429     if (aps.length == 1 && rc.av == aps[0].av)
430     {
431       associateViewsMenu.setVisible(false);
432       return;
433     }
434
435     associateViewsMenu.setVisible(true);
436
437     if ( (viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
438     {
439       viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
440     }
441
442     associateViewsMenu.removeAll();
443
444     JRadioButtonMenuItem item;
445     ButtonGroup buttonGroup = new ButtonGroup();
446     int i, iSize = aps.length;
447     final PCAPanel thisPCAPanel = this;
448     for (i = 0; i < iSize; i++)
449     {
450       final AlignmentPanel ap = aps[i];
451       item = new JRadioButtonMenuItem(ap.av.viewName, ap.av == rc.av);
452       buttonGroup.add(item);
453       item.addActionListener(new ActionListener()
454       {
455         public void actionPerformed(ActionEvent evt)
456         {
457           rc.applyToAllViews = false;
458           rc.av = ap.av;
459           rc.ap = ap;
460           PaintRefresher.Register(thisPCAPanel, ap.av.getSequenceSetId());
461         }
462       });
463
464       associateViewsMenu.add(item);
465     }
466
467     final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem("All Views");
468
469     buttonGroup.add(itemf);
470
471     itemf.setSelected(rc.applyToAllViews);
472     itemf.addActionListener(new ActionListener()
473     {
474       public void actionPerformed(ActionEvent evt)
475       {
476         rc.applyToAllViews = itemf.isSelected();
477       }
478     });
479     associateViewsMenu.add(itemf);
480
481   }
482
483 }