check for null viewport on dataset recovery
[jalview.git] / src / jalview / gui / PCAPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 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       JOptionPane.showInternalMessageDialog(Desktop.desktop,
171                                             "Out of memory calculating PCA!!"
172                                             +
173                                             "\nSee help files for increasing Java Virtual Machine memory."
174                                             , "Out of memory",
175                                             JOptionPane.WARNING_MESSAGE);
176       System.out.println("PCAPanel: " + er);
177       System.gc();
178
179     }
180
181   }
182
183   /**
184    * DOCUMENT ME!
185    */
186   void doDimensionChange()
187   {
188     if (top == 0)
189     {
190       return;
191     }
192
193     int dim1 = top - xCombobox.getSelectedIndex();
194     int dim2 = top - yCombobox.getSelectedIndex();
195     int dim3 = top - zCombobox.getSelectedIndex();
196
197     float[][] scores = pca.getComponents(dim1, dim2, dim3, 100);
198
199     for (int i = 0; i < pca.getM().rows; i++)
200     {
201       ( (SequencePoint) rc.points.elementAt(i)).coord = scores[i];
202     }
203
204     rc.img = null;
205     rc.rotmat.setIdentity();
206     rc.initAxes();
207     rc.paint(rc.getGraphics());
208   }
209
210   /**
211    * DOCUMENT ME!
212    *
213    * @param e DOCUMENT ME!
214    */
215   protected void xCombobox_actionPerformed(ActionEvent e)
216   {
217     doDimensionChange();
218   }
219
220   /**
221    * DOCUMENT ME!
222    *
223    * @param e DOCUMENT ME!
224    */
225   protected void yCombobox_actionPerformed(ActionEvent e)
226   {
227     doDimensionChange();
228   }
229
230   /**
231    * DOCUMENT ME!
232    *
233    * @param e DOCUMENT ME!
234    */
235   protected void zCombobox_actionPerformed(ActionEvent e)
236   {
237     doDimensionChange();
238   }
239
240   public void outputValues_actionPerformed(ActionEvent e)
241   {
242     CutAndPasteTransfer cap = new CutAndPasteTransfer();
243     Desktop.addInternalFrame(cap, "PCA details", 500,
244                              500);
245
246     cap.setText(pca.getDetails());
247   }
248
249   public void showLabels_actionPerformed(ActionEvent e)
250   {
251     rc.showLabels(showLabels.getState());
252   }
253
254   public void print_actionPerformed(ActionEvent e)
255   {
256     PCAPrinter printer = new PCAPrinter();
257     printer.start();
258   }
259
260   public void originalSeqData_actionPerformed(ActionEvent e)
261   {
262     // this was cut'n'pasted from the equivalent TreePanel method - we should make this an abstract function of all jalview analysis windows
263     if (seqstrings == null)
264     {
265       jalview.bin.Cache.log.info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
266       return;
267     }
268     // decide if av alignment is sufficiently different to original data to warrant a new window to be created
269     // create new alignmnt window with hidden regions (unhiding hidden regions yields unaligned seqs)
270     // or create a selection box around columns in alignment view
271     // test Alignment(SeqCigar[])
272     char gc = '-';
273     try {
274       // we try to get the associated view's gap character
275       // but this may fail if the view was closed...
276       gc = av.
277       getGapCharacter();
278     } catch (Exception ex) {};
279     Object[] alAndColsel = seqstrings.getAlignmentAndColumnSelection(gc);
280
281     if (alAndColsel != null && alAndColsel[0] != null)
282     {
283       // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
284
285       Alignment al = new Alignment( (SequenceI[]) alAndColsel[0]);
286       Alignment dataset = (av!=null && av.getAlignment()!=null) ? av.getAlignment().getDataset() : null;
287       if (dataset != null)
288       {
289         al.setDataset(dataset);
290       }
291
292       if (true)
293       {
294         // make a new frame!
295         AlignFrame af = new AlignFrame(al, (ColumnSelection) alAndColsel[1],
296                                        AlignFrame.DEFAULT_WIDTH,
297                                        AlignFrame.DEFAULT_HEIGHT
298             );
299
300         //>>>This is a fix for the moment, until a better solution is found!!<<<
301         // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
302
303         //           af.addSortByOrderMenuItem(ServiceName + " Ordering",
304         //                                     msaorder);
305
306         Desktop.addInternalFrame(af, "Original Data for " + this.title,
307                                  AlignFrame.DEFAULT_WIDTH,
308                                  AlignFrame.DEFAULT_HEIGHT);
309       }
310     }
311     /*      CutAndPasteTransfer cap = new CutAndPasteTransfer();
312            for (int i = 0; i < seqs.length; i++)
313            {
314              cap.appendText(new jalview.util.Format("%-" + 15 + "s").form(
315       seqs[i].getName()));
316              cap.appendText(" " + seqstrings[i] + "\n");
317
318            }
319
320            Desktop.addInternalFrame(cap, "Original Data",
321                400, 400);
322      */
323   }
324
325   class PCAPrinter
326       extends Thread implements Printable
327   {
328     public void run()
329     {
330       PrinterJob printJob = PrinterJob.getPrinterJob();
331       PageFormat pf = printJob.pageDialog(printJob.defaultPage());
332
333       printJob.setPrintable(this, pf);
334
335       if (printJob.printDialog())
336       {
337         try
338         {
339           printJob.print();
340         }
341         catch (Exception PrintException)
342         {
343           PrintException.printStackTrace();
344         }
345       }
346     }
347
348     public int print(Graphics pg, PageFormat pf, int pi)
349         throws PrinterException
350     {
351       pg.translate( (int) pf.getImageableX(), (int) pf.getImageableY());
352
353       rc.drawBackground(pg, rc.bgColour);
354       rc.drawScene(pg);
355       if (rc.drawAxes == true)
356       {
357         rc.drawAxes(pg);
358       }
359
360       if (pi == 0)
361       {
362         return Printable.PAGE_EXISTS;
363       }
364       else
365       {
366         return Printable.NO_SUCH_PAGE;
367       }
368     }
369   }
370
371   /**
372    * DOCUMENT ME!
373    *
374    * @param e DOCUMENT ME!
375    */
376   public void eps_actionPerformed(ActionEvent e)
377   {
378     makePCAImage(jalview.util.ImageMaker.EPS);
379   }
380
381   /**
382    * DOCUMENT ME!
383    *
384    * @param e DOCUMENT ME!
385    */
386   public void png_actionPerformed(ActionEvent e)
387   {
388     makePCAImage(jalview.util.ImageMaker.PNG);
389   }
390
391   void makePCAImage(int type)
392   {
393     int width = rc.getWidth();
394     int height = rc.getHeight();
395
396     jalview.util.ImageMaker im;
397
398     if (type == jalview.util.ImageMaker.PNG)
399     {
400       im = new jalview.util.ImageMaker(this,
401                                        jalview.util.ImageMaker.PNG,
402                                        "Make PNG image from PCA",
403                                        width, height,
404                                        null, null);
405     }
406     else
407     {
408       im = new jalview.util.ImageMaker(this,
409                                        jalview.util.ImageMaker.EPS,
410                                        "Make EPS file from PCA",
411                                        width, height,
412                                        null, this.getTitle());
413     }
414
415     if (im.getGraphics() != null)
416     {
417       rc.drawBackground(im.getGraphics(), Color.black);
418       rc.drawScene(im.getGraphics());
419       if (rc.drawAxes == true)
420       {
421         rc.drawAxes(im.getGraphics());
422       }
423       im.writeImage();
424     }
425   }
426
427   public void viewMenu_menuSelected()
428   {
429     buildAssociatedViewMenu();
430   }
431
432   void buildAssociatedViewMenu()
433   {
434     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av.
435         getSequenceSetId());
436     if (aps.length == 1 && rc.av == aps[0].av)
437     {
438       associateViewsMenu.setVisible(false);
439       return;
440     }
441
442     associateViewsMenu.setVisible(true);
443
444     if ( (viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
445     {
446       viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
447     }
448
449     associateViewsMenu.removeAll();
450
451     JRadioButtonMenuItem item;
452     ButtonGroup buttonGroup = new ButtonGroup();
453     int i, iSize = aps.length;
454     final PCAPanel thisPCAPanel = this;
455     for (i = 0; i < iSize; i++)
456     {
457       final AlignmentPanel ap = aps[i];
458       item = new JRadioButtonMenuItem(ap.av.viewName, ap.av == rc.av);
459       buttonGroup.add(item);
460       item.addActionListener(new ActionListener()
461       {
462         public void actionPerformed(ActionEvent evt)
463         {
464           rc.applyToAllViews = false;
465           rc.av = ap.av;
466           rc.ap = ap;
467           PaintRefresher.Register(thisPCAPanel, ap.av.getSequenceSetId());
468         }
469       });
470
471       associateViewsMenu.add(item);
472     }
473
474     final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem("All Views");
475
476     buttonGroup.add(itemf);
477
478     itemf.setSelected(rc.applyToAllViews);
479     itemf.addActionListener(new ActionListener()
480     {
481       public void actionPerformed(ActionEvent evt)
482       {
483         rc.applyToAllViews = itemf.isSelected();
484       }
485     });
486     associateViewsMenu.add(itemf);
487
488   }
489
490 }