Debian Codegraph @

src/dr/app/treespace/TreeSpaceFrame.java

raw symbols SCIP
1 /*
2 * TreeSpaceFrame.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.app.treespace;
27
28 import dr.app.gui.DeleteActionResponder;
29 import dr.app.gui.SelectAllActionResponder;
30 import dr.app.treespace.inputpanel.InputPanel;
31 import dr.app.util.Utils;
32 import dr.evolution.io.Importer;
33 import dr.evolution.io.TreeImporter;
34 import dr.evolution.tree.Tree;
35 import jam.framework.DocumentFrame;
36 import jam.framework.Exportable;
37 import jam.util.IconUtils;
38 import jebl.evolution.io.ImportException;
39 import jebl.evolution.io.NexusImporter;
40 import jebl.evolution.trees.RootedTree;
41
42 import javax.swing.*;
43 import javax.swing.event.ChangeEvent;
44 import javax.swing.event.ChangeListener;
45 import javax.swing.filechooser.FileNameExtensionFilter;
46 import javax.swing.plaf.BorderUIResource;
47 import java.awt.*;
48 import java.io.*;
49
50 /**
51 * @author Andrew Rambaut
52 * @version $Id$
53 */
54 public class TreeSpaceFrame extends DocumentFrame {
55 private static final long serialVersionUID = 2114148696789612509L;
56
57 private final TreeSpaceDocument document = new TreeSpaceDocument();
58
59 private final JTabbedPane tabbedPane = new JTabbedPane();
60 private final JLabel statusLabel = new JLabel("No data loaded");
61 private final InputPanel inputPanel;
62
63 private final CladePanel cladePanel;
64 private final CladePlotter cladePlotter;
65
66 private final TreePanel treePanel;
67
68 private final TreePlotter treePlotter;
69 private final JPanel plotterPanel;
70
71 private JFileChooser importChooser; // make JFileChooser chooser remember previous path
72 private JFileChooser exportChooser; // make JFileChooser chooser remember previous path
73
74 private final Icon gearIcon = IconUtils.getIcon(this.getClass(), "images/gear.png");
75
76 private CladeSystem cladeSystem = new CladeSystem();
77
78 public TreeSpaceFrame(String title) {
79 super();
80
81 setTitle(title);
82
83 // Prevent the application to close in requestClose()
84 // after a user cancel or a failure in beast file generation
85 setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
86
87 // getOpenAction().setEnabled(false);
88 // getSaveAction().setEnabled(false);
89
90 getFindAction().setEnabled(false);
91
92 getZoomWindowAction().setEnabled(false);
93
94 inputPanel = new InputPanel(this, document, getImportAction());
95 cladePanel = new CladePanel(this, document);
96 treePanel = new TreePanel(this, document);
97 cladePlotter = new CladePlotter(cladeSystem);
98
99 treePlotter = new TreePlotter();
100 plotterPanel = new JPanel(new BorderLayout());
101 plotterPanel.add(new JScrollPane(treePlotter), BorderLayout.CENTER);
102
103 tabbedPane.addChangeListener(new ChangeListener() {
104 public void stateChanged(final ChangeEvent e) {
105 tabbedPaneChanged();
106 }
107 });
108
109 document.addListener(new TreeSpaceDocument.Listener() {
110 public void dataChanged() {
111 setDirty();
112 }
113
114 public void settingsChanged() {
115 setDirty();
116 }
117 });
118 }
119
120 public void initializeComponents() {
121
122 tabbedPane.addTab("Input", inputPanel);
123 tabbedPane.addTab("Trees", treePanel);
124 tabbedPane.addTab("Clades", cladePanel);
125 tabbedPane.addTab("Graph", cladePlotter);
126 tabbedPane.addTab("Plot", plotterPanel);
127
128 JPanel panel = new JPanel(new BorderLayout(6, 6));
129 panel.setBorder(new BorderUIResource.EmptyBorderUIResource(new java.awt.Insets(12, 12, 12, 12)));
130 panel.add(tabbedPane, BorderLayout.CENTER);
131 panel.setPreferredSize(new java.awt.Dimension(800, 600));
132
133 // getExportAction().setEnabled(false);
134 // JButton generateButton = new JButton(getExportAction());
135 // generateButton.putClientProperty("JButton.buttonType", "roundRect");
136
137 JPanel panel2 = new JPanel(new BorderLayout(6, 6));
138 panel2.add(statusLabel, BorderLayout.NORTH);
139 // panel2.add(generateButton, BorderLayout.EAST);
140
141 panel.add(panel2, BorderLayout.SOUTH);
142
143 getContentPane().setLayout(new java.awt.BorderLayout(0, 0));
144 getContentPane().add(panel, BorderLayout.CENTER);
145
146 // setAllOptions();
147
148 setSize(new java.awt.Dimension(1024, 768));
149 setMinimumSize(new java.awt.Dimension(800, 600));
150
151 // make JFileChooser chooser remember previous path
152 exportChooser = new JFileChooser(Utils.getCWD());
153 exportChooser.setDialogTitle("Generate File...");
154
155
156 importChooser = new JFileChooser(Utils.getCWD());
157
158 importChooser.setMultiSelectionEnabled(true);
159 importChooser.setFileFilter(new FileNameExtensionFilter(
160 "NEXUS (*.nex) & BEAST Tree (*.trees) Files", "nex", "nexus", "nx", "tree", "tre", "trees"));
161 importChooser.setDialogTitle("Import Data Files...");
162 }
163
164 public final void tabbedPaneChanged() {
165 if (tabbedPane.getSelectedComponent() instanceof DeleteActionResponder) {
166 getDeleteAction().setEnabled(
167 ((DeleteActionResponder)(tabbedPane.getSelectedComponent()))
168 .getDeleteAction()
169 .isEnabled()
170 );
171 }
172 }
173
174 public void doDelete() {
175 if (tabbedPane.getSelectedComponent() instanceof DeleteActionResponder) {
176 ((DeleteActionResponder)(tabbedPane.getSelectedComponent())).delete();
177 }
178 }
179
180 public void doSelectAll() {
181 if (tabbedPane.getSelectedComponent() instanceof SelectAllActionResponder) {
182 ((SelectAllActionResponder)(tabbedPane.getSelectedComponent())).selectAll();
183 }
184 }
185
186
187 public void setRemoveActionEnabled(final DeleteActionResponder responder, final boolean isEnabled) {
188 if (responder == tabbedPane.getSelectedComponent()) {
189 getDeleteAction().setEnabled(isEnabled);
190 }
191 }
192
193
194 public boolean requestClose() {
195 // if (isDirty()) {
196 // int option = JOptionPane.showConfirmDialog(this,
197 // "You have made changes but have not generated\n" +
198 // "an output file. Do you wish to generate\n" +
199 // "before closing this window?",
200 // "Unused changes",
201 // JOptionPane.YES_NO_CANCEL_OPTION,
202 // JOptionPane.WARNING_MESSAGE);
203 //
204 // if (option == JOptionPane.YES_OPTION) {
205 // return !doGenerate();
206 // } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.DEFAULT_OPTION) {
207 // return false;
208 // }
209 // return true;
210 // }
211 return true;
212 }
213
214 protected boolean readFromFile(File file) throws IOException {
215 return false;
216 }
217
218 public String getDefaultFileName() {
219 return "untitled";
220 }
221
222 protected boolean writeToFile(File file) throws IOException {
223 return false;
224 }
225
226 public final void doImport() {
227 int returnVal = importChooser.showOpenDialog(this);
228 if (returnVal == JFileChooser.APPROVE_OPTION) {
229 File[] files = importChooser.getSelectedFiles();
230 for (File file : files) {
231 if (file == null || file.getName().equals("")) {
232 JOptionPane.showMessageDialog(this, "Invalid file name",
233 "Invalid file name", JOptionPane.ERROR_MESSAGE);
234 } else {
235 try {
236 importDataFile(file);
237
238 setDirty();
239 // } catch (FileNotFoundException fnfe) {
240 // JOptionPane.showMessageDialog(this, "Unable to open file: File not found",
241 // "Unable to open file", JOptionPane.ERROR_MESSAGE);
242 } catch (IOException ioe) {
243 JOptionPane.showMessageDialog(this, "File I/O Error unable to read file: " + ioe.getMessage(),
244 "Unable to read file", JOptionPane.ERROR_MESSAGE);
245 return;
246
247 } catch (NexusImporter.MissingBlockException ex) {
248 JOptionPane.showMessageDialog(this, "TAXON, DATA or CHARACTERS block is missing in Nexus file: " + ex,
249 "Missing Block in Nexus File",
250 JOptionPane.ERROR_MESSAGE);
251
252 } catch (ImportException ime) {
253 JOptionPane.showMessageDialog(this, "Error parsing imported file: " + ime,
254 "Error reading file",
255 JOptionPane.ERROR_MESSAGE);
256 return;
257
258 // } catch (Exception ex) {
259 // JOptionPane.showMessageDialog(this, "Fatal exception: " + ex,
260 // "Error reading file",
261 // JOptionPane.ERROR_MESSAGE);
262 // return;
263 }
264 }
265 }
266
267 // setAllOptions();
268 }
269 }
270
271 public void importDataFile(File file) throws IOException, ImportException {
272 Reader reader = new FileReader(file);
273
274 BufferedReader bufferedReader = new BufferedReader(reader);
275 String line = bufferedReader.readLine();
276 while (line != null && line.length() == 0) {
277 line = bufferedReader.readLine();
278 }
279
280 if ((line != null && line.toUpperCase().contains("#NEXUS"))) {
281 int treeCount = 0;
282
283 do {
284 line = bufferedReader.readLine();
285 } while (line != null && !line.contains("("));
286
287 while (line != null) {
288 if (line.contains("(")) {
289 treeCount++;
290 if (treeCount > 1) {
291 break;
292 }
293 }
294 line = bufferedReader.readLine();
295 }
296
297 // is a NEXUS file
298 RootedTree tree = importFirstTree(file);
299 if (tree != null) {
300 if (treeCount > 1) {
301 InputFile inputFile = new InputFile(file, tree, -1);
302 document.addTreeFile(inputFile);
303
304 treePlotter.setTrees(loadTrees(inputFile));
305
306 inputFile.setTreeCount(treeCount);
307
308 document.fireDataChanged();
309 } else {
310 InputFile inputFile = new InputFile(file, tree);
311 document.addTreeFile(inputFile);
312
313 treePlotter.setTrees(loadTrees(inputFile));
314
315 inputFile.setTreeCount(treeCount);
316
317 document.fireDataChanged();
318 }
319 }
320 } else {
321 JOptionPane.showMessageDialog(this, "Error parsing imported file. This may not be a NEXUS file",
322 "Error reading file",
323 JOptionPane.ERROR_MESSAGE);
324 }
325 }
326
327 // nexus
328 private RootedTree importFirstTree(File file) throws IOException, ImportException {
329 RootedTree tree = null;
330
331 FileReader reader = new FileReader(file);
332
333 NexusImporter importer = new NexusImporter(reader);
334
335 tree = (RootedTree)importer.importNextTree();
336
337 return tree;
338 }
339
340 private TreeLineages loadTrees(InputFile inputFile) throws IOException {
341
342 PrintStream progressStream = System.out;
343
344 int totalTrees = 10000;
345 int totalTreesUsed = 0;
346
347 progressStream.println("Reading trees (bar assumes 10,000 trees)...");
348 progressStream.println("0 25 50 75 100");
349 progressStream.println("|--------------|--------------|--------------|--------------|");
350
351 int stepSize = totalTrees / 60;
352 if (stepSize < 1) stepSize = 1;
353
354 TreeLineages treeLineages = new TreeLineages();
355
356 FileReader fileReader = new FileReader(inputFile.getFile());
357 jebl.evolution.io.NexusImporter importer = new NexusImporter(fileReader);
358 try {
359 totalTrees = 0;
360 while (importer.hasTree()) {
361 RootedTree tree = (RootedTree)importer.importNextTree();
362
363 if (totalTrees >= inputFile.getBurnin()) {
364 treeLineages.addTree(tree);
365 totalTreesUsed += 1;
366 }
367
368 if (totalTrees > 0 && totalTrees % stepSize == 0) {
369 progressStream.print("*");
370 progressStream.flush();
371 }
372 totalTrees++;
373 }
374
375 } catch (ImportException e) {
376 System.err.println("Error Parsing Input Tree: " + e.getMessage());
377 return null;
378 }
379 fileReader.close();
380 progressStream.println();
381 progressStream.println();
382
383 if (totalTrees < 1) {
384 System.err.println("No trees");
385 return null;
386 }
387 if (totalTreesUsed <= 1) {
388 if (inputFile.getBurnin() > 0) {
389 System.err.println("No trees to use: burnin too high");
390 return null;
391 }
392 }
393
394 progressStream.println("Total trees read: " + totalTrees);
395 if (inputFile.getBurnin() > 0) {
396 progressStream.println("Ignoring first " + inputFile.getBurnin() + " trees.");
397 }
398
399 treeLineages.setupTrees();
400
401 return treeLineages;
402 }
403
404 private int processTrees1(InputFile inputFile) throws IOException {
405
406 PrintStream progressStream = System.out;
407
408 int totalTrees = 10000;
409 int totalTreesUsed = 0;
410
411 progressStream.println("Reading trees (bar assumes 10,000 trees)...");
412 progressStream.println("0 25 50 75 100");
413 progressStream.println("|--------------|--------------|--------------|--------------|");
414
415 int stepSize = totalTrees / 60;
416 if (stepSize < 1) stepSize = 1;
417
418 CladeSystem cladeSystem = document.getCladeSystem();
419
420 FileReader fileReader = new FileReader(inputFile.getFile());
421 TreeImporter importer = new dr.evolution.io.NexusImporter(fileReader);
422 try {
423 totalTrees = 0;
424 while (importer.hasTree()) {
425 Tree tree = importer.importNextTree();
426
427 if (totalTrees >= inputFile.getBurnin()) {
428 cladeSystem.add(tree, true);
429 totalTreesUsed += 1;
430 }
431
432 if (totalTrees > 0 && totalTrees % stepSize == 0) {
433 progressStream.print("*");
434 progressStream.flush();
435 }
436 totalTrees++;
437 }
438
439 } catch (Importer.ImportException e) {
440 System.err.println("Error Parsing Input Tree: " + e.getMessage());
441 return 0;
442 }
443 fileReader.close();
444 progressStream.println();
445 progressStream.println();
446
447 if (totalTrees < 1) {
448 System.err.println("No trees");
449 return 0;
450 }
451 if (totalTreesUsed <= 1) {
452 if (inputFile.getBurnin() > 0) {
453 System.err.println("No trees to use: burnin too high");
454 return 0;
455 }
456 }
457 cladeSystem.normalizeClades(totalTreesUsed);
458
459 progressStream.println("Total trees read: " + totalTrees);
460 if (inputFile.getBurnin() > 0) {
461 progressStream.println("Ignoring first " + inputFile.getBurnin() + " trees.");
462 }
463
464 int cladeCount = cladeSystem.getCladeMap().keySet().size();
465
466 progressStream.println("Total unique clades: " + cladeCount);
467 progressStream.println();
468
469 progressStream.println("Processing trees for correlated clades:");
470 fileReader = new FileReader(inputFile.getFile());
471 importer = new dr.evolution.io.NexusImporter(fileReader);
472 try {
473 totalTrees = 0;
474 while (importer.hasTree()) {
475 Tree tree = importer.importNextTree();
476
477 if (totalTrees >= inputFile.getBurnin()) {
478 cladeSystem.addCooccurances(tree);
479 }
480
481 if (totalTrees > 0 && totalTrees % stepSize == 0) {
482 progressStream.print("*");
483 progressStream.flush();
484 }
485 totalTrees++;
486 }
487
488 } catch (Importer.ImportException e) {
489 System.err.println("Error Parsing Input Tree: " + e.getMessage());
490 return 0;
491 }
492 fileReader.close();
493 progressStream.println();
494 progressStream.println();
495
496 double THRESHOLD = 0.05;
497
498 PrintWriter writer = new PrintWriter("clade_co-occurance.txt");
499
500 writer.println("source\tsize\ttarget\tco-occurence");
501 java.util.List<CladeSystem.Clade> allClades = cladeSystem.getClades();
502
503 for (CladeSystem.Clade clade1 : allClades) {
504 String name1;
505 int card1 = clade1.bits.cardinality();
506 if (card1 == 1) {
507 name1 = clade1.label;
508 } else {
509 name1 = "clade" + (clade1.index + 1);
510 }
511
512 if (clade1.parents != null) {
513 for (CladeSystem.Clade clade2 : clade1.parents.keySet()) {
514 String name2;
515 int card2 = clade2.bits.cardinality();
516 name2 = "clade" + (clade2.index+1);
517
518 double value = clade1.parents.get(clade2);
519 value /= totalTreesUsed;
520 if (value > THRESHOLD) {
521 if (card1 > card2) {
522 writer.println(name1 + "_" + card1 + "\t" + card1 + "\t" + name2 + "_" + card2 + "\t" + value);
523 } else {
524 writer.println(name2 + "_" + card2 + "\t" + card2 + "\t" + name1 + "_" + card1 + "\t" + value);
525 }
526 }
527 }
528 }
529 }
530 writer.close();
531
532 writer = new PrintWriter("clade_frequency.txt");
533
534 writer.println("source\tsize\tfrequency");
535
536 for (CladeSystem.Clade clade1 : allClades) {
537 String name1;
538 int card1 = clade1.bits.cardinality();
539 if (card1 == 1) {
540 name1 = clade1.label;
541 } else {
542 name1 = "clade" + (clade1.index + 1);
543 }
544
545 double value = clade1.count;
546 value /= totalTreesUsed;
547 if (value > THRESHOLD) {
548 writer.println(name1 + "_" + card1 + "\t" + card1 + "\t" + value);
549 }
550 }
551 writer.close();
552 progressStream.println();
553
554 cladePlotter.setCladeSystem(cladeSystem);
555
556 return totalTreesUsed;
557 }
558
559 public void setStatusMessage(String text) {
560 statusLabel.setText(text);
561 }
562
563 public final boolean doGenerate() {
564
565 try {
566 // generator.checkOptions();
567 } catch (IllegalArgumentException iae) {
568 JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to generate file",
569 JOptionPane.ERROR_MESSAGE);
570 return false;
571 }
572
573 // offer stem as default
574 // exportChooser.setSelectedFile(new File(beautiOptions.fileNameStem + ".xml"));
575
576 final int returnVal = exportChooser.showSaveDialog(this);
577 if( returnVal == JFileChooser.APPROVE_OPTION ) {
578 File file = exportChooser.getSelectedFile();
579
580 int n = JOptionPane.YES_OPTION;
581
582 if (file.exists()) {
583 n = JOptionPane.showConfirmDialog(this, file.getName(),
584 "Overwrite the exsting file?", JOptionPane.YES_NO_OPTION);
585 }
586
587 if (n == JOptionPane.YES_OPTION) {
588 try {
589 generate(file);
590
591 } catch (IOException ioe) {
592 JOptionPane.showMessageDialog(this, "Unable to generate file: " + ioe.getMessage(),
593 "Unable to generate file", JOptionPane.ERROR_MESSAGE);
594 return false;
595 }
596 } else {
597 doGenerate();
598 }
599 }
600
601 clearDirty();
602 return true;
603 }
604
605 protected void generate(File file) throws IOException {
606 // getAllOptions();
607
608 FileWriter fw = new FileWriter(file);
609 // generator.generateXML(fw);
610 fw.close();
611 }
612
613 public JComponent getExportableComponent() {
614
615 JComponent exportable = null;
616 Component comp = tabbedPane.getSelectedComponent();
617
618 if (comp instanceof Exportable) {
619 exportable = ((Exportable) comp).getExportableComponent();
620 } else if (comp instanceof JComponent) {
621 exportable = (JComponent) comp;
622 }
623
624 return exportable;
625 }
626
627 public boolean doSave() {
628 return doSaveAs();
629 }
630
631 public boolean doSaveAs() {
632 FileDialog dialog = new FileDialog(this,
633 "Save Template As...",
634 FileDialog.SAVE);
635
636 dialog.setVisible(true);
637 if (dialog.getFile() == null) {
638 // the dialog was cancelled...
639 return false;
640 }
641
642 File file = new File(dialog.getDirectory(), dialog.getFile());
643
644 try {
645 if (writeToFile(file)) {
646
647 clearDirty();
648 }
649 } catch (IOException ioe) {
650 JOptionPane.showMessageDialog(this, "Unable to save file: " + ioe,
651 "Unable to save file",
652 JOptionPane.ERROR_MESSAGE);
653 }
654
655 return true;
656 }
657
658 public Action getImportAction() {
659 return importAlignmentAction;
660 }
661
662 protected AbstractAction importAlignmentAction = new AbstractAction("Import Alignment...") {
663 private static final long serialVersionUID = 3217702096314745005L;
664
665 public void actionPerformed(java.awt.event.ActionEvent ae) {
666 doImport();
667 }
668 };
669
670 // public Action getImportTraitsAction() {
671 // return importTraitsAction;
672 // }
673 //
674 // protected AbstractAction importTraitsAction = new AbstractAction("Import Traits...") {
675 // private static final long serialVersionUID = 3217702096314745005L;
676 //
677 // public void actionPerformed(java.awt.event.ActionEvent ae) {
678 // doImportTraits();
679 // }
680 // };
681
682 public Action getExportAction() {
683 return generateAction;
684 }
685
686 protected AbstractAction generateAction = new AbstractAction("Generate Map File...", gearIcon) {
687 private static final long serialVersionUID = -5329102618630268783L;
688
689 public void actionPerformed(java.awt.event.ActionEvent ae) {
690 doGenerate();
691 }
692 };
693
694
695
696 }