-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathds_widget.py
More file actions
1748 lines (1483 loc) · 62 KB
/
ds_widget.py
File metadata and controls
1748 lines (1483 loc) · 62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Dataset widget to display the contents of a dataset."""
# Disclaimer
# ----------
#
# Copyright (C) 2021 Helmholtz-Zentrum Hereon
# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht
#
# This file is part of psy-view and is released under the GNU LGPL-3.O license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3.0 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU LGPL-3.0 license for more details.
#
# You should have received a copy of the GNU LGPL-3.0 license
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from __future__ import annotations
import os.path as osp
import os
from typing import (
List,
TYPE_CHECKING,
Optional,
Union,
Dict,
Iterator,
Type,
Any,
Callable,
Hashable,
Tuple,
)
import contextlib
import yaml
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import Qt # pylint: disable=no-name-in-module
import psy_view.utils as utils
from psyplot_gui.content_widget import (
DatasetTree, DatasetTreeItem, escape_html)
from psyplot_gui.common import (
DockMixin, get_icon as get_psy_icon, PyErrorMessage)
import psyplot.data as psyd
from psy_view.rcsetup import rcParams
from psy_view.plotmethods import (
PlotMethodWidget,
MapPlotWidget,
Plot2DWidget,
LinePlotWidget,
)
from psyplot.config.rcsetup import get_configdir
from matplotlib.animation import FuncAnimation
if TYPE_CHECKING:
from xarray import DataArray, Dataset
from psyplot.project import PlotterInterface, Project
from psyplot.plotter import Plotter
from matplotlib.figure import Figure
from matplotlib.backend_bases import MouseEvent
from psyplot_gui.main import MainWindow
NOTSET = "__NOVARIABLEAVAILABLE"
def get_dims_to_iterate(arr: DataArray) -> List[str]:
"""Get the dimensions of an array to iterate over
This function takes a data array and returns the dimension in the base
dataset that one can interator over.
Parameters
----------
arr: xarray.DataArray
The data array to iterate over
Returns
-------
list of strings
The dimension strings
"""
base_var = next(arr.psy.iter_base_variables)
return [dim for dim, size in zip(base_var.dims, base_var.shape)
if size > 1 and arr[dim].ndim == 0]
TOO_MANY_FIGURES_WARNING = """
Multiple figures are open but you specified only {} filenames: {}.<br>
Saving the figures will cause that not all images are saved! We recommend to
export to a single PDF (that then includes multiple pages), or modify your
filename with strings like
<ul>
<li> <code>%i</code> for a continuous counter of the images</li>
<li><code>%(name)s</code> for variable names</li>
<li>or other netCDF attributes (see the
<a href="https://psyplot.github.io/psyplot/api/psyplot.project.html#psyplot.project.Project.export">
examples of exporting psyplot projects</a>)</li>
</ul>
Shall I continue anyway and save the figures?
"""
class DatasetWidget(QtWidgets.QSplitter):
"""A widget to control the visualization of the variables in a dataset"""
#: The title of the widget
title: str = 'psy-view Plot Control'
#: Display the dock widget at the right side of the GUI
dock_position = Qt.RightDockWidgetArea
_animating: bool = False
_ani: Optional[FuncAnimation] = None
_init_step: int = 0
#: A :class:`PyQt5.QtWidgets.QGroupBox` that contains the variable buttons
variable_frame: Optional[QtWidgets.QGroupBox] = None
#: Buttons for selecting variables in the :attr:`ds`
variable_buttons: Dict[str, QtWidgets.QPushButton]
_new_plot: bool = False
_preset: Optional[Union[str, Dict]] = None
#: Attributes to use in the dataset tree
ds_attr_columns: List[str] = ['long_name', 'dims', 'shape']
def __init__(self, ds: Optional[Dataset] = None, *args, **kwargs) -> None:
"""
Parameters
----------
ds: xarray.Dataset
A dataset to visualize with this widget
"""
super().__init__(*args, **kwargs)
self._ds_nums: Dict[int, Dataset] = {}
self.setChildrenCollapsible(False)
self.ds: Optional[Dataset] = ds
self.setOrientation(Qt.Vertical)
self.error_msg = PyErrorMessage(self)
# first row: dataset name
self.open_box = QtWidgets.QHBoxLayout()
self.lbl_ds = QtWidgets.QLineEdit()
self.open_box.addWidget(self.lbl_ds)
self.btn_open = utils.add_pushbutton(
get_psy_icon('run_arrow.png'), lambda: self.set_dataset(),
"Select and open a netCDF dataset", self.open_box, icon=True)
self.open_widget = QtWidgets.QWidget()
self.open_widget.setLayout(self.open_box)
self.addWidget(self.open_widget)
# second row: dataset representation
self.setup_ds_tree()
if ds is not None:
self.add_ds_item()
self.ds_tree.itemExpanded.connect(self.change_ds)
self.ds_tree.itemExpanded.connect(self.load_variable_desc)
self.addWidget(self.ds_tree)
# third row, navigation
self.navigation_box = QtWidgets.QHBoxLayout()
# -- animate backwards button
self.btn_animate_backward = utils.add_pushbutton(
"◀◀", lambda: self.animate_backward(),
"Animate the time dimension backwards", self.navigation_box)
self.btn_animate_backward.setCheckable(True)
# -- go to previous button
self.btn_prev = utils.add_pushbutton(
'◀', self.go_to_previous_step,
"Go to previous time step", self.navigation_box)
# -- dimension menu for animation
self.combo_dims = QtWidgets.QComboBox()
self.navigation_box.addWidget(self.combo_dims)
# -- go to next button
self.btn_next = utils.add_pushbutton(
'▶', self.go_to_next_step,
"Go to next time step", self.navigation_box)
# -- animate forward button
self.btn_animate_forward = utils.add_pushbutton(
"▶▶", lambda: self.animate_forward(),
"Animate the time dimension", self.navigation_box)
self.btn_animate_forward.setCheckable(True)
# -- interval slider
self.sl_interval = QtWidgets.QSlider(Qt.Horizontal)
self.sl_interval.setMinimum(40) # 24 fps
self.sl_interval.setMaximum(10000)
self.sl_interval.setSingleStep(50)
self.sl_interval.setPageStep(500)
self.sl_interval.setValue(500)
self.sl_interval.valueChanged.connect(self.reset_timer_interval)
self.navigation_box.addWidget(self.sl_interval)
# -- interval label
self.lbl_interval = QtWidgets.QLabel('500 ms')
self.navigation_box.addWidget(self.lbl_interval)
# --- export/import menus
self.export_box = QtWidgets.QHBoxLayout()
# -- Export button
self.btn_export = QtWidgets.QToolButton()
self.btn_export.setText('Export')
self.btn_export.setPopupMode(QtWidgets.QToolButton.InstantPopup)
self.btn_export.setMenu(self.setup_export_menu())
self.btn_export.setEnabled(False)
self.export_box.addWidget(self.btn_export)
# --- Presets button
self.frm_preset = QtWidgets.QFrame()
self.frm_preset.setFrameStyle(QtWidgets.QFrame.StyledPanel)
hbox = QtWidgets.QHBoxLayout(self.frm_preset)
self.btn_preset = QtWidgets.QToolButton()
self.btn_preset.setText('Preset')
self.btn_preset.setPopupMode(QtWidgets.QToolButton.InstantPopup)
self.btn_preset.setMenu(self.setup_preset_menu())
hbox.addWidget(self.btn_preset)
# --- presets label
self.lbl_preset = QtWidgets.QLabel('')
self.lbl_preset.setVisible(False)
hbox.addWidget(self.lbl_preset)
# --- unset preset button
self.btn_unset_preset = utils.add_pushbutton(
get_psy_icon('invalid.png'), self.unset_preset,
"Unset the current preset", hbox, icon=True)
self.btn_unset_preset.setVisible(False)
self.export_box.addWidget(self.frm_preset)
self.btn_reload = utils.add_pushbutton(
get_psy_icon("refresh.png"), self.reload,
"Close all open datasets and recreate the plots",
self.export_box, icon=True
)
self.export_box.addStretch(0)
vbox = QtWidgets.QVBoxLayout()
vbox.addLayout(self.navigation_box)
vbox.addLayout(self.export_box)
self.addLayout(vbox)
# fourth row: array selector
self.array_frame = QtWidgets.QGroupBox('Current plot')
hbox = QtWidgets.QHBoxLayout()
self.combo_array = QtWidgets.QComboBox()
self.combo_array.setEditable(False)
self.combo_array.currentIndexChanged.connect(lambda: self.refresh())
self.combo_array.currentIndexChanged.connect(self.show_current_figure)
hbox.addWidget(self.combo_array)
self.btn_add = utils.add_pushbutton(
QtGui.QIcon(get_psy_icon('plus')), self.new_plot,
"Create a new plot", hbox, icon=True)
self.btn_add.setEnabled(ds is not None)
self.btn_del = utils.add_pushbutton(
QtGui.QIcon(get_psy_icon('minus')), self.close_current_plot,
"Remove the current plot", hbox, icon=True)
self.btn_del.setEnabled(False)
hbox.addWidget(self.btn_add)
hbox.addWidget(self.btn_del)
self.array_frame.setLayout(hbox)
self.addWidget(self.array_frame)
# fifth row: plot interface
self.plot_tabs = QtWidgets.QTabWidget()
self.setup_plot_tabs()
self.plot_tabs.currentChanged.connect(self.switch_tab)
self.addWidget(self.plot_tabs)
# sixth row: variables
self.variable_scroll = QtWidgets.QScrollArea()
self.variable_scroll.setWidgetResizable(True)
self.setup_variable_buttons()
self.addWidget(self.variable_scroll)
# seventh row: dimensions
self.dimension_table = QtWidgets.QTableWidget()
self.addWidget(self.dimension_table)
self.disable_navigation()
if self.ds is not None:
self.refresh()
self.cids: Dict[str, int] = {}
def reload(self) -> None:
"""Close the plot and recreate it."""
import psyplot.project as psy
sp = self._sp
fname = sp.dsnames_map[self.ds.psy.num] # type: ignore
project = sp.save_project()
sp.close(True, True, True)
self.ds_tree.clear()
self._ds_nums.clear()
self.refresh()
self._sp = sp = psy.Project.load_project(project)
self._ds_nums = sp.datasets
num = next(num for num, f in sp.dsnames_map.items() if f == fname)
self.ds = self.open_datasets[num]
for ds in self._ds_nums.values():
self._add_ds_item(ds)
sp.show()
self.refresh()
def setup_ds_tree(self) -> None:
"""Setup the number of columns and the header of the dataset tree."""
self.ds_tree = tree = QtWidgets.QTreeWidget()
tree.setColumnCount(len(self.ds_attr_columns) + 1)
tree.setHeaderLabels([''] + self.ds_attr_columns)
def showEvent(self, event):
ret = super().showEvent(event)
current_size = self.size()
current_sizes = self.sizes()
itree = self.indexOf(self.ds_tree)
itable = self.indexOf(self.dimension_table)
diff = 0
if current_sizes[itree] < 400:
diff += 400 - current_sizes[itree]
current_sizes[itree] = 400
if current_sizes[itable] < 300:
diff += 300 - current_sizes[itable]
current_sizes[itable] = 300
if diff:
self.resize(current_size.width(), current_size.height() + diff)
self.setSizes(current_sizes)
return ret
def close_current_plot(self) -> None:
"""Close the figure of the current variable."""
self.variable_buttons[self.variable].click()
def excepthook(self, type, value, traceback) -> None:
"""A method to replace the sys.excepthook"""
self.error_msg.excepthook(type, value, traceback)
@property
def arr_name(self) -> Optional[str]:
"""Get the name of the array of the current plot (if there is one)."""
if not self.combo_array.count():
return None
else:
return self.combo_array.currentText().split(':')[0]
def change_ds(self, ds_item: DatasetTreeItem) -> None:
"""Change the current dataset to another one.
Parameters
----------
ds_item: psyplot_gui.content_widget.DatasetTreeItem
The item in the tree of the new dataset to use
"""
ds_items = self.ds_items
if ds_item in ds_items:
with self.block_tree():
self.ds = ds_item.ds()
self.expand_ds_item(ds_item)
self.setup_variable_buttons()
self.change_combo_array()
self.refresh(reset_combo=False)
def expand_ds_item(self, ds_item: DatasetTreeItem) -> None:
"""Expand an item of a dataset.
Parameters
----------
ds_item: DatasetTreeItem
The item to expand
"""
tree = self.ds_tree
tree.collapseAll()
tree.expandItem(ds_item)
ds = ds_item.ds()
if len(ds) <= 10:
tree.expandItem(ds_item.child(0))
if len(ds.coords) <= 10:
tree.expandItem(ds_item.child(1))
if len(ds.attrs) <= 10:
tree.expandItem(ds_item.attrs)
def _open_dataset(self) -> Optional[Dataset]:
"""Open a dialog to open a new dataset from disk.
Returns
-------
xarray.Dataset or None
The :class:`xarray.Dataset` of the selected file, or None if the
user aborted the dialog.
"""
current = self.lbl_ds.text()
if not current or not osp.exists(current):
current = os.getcwd()
fname, ok = QtWidgets.QFileDialog.getOpenFileName(
self, 'Open dataset', current,
'NetCDF files (*.nc *.nc4);;'
'Shape files (*.shp);;'
'All files (*)'
)
if not ok:
return None
ds = psyd.open_dataset(fname)
return ds
@contextlib.contextmanager
def block_tree(self) -> Iterator[None]:
"""Block all signals of a tree temporarily.
Use this via::
with self.block_tree():
do_something
"""
self.ds_tree.blockSignals(True)
yield
self.ds_tree.blockSignals(False)
def set_dataset(self, ds: Optional[Dataset] = None) -> None:
"""Ask for a file name and open the dataset."""
if ds is None:
ds = self._open_dataset()
if ds is None:
return
self.ds = ds
with self.block_tree():
self.add_ds_item()
self.setup_variable_buttons()
self.btn_add.setEnabled(True)
self.btn_del.setEnabled(True)
def add_ds_item(self) -> None:
"""Add a new :class:`DatasetTreeItem` for the current :attr:`ds`."""
ds: Dataset = self.ds # type: ignore
self._add_ds_item(ds)
def _add_ds_item(self, ds: Dataset) -> None:
tree = self.ds_tree
ds_item = DatasetTreeItem(ds, self.ds_attr_columns, 0)
fname = psyd.get_filename_ds(ds, False)[0]
if fname is not None:
self.lbl_ds.setText(fname)
fname = osp.basename(fname)
else:
self.lbl_ds.setText('')
fname = ''
ds_item.setText(0, fname)
tree.addTopLevelItem(ds_item)
self.expand_ds_item(ds_item)
tree.resizeColumnToContents(0)
if ds.psy.num not in self.open_datasets:
# make sure we do not loose track of open datasets
self._ds_nums[ds.psy.num] = ds
@property
def open_datasets(self) -> Dict[int, Dataset]:
"""Get a mapping from path to dataset number of the open datasets."""
return self._ds_nums
@property
def ds_items(self) -> List[DatasetTreeItem]:
"""Get the :class:`DatasetTreeItems` for the open datasets."""
tree = self.ds_tree
return list(map(tree.topLevelItem, range(tree.topLevelItemCount())))
@property
def ds_item(self) -> Optional[DatasetTreeItem]:
"""Get the current dataset item (if there is one)."""
ds = self.ds
for item in self.ds_items:
if item.ds() is ds:
return item
return None
def expand_current_variable(
self, variable: Optional[Union[Any, Hashable]] = None) -> None:
"""Expand the item in the dataset tree of variable.
Parameters
----------
variable: str
The name of the variable to expand. If None, the current variable is
used.
"""
tree = self.ds_tree
top: DatasetTreeItem = self.ds_item # type: ignore
tree.expandItem(top)
tree.expandItem(top.child(0))
if variable is None:
variable: str = self.variable # type: ignore
for var_item in map(top.child(0).child,
range(top.child(0).childCount())):
if var_item.text(0) == variable:
tree.expandItem(var_item)
else:
tree.collapseItem(var_item)
def setup_variable_buttons(self, ncols: int = 4) -> None:
"""Setup the variable buttons for the current dataset."""
variable_frame = QtWidgets.QGroupBox('Variables')
self.variable_scroll.setWidget(variable_frame)
self.variable_frame = variable_frame
self.variable_layout = QtWidgets.QGridLayout(self.variable_frame)
self.variable_buttons = {}
ds = self.ds
if ds is not None:
for i, v in enumerate(ds):
btn = utils.add_pushbutton(
v, self._draw_variable(v), f"Visualize variable {v}")
btn.setCheckable(True)
self.variable_buttons[v] = btn
self.variable_layout.addWidget(btn, i // ncols, i % ncols)
if len(ds):
rows = len(ds) // ncols
minrows = max(1, min(3, rows))
self.variable_scroll.setMinimumHeight(
(minrows + 2) * btn.sizeHint().height())
def load_variable_desc(self, item: QtWidgets.QTreeWidgetItem) -> None:
"""Load the description of the variable of a given tree item.
Parameters
----------
item: PyQt5.QtWidget.QTreeWidgetItem
The item of the variable in the :attr:`ds_tree`. If this is not an
item of a variable, nothing is done.
"""
parent = item.parent()
tree = self.ds_tree
if parent is tree or parent is None or not (
DatasetTree.is_variable(item) or DatasetTree.is_coord(item)):
return
if tree.isColumnHidden(1):
tree.showColumn(1)
tree.resizeColumnToContents(0)
top = item
while top.parent() and top.parent() is not self:
top = top.parent()
ds = top.ds()
if ds is None:
return
desc = escape_html(str(ds.variables[item.text(0)]))
item.setToolTip(0, '<pre>' + desc + '</pre>')
def clear_table(self) -> None:
"""Clear the table that shows the available dimensions."""
self.dimension_table.clear()
self.dimension_table.setColumnCount(5)
self.dimension_table.setHorizontalHeaderLabels(
['Type', 'First', 'Current', 'Last', 'Units'])
self.dimension_table.setRowCount(0)
def addLayout(self, layout: QtWidgets.QLayout) -> QtWidgets.QWidget:
"""Add a layout to the splitter.
This convenience function creates a new QWidget that wraps the given
layout and returns it.
Parameters
----------
layout: QtWidget.QLayout
The layout to add
Returns
-------
QtWidgets.QWidget
The widget that wraps the given layout
"""
widget = QtWidgets.QWidget()
widget.setLayout(layout)
self.addWidget(widget)
return widget
def go_to_previous_step(self) -> None:
"""Decrease the movie dimension to the previous step."""
dim = self.combo_dims.currentText()
self.increase_dim(dim, -1)()
def go_to_next_step(self) -> None:
"""Increase the movie dimension to the next step."""
dim = self.combo_dims.currentText()
self.increase_dim(dim)()
def animate_backward(self) -> None:
"""Start the current animation in backward direction, or stop it."""
if self._animating:
self.stop_animation()
self.btn_animate_backward.setText('◀◀')
self.enable_navigation()
else:
self._animate_forward = False
self.btn_animate_backward.setText('■')
self.disable_navigation(self.btn_animate_backward)
self.start_animation()
def animate_forward(self, nframes=None):
"""Start the current animation in forward direction, or stop it."""
if self._animating:
self.stop_animation()
self.btn_animate_forward.setText('▶▶')
self.enable_navigation()
else:
self._animate_forward = True
self.btn_animate_forward.setText('■')
self.disable_navigation(self.btn_animate_forward)
self.start_animation(nframes)
def setup_plot_tabs(self) -> None:
"""Setup the tabs of the various plot methods."""
self.plot_tabs.addTab(MapPlotWidget(self.get_sp, self.ds),
'mapplot')
self.plot_tabs.addTab(Plot2DWidget(self.get_sp, self.ds),
'plot2d')
lineplot_widget = LinePlotWidget(self.get_sp, self.ds)
self.plot_tabs.addTab(lineplot_widget, 'lineplot')
for w in map(self.plot_tabs.widget, range(self.plot_tabs.count())):
w.replot.connect(self.replot)
w.reset.connect(self.reset)
w.changed.connect(lambda: self.refresh())
def replot(self, plotmethod: str) -> None:
"""Regenerate the plot of a given plotmethod, without closing it.
Parameters
----------
plotmethod: str
The name of the plotmethod
See Also
--------
reset: The same method, but closes the plot before genereting a new one.
"""
self.plotmethod = plotmethod
self.make_plot()
self.refresh()
def reset(self, plotmethod: str) -> None:
"""Close the plot of the given plotmethod and regenerate it.
The same as :meth:`replot`, but closes the plot.
Parameters
----------
plotmethod: str
The name of the plotmethod
See Also
--------
reset: The same method, but closes the plot before genereting a new one.
"""
self.plotmethod = plotmethod
self.close_sp()
self.make_plot()
self.refresh()
def disable_navigation(
self, but: Optional[QtWidgets.QPushButton] = None
) -> None:
"""Disable the navigation buttons.
This function disables all navigation buttons but the one you specify.
Parameters
----------
but: PyQt5.QtWidgets.QPushButton
If not None, this button is not disabled.
"""
for item in map(self.navigation_box.itemAt,
range(self.navigation_box.count())):
w = item.widget()
if w is not but and w is not self.sl_interval:
w.setEnabled(False)
def enable_navigation(self) -> None:
"""Enable all navigation buttons again."""
for item in map(self.navigation_box.itemAt,
range(self.navigation_box.count())):
w = item.widget()
w.setEnabled(True)
def disable_variables(self):
"""Disable all variable selection buttons."""
for btn in self.variable_buttons.values():
btn.setEnabled(False)
def enable_variables(self):
"""Enable all variable selection buttons again."""
valid_variables = self.plotmethod_widget.valid_variables(self.ds)
for v, btn in self.variable_buttons.items():
btn.setEnabled(v in valid_variables)
def start_animation(self, nframes: Optional[int] = None):
"""Start the animation along the selected dimension.
Parameters
----------
nframes: int or None
If not None, the number of frames to draw
See Also
--------
animation_frames: The iterator to generate the frames
"""
self._animating = True
self._animation_frames = nframes
self._starting_step = 1
self.disable_variables()
self.plot_tabs.setEnabled(False)
if self.sp is not None:
if self.animation is None or self.animation.event_source is None:
self.animation = FuncAnimation(
self.fig, self.update_dims, frames=self.animation_frames(),
init_func=self.sp.draw, interval=self.sl_interval.value(),
repeat=False)
# HACK: Make sure that the animation starts although the figure
# is already shown
self.animation._draw_frame(next(self.animation_frames()))
else:
self.animation.event_source.start()
def reset_timer_interval(self, value: int) -> None:
"""Change the interval of the timer."""
self.lbl_interval.setText('%i ms' % value)
if self.animation is None or self.animation.event_source is None:
pass
else:
self.animation.event_source.stop()
self.animation._interval = value
self.animation.event_source.interval = value
self.animation.event_source.start()
def stop_animation(self) -> None:
"""Stop the current animation."""
self._animating = False
if (self.animation is not None and
self.animation.event_source is not None):
self.animation.event_source.stop()
self.plot_tabs.setEnabled(True)
self.enable_variables()
self.refresh()
def animation_frames(self) -> Iterator[Dict[str, int]]:
"""Get the animation frames for the :attr:`combo_dims` dimension."""
while self._animating and self._animation_frames is None or \
self._animation_frames:
if self._animation_frames is not None and not self._init_step:
self._animation_frames -= 1
dim = self.combo_dims.currentText()
i = self.data.psy.idims[dim]
imax = self.ds.dims[dim] - 1 # type: ignore
if self._init_step:
self._init_step -= 1
elif self._starting_step:
self._starting_step -= 1
elif self._animate_forward:
i += -i if i == imax else 1
else:
i += imax if i == 0 else -1
yield {dim: i}
def update_dims(self, dims: Dict[str, Any]):
if self.sp is not None:
self.sp.update(dims=dims)
def _load_preset(self) -> None:
"""Open a file dialog and load the selected preset."""
fname, ok = QtWidgets.QFileDialog.getOpenFileName(
self, 'Load preset', osp.join(get_configdir(), 'presets'),
'YAML files (*.yml *.yaml);;'
'All files (*)')
if ok:
self.load_preset(fname)
def load_preset(self, preset: Optional[Union[str, Dict[str, Any]]]):
"""Load a given preset from disk.
Parameters
----------
preset: str or dict
The name or path to the preset, or a dictionary
"""
self.preset = preset # type: ignore
if self.sp:
loaded_preset: Dict[str, Any] = self.preset # now that it's loaded
if loaded_preset:
self.sp.load_preset(loaded_preset)
self.refresh()
self.maybe_show_preset()
@property
def preset(self) -> Dict[str, Any]:
"""Get the currently loaded preset."""
if self._preset is None:
return {}
import psyplot.project as psy
preset = self._preset
try:
preset = psy.Project._load_preset(preset)
except yaml.constructor.ConstructorError:
answer = QtWidgets.QMessageBox.question(
self, "Can I trust this?",
f"Failed to load the preset at <i>{preset}</i> in safe mode. Can we "
"trust this preset and load it in unsafe mode?")
if answer == QtWidgets.QMessageBox.Yes:
psyd.rcParams['presets.trusted'].append(
psy.Project._resolve_preset_path(preset))
preset = psy.Project._load_preset(preset)
else:
preset = {}
return preset # type: ignore
@preset.setter
def preset(self, value: Optional[Union[str, Dict[str, Any]]]):
self._preset = value
def unset_preset(self) -> None:
"""Unset the current preset and do not use it anymore."""
self.preset = None # type: ignore
self.maybe_show_preset()
def maybe_show_preset(self) -> None:
"""Show the name of the current preset if one is selected."""
if self._preset is not None and isinstance(self._preset, str):
self.lbl_preset.setText('<i>' +
osp.basename(osp.splitext(self._preset)[0]) + '</i>')
self.lbl_preset.setVisible(True)
self.btn_unset_preset.setVisible(True)
elif self._preset is not None:
self.lbl_preset.setText('<i>custom</i>')
self.lbl_preset.setVisible(True)
self.btn_unset_preset.setVisible(True)
else:
self.lbl_preset.setVisible(False)
self.btn_unset_preset.setVisible(False)
def save_current_preset(self) -> None:
"""Save the preset of the current plot to a file."""
if self.sp is not None:
preset_func = self.sp.save_preset
self._save_preset(preset_func)
def save_full_preset(self) -> None:
"""Save the preset of all open plots to a file."""
sp = self._sp
if sp is not None:
return self._save_preset(sp.save_preset)
return None
def _save_preset(self, save_func: Callable[[str], Any]) -> None:
"""Save the preset to a file.
Parameters
----------
save_func: function
The function that is called to save the preset. Must accept the
path as an argument
"""
fname, ok = QtWidgets.QFileDialog.getSaveFileName(
self, 'Save preset', osp.join(get_configdir(), 'presets'),
'YAML files (*.yml *.yaml);;'
'All files (*)')
if not ok:
return None
save_func(fname)
def setup_preset_menu(self) -> QtWidgets.QMenu:
"""Set up the menu to select/load presets."""
self.preset_menu = menu = QtWidgets.QMenu()
self._save_preset_actions = []
self._load_preset_action = menu.addAction(
"Load preset", self._load_preset)
self._unset_preset_action = menu.addAction(
"Unset preset", self.unset_preset)
menu.addSeparator()
self._save_preset_actions.append(
menu.addAction('Save format of current plot as preset',
self.save_current_preset))
self._save_preset_actions.append(
menu.addAction('Save format of all plots as preset',
self.save_full_preset))
for action in self._save_preset_actions:
action.setEnabled(False)
return menu
def setup_export_menu(self) -> QtWidgets.QMenu:
"""Set up the menu to export the current plot."""
self.export_menu = menu = QtWidgets.QMenu()
menu.addAction('image (PDF, PNG, etc.)', self.export_image)
menu.addAction('all images (PDF, PNG, etc.)', self.export_all_images)
menu.addAction('animation (GIF, MP4, etc.', self.export_animation)
menu.addAction('psyplot project (.pkl file)', self.export_project)
menu.addAction('psyplot project with data',
self.export_project_with_data)
py_action = menu.addAction('python script (.py)', self.export_python)
py_action.setEnabled(False) # psyplot does not yet export to python
return menu
def export_image(self) -> None:
"""Ask for a filename and export the current plot to a file."""
if self.sp is not None:
fname, ok = QtWidgets.QFileDialog.getSaveFileName(
self, "Export image", os.getcwd(),
"Images (*.png *.pdf *.jpg *.svg)")
if ok:
self.sp.export(fname, **rcParams['savefig_kws'])
def export_all_images(self) -> None:
"""Ask for a filename and export all plots to one (or more) files."""
fname, ok = QtWidgets.QFileDialog.getSaveFileName(
self, "Export image", os.getcwd(),
"Images (*.png *.pdf *.jpg *.svg)")
if ok and self._sp:
# test filenames
if not osp.splitext(fname)[-1].lower() == '.pdf':
fnames = [
sp.format_string(fname, False, i)
for i, sp in enumerate(self._sp.figs.values())]
if len(fnames) != len(set(fnames)):
answer = QtWidgets.QMessageBox.question(
self, "Too many figures",
TOO_MANY_FIGURES_WARNING.format(
len(set(fnames)), ', '.join(set(fnames))))
if answer == QtWidgets.QMessageBox.No:
return
self._sp.export(fname, **rcParams['savefig_kws'])
def export_animation(self) -> None:
"""Ask for a filename and export the animation."""
fname, ok = QtWidgets.QFileDialog.getSaveFileName(
self, "Export animation", os.getcwd(),
"Movie (*.mp4 *.mov *.gif)")
if ok:
dim = self.combo_dims.currentText()
nframes: int = self.ds.dims[dim] # type: ignore