forked from psyplot/psyplot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotter.py
More file actions
executable file
·2493 lines (2153 loc) · 87.9 KB
/
plotter.py
File metadata and controls
executable file
·2493 lines (2153 loc) · 87.9 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
"""Core package for interactive visualization in the psyplot package
This package defines the :class:`Plotter` and :class:`Formatoption` classes,
the core of the visualization in the :mod:`psyplot` package. Each
:class:`Plotter` combines a set of formatoption keys where each formatoption
key is represented by a :class:`Formatoption` subclass."""
# Disclaimer
# ----------
#
# Copyright (C) 2021 Helmholtz-Zentrum Hereon
# Copyright (C) 2020-2021 Helmholtz-Zentrum Geesthacht
# Copyright (C) 2016-2021 University of Lausanne
#
# This file is part of psyplot 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/>.
import six
import weakref
from abc import ABCMeta, abstractmethod
from textwrap import TextWrapper
import logging
from itertools import chain, groupby, tee, repeat, starmap
from collections import defaultdict
from threading import RLock
from datetime import datetime, timedelta
from numpy import datetime64, timedelta64, ndarray, inf
from xarray.core.formatting import format_timestamp, format_timedelta
from psyplot import rcParams
from psyplot.warning import warn, critical, PsyPlotRuntimeWarning
from psyplot.compat.pycompat import map, filter, zip, range
from psyplot.config.rcsetup import SubDict
from psyplot.docstring import docstrings, dedent
from psyplot.data import (
InteractiveList, _no_auto_update_getter, CFDecoder)
from psyplot.utils import (DefaultOrderedDict, _TempBool, _temp_bool_prop,
unique_everseen, check_key)
#: the default function to use when printing formatoption infos (the default is
#: use print or in the gui, use the help explorer)
default_print_func = six.print_
#: :class:`dict`. Mapping from group to group names
groups = {
'data': 'Data manipulation formatoptions',
'axes': 'Axes formatoptions',
'labels': 'Label formatoptions',
'plotting': 'Plot formatoptions',
'post_processing': 'Post processing formatoptions',
'colors': 'Color coding formatoptions',
'misc': 'Miscallaneous formatoptions',
'ticks': 'Axis tick formatoptions',
'vector': 'Vector plot formatoptions',
'masking': 'Masking formatoptions',
'regression': 'Fitting formatoptions',
}
def _identity(*args):
"""identity function to make no validation
Returns
-------
object
just return the last argument in ``*args``"""
return args[-1]
def format_time(x):
"""Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
Parameters
----------
x: object
The value to format. If not a time object, the value is returned
Returns
-------
str or `x`
Either the formatted time object or the initial `x`"""
if isinstance(x, (datetime64, datetime)):
return format_timestamp(x)
elif isinstance(x, (timedelta64, timedelta)):
return format_timedelta(x)
elif isinstance(x, ndarray):
return list(x) if x.ndim else x[()]
return x
def is_data_dependent(fmto, data):
"""Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependent`
attribute is a callable
Returns
-------
bool
True, if the formatoption depends on the data"""
if callable(fmto.data_dependent):
return fmto.data_dependent(data)
return fmto.data_dependent
def _child_property(childname):
def get_x(self):
return getattr(self.plotter, self._child_mapping[childname])
return property(
get_x, doc=childname + " Formatoption instance in the plotter")
class FormatoptionMeta(ABCMeta):
"""Meta class for formatoptions
This class serves as a meta class for formatoptions and allows a more
efficient docstring generation by using the
:attr:`psyplot.docstring.docstrings` when creating a new formatoption
class"""
def __new__(cls, clsname, bases, dct):
"""Assign an automatic documentation to the formatoption"""
doc = dct.get('__doc__')
if doc is not None:
dct['__doc__'] = docstrings.dedent(doc)
new_cls = super(FormatoptionMeta, cls).__new__(cls, clsname, bases,
dct)
for childname in chain(new_cls.children, new_cls.dependencies,
new_cls.connections, new_cls.parents):
setattr(new_cls, childname, _child_property(childname))
if new_cls.plot_fmt:
new_cls.data_dependent = True
return new_cls
# priority values
#: Priority value of formatoptions that are updated before the data is loaded.
START = 30
#: Priority value of formatoptions that are updated before the plot it made.
BEFOREPLOTTING = 20
#: Priority value of formatoptions that are updated at the end.
END = 10
@six.add_metaclass(FormatoptionMeta)
class Formatoption(object):
"""Abstract formatoption
This class serves as an abstract version of an formatoption descriptor
that can be used by :class:`~psyplot.plotter.Plotter` instances."""
priority = END
""":class:`int`. Priority value of the the formatoption determining when
the formatoption is updated.
- 10: at the end (for labels, etc.)
- 20: before the plotting (e.g. for colormaps, etc.)
- 30: before loading the data (e.g. for lonlatbox)"""
#: :class:`str`. Formatoption key of this class in the
#: :class:`~psyplot.plotter.Plotter` class
key = None
_plotter = None
@property
def plotter(self):
""":class:`~psyplot.plotter.Plotter`. Plotter instance this
formatoption belongs to"""
if self._plotter is None:
return
return self._plotter()
@plotter.setter
def plotter(self, value):
if value is not None:
self._plotter = weakref.ref(value)
else:
self._plotter = value
#: `list of str`. List of formatoptions that have to be updated before this
#: one is updated. Those formatoptions are only updated if they exist in
#: the update parameters.
children = []
#: `list of str`. List of formatoptions that force an update of this
#: formatoption if they are updated.
dependencies = []
#: `list of str`. Connections to other formatoptions that are (different
#: from :attr:`dependencies` and :attr:`children`) not important for the
#: update process
connections = []
#: `list of str`. List of formatoptions that, if included in the update,
#: prevent the update of this formatoption.
parents = []
#: :class:`bool`. Has to be True if the formatoption has a ``make_plot``
#: method to make the plot.
plot_fmt = False
#: :class:`bool`. True if an update of this formatoption requires a
#: clearing of the axes and reinitialization of the plot
requires_clearing = False
#: :class:`str`. Key of the group name in :data:`groups` of this
#: formatoption keyword
group = 'misc'
#: :class:`bool` or a callable. This attribute indicates whether this
#: :class:`Formatoption` depends on the data and should be updated if the
#: data changes. If it is a callable, it must accept one argument: the
#: new data. (Note: This is automatically set to True for plot
#: formatoptions)
data_dependent = False
#: :class:`bool`. True if this formatoption needs an update after the plot
#: has changed
update_after_plot = False
#: :class:`set` of the :class:`Formatoption` instance that are shared
#: with this instance.
shared = set()
#: int or None. Index that is used in case the plotting data is a
#: :class:`psyplot.InteractiveList`
index_in_list = 0
#: :class:`str`. A bit more verbose name than the formatoption key to be
#: included in the gui. If None, the key is used in the gui
name = None
#: Boolean that is True if an update of the formatoption requires a replot
requires_replot = False
@property
def init_kwargs(self):
""":class:`dict` key word arguments that are passed to the
initialization of a new instance when accessed from the descriptor"""
return self._child_mapping
@property
def project(self):
"""Project of the plotter of this instance"""
return self.plotter.project
@property
def ax(self):
"""The axes this Formatoption plots on"""
return self.plotter.ax
@property
def lock(self):
"""A :class:`threading.Rlock` instance to lock while updating
This lock is used when multiple :class:`plotter` instances are
updated at the same time while sharing formatoptions."""
try:
return self._lock
except AttributeError:
self._lock = RLock()
return self._lock
@property
def logger(self):
"""Logger of the plotter"""
return self.plotter.logger.getChild(self.key)
@property
def groupname(self):
"""Long name of the group this formatoption belongs too."""
try:
return groups[self.group]
except KeyError:
warn("Unknown formatoption group " + str(self.group),
PsyPlotRuntimeWarning)
return self.group
@property
def raw_data(self):
"""The original data of the plotter of this formatoption"""
if self.index_in_list is not None and isinstance(
self.plotter.data, InteractiveList):
return self.plotter.data[self.index_in_list]
else:
return self.plotter.data
@property
def decoder(self):
"""The :class:`~psyplot.data.CFDecoder` instance that decodes the
:attr:`raw_data`"""
# If the decoder is modified by one of the formatoptions, use this one
if self.plotter.plot_data_decoder is not None:
if self.index_in_list is not None and isinstance(
self.plotter.plot_data, InteractiveList):
ret = self.plotter.plot_data_decoder[self.index_in_list]
if ret is not None:
return ret
else:
return self.plotter.plot_data_decoder
data = self.raw_data
check = isinstance(data, InteractiveList)
while check:
data = data[0]
check = isinstance(data, InteractiveList)
return data.psy.decoder
@decoder.setter
def decoder(self, value):
self.set_decoder(value, self.index_in_list)
@property
def any_decoder(self):
"""Return the first possible decoder"""
ret = self.decoder
while not isinstance(ret, CFDecoder):
ret = ret[0]
return ret
@property
def data(self):
"""The data that is plotted"""
if self.index_in_list is not None and isinstance(
self.plotter.plot_data, InteractiveList):
return self.plotter.plot_data[self.index_in_list]
else:
return self.plotter.plot_data
@data.setter
def data(self, value):
self.set_data(value, self.index_in_list)
@property
def iter_data(self):
"""Returns an iterator over the plot data arrays"""
data = self.data
if isinstance(data, InteractiveList):
return iter(data)
return iter([data])
@property
def iter_raw_data(self):
"""Returns an iterator over the original data arrays"""
data = self.raw_data
if isinstance(data, InteractiveList):
return iter(data)
return iter([data])
@property
def validate(self):
"""Validation method of the formatoption"""
try:
return self._validate
except AttributeError:
try:
self._validate = self.plotter.get_vfunc(self.key)
except KeyError:
warn("Could not find a validation function for %s "
"formatoption keyword! No validation will be made!" % (
self.key), PsyPlotRuntimeWarning, logger=self.logger)
self._validate = _identity
return self._validate
@validate.setter
def validate(self, value):
self._validate = value
@property
def default(self):
"""Default value of this formatoption"""
return self.plotter.rc[self.key]
@property
def default_key(self):
"""The key of this formatoption in the :attr:`psyplot.rcParams`"""
return self.plotter.rc._get_val_and_base(self.key)[0]
@property
def shared_by(self):
"""None if the formatoption is not controlled by another formatoption
of another plotter, otherwise the corresponding :class:`Formatoption`
instance"""
return self.plotter._shared.get(self.key)
@property
def value(self):
"""Value of the formatoption in the corresponding :attr:`plotter` or
the shared value"""
shared_by = self.shared_by
if shared_by:
return shared_by.value2share
return self.plotter[self.key]
@property
@dedent
def changed(self):
"""
:class:`bool` indicating whether the value changed compared to the
default or not."""
return self.diff(self.default)
@property
@dedent
def value2share(self):
"""
The value that is passed to shared formatoptions (by default, the
:attr:`value` attribute)"""
return self.value
@property
@dedent
def value2pickle(self):
"""
The value that can be used when pickling the information of the project
"""
return self.value
@docstrings.get_sections(base='Formatoption')
@dedent
def __init__(self, key, plotter=None, index_in_list=None,
additional_children=[], additional_dependencies=[],
**kwargs):
"""
Parameters
----------
key: str
formatoption key in the `plotter`
plotter: psyplot.plotter.Plotter
Plotter instance that holds this formatoption. If None, it is
assumed that this instance serves as a descriptor.
index_in_list: int or None
The index that shall be used if the data is a
:class:`psyplot.InteractiveList`
additional_children: list or str
Additional children to use (see the :attr:`children` attribute)
additional_dependencies: list or str
Additional dependencies to use (see the :attr:`dependencies`
attribute)
``**kwargs``
Further keywords may be used to specify different names for
children, dependencies and connection formatoptions that match the
setup of the plotter. Hence, keywords may be anything of the
:attr:`children`, :attr:`dependencies` and :attr:`connections`
attributes, with values being the name of the new formatoption in
this plotter."""
self.key = key
self.plotter = plotter
self.index_in_list = index_in_list
self.shared = set()
self.additional_children = additional_children
self.additional_dependencies = additional_dependencies
self.children = self.children + additional_children
self.dependencies = self.dependencies + additional_dependencies
self._child_mapping = dict(zip(*tee(chain(
self.children, self.dependencies, self.connections,
self.parents), 2)))
# check kwargs
for key in (key for key in kwargs if key not in self._child_mapping):
raise TypeError(
'%s.__init__() got an unexpected keyword argument %r' % (
self.__class__.__name__, key))
# set up child mapping
self._child_mapping.update(kwargs)
# reset the dependency lists to match the current plotter setup
for attr in ['children', 'dependencies', 'connections', 'parents']:
setattr(self, attr,
[self._child_mapping[key] for key in getattr(self, attr)])
def __set__(self, instance, value):
if isinstance(value, Formatoption):
setattr(instance, '_' + self.key, value)
else:
fmto = getattr(instance, self.key)
fmto.set_value(value)
def __get__(self, instance, owner):
if instance is None:
return self
try:
return getattr(instance, '_' + self.key)
except AttributeError:
fmto = self.__class__(
self.key, instance, self.index_in_list,
additional_children=self.additional_children,
additional_dependencies=self.additional_dependencies,
**self.init_kwargs)
setattr(instance, '_' + self.key, fmto)
return fmto
def __delete__(self, instance, owner):
fmto = getattr(instance, '_' + self.key)
with instance.no_validation:
instance[self.key] = fmto.default
@docstrings.get_sections(base='Formatoption.set_value')
@dedent
def set_value(self, value, validate=True, todefault=False):
"""
Set (and validate) the value in the plotter. This method is called by
the plotter when it attempts to change the value of the formatoption.
Parameters
----------
value
Value to set
validate: bool
if True, validate the `value` before it is set
todefault: bool
True if the value is updated to the default value"""
# do nothing if the key is shared
if self.key in self.plotter._shared:
return
with self.plotter.no_validation:
self.plotter[self.key] = value if not validate else \
self.validate(value)
def set_data(self, data, i=None):
"""
Replace the data to plot
This method may be used to replace the data that is visualized by the
plotter. It changes it's behaviour depending on whether an
:class:`psyplot.data.InteractiveList` is visualized or a single
:class:`pysplot.data.InteractiveArray`
Parameters
----------
data: psyplot.data.InteractiveBase
The data to insert
i: int
The position in the InteractiveList where to insert the data (if
the plotter visualizes a list anyway)
Notes
-----
This method uses the :attr:`Formatoption.data` attribute
"""
if self.index_in_list is not None:
i = self.index_in_list
if i is not None and isinstance(self.plotter.plot_data,
InteractiveList):
self.plotter.plot_data[i] = data
else:
self.plotter.plot_data = data
def set_decoder(self, decoder, i=None):
"""
Replace the data to plot
This method may be used to replace the data that is visualized by the
plotter. It changes it's behaviour depending on whether an
:class:`psyplot.data.InteractiveList` is visualized or a single
:class:`pysplot.data.InteractiveArray`
Parameters
----------
decoder: psyplot.data.CFDecoder
The decoder to insert
i: int
The position in the InteractiveList where to insert the data (if
the plotter visualizes a list anyway)
"""
# we do not modify the raw data but instead set it on the plotter
# TODO: This is not safe for encapsulated InteractiveList instances!
if i is not None and isinstance(
self.plotter.plot_data, InteractiveList):
n = len(self.plotter.plot_data)
decoders = self.plotter.plot_data_decoder or [None] * n
decoders[i] = decoder
self.plotter.plot_data_decoder = decoders
else:
if (isinstance(self.plotter.plot_data, InteractiveList) and
isinstance(decoder, CFDecoder)):
decoder = [decoder] * len(self.plotter.plot_data)
self.plotter.plot_data_decoder = decoder
def get_decoder(self, i=None):
# we do not modify the raw data but instead set it on the plotter
# TODO: This is not safe for encapsulated InteractiveList instances!
if i is not None and isinstance(
self.plotter.plot_data, InteractiveList):
n = len(self.plotter.plot_data)
decoders = self.plotter.plot_data_decoder or [None] * n
return decoders[i] or self.plotter.plot_data[i].psy.decoder
else:
return self.decoder
def check_and_set(self, value, todefault=False, validate=True):
"""Checks the value and sets the value if it changed
This method checks the value and sets it only if the :meth:`diff`
method result of the given `value` is True
Parameters
----------
value
A possible value to set
todefault: bool
True if the value is updated to the default value
Returns
-------
bool
A boolean to indicate whether it has been set or not"""
if validate:
value = self.validate(value)
if self.diff(value):
self.set_value(value, validate=False, todefault=todefault)
return True
return False
def diff(self, value):
"""Checks whether the given value differs from what is currently set
Parameters
----------
value
A possible value to set (make sure that it has been validate via
the :attr:`validate` attribute before)
Returns
-------
bool
True if the value differs from what is currently set"""
return value != self.value
def initialize_plot(self, value, *args, **kwargs):
"""Method that is called when the plot is made the first time
Parameters
----------
value
The value to use for the initialization"""
self.update(value, *args, **kwargs)
@abstractmethod
def update(self, value):
"""Method that is call to update the formatoption on the axes
Parameters
----------
value
Value to update"""
pass
def get_fmt_widget(self, parent, project):
"""Get a widget to update the formatoption in the GUI
This method should return a QWidget that is loaded by the psyplot-gui
when the formatoption is selected in the
:attr:`psyplot_gui.main.Mainwindow.fmt_widget`. It should call the
:meth:`~psyplot_gui.fmt_widget.FormatoptionWidget.insert_text` method
when the update text for the formatoption should be changed.
Parameters
----------
parent: psyplot_gui.fmt_widget.FormatoptionWidget
The parent widget that contains the returned QWidget
project: psyplot.project.Project
The current subproject (see :func:`psyplot.project.gcp`)
Returns
-------
PyQt5.QtWidgets.QWidget
The widget to control the formatoption"""
return None
def share(self, fmto, initializing=False, **kwargs):
"""Share the settings of this formatoption with other data objects
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to share the attributes with
``**kwargs``
Any other keyword argument that shall be passed to the update
method of `fmto`"""
# lock all the childrens and the formatoption itself
self.lock.acquire()
fmto._lock_children()
fmto.lock.acquire()
# update the other plotter
if initializing:
fmto.initialize_plot(self.value2share, **kwargs)
else:
fmto.update(self.value2share, **kwargs)
self.shared.add(fmto)
# release the locks
fmto.lock.release()
fmto._release_children()
self.lock.release()
def _lock_children(self):
"""acquire the locks of the children"""
plotter = self.plotter
for key in self.children + self.dependencies:
try:
getattr(plotter, key).lock.acquire()
except AttributeError:
pass
def _release_children(self):
"""release the locks of the children"""
plotter = self.plotter
for key in self.children + self.dependencies:
try:
getattr(plotter, key).lock.release()
except AttributeError:
pass
def finish_update(self):
"""Finish the update, initialization and sharing process
This function is called at the end of the :meth:`Plotter.start_update`,
:meth:`Plotter.initialize_plot` or the :meth:`Plotter.share` methods.
"""
pass
@dedent
def remove(self):
"""
Method to remove the effects of this formatoption
This method is called when the axes is cleared due to a
formatoption with :attr:`requires_clearing` set to True. You don't
necessarily have to implement this formatoption if your plot results
are removed by the usual :meth:`matplotlib.axes.Axes.clear` method."""
pass
@docstrings.get_extended_summary(base="Formatoption.convert_coordinate")
@docstrings.get_sections(
base="Formatoption.convert_coordinate",
sections=["Parameters", "Returns"]
)
def convert_coordinate(self, coord, *variables):
"""Convert a coordinate to units necessary for the plot.
This method takes a single coordinate variable (e.g. the `bounds` of a
coordinate, or the coordinate itself) and transforms the units that the
plotter requires.
One might also provide additional `variables` that are supposed to be
on the same unit, in case the given `coord` does not specify a `units`
attribute. `coord` might be a CF-conform `bounds` variable, and one of
the variables might be the corresponding `coordinate`.
Parameters
----------
coord: xr.Variable
The variable to transform
``*variables``
The variables that are on the same unit as `coord`
Returns
-------
xr.Variable
The transformed `coord`
Notes
-----
By default, this method uses the :meth:`~Plotter.convert_coordinate`
method of the :attr:`plotter`.
"""
return self.plotter.convert_coordinate(coord, *variables)
class DictFormatoption(Formatoption):
"""
Base formatoption class defining an alternative set_value that works for
dictionaries."""
@docstrings.dedent
def set_value(self, value, validate=True, todefault=False):
"""
Set (and validate) the value in the plotter
Parameters
----------
%(Formatoption.set_value.parameters)s
Notes
-----
- If the current value in the plotter is None, then it will be set with
the given `value`, otherwise the current value in the plotter is
updated
- If the value is an empty dictionary, the value in the plotter is
cleared"""
value = value if not validate else self.validate(value)
# if the key in the plotter is not already set (i.e. it is initialized
# with None, we set it)
if self.plotter[self.key] is None:
with self.plotter.no_validation:
self.plotter[self.key] = value.copy()
# in case of an empty dict, clear the value
elif not value:
self.plotter[self.key].clear()
# otherwhise we update the dictionary
else:
if todefault:
self.plotter[self.key].clear()
self.plotter[self.key].update(value)
class PostTiming(Formatoption):
"""
Determine when to run the :attr:`post` formatoption
This formatoption determines, whether the :attr:`post` formatoption
should be run never, after replot or after every update.
Possible types
--------------
'never'
Never run post processing scripts
'always'
Always run post processing scripts
'replot'
Only run post processing scripts when the data changes or a replot
is necessary
See Also
--------
post: The post processing formatoption"""
default = 'never'
priority = -inf
group = 'post_processing'
name = 'Timing of the post processing'
@staticmethod
def validate(value):
value = six.text_type(value)
possible_values = ['never', 'always', 'replot']
if value not in possible_values:
raise ValueError('String must be one of %s, not %r' % (
possible_values, value))
return value
def update(self, value):
pass
def get_fmt_widget(self, parent, project):
from psyplot_gui.compat.qtcompat import QComboBox
combo = QComboBox(parent)
combo.addItems(['never', 'always', 'replot'])
combo.setCurrentText(
next((plotter[self.key] for plotter in project.plotters), 'never'))
combo.currentTextChanged.connect(parent.set_obj)
return combo
class PostProcDependencies(object):
"""The dependencies of this formatoption"""
def __get__(self, instance, owner):
if (instance is None or instance.plotter is None or
not instance.plotter._initialized):
return []
elif instance.post_timing.value == 'always':
return list(set(instance.plotter) - {instance.key})
else:
return []
def __set__(self, instance, value):
pass
class PostProcessing(Formatoption):
"""
Apply your own postprocessing script
This formatoption let's you apply your own post processing script. Just
enter the script as a string and it will be executed. The formatoption
will be made available via the ``self`` variable
Possible types
--------------
None
Don't do anything
str
The post processing script as string
Note
----
This formatoption uses the built-in :func:`exec` function to compile the
script. Since this poses a security risk when loading psyplot projects,
it is by default disabled through the :attr:`Plotter.enable_post`
attribute. If you are sure that you can trust the script in this
formatoption, set this attribute of the corresponding :class:`Plotter` to
``True``
Examples
--------
Assume, you want to manually add the mean of the data to the title of the
matplotlib axes. You can simply do this via
.. code-block:: python
from psyplot.plotter import Plotter
from xarray import DataArray
plotter = Plotter(DataArray([1, 2, 3]))
# enable the post formatoption
plotter.enable_post = True
plotter.update(post="self.ax.set_title(str(self.data.mean()))")
plotter.ax.get_title()
'2.0'
By default, the ``post`` formatoption is only ran, when it is explicitly
updated. However, you can use the :attr:`post_timing` formatoption, to
run it automatically. E.g. for running it after every update of the
plotter, you can set
.. code-block:: python
plotter.update(post_timing='always')
See Also
--------
post_timing: Determine the timing of this formatoption"""
children = ['post_timing']
default = None
priority = -inf
group = 'post_processing'
name = 'Custom post processing script'
@staticmethod
def validate(value):
if value is None:
return value
elif not isinstance(value, six.string_types):
raise ValueError("Expected a string, not %s" % (type(value), ))
else:
return six.text_type(value)
@property
def data_dependent(self):
"""True if the corresponding :class:`post_timing <PostTiming>`
formatoption is set to ``'replot'`` to run the post processing script
after every change of the data"""
return self.post_timing.value == 'replot'
dependencies = PostProcDependencies()
def update(self, value):
if value is None:
return
if not self.plotter.enable_post:
warn(
"Post processing is disabled. Set the ``enable_post`` "
"attribute to True to run the script")
else:
exec(value, {'self': self})
class Plotter(dict):
"""Interactive plotting object for one or more data arrays
This class is the base for the interactive plotting with the psyplot
module. It capabilities are determined by it's descriptor classes that are
derived from the :class:`Formatoption` class"""
#: List of base strings in the :attr:`psyplot.rcParams` dictionary
_rcparams_string = []
post_timing = PostTiming('post_timing')
post = PostProcessing('post')