-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathplot_creator.py
More file actions
2433 lines (2133 loc) · 86.7 KB
/
plot_creator.py
File metadata and controls
2433 lines (2133 loc) · 86.7 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
"""This module contains a widget to create new plots with psyplot
The main class is the :class:`PlotCreator` which is used to handle the
different plotting methods of the :class:`psyplot.project.ProjectPlotter`
class"""
# SPDX-FileCopyrightText: 2016-2024 University of Lausanne
# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht
# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum hereon GmbH
#
# SPDX-License-Identifier: LGPL-3.0-only
from __future__ import division
import logging
import os
import re
import types
from collections import defaultdict
from functools import partial
from itertools import chain, cycle, product, repeat, starmap
from math import floor
import matplotlib as mpl
import numpy as np
import psyplot.project as psy
import six
import xarray
from psyplot.config.rcsetup import get_configdir
from psyplot.utils import _temp_bool_prop
from psyplot_gui.common import (
ListValidator,
LoadFromConsoleButton,
PyErrorMessage,
get_icon,
)
from psyplot_gui.compat.qtcompat import (
QAbstractItemView,
QAction,
QCheckBox,
QComboBox,
QDialog,
QDialogButtonBox,
QDoubleValidator,
QFileDialog,
QGraphicsRectItem,
QGraphicsScene,
QGraphicsView,
QGridLayout,
QHBoxLayout,
QIcon,
QIntValidator,
QLabel,
QLineEdit,
QListView,
QMenu,
QPushButton,
QSplitter,
QStyledItemDelegate,
Qt,
QTableWidget,
QTableWidgetItem,
QTabWidget,
QtCore,
QToolButton,
QValidator,
QVBoxLayout,
QWidget,
asstring,
isstring,
with_qt5,
)
from psyplot_gui.preferences import RcParamsTree
logger = logging.getLogger(__name__)
class CoordComboBox(QComboBox):
"""Combobox showing coordinate information of a dataset
This combobox loads its data from the current dataset and allows the
popups to be left open. It also has a :attr:`leftclick` signal that is
emitted when the popup is about to be closed because the user clicked on a
value"""
close_popups = _temp_bool_prop("close_popups", default=True)
use_coords = _temp_bool_prop("use_coords", default=False)
leftclick = QtCore.pyqtSignal(QComboBox)
def __init__(self, ds_func, dim, parent=None):
"""
Parameters
----------
ds_func: function
The function that, when called without arguments, returns the
xarray.Dataset to use
dim: str
The coordinate name for this combobox
parent: PyQt5.QtWidgets.QWidget
The parent widget"""
super(CoordComboBox, self).__init__(parent)
self.dim = dim
self._is_empty = True
self.get_ds = ds_func
self._changed = False
self._right_clicked = False
# modify the view
view = self.view()
# We allow the selection of multiple items with a left-click
view.setSelectionMode(QListView.ExtendedSelection)
# The following modifications will cause this behaviour:
# Left-click:
# Case 1: Any of the already existing plot arrays is selected
# Add the selected values in the popup to the dimension in
# the currently selected plot items
# Case 2: No plot arrays are selected or none exists
# Create new plot items from the selection in the popup
# Right-Click:
# Set the currentIndex which will be used when new plot items
# are created
#
# Therefore we first enable a CustomContextMenu
view.setContextMenuPolicy(Qt.CustomContextMenu)
# We have to disable the default MousePressEvent in the views viewport
# because otherwise the Left-click behaviour would occur as well when
# hitting the right button
# Therefore:
# install an EventFilter such that only the customContextMenuRequested
# signal of the view is fired and not the pressed signal (which would
# hide the popup)
view.viewport().installEventFilter(self)
view.customContextMenuRequested.connect(self.right_click)
# Furthermore we implement, that the pop up shall not be closed if the
# keep open property is True. Therefore we have to track when the
# index changes
view.pressed.connect(self.handleItemPressed)
view.doubleClicked.connect(self.hide_anyway)
def eventFilter(self, obj, event):
"""Reimplemented to filter right-click events on the view()"""
ret = (
event.type() == QtCore.QEvent.MouseButtonPress
) and event.button() == Qt.RightButton
return ret
def handleItemPressed(self, index):
"""Function to be called when an item is pressed to make sure that
we know whether anything changed before closing the popup"""
item = self.model().itemFromIndex(index)
if item.checkState() == Qt.Checked:
item.setCheckState(Qt.Unchecked)
else:
item.setCheckState(Qt.Checked)
self.setCurrentIndex(0)
self._changed = True
def right_click(self, point):
"""Function that is called when an item is right_clicked"""
ind = self.view().indexAt(point).row()
self.setCurrentIndex(ind)
self._right_clicked = True
self._changed = True
def hide_anyway(self, index=None):
"""Function to hide the popup despite of the :attr:`_changed` attribute"""
self._changed = True
self.hidePopup()
def hidePopup(self):
"""Reimplemented to only close the popup when the :attr:`close_popup`
attribute is True or it is clicked outside the window"""
if not self._right_clicked:
self.leftclick.emit(self)
if not self._changed or self.close_popups:
super(CoordComboBox, self).hidePopup()
self._changed = False
self._right_clicked = False
def mousePressEvent(self, *args, **kwargs):
"""Reimplemented to fill the box with content from the dataset"""
self.load_coord()
super(CoordComboBox, self).mousePressEvent(*args, **kwargs)
def mouseDoubleClickEvent(self, *args, **kwargs):
"""Reimplemented to fill the box with content from the dataset"""
self.load_coord()
super(CoordComboBox, self).mouseDoubleClickEvent(*args, **kwargs)
def load_coord(self):
"""Load the coordinate data from the dataset and fill the combobox with
it (if it is empty)"""
if self._is_empty:
ds = self.get_ds()
self.addItem("")
if self.use_coords:
self.addItems(ds[self.dim].astype(str).values)
else:
self.addItems(list(map(str, range(len(ds[self.dim])))))
self._is_empty = False
class ArrayNameValidator(QValidator):
"""Class to make sure that only those arrays names are inserted that are
not currently in the main project or the tree"""
def __init__(self, text, table, *args, **kwargs):
super(ArrayNameValidator, self).__init__(*args, **kwargs)
self.table = table
self.current_text = text
self.current_names = list(table.current_names)
def fixup(self, s):
s = asstring(s)
if not s:
return self.table.next_available_name()
return self.table.next_available_name(s + "_{0}")
def validate(self, s, pos):
s = asstring(s)
if not s:
return QValidator.Intermediate, s, pos
elif s == self.current_text:
pass
elif s in chain(psy.gcp(True).arr_names, self.current_names):
return QValidator.Intermediate, s, pos
return QValidator.Acceptable, s, pos
class ArrayNameItemDelegate(QStyledItemDelegate):
"""Delegate using the :class:`ArrayNameValidator` for validation"""
def createEditor(self, widget, option, index):
if not index.isValid():
return
editor = QLineEdit(widget)
item = self.parent().item(index.row(), index.column())
validator = ArrayNameValidator(
item.text() if item else "", self.parent(), editor
)
editor.setValidator(validator)
return editor
class VariableItemDelegate(QStyledItemDelegate):
"""Delegate alowing only the variables in the parents dataset.
The parent must hold a `get_ds` method that returns a dataset when called
"""
def createEditor(self, widget, option, index):
if not index.isValid():
return
editor = QLineEdit(widget)
ds = self.parent().get_ds()
validator = ListValidator(
ds.variables.keys(), self.parent().sep, editor
)
editor.setValidator(validator)
return editor
class VariablesTable(QTableWidget):
"""Table to display the variables of a dataset"""
#: The variables in the dataset
variables = []
@property
def selected_variables(self):
"""The currently selected variables"""
return [
self.variables[i]
for i in map(
list(map(asstring, self.variables)).index,
sorted(
set(
item.text()
for item in self.selectedItems()
if item.column() == 0
)
),
)
]
def __init__(
self, get_func, columns=["long_name", "dims", "shape"], *args, **kwargs
):
"""
Parameters
----------
get_func: function
The function that, when called without arguments, returns the
xarray.Dataset to use
columns: list of str
The attribute that will be used as columns for the variables"""
super(VariablesTable, self).__init__(*args, **kwargs)
self.variables = []
self.get_ds = get_func
self.set_columns(columns)
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.verticalHeader().setVisible(False)
def set_columns(self, columns=None):
if columns is None:
columns = self.column_labels
else:
self.column_labels = columns
self.setColumnCount(len(columns) + 1)
self.setHorizontalHeaderLabels(["variable"] + columns)
def fill_from_ds(self, ds=None):
"""Clear the table and insert items from the given `dataset`"""
self.clear()
self.set_columns()
if ds is None:
ds = self.get_ds()
if ds is None:
return
coords = list(ds.coords)
self.variables = vnames = [v for v in ds.variables if v not in coords]
self.setRowCount(len(vnames))
for i, vname in enumerate(vnames):
variable = ds.variables[vname]
self.setItem(i, 0, QTableWidgetItem(asstring(vname)))
for j, attr in enumerate(self.column_labels, 1):
if attr == "dims":
self.setItem(
i, j, QTableWidgetItem(", ".join(variable.dims))
)
else:
self.setItem(
i,
j,
QTableWidgetItem(
str(
variable.attrs.get(
attr, getattr(variable, attr, "")
)
)
),
)
class CoordsTable(QTableWidget):
"""A table showing the coordinates of in a dataset via instances of
:class:`CoordComboBox`"""
def __init__(self, get_func, *args, **kwargs):
"""
Parameters
----------
get_func: function
The function that, when called without arguments, returns the
xarray.Dataset to use
``*args, **kwargs``
Determined by the :class:`PyQt5.QtWidgets.QTableWidget` class"""
super(CoordsTable, self).__init__(*args, **kwargs)
self.get_ds = get_func
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.setRowCount(1)
self.verticalHeader().setVisible(False)
self.horizontalHeader().setStretchLastSection(True)
self.verticalHeader().setStretchLastSection(True)
@property
def combo_boxes(self):
"""A list of :class:`CoordComboBox` in this table"""
return list(
filter(
lambda w: w is not None,
(self.cellWidget(0, i) for i in range(self.columnCount())),
)
)
def fill_from_ds(self, ds=None):
"""Clear the table and create new comboboxes"""
for cb in self.combo_boxes:
cb.blockSignals(True)
self.clear()
if ds is None:
ds = self.get_ds()
if ds is None:
return
coords = list(ds.coords)
vnames = [v for v in ds.variables if v not in coords]
self.dims = dims = list(
set(chain(*(ds.variables[vname].dims for vname in vnames)))
)
try:
dims.sort()
except TypeError:
pass
self.setColumnCount(len(dims))
for i, dim in enumerate(dims):
header_item = QTableWidgetItem(dim)
self.setHorizontalHeaderItem(i, header_item)
self.setCellWidget(0, i, CoordComboBox(self.get_ds, dim))
def sizeHint(self):
"""Reimplemented to adjust the heigth based upon the header and the
first row"""
return QtCore.QSize(
super(CoordsTable, self).sizeHint().width(),
self.horizontalHeader().height() + self.rowHeight(0),
)
class DragDropTable(QTableWidget):
"""Table that allows to exchange rows via drag and drop
This class was mainly taken from
http://stackoverflow.com/questions/26227885/drag-and-drop-rows-within-qtablewidget
"""
def __init__(self, *args, **kwargs):
super(DragDropTable, self).__init__(*args, **kwargs)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.viewport().setAcceptDrops(True)
self.setDragDropOverwriteMode(False)
self.setDropIndicatorShown(True)
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setDragDropMode(QAbstractItemView.InternalMove)
def dropEvent(self, event):
if event.source() == self and (
event.dropAction() == Qt.MoveAction
or self.dragDropMode() == QAbstractItemView.InternalMove
):
self.dropOn(event)
else:
super(DragDropTable, self).dropEvent(event)
def moveRows(self, row, remove=False):
"""Move all selected rows to the given `row`"""
selRows = sorted({ind.row() for ind in self.selectedIndexes()})
top = selRows[0]
dropRow = row
if dropRow == -1:
dropRow = self.rowCount()
offset = dropRow - top
for i, row in enumerate(selRows):
r = row + offset
if r > self.rowCount() or r < 0:
r = 0
self.insertRow(r)
selRows = sorted({ind.row() for ind in self.selectedIndexes()})
top = selRows[0]
offset = dropRow - top
for i, row in enumerate(selRows):
r = row + offset
if r > self.rowCount() or r < 0:
r = 0
for j in range(self.columnCount()):
source = QTableWidgetItem(self.item(row, j))
self.setItem(r, j, source)
if remove:
for row in reversed(selRows):
self.removeRow(row)
def droppingOnItself(self, event, index):
dropAction = event.dropAction()
if self.dragDropMode() == QAbstractItemView.InternalMove:
dropAction = Qt.MoveAction
if (
event.source() == self
and event.possibleActions() & Qt.MoveAction
and dropAction == Qt.MoveAction
):
selectedIndexes = self.selectedIndexes()
child = index
while child.isValid() and child != self.rootIndex():
if child in selectedIndexes:
return True
child = child.parent()
return False
def dropOn(self, event):
if event.isAccepted():
return False, None, None, None
index = QtCore.QModelIndex()
row = -1
if self.viewport().rect().contains(event.pos()):
index = self.indexAt(event.pos())
if not index.isValid() or not self.visualRect(index).contains(
event.pos()
):
index = self.rootIndex()
if self.model().supportedDropActions() & event.dropAction():
if index != self.rootIndex():
dropIndicatorPosition = self.position(
event.pos(), self.visualRect(index), index
)
if dropIndicatorPosition == QAbstractItemView.AboveItem:
row = index.row()
# index = index.parent()
elif dropIndicatorPosition == QAbstractItemView.BelowItem:
row = index.row() + 1
# index = index.parent()
else:
row = index.row()
if not self.droppingOnItself(event, index):
self.moveRows(row, remove=event.source() is None)
event.accept()
def position(self, pos, rect, index):
r = QAbstractItemView.OnViewport
margin = 2
if pos.y() - rect.top() < margin:
r = QAbstractItemView.AboveItem
elif rect.bottom() - pos.y() < margin:
r = QAbstractItemView.BelowItem
elif rect.contains(pos, True):
r = QAbstractItemView.OnItem
if r == QAbstractItemView.OnItem and not (
self.model().flags(index) & Qt.ItemIsDropEnabled
):
if pos.y() < rect.center().y():
r = QAbstractItemView.AboveItem
else:
r = QAbstractItemView.BelowItem
return r
class ArrayTable(DragDropTable):
"""Table that shows the arrays that will be used for plotting
It contains the following columns:
1. The variable column which holds the variable names of the arrays.
multiple variables may be separated by ';;'
2. The array name. The :attr:`psyplot.data.InteractiveBase.arr_name`
attribute. Depending on the plot methods
:attr:`~psyplot.project._PlotterInterface._prefer_list`, multiple
array names are allowed or not. If this attribute is True,
arrays with the same array name will be concatenated into one
:class:`psyplot.data.InteractiveList`
3. The axes column. Use the right-click context menu to select a
subplot
4. The check column. Checks for variable names, array names, axes and
dimensions via the :meth:`psyplot.project._PlotterInterface.check_data`
method
5. Columns containing the dimension informations"""
#: Pattern to interprete subplots
subplot_patt = re.compile(
r"\((?P<fig>\d+),\s*" # figure
r"(?P<rows>\d+),\s*" # rows
r"(?P<cols>\d+),\s*" # columns
r"(?P<num1>\d+),\s*" # position
r"(?P<num2>\d+)\s*\)" # end subplot
)
#: pattern to interprete arbitrary axes
axes_patt = re.compile(
r"\((?P<fig>\d+),\s*" # figure
r"(?P<x0>0*\.\d+),\s*" # lower left x
r"(?P<y0>0*\.\d+),\s*" # lower left y
r"(?P<x1>0*\.\d+),\s*" # upper right x
r"(?P<y1>0*\.\d+)\s*\)" # upper right y
)
#: The separator for variable names
sep = ";;"
#: Tool tip for the variable column
VARIABLE_TT = (
"The variables of the array from the dataset. Multiple"
"variables for one array may be separated by '%s'" % (sep)
)
#: Base tool tip for a dimension column
DIMS_TT = (
"The values for dimension %s."
" You can use integers either explicit, e.g."
"<ul>"
"<li>1, 2, 3, ...,</li>"
"</ul>"
"or slices like <em>start:end:step</em>, e.g."
"<ul>"
"<li>'1:6:2'</li>"
"</ul>"
"where the latter is equivalent to '1, 3, 5'"
)
def dropEvent(self, event):
"""Reimplemented to call the :meth:`check_arrays` after the call"""
# apparently the row deletion occurs after the call of this method.
# therefore our call of `check_arrays` leads to the (wrong) result
# of a duplicated entry. We therefore filter them out here and make
# sure that those arrays are not considered when checking for
# duplicates
messages = dict(
zip(self.current_names, [msg for b, msg in self.check_arrays()])
)
super(ArrayTable, self).dropEvent(event)
ignores = [
arr_name
for arr_name, msg in messages.items()
if not msg.startswith("Found duplicated entry of")
]
self.check_arrays(ignore_duplicates=ignores)
@property
def prefer_list(self):
"""Return the _prefer_list attribute of the plot_method"""
return self.plot_method and self.plot_method._prefer_list
@property
def current_names(self):
"""The names that are currently in use"""
if self.prefer_list:
return []
arr_col = self.arr_col
return [
asstring(item.text())
for item in filter(
None,
map(lambda i: self.item(i, arr_col), range(self.rowCount())),
)
]
@property
def vnames(self):
"""The list of variable names per array"""
var_col = self.var_col
return [
self.item(i, var_col).text().split(";;")
for i in range(self.rowCount())
]
@property
def arr_names_dict(self):
"""The final dictionary containing the array names necessary for the
`arr_names` parameter in the
:meth:`psyplot.data.ArrayList.from_dataset` method"""
ret = dict()
arr_col = self.arr_col
for irow in range(self.rowCount()):
arr_name = asstring(self.item(irow, arr_col).text())
if self.plot_method and self.plot_method._prefer_list:
d = ret.setdefault(arr_name, defaultdict(list))
d["name"].append(self._get_variables(irow))
for key, val in self._get_dims(irow).items():
d[key].append(val)
else:
ret[arr_name] = d = {"name": self._get_variables(irow)}
d.update(self._get_dims(irow))
return ret
@property
def axes(self):
"""A list of axes settings corresponding to the arrays in the
:attr:`arr_names_dict`"""
ret = []
d = set()
arr_col = self.arr_col
axes_col = self.axes_col
# get the projection
pm = self.plot_method
kwargs = {}
if pm is not None:
projection = self.plot_method.plotter_cls._get_sample_projection()
if projection is not None:
kwargs["projection"] = projection
for irow in range(self.rowCount()):
arr_name = self.item(irow, arr_col).text()
if arr_name in d:
continue
d.add(arr_name)
axes_type, args = self.axes_info(self.item(irow, axes_col))
if axes_type == "subplot":
ret.append(SubplotCreator.create_subplot(*args, **kwargs))
elif axes_type == "axes":
ret.append(AxesCreator.create_axes(*args, **kwargs))
else:
ret.append(None)
return ret
@property
def var_col(self):
"""The index of the variable column"""
return self.desc_cols.index(self.VARIABLE_LABEL)
@property
def arr_col(self):
"""The index of the array name column"""
return self.desc_cols.index(self.ARRAY_LABEL)
@property
def axes_col(self):
"""The index of the axes column"""
return self.desc_cols.index(self.AXES_LABEL)
@property
def check_col(self):
"""The index of the check column"""
return self.desc_cols.index(self.CHECK_LABEL)
def __init__(self, get_func, columns=[], *args, **kwargs):
"""
Parameters
----------
get_func: function
The function that, when called without arguments, returns the
xarray.Dataset to use
columns: list of str
The coordinates in the dataset"""
super(ArrayTable, self).__init__(*args, **kwargs)
self.get_ds = get_func
self.VARIABLE_LABEL = "variable"
self.ARRAY_LABEL = "array name"
self.AXES_LABEL = "axes"
self.CHECK_LABEL = "check"
self.desc_cols = [
self.VARIABLE_LABEL,
self.ARRAY_LABEL,
self.AXES_LABEL,
self.CHECK_LABEL,
]
self.plot_method = None
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showAxesCreator)
self.set_columns(columns)
self.setItemDelegateForColumn(self.var_col, VariableItemDelegate(self))
self.setItemDelegateForColumn(
self.arr_col, ArrayNameItemDelegate(self)
)
self.itemChanged.connect(self.check_item)
self.itemChanged.connect(self.update_other_items)
def set_columns(self, columns):
"""Set the columns of the table
Parameters
----------
columns: list of str
The coordinates in the dataset"""
if columns is None:
columns = self.column_labels
else:
self.column_labels = columns
self.setColumnCount(len(columns) + len(self.desc_cols))
self.setHorizontalHeaderLabels(self.desc_cols + columns)
for i, col in enumerate(columns, len(self.desc_cols)):
self.horizontalHeaderItem(i).setToolTip(self.DIMS_TT % col)
self.horizontalHeaderItem(self.var_col).setToolTip(self.VARIABLE_TT)
def setup_from_ds(self, ds=None, plot_method=None):
"""Fill the table based upon the given dataset.
Parameters
----------
ds: xarray.Dataset or None
If None, the dataset from the :attr:`get_ds` function is used
plot_method: psyplot.project._PlotterInterface or None
The plot method of the :class:`psyplot.project.ProjectPlotter`
class or None if no plot shall be made"""
self.clear()
self.setRowCount(0)
if ds is None:
ds = self.get_ds()
if plot_method is not None:
self.set_pm(plot_method)
if ds is None:
self.set_columns([])
return
coords = list(ds.coords)
vnames = [v for v in ds.variables if v not in coords]
self.dims = dims = list(
set(chain(*(ds.variables[vname].dims for vname in vnames)))
)
try:
dims.sort()
except TypeError:
pass
self.set_columns(dims)
def next_available_name(self, *args, **kwargs):
"""Gives the next possible name to use"""
counter = iter(range(1000))
current_names = self.current_names
mp = psy.gcp(True)
while True:
name = mp.next_available_name(*args, counter=counter, **kwargs)
if name not in current_names:
return name
def insert_array(self, name, check=True, **kwargs):
"""Appends the settings for an array the the list in a new row"""
dims = set(self.get_ds().variables[name].dims)
irow = self.rowCount()
self.setRowCount(irow + 1)
self.setItem(irow, 0, QTableWidgetItem(asstring(name)))
self.setItem(irow, 1, QTableWidgetItem(self.next_available_name()))
self.setItem(irow, 2, QTableWidgetItem(""))
for dim in dims.intersection(kwargs):
icol = len(self.desc_cols) + self.dims.index(dim)
self.setItem(irow, icol, QTableWidgetItem(kwargs[dim]))
if check:
self.check_array(irow)
def remove_arrays(self, selected=True):
"""Remove array rows from the list
Parameters
----------
selected: bool
If True, only the selected rows are removed"""
if selected:
irows = sorted({ind.row() for ind in self.selectedIndexes()})
else:
irows = list(range(self.rowCount()))
for irow in irows[::-1]:
self.removeRow(irow)
def update_selected(self, check=True, dims={}):
"""Updates the dimensions of the selectiond arrays with the given
`dims`
Parameters
----------
check: bool
whether the array shall be checked afterwards
dims: dict
a mapping from coordinate names to string values that shall be
appended to the current text"""
ds = self.get_ds()
irows = {item.row() for item in self.selectedItems()}
var_col = self.desc_cols.index(self.VARIABLE_LABEL)
for irow in irows:
vname = (
asstring(self.item(irow, var_col).text())
.split(self.sep)[0]
.strip()
)
var_dims = set(ds.variables[vname].dims)
for dim in var_dims.intersection(dims):
icol = len(self.desc_cols) + self.dims.index(dim)
item = self.item(irow, icol)
curr_text = asstring(item.text())
if curr_text:
curr_text += ", "
item.setText(curr_text + dims[dim])
if check:
for irow in irows:
self.check_array(irow)
def add_subplots(self, rows, cols, maxn=None):
"""Add multiple subplots to the selected arrays"""
import matplotlib.pyplot as plt
irows = sorted({ind.row() for ind in self.selectedIndexes()})
irows = irows or list(range(self.rowCount()))
maxn = maxn or rows * cols
figs = chain(
*([i] * maxn for i in range(1, 1000) if i not in plt.get_fignums())
)
nums = cycle(range(1, maxn + 1))
seen = set()
axes_col = self.desc_cols.index(self.AXES_LABEL)
arr_col = self.desc_cols.index(self.ARRAY_LABEL)
for irow in irows:
arr_item = self.item(irow, arr_col)
if arr_item is None or arr_item.text() in seen:
continue
seen.add(arr_item.text())
num = next(nums)
text = "(%i, %i, %i, %i, %i)" % (next(figs), rows, cols, num, num)
item = QTableWidgetItem(text)
self.setItem(irow, axes_col, item)
def add_single_subplot(self, rows, cols, row, col):
"""Add one subplot to the selected arrays on multiple figures"""
import matplotlib.pyplot as plt
irows = sorted({ind.row() for ind in self.selectedIndexes()})
irows = irows or list(range(self.rowCount()))
figs = (num for num in range(1, 1000) if num not in plt.get_fignums())
num = (row - 1) * rows + col
seen = set()
axes_col = self.desc_cols.index(self.AXES_LABEL)
arr_col = self.desc_cols.index(self.ARRAY_LABEL)
for irow in irows:
arr_item = self.item(irow, arr_col)
if arr_item is None or arr_item.text() in seen:
continue
seen.add(arr_item.text())
text = "(%i, %i, %i, %i, %i)" % (next(figs), rows, cols, num, num)
item = QTableWidgetItem(text)
self.setItem(irow, axes_col, item)
def showAxesCreator(self, pos):
"""Context menu for right-click on a row"""
irows = sorted({ind.row() for ind in self.selectedIndexes()})
if not irows:
return
menu = QMenu(self)
menu.addAction(self.axes_creator_action(irows))
menu.exec_(self.mapToGlobal(pos))
def axes_creator_action(self, rows):
"""Action to open a :class:`AxesCreatorCollection` for the selected
rows"""
axes_col = self.desc_cols.index(self.AXES_LABEL)
items = [self.item(row, axes_col) for row in rows]
action = QAction("Select subplot", self)
types_and_args = list(
filter(lambda t: t[0], map(self.axes_info, items))
)
types = [t[0] for t in types_and_args]
if types and all(t == types[0] for t in types):
if types[0] == "subplot":
creator_kws = ["fig", "rows", "cols", "num1", "num2"]
elif types[0] == "axes":
creator_kws = ["fig", "x0", "y0", "x1", "y1"]
else:
creator_kws = []
func_name = types[0]
args = [t[1] for t in types_and_args]
#: the initialization keywords of the :class:`SubplotCreator` class
kwargs = {}
if len(items) > 0:
kwargs["fig"] = ""
for kw, vals in zip(creator_kws, zip(*args)):
if all(val == vals[0] for val in vals):
kwargs[kw] = vals[0]
else:
func_name = None
kwargs = {}
action.triggered.connect(
self._open_axes_creator(items, func_name, kwargs)
)
return action
def _change_axes(self, items, iterator):
seen = set()
arr_col = self.desc_cols.index(self.ARRAY_LABEL)
for item, text in zip(items, iterator):
arr_name = self.item(item.row(), arr_col).text()
if arr_name in seen:
continue
seen.add(arr_name)
item.setText(text)
def _open_axes_creator(self, items, func_name, kwargs):
def func():
if hasattr(self, "_axes_creator"):
self._axes_creator.close()
self._axes_creator = obj = AxesCreatorCollection(
func_name, kwargs, parent=self
)
obj.okpressed.connect(partial(self._change_axes, items))
obj.exec_()
return func
def axes_info(self, s):
"""Interpretes an axes information"""
s = asstring(s) if isstring(s) else asstring(s.text())
m = self.subplot_patt.match(s)
if m:
return "subplot", list(map(int, m.groups()))
m = self.axes_patt.match(s)
if m:
return "axes", [int(m.groupdict()["fig"])] + list(
map(float, m.groups()[1:])
)
return None, None
def set_pm(self, s):
"""Set the plot method"""