Debian Codegraph @

src/dr/app/tempest/SamplesPanel.java

raw symbols SCIP
1 /*
2 * SamplesPanel.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.tempest;
27
28 import dr.app.beauti.options.DateGuesser;
29 import dr.app.beauti.tipdatepanel.GuessDatesDialog;
30 import dr.app.beauti.util.PanelUtils;
31 import dr.app.util.OSType;
32 import dr.app.util.Utils;
33 import dr.evolution.util.*;
34 import dr.app.gui.table.*;
35 import dr.util.DataTable;
36 import jam.framework.Exportable;
37 import jam.table.HeaderRenderer;
38 import dr.app.gui.table.TableEditorStopper;
39 import jam.table.TableRenderer;
40
41 import javax.swing.*;
42 import javax.swing.event.ListSelectionEvent;
43 import javax.swing.event.ListSelectionListener;
44 import javax.swing.filechooser.FileNameExtensionFilter;
45 import javax.swing.plaf.BorderUIResource;
46 import javax.swing.table.AbstractTableModel;
47 import java.awt.*;
48 import java.awt.event.ActionEvent;
49 import java.awt.event.ItemEvent;
50 import java.awt.event.ItemListener;
51 import java.io.File;
52 import java.io.FileNotFoundException;
53 import java.io.FileReader;
54 import java.io.IOException;
55 import java.util.ArrayList;
56 import java.util.HashMap;
57 import java.util.Map;
58
59 /**
60 * @author Andrew Rambaut
61 * @version $Id: DataPanel.java,v 1.17 2006/09/05 13:29:34 rambaut Exp $
62 */
63 public class SamplesPanel extends JPanel implements Exportable {
64
65 /**
66 *
67 */
68 private static final long serialVersionUID = 5283922195494563924L;
69 JScrollPane scrollPane = new JScrollPane();
70 JTable dataTable = null;
71 DataTableModel dataTableModel = null;
72
73 ClearDatesAction clearDatesAction = new ClearDatesAction();
74 GuessDatesAction guessDatesAction = new GuessDatesAction();
75 ImportDatesAction importDatesAction = new ImportDatesAction();
76
77 JComboBox unitsCombo = new JComboBox(new String[]{"Years", "Months", "Days"});
78 JComboBox directionCombo = new JComboBox(new String[]{"Since some time in the past", "Before the present"});
79
80 TempestFrame frame = null;
81
82 TaxonList taxonList = null;
83
84 int datesUnits;
85 int datesDirection;
86 double maximumTipHeight = 0.0;
87
88 DateGuesser guesser = new DateGuesser();
89
90 double[] heights = null;
91
92 GuessDatesDialog guessDatesDialog = null;
93
94 public SamplesPanel(TempestFrame parent, TaxonList taxonList) {
95
96 this.frame = parent;
97
98 frame.setImportAction(importDatesAction);
99 dataTableModel = new DataTableModel();
100 TableSorter sorter = new TableSorter(dataTableModel);
101 dataTable = new JTable(sorter);
102
103 sorter.setTableHeader(dataTable.getTableHeader());
104
105 dataTable.getTableHeader().setReorderingAllowed(false);
106 dataTable.getTableHeader().setDefaultRenderer(
107 new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
108
109 dataTable.getColumnModel().getColumn(0).setCellRenderer(
110 new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
111 dataTable.getColumnModel().getColumn(0).setPreferredWidth(80);
112
113 dataTable.getColumnModel().getColumn(1).setCellRenderer(
114 new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
115 dataTable.getColumnModel().getColumn(1).setPreferredWidth(80);
116 dataTable.getColumnModel().getColumn(1).setCellEditor(
117 new DateCellEditor());
118
119 dataTable.getColumnModel().getColumn(2).setCellRenderer(
120 new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
121 dataTable.getColumnModel().getColumn(2).setPreferredWidth(80);
122 dataTable.getColumnModel().getColumn(2).setCellEditor(
123 new DateCellEditor());
124
125 dataTable.getColumnModel().getColumn(3).setCellRenderer(
126 new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
127 dataTable.getColumnModel().getColumn(3).setPreferredWidth(80);
128
129 TableEditorStopper.ensureEditingStopWhenTableLosesFocus(dataTable);
130
131 dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
132 public void valueChanged(ListSelectionEvent evt) {
133 selectionChanged();
134 }
135 });
136
137 scrollPane = new JScrollPane(dataTable,
138 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
139 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
140 scrollPane.setOpaque(false);
141
142 PanelUtils.setupComponent(unitsCombo);
143 PanelUtils.setupComponent(directionCombo);
144
145 JToolBar toolBar1 = new JToolBar();
146 toolBar1.setFloatable(false);
147 toolBar1.setOpaque(false);
148
149 toolBar1.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
150 JButton button = new JButton(importDatesAction);
151 PanelUtils.setupComponent(button);
152 toolBar1.add(button);
153 button = new JButton(guessDatesAction);
154 PanelUtils.setupComponent(button);
155 toolBar1.add(button);
156 button = new JButton(clearDatesAction);
157 PanelUtils.setupComponent(button);
158 toolBar1.add(button);
159 toolBar1.add(new JToolBar.Separator(new Dimension(12, 12)));
160 final JLabel unitsLabel = new JLabel("Dates specified as ");
161 toolBar1.add(unitsLabel);
162 toolBar1.add(unitsCombo);
163 toolBar1.add(directionCombo);
164
165 setOpaque(false);
166 setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12)));
167 setLayout(new BorderLayout(0, 0));
168
169 add(toolBar1, "North");
170 add(scrollPane, "Center");
171
172 ItemListener listener = new ItemListener() {
173 public void itemStateChanged(ItemEvent ev) {
174 timeScaleChanged();
175 }
176 };
177 unitsCombo.addItemListener(listener);
178 directionCombo.addItemListener(listener);
179
180 setTaxonList(taxonList);
181 }
182
183 public final void timeScaleChanged() {
184 Units.Type units = Units.Type.YEARS;
185 switch (unitsCombo.getSelectedIndex()) {
186 case 0:
187 units = Units.Type.YEARS;
188 break;
189 case 1:
190 units = Units.Type.MONTHS;
191 break;
192 case 2:
193 units = Units.Type.DAYS;
194 break;
195 }
196
197 boolean backwards = directionCombo.getSelectedIndex() == 1;
198
199 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
200 Date date = taxonList.getTaxon(i).getDate();
201 double d = date.getTimeValue();
202
203 Date newDate = createDate(d, units, backwards, 0.0);
204
205 newDate.setUncertainty(date.getUncertainty());
206
207 taxonList.getTaxon(i).setDate(newDate);
208 }
209
210 calculateHeights();
211
212 dataTableModel.fireTableDataChanged();
213 frame.timeScaleChanged();
214 }
215
216 private Date createDate(double timeValue, Units.Type units, boolean backwards, double origin) {
217 if (backwards) {
218 return Date.createTimeAgoFromOrigin(timeValue, units, origin);
219 } else {
220 return Date.createTimeSinceOrigin(timeValue, units, origin);
221 }
222 }
223
224 private void setTaxonList(TaxonList taxonList) {
225 this.taxonList = taxonList;
226
227 setupTable();
228
229 unitsCombo.setSelectedIndex(datesUnits);
230 directionCombo.setSelectedIndex(datesDirection);
231
232 calculateHeights();
233
234 dataTableModel.fireTableDataChanged();
235 }
236
237 private void setupTable() {
238 dataTableModel.fireTableDataChanged();
239 }
240
241 public void getOptions() {
242 datesUnits = unitsCombo.getSelectedIndex();
243 datesDirection = directionCombo.getSelectedIndex();
244 }
245
246 public JComponent getExportableComponent() {
247 return dataTable;
248 }
249
250 public void selectionChanged() {
251 // nothing to do
252 }
253
254 public void clearDates() {
255 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
256 java.util.Date origin = new java.util.Date(0);
257
258 double d = 0.0;
259
260 Date date = Date.createTimeSinceOrigin(d, Units.Type.YEARS, origin);
261 taxonList.getTaxon(i).setAttribute("date", date);
262 }
263
264 // adjust the dates to the current timescale...
265 timeScaleChanged();
266
267 dataTableModel.fireTableDataChanged();
268 }
269
270 public void guessDates() {
271
272 if (guessDatesDialog == null) {
273 guessDatesDialog = new GuessDatesDialog(frame);
274 }
275
276 int result = guessDatesDialog.showDialog();
277
278 if (result == -1 || result == JOptionPane.CANCEL_OPTION) {
279 return;
280 }
281
282 guesser.guessDates = true;
283 guessDatesDialog.setupGuesser(guesser);
284
285 String warningMessage = null;
286
287 guesser.guessDates(taxonList);
288
289 if (warningMessage != null) {
290 JOptionPane.showMessageDialog(this, "Warning: some dates may not be set correctly - \n" + warningMessage,
291 "Error guessing dates",
292 JOptionPane.WARNING_MESSAGE);
293 }
294
295 // adjust the dates to the current timescale...
296 timeScaleChanged();
297
298 dataTableModel.fireTableDataChanged();
299 }
300
301 private Map<String, FileDialog> fileDialogs = new HashMap<String, FileDialog>();
302 private Map<String, JFileChooser> fileChoosers = new HashMap<String, JFileChooser>();
303 /**
304 * Use the native file dialog on the Mac because the Swing one is bad. On linux, the native
305 * one is bad. No preference on Windows.
306 * @param title
307 * @return
308 */
309 public File[] selectImportFiles(final String title, boolean multipleSelection, FileNameExtensionFilter[] fileNameExtensionFilters) {
310 if (Boolean.parseBoolean(System.getProperty("use.native.choosers", Boolean.toString(OSType.isMac())))) {
311 FileDialog importDialog = fileDialogs.get(title);
312 if (importDialog == null) {
313 importDialog = new FileDialog(frame, title, FileDialog.LOAD);
314 fileDialogs.put(title, importDialog);
315 }
316
317 importDialog.setVisible(true);
318 if (importDialog.getFile() != null) {
319 return new File[] { new File(importDialog.getDirectory(), importDialog.getFile()) };
320 }
321 } else {
322 JFileChooser importChooser = fileChoosers.get(title);
323 if (importChooser == null) {
324 importChooser = new JFileChooser(Utils.getCWD());
325
326 importChooser.setMultiSelectionEnabled(multipleSelection);
327 for (FileNameExtensionFilter fileNameExtensionFilter : fileNameExtensionFilters) {
328 importChooser.setFileFilter(fileNameExtensionFilter);
329 }
330 importChooser.setDialogTitle(title);
331
332 fileChoosers.put(title, importChooser);
333 }
334
335 int returnVal = importChooser.showOpenDialog(this);
336 if (returnVal == JFileChooser.APPROVE_OPTION) {
337 if (importChooser.isMultiSelectionEnabled()) {
338 return importChooser.getSelectedFiles();
339 } else {
340 return new File[] { importChooser.getSelectedFile() };
341 }
342 }
343 }
344
345 return null;
346 }
347
348 private void importDates() {
349
350 File[] files = selectImportFiles("Import Dates File...", false, new FileNameExtensionFilter[]{
351 new FileNameExtensionFilter("Tab-delimited text files", "txt", "tab", "dat")});
352
353 DataTable<String[]> dataTable;
354
355 if (files != null && files.length != 0) {
356 try {
357 // Load the file as a table
358 dataTable = DataTable.Text.parse(new FileReader(files[0]), true, true, true, false);
359
360 } catch (FileNotFoundException fnfe) {
361 JOptionPane.showMessageDialog(this, "Unable to open file: File not found",
362 "Unable to open file",
363 JOptionPane.ERROR_MESSAGE);
364 return;
365 } catch (IOException ioe) {
366 JOptionPane.showMessageDialog(this, "Unable to read file: " + ioe.getMessage(),
367 "Unable to read file",
368 JOptionPane.ERROR_MESSAGE);
369 return;
370 } catch (Exception ex) {
371 ex.printStackTrace(System.err);
372 JOptionPane.showMessageDialog(this, "Fatal exception: " + ex,
373 "Error reading file",
374 JOptionPane.ERROR_MESSAGE);
375 ex.printStackTrace();
376 return;
377 }
378 } else {
379 return;
380 }
381
382 if (dataTable.getColumnCount() == 0) {
383 // expecting at least 2 columns - labels and dates
384 JOptionPane.showMessageDialog(frame,
385 "Expecting a tab delimited file with at\n" +
386 "least 2 columns (taxon labels and dates).",
387 "Incompatible values", JOptionPane.ERROR_MESSAGE);
388 return;
389 }
390
391 String[] columnLabels = dataTable.getColumnLabels();
392 String[] taxonNames = dataTable.getRowLabels();
393
394 if (columnLabels.length < 2) {
395 // only one column so leave it
396 return;
397 }
398
399 boolean hasColumnHeadings = taxonList.getTaxonIndex(columnLabels[0]) < 0;
400
401 // assume the second column contains the dates
402 int dateColumn = 0;
403
404 if (hasColumnHeadings && columnLabels.length > 1) {
405 java.util.List<Integer> dateColumns = new ArrayList<Integer>();
406
407 // see if there is a column labelled 'dates' or something
408 for (int i = 1; i < dataTable.getColumnCount(); i++) {
409 if (columnLabels[i].toLowerCase().contains("date")) {
410 dateColumns.add(i - 1);
411 }
412 }
413
414 if (dateColumns.size() > 0) {
415 // if there are multiple date column possibilities, take the first
416 // @todo - allow the user to select the column to use
417 dateColumn = dateColumns.get(0);
418 }
419 }
420
421 Map<Taxon, String> taxonDateMap = new HashMap<Taxon, String>();
422
423 String[] values = dataTable.getColumn(dateColumn);
424
425 if (!hasColumnHeadings) {
426 final int index = taxonList.getTaxonIndex(columnLabels[0]);
427 if (index >= 0) {
428 taxonDateMap.put(taxonList.getTaxon(index), columnLabels[dateColumn + 1]);
429 }
430 }
431
432 int j = 0;
433 for (final String taxonName : taxonNames) {
434
435 final int index = taxonList.getTaxonIndex(taxonName);
436 if (index >= 0) {
437 taxonDateMap.put(taxonList.getTaxon(index), values[j]);
438 }
439 j++;
440 }
441
442 if (guessDatesDialog == null) {
443 guessDatesDialog = new GuessDatesDialog(frame);
444 }
445
446 guessDatesDialog.setDescription("Parse date values from file");
447
448 int result = guessDatesDialog.showDialog(true);
449
450 if (result == -1 || result == JOptionPane.CANCEL_OPTION) {
451 return;
452 }
453
454 guesser.guessDates = true;
455 guessDatesDialog.setupGuesser(guesser);
456
457 guesser.guessDates(taxonList, taxonDateMap);
458
459 // adjust the dates to the current timescale...
460 timeScaleChanged();
461
462 dataTableModel.fireTableDataChanged();
463 }
464
465 public class ClearDatesAction extends AbstractAction {
466 /**
467 *
468 */
469 private static final long serialVersionUID = -7281309694753868635L;
470
471 public ClearDatesAction() {
472 super("Clear Dates");
473 setToolTipText("Use this tool to remove sampling dates from each taxon");
474 }
475
476 public void actionPerformed(ActionEvent ae) {
477 clearDates();
478 }
479 }
480
481 public class GuessDatesAction extends AbstractAction {
482 /**
483 *
484 */
485 private static final long serialVersionUID = 8514706149822252033L;
486
487 public GuessDatesAction() {
488 super("Parse Dates");
489 setToolTipText("Use this tool to parse the sampling dates from the taxon labels");
490 }
491
492 public void actionPerformed(ActionEvent ae) {
493 guessDates();
494 }
495 }
496
497 public class ImportDatesAction extends AbstractAction {
498 /**
499 *
500 */
501 private static final long serialVersionUID = 8514706149822252033L;
502
503 ImportDatesAction() {
504 super("Import Dates");
505 setToolTipText("Use this tool to import the sampling dates from a file");
506 }
507
508 public void actionPerformed(ActionEvent ae) {
509 importDates();
510 }
511 }
512
513 private void calculateHeights() {
514
515 maximumTipHeight = 0.0;
516 if (taxonList == null || taxonList.getTaxonCount() == 0) return;
517
518 heights = null;
519
520 Date mostRecent = null;
521 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
522 Date date = taxonList.getTaxon(i).getDate();
523 if ((date != null) && (mostRecent == null || date.after(mostRecent))) {
524 mostRecent = date;
525 }
526 }
527
528 if (mostRecent != null) {
529 heights = new double[taxonList.getTaxonCount()];
530
531 TimeScale timeScale = new TimeScale(mostRecent.getUnits(), true, mostRecent.getAbsoluteTimeValue());
532 double time0 = timeScale.convertTime(mostRecent.getTimeValue(), mostRecent);
533
534 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
535 Date date = taxonList.getTaxon(i).getDate();
536 if (date != null) {
537 heights[i] = timeScale.convertTime(date.getTimeValue(), date) - time0;
538 if (heights[i] > maximumTipHeight) maximumTipHeight = heights[i];
539 }
540 }
541 }
542 }
543
544 class DataTableModel extends AbstractTableModel {
545
546 /**
547 *
548 */
549 private static final long serialVersionUID = -6707994233020715574L;
550 String[] columnNames = {"Name", "Date", "Precision", "Height"};
551
552 public DataTableModel() {
553 }
554
555 public int getColumnCount() {
556 return columnNames.length;
557 }
558
559 public int getRowCount() {
560 if (taxonList == null) return 0;
561
562 return taxonList.getTaxonCount();
563 }
564
565 public Object getValueAt(int row, int col) {
566 Date date = taxonList.getTaxon(row).getDate();
567 switch (col) {
568 case 0:
569 return taxonList.getTaxonId(row);
570 case 1:
571 if (date != null) {
572 return date.getTimeValue();
573 } else {
574 return "-";
575 }
576 case 2:
577 if (date != null) {
578 return date.getUncertainty();
579 } else {
580 return "-";
581 }
582 case 3:
583 if (heights != null) {
584 return heights[row];
585 } else {
586 return "0.0";
587 }
588 }
589 return null;
590 }
591
592 public void setValueAt(Object aValue, int row, int col) {
593 if (col == 0) {
594 taxonList.getTaxon(row).setId(aValue.toString());
595 } else if (col == 1) {
596 Date date = taxonList.getTaxon(row).getDate();
597 if (date != null) {
598 double d = (Double) aValue;
599 Date newDate = createDate(d, date.getUnits(), date.isBackwards(), date.getOrigin());
600 taxonList.getTaxon(row).setDate(newDate);
601 }
602 } else if (col == 2) {
603 Date date = taxonList.getTaxon(row).getDate();
604 if (date != null) {
605 double d = (Double) aValue;
606 if (d >= 0.0) {
607 date.setUncertainty(d);
608 }
609 }
610 }
611
612 timeScaleChanged();
613 }
614
615 public boolean isCellEditable(int row, int col) {
616 if (col == 0) return true;
617 if (col == 1 || col == 2) {
618 Date date = taxonList.getTaxon(row).getDate();
619 return (date != null);
620 }
621 return false;
622 }
623
624 public String getColumnName(int column) {
625 return columnNames[column];
626 }
627
628 public Class getColumnClass(int c) {
629 return getValueAt(0, c).getClass();
630 }
631
632 public String toString() {
633 StringBuffer buffer = new StringBuffer();
634
635 buffer.append(getColumnName(0));
636 for (int j = 1; j < getColumnCount(); j++) {
637 buffer.append("\t");
638 buffer.append(getColumnName(j));
639 }
640 buffer.append("\n");
641
642 for (int i = 0; i < getRowCount(); i++) {
643 buffer.append(getValueAt(i, 0));
644 for (int j = 1; j < getColumnCount(); j++) {
645 buffer.append("\t");
646 buffer.append(getValueAt(i, j));
647 }
648 buffer.append("\n");
649 }
650
651 return buffer.toString();
652 }
653 }
654 }